repo stringlengths 7 63 | file_url stringlengths 81 284 | file_path stringlengths 5 200 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:02:33 2026-01-05 05:24:06 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/status/ServicesHostGroups/xml/serviceSummaryByHGXML.php | centreon/www/include/monitoring/status/ServicesHostGroups/xml/serviceSummaryByHGXML.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__ . '/../../../../../../bootstrap.php');
include_once _CENTREON_PATH_ . 'www/class/centreonUtils.class.php';
include_once _CENTREON_PATH_ . 'www/class/centreonXMLBGRequest.class.php';
include_once _CENTREON_PATH_ . 'www/include/monitoring/status/Common/common-Func.php';
include_once _CENTREON_PATH_ . 'www/include/common/common-Func.php';
// Create XML Request Objects
CentreonSession::start(1);
$obj = new CentreonXMLBGRequest($dependencyInjector, session_id(), 1, 1, 0, 1);
if (! isset($obj->session_id) || ! CentreonSession::checkSession($obj->session_id, $obj->DB)) {
echo 'Bad Session ID';
exit();
}
// Set Default Poller
$obj->getDefaultFilters();
/**
* @var Centreon $centreon
*/
$centreon = $_SESSION['centreon'];
/**
* true: URIs will correspond to deprecated pages
* false: URIs will correspond to new page (Resource Status)
*/
$useDeprecatedPages = $centreon->user->doesShowDeprecatedPages();
// Check Arguments From GET request
$o = isset($_GET['o']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_GET['o']) : 'svcSumHG_pb';
$p = filter_input(INPUT_GET, 'p', FILTER_VALIDATE_INT, ['options' => ['default' => 2]]);
$num = filter_input(INPUT_GET, 'num', FILTER_VALIDATE_INT, ['options' => ['default' => 0]]);
$limit = filter_input(INPUT_GET, 'limit', FILTER_VALIDATE_INT, ['options' => ['default' => 30]]);
// if instance value is not set, displaying all active pollers' linked resources
$instance = filter_var($obj->defaultPoller ?? -1, FILTER_VALIDATE_INT);
$hostgroup = isset($_GET['hg_search']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_GET['hg_search']) : '';
$search = isset($_GET['search']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_GET['search']) : '';
$sort_type = isset($_GET['sort_type']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_GET['sort_type']) : 'alias';
$order = isset($_GET['order']) && $_GET['order'] === 'DESC' ? 'DESC' : 'ASC';
$grouplistStr = $obj->access->getAccessGroupsString();
$kernel = App\Kernel::createForWeb();
$resourceController = $kernel->getContainer()->get(
Centreon\Application\Controller\MonitoringResourceController::class
);
// saving bound values
$queryValues = [];
// Get Host status
$rq1 = 'SELECT SQL_CALC_FOUND_ROWS DISTINCT
1 AS REALTIME, h.name AS host_name, hg.name AS hgname, hgm.hostgroup_id, h.host_id, h.state, h.icon_image
FROM hostgroups hg, hosts_hostgroups hgm, hosts h ';
if (! $obj->is_admin) {
$rq1 .= ', centreon_acl ';
}
$rq1 .= 'WHERE h.host_id = hgm.host_id '
. 'AND hgm.hostgroup_id = hg.hostgroup_id '
. "AND h.enabled = '1' "
. "AND h.name NOT LIKE '\_Module\_%' ";
if (! $obj->is_admin) {
$rq1 .= $obj->access->queryBuilder('AND', 'h.host_id', 'centreon_acl.host_id') . ' '
. $obj->access->queryBuilder('AND', 'group_id', $grouplistStr) . ' '
. $obj->access->queryBuilder('AND', 'hg.hostgroup_id', $obj->access->getHostGroupsString('ID'));
}
if ($instance !== -1) {
$rq1 .= ' AND h.instance_id = :instance ';
$queryValues['instance'] = [
PDO::PARAM_INT => (int) $instance,
];
}
if (str_ends_with($o, '_pb')) {
$rq1 .= ' AND h.host_id IN ( '
. 'SELECT s.host_id FROM services s '
. 'WHERE s.state != 0 AND s.state != 4 AND s.enabled = 1) ';
} elseif (str_ends_with($o, '_ack_0')) {
$rq1 .= ' AND h.host_id IN ( '
. 'SELECT s.host_id FROM services s '
. 'WHERE s.acknowledged = 0 AND s.state != 0 AND s.state != 4 AND s.enabled = 1) ';
} elseif (str_ends_with($o, '_ack_1')) {
$rq1 .= ' AND h.host_id IN ( '
. 'SELECT s.host_id FROM services s '
. 'WHERE s.acknowledged = 1 AND s.state != 0 AND s.state != 4 AND s.enabled = 1) ';
}
if ($search != '') {
$rq1 .= ' AND h.name LIKE :search';
$queryValues['search'] = [
PDO::PARAM_STR => '%' . $search . '%',
];
}
if ($hostgroup != '') {
$rq1 .= ' AND hg.name LIKE :hgName';
$queryValues['hgName'] = [
PDO::PARAM_STR => $hostgroup,
];
}
$rq1 .= ' AND h.enabled = 1 ORDER BY :sort_type, host_name ';
($order != 'ASC') ? $rq1 .= 'DESC' : $rq1 .= 'ASC';
$rq1 .= ' LIMIT :numLimit, :limit';
$queryValues['sort_type'] = [
PDO::PARAM_STR => $sort_type,
];
$queryValues['numLimit'] = [
PDO::PARAM_INT => (int) ($num * $limit),
];
$queryValues['limit'] = [
PDO::PARAM_INT => (int) $limit,
];
$dbResult = $obj->DBC->prepare($rq1);
foreach ($queryValues as $bindId => $bindData) {
foreach ($bindData as $bindType => $bindValue) {
$dbResult->bindValue($bindId, $bindValue, $bindType);
}
}
$dbResult->execute();
$numRows = $obj->DBC->query('SELECT FOUND_ROWS() AS REALTIME')->fetchColumn();
$class = 'list_one';
$ct = 0;
$tab_final = [];
$tabHGUrl = [];
$obj->XML = new CentreonXML();
$obj->XML->startElement('reponse');
$obj->XML->startElement('i');
$obj->XML->writeElement('numrows', $numRows);
$obj->XML->writeElement('num', $num);
$obj->XML->writeElement('limit', $limit);
$obj->XML->writeElement('p', $p);
$obj->XML->writeElement('s', '1');
$obj->XML->endElement();
while ($ndo = $dbResult->fetch()) {
if (! isset($tab_final[$ndo['hgname']])) {
$tab_final[$ndo['hgname']] = [];
}
if (! isset($tab_final[$ndo['hgname']][$ndo['host_name']])) {
$tab_final[$ndo['hgname']][$ndo['host_name']] = ['0' => 0, '1' => 0, '2' => 0, '3' => 0, '4' => 0];
}
if (str_contains('svcSumHG_', $o)) {
$tab_final[$ndo['hgname']][$ndo['host_name']][0]
= $obj->monObj->getServiceStatusCount($ndo['host_name'], $obj, $o, CentreonMonitoring::SERVICE_STATUS_OK);
}
$tab_final[$ndo['hgname']][$ndo['host_name']][1]
= 0 + $obj->monObj->getServiceStatusCount($ndo['host_name'], $obj, $o, CentreonMonitoring::SERVICE_STATUS_WARNING);
$tab_final[$ndo['hgname']][$ndo['host_name']][2]
= 0 + $obj->monObj->getServiceStatusCount($ndo['host_name'], $obj, $o, CentreonMonitoring::SERVICE_STATUS_CRITICAL);
$tab_final[$ndo['hgname']][$ndo['host_name']][3]
= 0 + $obj->monObj->getServiceStatusCount($ndo['host_name'], $obj, $o, CentreonMonitoring::SERVICE_STATUS_UNKNOWN);
$tab_final[$ndo['hgname']][$ndo['host_name']][4]
= 0 + $obj->monObj->getServiceStatusCount($ndo['host_name'], $obj, $o, CentreonMonitoring::SERVICE_STATUS_PENDING);
$tab_final[$ndo['hgname']][$ndo['host_name']]['cs'] = $ndo['state'];
$tab_final[$ndo['hgname']][$ndo['host_name']]['hid'] = $ndo['host_id'];
$tab_final[$ndo['hgname']][$ndo['host_name']]['icon'] = $ndo['icon_image'];
}
$dbResult->closeCursor();
$buildParameter = function (string $id, string $name) {
return [
'id' => $id,
'name' => $name,
];
};
$buildServicesUri = function (string $hostname, array $statuses) use ($resourceController, $buildParameter) {
return $resourceController->buildListingUri([
'filter' => json_encode([
'criterias' => [
'search' => 'h.name:^' . $hostname . '$',
'resourceTypes' => [$buildParameter('service', 'Service')],
'statuses' => $statuses,
],
]),
]);
};
$okStatus = $buildParameter('OK', 'Ok');
$warningStatus = $buildParameter('WARNING', 'Warning');
$criticalStatus = $buildParameter('CRITICAL', 'Critical');
$unknownStatus = $buildParameter('UNKNOWN', 'Unknown');
$pendingStatus = $buildParameter('PENDING', 'Pending');
$hg = '';
$count = 0;
if (isset($tab_final)) {
foreach ($tab_final as $hg_name => $tab_host) {
foreach ($tab_host as $host_name => $tab) {
if (isset($hg_name) && $hg != $hg_name) {
if ($hg != '') {
$obj->XML->endElement();
}
$hg = $hg_name;
$obj->XML->startElement('hg');
$obj->XML->writeElement('hgn', CentreonUtils::escapeSecure($hg_name));
}
$obj->XML->startElement('l');
$obj->XML->writeAttribute('class', $obj->getNextLineClass());
$obj->XML->writeElement('sc', $tab[2]);
$obj->XML->writeElement('scc', $obj->colorService[2]);
$obj->XML->writeElement('sw', $tab[1]);
$obj->XML->writeElement('swc', $obj->colorService[1]);
$obj->XML->writeElement('su', $tab[3]);
$obj->XML->writeElement('suc', $obj->colorService[3]);
$obj->XML->writeElement('sk', $tab[0]);
$obj->XML->writeElement('skc', $obj->colorService[0]);
$obj->XML->writeElement('sp', $tab[4]);
$obj->XML->writeElement('spc', $obj->colorService[4]);
$obj->XML->writeElement('o', $ct++);
$obj->XML->writeElement('hn', CentreonUtils::escapeSecure($host_name), false);
if (isset($tab['icon']) && $tab['icon']) {
$obj->XML->writeElement('hico', $tab['icon']);
} else {
$obj->XML->writeElement('hico', 'none');
}
$obj->XML->writeElement('hnl', CentreonUtils::escapeSecure(urlencode($host_name)));
$obj->XML->writeElement('hid', $tab['hid']);
$obj->XML->writeElement('hcount', $count);
$obj->XML->writeElement('hs', $obj->statusHost[$tab['cs']]);
$obj->XML->writeElement('hc', $obj->colorHost[$tab['cs']]);
$obj->XML->writeElement(
'h_details_uri',
$useDeprecatedPages
? 'main.php?p=20202&o=hd&host_name=' . $host_name
: $resourceController->buildHostDetailsUri($tab['hid'])
);
$serviceListingDeprecatedUri = 'main.php?p=20201&o=svc&host_search=' . $host_name;
$obj->XML->writeElement(
's_listing_uri',
$useDeprecatedPages
? $serviceListingDeprecatedUri . '&statusFilter='
: $resourceController->buildListingUri([
'filter' => json_encode([
'criterias' => [
'search' => 'h.name:^' . $host_name . '$',
],
]),
])
);
$obj->XML->writeElement(
's_listing_ok',
$useDeprecatedPages
? $serviceListingDeprecatedUri . '&statusFilter=ok'
: $buildServicesUri($host_name, [$okStatus])
);
$obj->XML->writeElement(
's_listing_warning',
$useDeprecatedPages
? $serviceListingDeprecatedUri . '&statusFilter=warning'
: $buildServicesUri($host_name, [$warningStatus])
);
$obj->XML->writeElement(
's_listing_critical',
$useDeprecatedPages
? $serviceListingDeprecatedUri . '&statusFilter=critical'
: $buildServicesUri($host_name, [$criticalStatus])
);
$obj->XML->writeElement(
's_listing_unknown',
$useDeprecatedPages
? $serviceListingDeprecatedUri . '&statusFilter=unknown'
: $buildServicesUri($host_name, [$unknownStatus])
);
$obj->XML->writeElement(
's_listing_pending',
$useDeprecatedPages
? $serviceListingDeprecatedUri . '&statusFilter=pending'
: $buildServicesUri($host_name, [$pendingStatus])
);
$obj->XML->writeElement('chartIcon', returnSvg('www/img/icons/chart.svg', 'var(--icons-fill-color)', 18, 18));
$obj->XML->writeElement('viewIcon', returnSvg('www/img/icons/view.svg', 'var(--icons-fill-color)', 18, 18));
$obj->XML->endElement();
$count++;
}
}
}
if (! $ct) {
$obj->XML->writeElement('infos', 'none');
}
$obj->XML->endElement();
// Send Header
$obj->header();
// Send XML
$obj->XML->output();
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/status/ServicesHostGroups/xml/serviceGridByHGXML.php | centreon/www/include/monitoring/status/ServicesHostGroups/xml/serviceGridByHGXML.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__ . '/../../../../../../bootstrap.php');
include_once _CENTREON_PATH_ . 'www/class/centreonUtils.class.php';
include_once _CENTREON_PATH_ . 'www/class/centreonXMLBGRequest.class.php';
include_once _CENTREON_PATH_ . 'www/include/monitoring/status/Common/common-Func.php';
include_once _CENTREON_PATH_ . 'www/include/common/common-Func.php';
include_once _CENTREON_PATH_ . 'www/class/centreonService.class.php';
// Create XML Request Objects
CentreonSession::start(1);
$obj = new CentreonXMLBGRequest($dependencyInjector, session_id(), 1, 1, 0, 1);
if (! isset($obj->session_id) || ! CentreonSession::checkSession($obj->session_id, $obj->DB)) {
echo 'Bad Session ID';
exit();
}
$statusService ??= null;
$statusFilter ??= null;
// Store in session the last type of call
$_SESSION['monitoring_serviceByHg_status'] = $statusService;
$_SESSION['monitoring_serviceByHg_status_filter'] = $statusFilter;
// Set Default Poller
$obj->getDefaultFilters();
/**
* @var Centreon $centreon
*/
$centreon = $_SESSION['centreon'];
/**
* true: URIs will correspond to deprecated pages
* false: URIs will correspond to new page (Resource Status)
*/
$useDeprecatedPages = $centreon->user->doesShowDeprecatedPages();
// Check Arguments From GET request
$o = isset($_GET['o']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_GET['o']) : 'svcOVSG_pb';
$p = filter_input(INPUT_GET, 'p', FILTER_VALIDATE_INT, ['options' => ['default' => 2]]);
$num = filter_input(INPUT_GET, 'num', FILTER_VALIDATE_INT, ['options' => ['default' => 0]]);
$limit = filter_input(INPUT_GET, 'limit', FILTER_VALIDATE_INT, ['options' => ['default' => 30]]);
// if instance value is not set, displaying all active pollers' linked resources
$instance = filter_var($obj->defaultPoller ?? -1, FILTER_VALIDATE_INT);
$hostgroup = isset($_GET['hg_search']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_GET['hg_search']) : '';
$search = isset($_GET['search']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_GET['search']) : '';
$sort_type = isset($_GET['sort_type']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_GET['sort_type']) : 'host_name';
$order = isset($_GET['order']) && $_GET['order'] === 'DESC' ? 'DESC' : 'ASC';
$grouplistStr = $obj->access->getAccessGroupsString();
$kernel = App\Kernel::createForWeb();
$resourceController = $kernel->getContainer()->get(
Centreon\Application\Controller\MonitoringResourceController::class
);
// saving bound values
$queryValues = [];
$filterRq2 = '';
// Get Host status
$rq1 = <<<'SQL_WRAP'
SELECT SQL_CALC_FOUND_ROWS DISTINCT
1 AS REALTIME, hg.name AS alias, h.host_id id, h.name AS host_name, hgm.hostgroup_id, h.state hs, h.icon_image
FROM hosts h
INNER JOIN hosts_hostgroups hgm
ON hgm.host_id = h.host_id
INNER JOIN hostgroups hg
ON hg.hostgroup_id = hgm.hostgroup_id
SQL_WRAP;
if (! $obj->is_admin) {
$rq1 .= <<<SQL
INNER JOIN centreon_acl
ON centreon_acl.host_id = h.host_id
AND centreon_acl.group_id IN ({$grouplistStr})
AND hg.name IN ({$obj->access->getHostGroupsString('NAME')})
SQL;
}
$rq1 .= <<<SQL
WHERE h.enabled = '1'
AND h.name NOT LIKE '\_Module\_%'
SQL;
if ($instance !== -1) {
$rq1 .= ' AND h.instance_id = :instance ';
$queryValues['instance'] = [PDO::PARAM_INT => (int) $instance];
}
if (str_ends_with($o, '_pb')) {
$rq1 .= <<<'SQL'
AND h.host_id IN (
SELECT s.host_id
FROM services s
WHERE s.state != 0 AND s.state != 4 AND s.enabled = 1
)
SQL;
$filterRq2 = ' AND s.state != 0 AND s.state != 4';
} elseif (str_ends_with($o, '_ack_0')) {
$rq1 .= <<<'SQL'
AND h.host_id IN (
SELECT s.host_id
FROM services s
WHERE s.acknowledged = 0 AND s.state != 0 AND s.state != 4 AND s.enabled = 1
)
SQL;
$filterRq2 = ' AND s.state != 0 AND s.state != 4 AND s.acknowledged = 0';
} elseif (str_ends_with($o, '_ack_1')) {
$rq1 .= <<<'SQL'
AND h.host_id IN (
SELECT s.host_id
FROM services s
WHERE s.acknowledged = 1 AND s.state != 0 AND s.state != 4 AND s.enabled = 1
)
SQL;
$filterRq2 = ' AND s.acknowledged = 1';
}
if ($search != '') {
$rq1 .= ' AND h.name LIKE :search';
$queryValues['search'] = [PDO::PARAM_STR => '%' . $search . '%'];
}
if ($hostgroup !== '') {
$rq1 .= ' AND hg.name LIKE :hgName';
$queryValues['hgName'] = [PDO::PARAM_STR => $hostgroup];
}
$rq1 .= ' AND h.enabled = 1 ORDER BY :sort_type, host_name ' . $order;
$rq1 .= ' LIMIT :numLimit, :limit';
$queryValues['sort_type'] = [PDO::PARAM_STR => $sort_type];
$queryValues['numLimit'] = [PDO::PARAM_INT => (int) ($num * $limit)];
$queryValues['limit'] = [PDO::PARAM_INT => (int) $limit];
$dbResult = $obj->DBC->prepare($rq1);
foreach ($queryValues as $bindId => $bindData) {
foreach ($bindData as $bindType => $bindValue) {
$dbResult->bindValue($bindId, $bindValue, $bindType);
}
}
$dbResult->execute();
$tabH = [];
$tabHG = [];
$tab_finalH = [];
$numRows = $obj->DBC->query('SELECT FOUND_ROWS() AS REALTIME')->fetchColumn();
while ($ndo = $dbResult->fetch()) {
if (! isset($tab_finalH[$ndo['alias']])) {
$tab_finalH[$ndo['alias']] = [$ndo['host_name'] => []];
}
$tab_finalH[$ndo['alias']][$ndo['host_name']]['cs'] = $ndo['hs'];
$tab_finalH[$ndo['alias']][$ndo['host_name']]['icon'] = $ndo['icon_image'];
$tab_finalH[$ndo['alias']][$ndo['host_name']]['tab_svc'] = [];
$tabH[$ndo['host_name']] = $ndo['id'];
$tabHG[$ndo['alias']] = $ndo['hostgroup_id'];
}
$dbResult->closeCursor();
// Resetting $queryValues
$queryValues = [];
// Get Services status
$rq2 = <<<'SQL'
SELECT DISTINCT 1 AS REALTIME, s.service_id, h.name as host_name, s.description, s.state svcs,
(CASE s.state WHEN 0 THEN 3 WHEN 2 THEN 0 WHEN 3 THEN 2 ELSE s.state END) AS tri
FROM services s
INNER JOIN hosts h
ON h.host_id = s.host_id
SQL;
if (! $obj->is_admin) {
$rq2 .= <<<SQL
INNER JOIN centreon_acl
ON centreon_acl.host_id = h.host_id
AND centreon_acl.service_id = s.service_id
AND centreon_acl.group_id IN ({$grouplistStr})
SQL;
}
$rq2 .= <<<SQL
WHERE h.name NOT LIKE '\_Module\_%'
AND h.enabled = '1'
AND s.enabled = '1'
{$filterRq2}
SQL;
if ($search != '') {
$rq2 .= ' AND h.name LIKE :search';
$queryValues[':search'] = [PDO::PARAM_STR => '%' . $search . '%'];
}
if ($instance != -1) {
$rq2 .= ' AND h.instance_id = :instance ';
$queryValues[':instance'] = [PDO::PARAM_INT => $instance];
}
$rq2 .= ' ORDER BY tri ASC, s.description ASC';
$tabService = [];
$tabHost = [];
$dbResult = $obj->DBC->prepare($rq2);
foreach ($queryValues as $bindId => $bindData) {
foreach ($bindData as $bindType => $bindValue) {
$dbResult->bindValue($bindId, $bindValue, $bindType);
}
}
$dbResult->execute();
while ($ndo = $dbResult->fetch()) {
if (! isset($tabService[$ndo['host_name']])) {
$tabService[$ndo['host_name']] = [];
}
if (! isset($tabService[$ndo['host_name']])) {
$tabService[$ndo['host_name']] = ['tab_svc' => []];
}
$tabService[$ndo['host_name']]['tab_svc'][$ndo['description']]['service_name'] = $ndo['svcs'];
$tabService[$ndo['host_name']]['tab_svc'][$ndo['description']]['service_id'] = $ndo['service_id'];
$tabHost[$ndo['host_name']] = $ndo['service_id'];
}
$dbResult->closeCursor();
// Begin XML Generation
$obj->XML = new CentreonXML();
$obj->XML->startElement('reponse');
$obj->XML->startElement('i');
$obj->XML->writeElement('numrows', $numRows);
$obj->XML->writeElement('num', $num);
$obj->XML->writeElement('limit', $limit);
$obj->XML->writeElement('host_name', _('Hosts'), 0);
$obj->XML->writeElement('services', _('Services'), 0);
$obj->XML->writeElement('p', $p);
$obj->XML->writeElement('s', '1');
$obj->XML->endElement();
$ct = 0;
$hg = '';
$count = 0;
if (isset($tab_finalH)) {
foreach ($tab_finalH as $hg_name => $tab_host) {
foreach ($tab_host as $host_name => $tab) {
if (isset($tabService[$host_name]['tab_svc']) && count($tabService[$host_name]['tab_svc'])) {
if (isset($hg_name) && $hg != $hg_name) {
if ($hg != '') {
$obj->XML->endElement();
}
$hg = $hg_name;
$obj->XML->startElement('hg');
$obj->XML->writeElement('hgn', CentreonUtils::escapeSecure($hg_name));
$obj->XML->writeElement('hgid', CentreonUtils::escapeSecure($tabHG[$hg_name]));
}
$obj->XML->startElement('l');
$obj->XML->writeAttribute('class', $obj->getNextLineClass());
if (isset($tabService[$host_name]['tab_svc'])) {
foreach ($tabService[$host_name]['tab_svc'] as $svc => $state) {
$serviceId = $state['service_id'];
$obj->XML->startElement('svc');
$obj->XML->writeElement('sn', CentreonUtils::escapeSecure($svc));
$obj->XML->writeElement('snl', CentreonUtils::escapeSecure(urlencode($svc)));
$obj->XML->writeElement('sc', $obj->colorService[$state['service_name']]);
$obj->XML->writeElement('svc_id', $serviceId);
$obj->XML->writeElement(
's_details_uri',
$useDeprecatedPages
? 'main.php?o=svcd&p=202&host_name=' . $host_name . '&service_description=' . $svc
: $resourceController->buildServiceDetailsUri($tabH[$host_name], $serviceId)
);
$obj->XML->endElement();
}
}
$obj->XML->writeElement('o', $ct);
$obj->XML->writeElement('hn', CentreonUtils::escapeSecure($host_name), false);
if (isset($tab['icon']) && $tab['icon']) {
$obj->XML->writeElement('hico', $tab['icon']);
} else {
$obj->XML->writeElement('hico', 'none');
}
$obj->XML->writeElement('hnl', CentreonUtils::escapeSecure(urlencode($host_name)));
$obj->XML->writeElement('hid', CentreonUtils::escapeSecure($tabH[$host_name]));
$obj->XML->writeElement('hs', $obj->statusHost[$tab['cs']]);
$obj->XML->writeElement('hc', $obj->colorHost[$tab['cs']]);
$obj->XML->writeElement('hcount', $count);
$obj->XML->writeElement(
'h_details_uri',
$useDeprecatedPages
? 'main.php?p=20201&o=hd&host_name=' . $host_name
: $resourceController->buildHostDetailsUri($tabH[$host_name])
);
$obj->XML->writeElement(
's_listing_uri',
$useDeprecatedPages
? 'main.php?o=svc&p=20201&statusFilter=&host_search=' . $host_name
: $resourceController->buildListingUri([
'filter' => json_encode([
'criterias' => [
'search' => 'h.name:^' . $host_name . '$',
],
]),
])
);
$obj->XML->writeElement(
'chartIcon',
returnSvg('www/img/icons/chart.svg', 'var(--icons-fill-color)', 18, 18)
);
$obj->XML->writeElement(
'viewIcon',
returnSvg('www/img/icons/view.svg', 'var(--icons-fill-color)', 18, 18)
);
$obj->XML->endElement();
$count++;
}
}
$ct++;
}
}
$obj->XML->endElement();
// Send Header
$obj->header();
// Send XML
$obj->XML->output();
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/status/ServicesServiceGroups/serviceGridBySG.php | centreon/www/include/monitoring/status/ServicesServiceGroups/serviceGridBySG.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($oreon)) {
exit();
}
include './include/common/autoNumLimit.php';
$sort_types = ! isset($_GET['sort_types']) ? 0 : $_GET['sort_types'];
$order = ! isset($_GET['order']) ? 'ASC' : $_GET['order'];
$num = ! isset($_GET['num']) ? 0 : $_GET['num'];
$search_type_host = ! isset($_GET['search_type_host']) ? 1 : $_GET['search_type_host'];
$search_type_service = ! isset($_GET['search_type_service']) ? 1 : $_GET['search_type_service'];
$sort_type = ! isset($_GET['sort_type']) ? 'host_name' : $_GET['sort_type'];
$host_search = ! isset($_GET['host_search']) ? 0 : $_GET['host_search'];
$sg_search = ! isset($_GET['sg_search']) ? 0 : $_GET['sg_search'];
// Check search value in Host search field
if (isset($_GET['host_search'])) {
$centreon->historySearch[$url] = $_GET['host_search'];
}
if (isset($_SESSION['monitoring_service_groups'])) {
$sg_search = $_SESSION['monitoring_service_groups'];
}
$aTypeAffichageLevel1 = ['svcOVSG' => _('Details'), 'svcSumSG' => _('Summary')];
$aTypeAffichageLevel2 = ['' => _('All'), 'pb' => _('Problems'), 'ack_1' => _('Acknowledge'), 'ack_0' => _('Not Acknowledged')];
$tab_class = ['0' => 'list_one', '1' => 'list_two'];
$rows = 10;
include_once $sg_path . '/serviceGridBySGJS.php';
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate($sg_path, '/templates/');
$tpl->assign('p', $p);
$tpl->assign('o', $o);
$tpl->assign('sort_types', $sort_types);
$tpl->assign('typeDisplay', _('Display'));
$tpl->assign('typeDisplay2', _('Display details'));
$tpl->assign('num', $num);
$tpl->assign('limit', $limit);
$tpl->assign('mon_host', _('Hosts'));
$tpl->assign('mon_status', _('Status'));
$tpl->assign('mon_ip', _('IP'));
$tpl->assign('mon_last_check', _('Last Check'));
$tpl->assign('mon_duration', _('Duration'));
$tpl->assign('search', _('Host'));
$tpl->assign('sgStr', _('Servicegroup'));
$tpl->assign('pollerStr', _('Poller'));
$tpl->assign('poller_listing', $oreon->user->access->checkAction('poller_listing'));
$tpl->assign('mon_status_information', _('Status information'));
// Get servicegroups list
$sgSearchSelect = '<select id="sg_search" name="sg_search"><option value=""></option>';
$servicegroups = [];
if (! $oreon->user->access->admin) {
$servicegroups = $oreon->user->access->getServiceGroups();
} else {
$query = 'SELECT DISTINCT sg.sg_name FROM servicegroup sg';
$DBRESULT = $pearDB->query($query);
while ($row = $DBRESULT->fetchRow()) {
$servicegroups[] = $row['sg_name'];
}
$DBRESULT->closeCursor();
}
foreach ($servicegroups as $servicegroup_name) {
if (isset($sg_search) && strcmp($sg_search, $servicegroup_name) == 0) {
$sgSearchSelect .= '<option value="' . $servicegroup_name . '" selected>' . $servicegroup_name . '</option>';
} else {
$sgSearchSelect .= '<option value="' . $servicegroup_name . '">' . $servicegroup_name . '</option>';
}
}
$sgSearchSelect .= '</select>';
$tpl->assign('sgSearchSelect', $sgSearchSelect);
$form = new HTML_QuickFormCustom('select_form', 'GET', '?p=' . $p);
$tpl->assign('order', strtolower($order));
$tab_order = ['sort_asc' => 'sort_desc', 'sort_desc' => 'sort_asc'];
$tpl->assign('tab_order', $tab_order);
// #Toolbar select $lang["lgd_more_actions"]
?>
<script type="text/javascript">
_tm = <?php echo $tM; ?>;
function setO(_i) {
document.forms['form'].elements['cmd'].value = _i;
document.forms['form'].elements['o1'].selectedIndex = 0;
document.forms['form'].elements['o2'].selectedIndex = 0;
}
function displayingLevel1(val) {
_o = val;
var sel2 = document.getElementById("typeDisplay2").value;
if (sel2 != '') {
_o = _o + "_" + sel2;
}
if (val == 'svcOVSG') {
_addrXML = "./include/monitoring/status/ServicesServiceGroups/xml/serviceGridBySGXML.php";
_addrXSL = "./include/monitoring/status/ServicesServiceGroups/xsl/serviceGridBySG.xsl";
} else {
_addrXML = "./include/monitoring/status/ServicesServiceGroups/xml/serviceSummaryBySGXML.php";
_addrXSL = "./include/monitoring/status/ServicesServiceGroups/xsl/serviceSummaryBySG.xsl";
}
monitoring_refresh();
}
function displayingLevel2(val) {
var sel1 = document.getElementById("typeDisplay").value;
_o = sel1;
if (val != '') {
_o = _o + "_" + val;
}
monitoring_refresh();
}
</script>
<?php
$form->addElement(
'select',
'typeDisplay',
_('Display'),
$aTypeAffichageLevel1,
['id' => 'typeDisplay', 'onChange' => 'displayingLevel1(this.value);']
);
$form->addElement(
'select',
'typeDisplay2',
_('Display '),
$aTypeAffichageLevel2,
['id' => 'typeDisplay2', 'onChange' => 'displayingLevel2(this.value);']
);
$form->setDefaults(['typeDisplay2' => 'pb']);
$tpl->assign('limit', $limit);
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl);
$form->accept($renderer);
$tpl->assign('form', $renderer->toArray());
$tpl->display('serviceGrid.ihtml');
?>
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/status/ServicesServiceGroups/serviceGridBySGJS.php | centreon/www/include/monitoring/status/ServicesServiceGroups/serviceGridBySGJS.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($centreon)) {
exit();
}
if (! isset($oreon->optGen['AjaxFirstTimeReloadStatistic']) || $oreon->optGen['AjaxFirstTimeReloadStatistic'] == 0) {
$tFS = 10;
} else {
$tFS = $oreon->optGen['AjaxFirstTimeReloadStatistic'] * 1000;
}
if (! isset($oreon->optGen['AjaxFirstTimeReloadMonitoring']) || $oreon->optGen['AjaxFirstTimeReloadMonitoring'] == 0) {
$tFM = 10;
} else {
$tFM = $oreon->optGen['AjaxFirstTimeReloadMonitoring'] * 1000;
}
$sid = session_id();
$time = time();
$obis = $o;
if (isset($_GET['problem'])) {
$obis .= '_pb';
}
if (isset($_GET['acknowledge'])) {
$obis .= '_ack_' . $_GET['acknowledge'];
}
?>
<script type="text/javascript">
var _debug = 0;
var _addrXML = "./include/monitoring/status/ServicesServiceGroups/xml/serviceGridBySGXML.php";
var _addrXSL = "./include/monitoring/status/ServicesServiceGroups/xsl/serviceGridBySG.xsl";
<?php include_once './include/monitoring/status/Common/commonJS.php'; ?>
//Service Groups view hasn't got HG filters
_hostgroup_enable = 0;
function set_header_title() {
var _img_asc = mk_imgOrder('./img/icones/7x7/sort_asc.gif', "asc");
var _img_desc = mk_imgOrder('./img/icones/7x7/sort_desc.gif', "desc");
if (document.getElementById('host_name')) {
var h = document.getElementById('host_name');
h.innerHTML = '<?php echo addslashes(_('Servicegroups / Hosts')); ?>';
h.indice = 'host_name';
h.onclick = function () {
change_type_order(this.indice)
};
h.style.cursor = "pointer";
if (document.getElementById('host_state')) {
var h = document.getElementById('host_state');
h.innerHTML = '<?php echo addslashes(_('Status')); ?>';
h.indice = 'host_state';
h.title = '<?php echo addslashes(_('Sort by Status')); ?>';
h.onclick = function () {
change_type_order(this.indice)
};
h.style.cursor = "pointer";
}
var h = document.getElementById('services');
h.innerHTML = '<?php echo addslashes(_('Services informations')); ?>';
h.indice = 'services';
var h = document.getElementById(_sort_type);
var _linkaction_asc = document.createElement("a");
if (_order == 'ASC')
_linkaction_asc.appendChild(_img_asc);
else
_linkaction_asc.appendChild(_img_desc);
_linkaction_asc.href = '#';
_linkaction_asc.onclick = function () {
change_order()
};
h.appendChild(_linkaction_asc);
}
}
function mainLoopLocal() {
_currentInputField = document.getElementById('host_search');
if (document.getElementById('host_search') && document.getElementById('host_search').value) {
_currentInputFieldValue = document.getElementById('host_search').value;
} else {
_currentInputFieldValue = "";
}
if ((_currentInputFieldValue.length >= 3 || _currentInputFieldValue.length == 0) &&
_oldInputFieldValue != _currentInputFieldValue
) {
if (!_lock) {
set_search_host(escapeURI(_currentInputFieldValue));
_host_search = _currentInputFieldValue;
monitoring_refresh();
if (_currentInputFieldValue.length >= 3) {
_currentInputField.className = "search_input_active";
} else {
_currentInputField.className = "search_input";
}
}
}
_oldInputFieldValue = _currentInputFieldValue;
setTimeout(mainLoopLocal, 250);
}
function initM(_time_reload, _o) {
// INIT Select objects
construct_selecteList_ndo_instance('instance_selected');
if (document.getElementById("host_search") && document.getElementById("host_search").value) {
_host_search = document.getElementById("host_search").value;
viewDebugInfo('search: ' + document.getElementById("host_search").value);
} else if (document.getElementById("host_search").length == 0) {
_host_search = "";
}
if (document.getElementById("sg_search") && document.getElementById("sg_search").value) {
_sg_search = document.getElementById("sg_search").value;
viewDebugInfo('search: ' + document.getElementById("sg_search").value);
} else if (document.getElementById("sg_search").value.length === 0) {
_sg_search = "";
}
if (_first) {
mainLoopLocal();
_first = 0;
}
_time =<?php echo $time; ?>;
if (_on) {
goM(_time_reload, _o);
}
}
function goM(_time_reload, _o) {
_lock = 1;
var proc = new Transformation();
proc.setCallback(function(t){monitoringCallBack(t); proc = null;});
proc.setXml(
_addrXML + "?" + '&host_search=' + _host_search + '&sg_search=' + _sg_search + '&num=' + _num +
'&limit=' + _limit + '&sort_type=' + _sort_type + '&order=' + _order +
'&date_time_format_status=' + _date_time_format_status + '&o=' + _o +
'&p=' + _p + '&time=<?php echo time(); ?>'
);
proc.setXslt(_addrXSL);
if (handleVisibilityChange()) {
proc.transform("forAjax");
}
if (_counter == 0) {
document.getElementById("host_search").value = _host_search;
document.getElementById("sg_search").value = _sg_search;
_counter += 1;
}
_lock = 0;
_timeoutID = cycleVisibilityChange(function(){goM(_time_reload, _o)}, _time_reload);
_time_live = _time_reload;
_on = 1;
set_header_title();
}
</SCRIPT>
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/status/ServicesServiceGroups/serviceSummaryBySGJS.php | centreon/www/include/monitoring/status/ServicesServiceGroups/serviceSummaryBySGJS.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($centreon)) {
exit();
}
if (! isset($oreon->optGen['AjaxFirstTimeReloadStatistic']) || $oreon->optGen['AjaxFirstTimeReloadStatistic'] == 0) {
$tFS = 10;
} else {
$tFS = $oreon->optGen['AjaxFirstTimeReloadStatistic'] * 1000;
}
if (! isset($oreon->optGen['AjaxFirstTimeReloadMonitoring']) || $oreon->optGen['AjaxFirstTimeReloadMonitoring'] == 0) {
$tFM = 10;
} else {
$tFM = $oreon->optGen['AjaxFirstTimeReloadMonitoring'] * 1000;
}
$sid = session_id();
$time = time();
$obis = $o;
if (isset($_GET['problem'])) {
$obis .= '_pb';
}
if (isset($_GET['acknowledge'])) {
$obis .= '_ack_' . $_GET['acknowledge'];
}
?>
<script type="text/javascript">
var _debug = 0;
var _addrXML = "./include/monitoring/status/ServicesServiceGroups/xml/serviceSummaryBySGXML.php";
var _addrXSL = "./include/monitoring/status/ServicesServiceGroups/xsl/serviceSummaryBySG.xsl";
<?php include_once './include/monitoring/status/Common/commonJS.php'; ?>
// Service Groups view hasn't got HG filters
_hostgroup_enable = 0;
function set_header_title() {
var _img_asc = mk_imgOrder('./img/icones/7x7/sort_asc.gif', "asc");
var _img_desc = mk_imgOrder('./img/icones/7x7/sort_desc.gif', "desc");
if (document.getElementById('host_name')) {
var h = document.getElementById('host_name');
h.innerHTML = '<?php echo addslashes(_('Servicegroups / Hosts')); ?>';
h.indice = 'host_name';
h.onclick = function () {
change_type_order(this.indice)
};
h.style.cursor = "pointer";
var h = document.getElementById('services');
h.innerHTML = '<?php echo addslashes(_('Services informations')); ?>';
h.indice = 'services';
var h = document.getElementById(_sort_type);
var _linkaction_asc = document.createElement("a");
if (_order == 'ASC')
_linkaction_asc.appendChild(_img_asc);
else
_linkaction_asc.appendChild(_img_desc);
_linkaction_asc.href = '#';
_linkaction_asc.onclick = function () {
change_order()
};
h.appendChild(_linkaction_asc);
}
}
function mainLoopLocal() {
_currentInputField = document.getElementById('host_search');
if (document.getElementById('host_search') && document.getElementById('host_search').value) {
_currentInputFieldValue = document.getElementById('host_search').value;
} else {
_currentInputFieldValue = "";
}
if ((_currentInputFieldValue.length >= 3 || _currentInputFieldValue.length == 0) &&
_oldInputFieldValue != _currentInputFieldValue
) {
if (!_lock) {
set_search_host(escapeURI(_currentInputFieldValue));
_host_search = _currentInputFieldValue;
_sg_search = _currentInputFieldValue;
monitoring_refresh();
if (_currentInputFieldValue.length >= 3) {
_currentInputField.className = "search_input_active";
} else {
_currentInputField.className = "search_input";
}
}
}
_oldInputFieldValue = _currentInputFieldValue;
setTimeout(mainLoopLocal, 250);
}
function initM(_time_reload, _o) {
// INIT Select objects
construct_selecteList_ndo_instance('instance_selected');
construct_HostGroupSelectList('hostgroups_selected');
if (document.getElementById("host_search") && document.getElementById("host_search").value) {
_host_search = document.getElementById("host_search").value;
viewDebugInfo('search: ' + document.getElementById("host_search").value);
} else if (document.getElementById("host_search").value.length === 0) {
_host_search = "";
}
if (document.getElementById("sg_search") && document.getElementById("sg_search").value) {
_sg_search = document.getElementById("sg_search").value;
viewDebugInfo('search: ' + document.getElementById("sg_search").value);
} else if (document.getElementById("sg_search").value.length == 0) {
_sg_search = "";
}
if (_first) {
mainLoopLocal();
_first = 0;
}
_time =<?php echo $time; ?>;
if (_on) {
goM(_time_reload, _o);
}
}
function goM(_time_reload, _o) {
_lock = 1;
var proc = new Transformation();
proc.setCallback(function(t){monitoringCallBack(t); proc = null;});
proc.setXml(_addrXML + "?" + '&host_search=' + _host_search + '&sg_search=' + _sg_search + '&num=' + _num +
'&limit=' + _limit + '&sort_type=' + _sort_type + '&order=' + _order +
'&date_time_format_status=' + _date_time_format_status + '&o=' + _o +
'&p=' + _p + '&time=<?php echo time(); ?>'
);
proc.setXslt(_addrXSL);
if (handleVisibilityChange()) {
proc.transform("forAjax");
}
if (_counter == 0) {
document.getElementById("host_search").value = _host_search;
document.getElementById("sg_search").value = _sg_search;
_counter += 1;
}
_lock = 0;
_timeoutID = cycleVisibilityChange(function(){goM(_time_reload, _o)}, _time_reload);
_time_live = _time_reload;
_on = 1;
set_header_title();
}
</SCRIPT>
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/status/ServicesServiceGroups/serviceSummaryBySG.php | centreon/www/include/monitoring/status/ServicesServiceGroups/serviceSummaryBySG.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($oreon)) {
exit();
}
include './include/common/autoNumLimit.php';
$sort_types = ! isset($_GET['sort_types']) ? 0 : $_GET['sort_types'];
$order = ! isset($_GET['order']) ? 'ASC' : $_GET['order'];
$num = ! isset($_GET['num']) ? 0 : $_GET['num'];
$search_type_host = ! isset($_GET['search_type_host']) ? 1 : $_GET['search_type_host'];
$search_type_service = ! isset($_GET['search_type_service']) ? 1 : $_GET['search_type_service'];
$sort_type = ! isset($_GET['sort_type']) ? 'host_name' : $_GET['sort_type'];
$host_search = ! isset($_GET['host_search']) ? 0 : $_GET['host_search'];
$sg_search = ! isset($_GET['sg_search']) ? 0 : $_GET['sg_search'];
// Check search value in Host search field
if (isset($_GET['host_search'])) {
$centreon->historySearch[$url] = $_GET['host_search'];
}
$aTypeAffichageLevel1 = ['svcOVSG' => _('Details'), 'svcSumSG' => _('Summary')];
$aTypeAffichageLevel2 = ['' => _('All'), 'pb' => _('Problems'), 'ack_1' => _('Acknowledge'), 'ack_0' => _('Not Acknowledged')];
// Check search value in Service Group search field
if (isset($_GET['sg_search'])) {
$centreon->historySearch[$url] = $_GET['sg_search'];
}
$tab_class = ['0' => 'list_one', '1' => 'list_two'];
$rows = 10;
include_once $sg_path . 'serviceSummaryBySGJS.php';
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate($sg_path, '/templates/');
$tpl->assign('p', $p);
$tpl->assign('o', $o);
$tpl->assign('sort_types', $sort_types);
$tpl->assign('num', $num);
$tpl->assign('limit', $limit);
$tpl->assign('mon_host', _('Hosts'));
$tpl->assign('mon_status', _('Status'));
$tpl->assign('typeDisplay', _('Display'));
$tpl->assign('typeDisplay2', _('Display details'));
$tpl->assign('mon_ip', _('IP'));
$tpl->assign('mon_last_check', _('Last Check'));
$tpl->assign('mon_duration', _('Duration'));
$tpl->assign('search', _('Host'));
$tpl->assign('sgStr', _('Servicegroup'));
$tpl->assign('pollerStr', _('Poller'));
$tpl->assign('poller_listing', $oreon->user->access->checkAction('poller_listing'));
$tpl->assign('mon_status_information', _('Status information'));
// Get servicegroups list
$sgSearchSelect = '<select id="sg_search" name="sg_search"><option value=""></option>';
$servicegroups = [];
if (! $oreon->user->access->admin) {
$servicegroups = $oreon->user->access->getServiceGroups();
} else {
$query = 'SELECT DISTINCT sg.sg_name FROM servicegroup sg';
$DBRESULT = $pearDB->query($query);
while ($row = $DBRESULT->fetchRow()) {
$servicegroups[] = $row['sg_name'];
}
$DBRESULT->closeCursor();
}
foreach ($servicegroups as $servicegroup_name) {
$sgSearchSelect .= '<option value="' . $servicegroup_name . '">' . $servicegroup_name . '</option>';
}
$sgSearchSelect .= '</select>';
$tpl->assign('sgSearchSelect', $sgSearchSelect);
$form = new HTML_QuickFormCustom('select_form', 'GET', '?p=' . $p);
$tpl->assign('order', strtolower($order));
$tab_order = ['sort_asc' => 'sort_desc', 'sort_desc' => 'sort_asc'];
$tpl->assign('tab_order', $tab_order);
// #Toolbar select $lang["lgd_more_actions"]
?>
<script type="text/javascript">
function setO(_i) {
document.forms['form'].elements['cmd'].value = _i;
document.forms['form'].elements['o1'].selectedIndex = 0;
document.forms['form'].elements['o2'].selectedIndex = 0;
}
function displayingLevel1(val) {
_o = val;
var sel2 = document.getElementById("typeDisplay2").value;
if (sel2 != '') {
_o = _o + "_" + sel2;
}
if (val == 'svcOVSG') {
_addrXML = "./include/monitoring/status/ServicesServiceGroups/xml/serviceGridBySGXML.php";
_addrXSL = "./include/monitoring/status/ServicesServiceGroups/xsl/serviceGridBySG.xsl";
} else {
_addrXML = "./include/monitoring/status/ServicesServiceGroups/xml/serviceSummaryBySGXML.php";
_addrXSL = "./include/monitoring/status/ServicesServiceGroups/xsl/serviceSummaryBySG.xsl";
}
monitoring_refresh();
}
function displayingLevel2(val) {
var sel1 = document.getElementById("typeDisplay").value;
_o = sel1;
if (val != '') {
_o = _o + "_" + val;
}
monitoring_refresh();
}
</script>
<?php
$attrs = ['onchange' => "javascript: setO(this.form.elements['o1'].value); submit();"];
$form->addElement(
'select',
'typeDisplay',
_('Display'),
$aTypeAffichageLevel1,
['id' => 'typeDisplay', 'onChange' => 'displayingLevel1(this.value);']
);
$form->addElement(
'select',
'typeDisplay2',
_('Display '),
$aTypeAffichageLevel2,
['id' => 'typeDisplay2', 'onChange' => 'displayingLevel2(this.value);']
);
$form->addElement('select', 'o1', null, [null => _('More actions...'), '3' => _('Verification Check'), '4' => _('Verification Check (Forced)'), '70' => _('Services : Acknowledge'), '71' => _('Services : Disacknowledge'), '80' => _('Services : Enable Notification'), '81' => _('Services : Disable Notification'), '90' => _('Services : Enable Check'), '91' => _('Services : Disable Check'), '72' => _('Hosts : Acknowledge'), '73' => _('Hosts : Disacknowledge'), '82' => _('Hosts : Enable Notification'), '83' => _('Hosts : Disable Notification'), '92' => _('Hosts : Enable Check'), '93' => _('Hosts : Disable Check')], $attrs);
$form->setDefaults(['o1' => null]);
$o1 = $form->getElement('o1');
$o1->setValue(null);
$attrs = ['onchange' => "javascript: setO(this.form.elements['o2'].value); submit();"];
$form->addElement('select', 'o2', null, [null => _('More actions...'), '3' => _('Verification Check'), '4' => _('Verification Check (Forced)'), '70' => _('Services : Acknowledge'), '71' => _('Services : Disacknowledge'), '80' => _('Services : Enable Notification'), '81' => _('Services : Disable Notification'), '90' => _('Services : Enable Check'), '91' => _('Services : Disable Check'), '72' => _('Hosts : Acknowledge'), '73' => _('Hosts : Disacknowledge'), '82' => _('Hosts : Enable Notification'), '83' => _('Hosts : Disable Notification'), '92' => _('Hosts : Enable Check'), '93' => _('Hosts : Disable Check')], $attrs);
$form->setDefaults(['o2' => null]);
$o2 = $form->getElement('o2');
$o2->setValue(null);
$o2->setSelected(null);
$tpl->assign('limit', $limit);
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl);
$form->accept($renderer);
$tpl->assign('form', $renderer->toArray());
$tpl->display('serviceGrid.ihtml');
?>
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/status/ServicesServiceGroups/xml/serviceGridBySGXML.php | centreon/www/include/monitoring/status/ServicesServiceGroups/xml/serviceGridBySGXML.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
*
*/
ini_set('display_errors', 'Off');
require_once realpath(__DIR__ . '/../../../../../../bootstrap.php');
include_once _CENTREON_PATH_ . 'www/class/centreonUtils.class.php';
include_once _CENTREON_PATH_ . 'www/class/centreonXMLBGRequest.class.php';
include_once _CENTREON_PATH_ . 'www/include/monitoring/status/Common/common-Func.php';
include_once _CENTREON_PATH_ . 'www/include/common/common-Func.php';
include_once _CENTREON_PATH_ . 'www/class/centreonService.class.php';
// Create XML Request Objects
CentreonSession::start();
$obj = new CentreonXMLBGRequest($dependencyInjector, session_id(), 1, 1, 0, 1);
$svcObj = new CentreonService($obj->DB);
if (! isset($obj->session_id) || ! CentreonSession::checkSession($obj->session_id, $obj->DB)) {
echo 'Bad Session ID';
exit();
}
// Set Default Poller
$obj->getDefaultFilters();
/**
* @var Centreon $centreon
*/
$centreon = $_SESSION['centreon'];
/**
* true: URIs will correspond to deprecated pages
* false: URIs will correspond to new page (Resource Status)
*/
$useDeprecatedPages = $centreon->user->doesShowDeprecatedPages();
// Check Arguments From GET tab
$o = isset($_GET['o']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_GET['o']) : 'h';
$p = filter_input(INPUT_GET, 'p', FILTER_VALIDATE_INT, ['options' => ['default' => 2]]);
$num = filter_input(INPUT_GET, 'num', FILTER_VALIDATE_INT, ['options' => ['default' => 0]]);
$limit = filter_input(INPUT_GET, 'limit', FILTER_VALIDATE_INT, ['options' => ['default' => 20]]);
// if instance value is not set, displaying all active pollers linked resources
$instance = filter_var($obj->defaultPoller ?? -1, FILTER_VALIDATE_INT);
$hSearch = isset($_GET['host_search']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_GET['host_search']) : '';
$sgSearch = isset($_GET['sg_search']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_GET['sg_search']) : '';
$sort_type = isset($_GET['sort_type']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_GET['sort_type']) : 'host_name';
$order = isset($_GET['order']) && $_GET['order'] === 'DESC' ? 'DESC' : 'ASC';
$kernel = App\Kernel::createForWeb();
$resourceController = $kernel->getContainer()->get(
Centreon\Application\Controller\MonitoringResourceController::class
);
// saving bound values
$queryValues = [];
$queryValues2 = [];
// Backup poller selection
$obj->setInstanceHistory($instance);
$_SESSION['monitoring_service_groups'] = $sgSearch;
// Filter on state
$s_search = '';
// Display service problems
if ($o == 'svcgridSG_pb' || $o == 'svcOVSG_pb') {
$s_search .= ' AND s.state != 0 AND s.state != 4 ';
}
// Display acknowledged services
if ($o == 'svcgridSG_ack_1' || $o == 'svcOVSG_ack_1') {
$s_search .= " AND s.acknowledged = '1' ";
}
// Display not acknowledged services
if ($o == 'svcgridSG_ack_0' || $o == 'svcOVSG_ack_0') {
$s_search .= ' AND s.state != 0 AND s.state != 4 AND s.acknowledged = 0 ';
}
// this query allows to manage pagination
$query = 'SELECT SQL_CALC_FOUND_ROWS DISTINCT 1 AS REALTIME, sg.servicegroup_id, h.host_id
FROM servicegroups sg, services_servicegroups sgm, hosts h, services s ';
if (! $obj->is_admin) {
$query .= ', centreon_acl ';
}
$query .= 'WHERE sgm.servicegroup_id = sg.servicegroup_id
AND sgm.host_id = h.host_id
AND h.host_id = s.host_id
AND sgm.service_id = s.service_id ';
// filter elements with acl (host, service, servicegroup)
if (! $obj->is_admin) {
$query .= $obj->access->queryBuilder('AND', 'h.host_id', 'centreon_acl.host_id')
. $obj->access->queryBuilder('AND', 'h.host_id', 'centreon_acl.host_id')
. $obj->access->queryBuilder('AND', 's.service_id', 'centreon_acl.service_id')
. $obj->access->queryBuilder('AND', 'group_id', $obj->access->getAccessGroupsString()) . ' '
. $obj->access->queryBuilder('AND', 'sg.servicegroup_id', $obj->access->getServiceGroupsString('ID')) . ' ';
}
// Servicegroup search
if ($sgSearch != '') {
$query .= ' AND sg.name = :sgSearch ';
$queryValues['sgSearch'] = [
PDO::PARAM_STR => $sgSearch,
];
}
// Host search
$h_search = '';
if ($hSearch != '') {
$h_search .= ' AND h.name LIKE :hSearch ';
// as this partial request is used in two queries, we need to bound it two times using two arrays
// to avoid incoherent number of bound variables in the second query
$queryValues['hSearch'] = $queryValues2['hSearch'] = [
PDO::PARAM_STR => '%' . $hSearch . '%',
];
}
$query .= $h_search . $s_search;
// Poller search
if ($instance != -1) {
$query .= ' AND h.instance_id = :instance ';
$queryValues['instance'] = [
PDO::PARAM_INT => $instance,
];
}
$query .= ' ORDER BY sg.name ' . $order . ' LIMIT :numLimit, :limit';
$queryValues['numLimit'] = [
PDO::PARAM_INT => (int) ($num * $limit),
];
$queryValues['limit'] = [
PDO::PARAM_INT => (int) $limit,
];
$dbResult = $obj->DBC->prepare($query);
foreach ($queryValues as $bindId => $bindData) {
foreach ($bindData as $bindType => $bindValue) {
$dbResult->bindValue($bindId, $bindValue, $bindType);
}
}
$dbResult->execute();
$numRows = $obj->DBC->query('SELECT FOUND_ROWS() AS REALTIME')->fetchColumn();
// Create XML Flow
$obj->XML = new CentreonXML();
$obj->XML->startElement('reponse');
$obj->XML->startElement('i');
$obj->XML->writeElement('numrows', $numRows);
$obj->XML->writeElement('num', $num);
$obj->XML->writeElement('limit', $limit);
$obj->XML->writeElement('host_name', _('Hosts'), 0);
$obj->XML->writeElement('services', _('Services'), 0);
$obj->XML->writeElement('p', $p);
$obj->XML->writeElement('s', '1');
$obj->XML->endElement();
// Construct query for servicegroups search
$aTab = [];
$sg_search = '';
$aTab = [];
if ($numRows > 0) {
$sg_search .= 'AND (';
$servicegroups = [];
while ($row = $dbResult->fetch()) {
$servicesgroups[$row['servicegroup_id']][] = $row['host_id'];
}
$servicegroupsSql1 = [];
foreach ($servicesgroups as $key => $value) {
$hostsSql = [];
foreach ($value as $hostId) {
$hostsSql[] = $hostId;
}
$servicegroupsSql1[] = '(sg.servicegroup_id = ' . $key
. ' AND h.host_id IN (' . implode(',', $hostsSql) . ')) ';
}
$sg_search .= implode(' OR ', $servicegroupsSql1);
$sg_search .= ') ';
if ($sgSearch != '') {
$sg_search .= 'AND sg.name = :sgSearch';
$queryValues2['sgSearch'] = [
PDO::PARAM_STR => $sgSearch,
];
}
$query2 = 'SELECT SQL_CALC_FOUND_ROWS DISTINCT 1 AS REALTIME, sg.name AS sg_name,
sg.name AS alias,
h.name AS host_name,
h.state AS host_state,
h.icon_image, h.host_id, s.state, s.description, s.service_id,
(CASE s.state WHEN 0 THEN 3 WHEN 2 THEN 0 WHEN 3 THEN 2 ELSE s.state END) AS tri
FROM servicegroups sg, services_servicegroups sgm, services s, hosts h ';
if (! $obj->is_admin) {
$query2 .= ', centreon_acl ';
}
$query2 .= 'WHERE sgm.servicegroup_id = sg.servicegroup_id
AND sgm.host_id = h.host_id
AND h.host_id = s.host_id
AND sgm.service_id = s.service_id ';
// filter elements with acl (host, service, servicegroup)
if (! $obj->is_admin) {
$query2 .= $obj->access->queryBuilder('AND', 'h.host_id', 'centreon_acl.host_id')
. $obj->access->queryBuilder('AND', 'h.host_id', 'centreon_acl.host_id')
. $obj->access->queryBuilder('AND', 's.service_id', 'centreon_acl.service_id')
. $obj->access->queryBuilder('AND', 'group_id', $obj->access->getAccessGroupsString()) . ' '
. $obj->access->queryBuilder('AND', 'sg.servicegroup_id', $obj->access->getServiceGroupsString('ID')) . ' ';
}
$query2 .= $sg_search . $h_search . $s_search . ' ORDER BY sg_name, tri ASC';
$dbResult = $obj->DBC->prepare($query2);
foreach ($queryValues2 as $bindId => $bindData) {
foreach ($bindData as $bindType => $bindValue) {
$dbResult->bindValue($bindId, $bindValue, $bindType);
}
}
$dbResult->execute();
$ct = 0;
$sg = '';
$h = '';
$flag = 0;
$count = 0;
while ($tab = $dbResult->fetch()) {
if (! isset($aTab[$tab['sg_name']])) {
$aTab[$tab['sg_name']] = ['sgn' => CentreonUtils::escapeSecure($tab['sg_name']), 'o' => $ct, 'host' => []];
}
if (! isset($aTab[$tab['sg_name']]['host'][$tab['host_name']])) {
$count++;
$icone = $tab['icon_image'] ?: 'none';
$aTab[$tab['sg_name']]['host'][$tab['host_name']] = ['h' => $tab['host_name'], 'hs' => _($obj->statusHost[$tab['host_state']]), 'hn' => CentreonUtils::escapeSecure($tab['host_name']), 'hico' => $icone, 'hnl' => CentreonUtils::escapeSecure(urlencode($tab['host_name'])), 'hid' => $tab['host_id'], 'hcount' => $count, 'hc' => $obj->colorHost[$tab['host_state']], 'service' => []];
}
if (! isset($aTab[$tab['sg_name']]['host'][$tab['host_name']]['service'][$tab['description']])) {
$aTab[$tab['sg_name']]['host'][$tab['host_name']]['service'][$tab['description']] = ['sn' => CentreonUtils::escapeSecure($tab['description']), 'snl' => CentreonUtils::escapeSecure(urlencode($tab['description'])), 'sc' => $obj->colorService[$tab['state']], 'svc_id' => $tab['service_id']];
}
$ct++;
}
}
foreach ($aTab as $key => $element) {
$obj->XML->startElement('sg');
$obj->XML->writeElement('sgn', $element['sgn']);
$obj->XML->writeElement('o', $element['o']);
foreach ($element['host'] as $host) {
$obj->XML->startElement('h');
$obj->XML->writeAttribute('class', $obj->getNextLineClass());
$obj->XML->writeElement('hn', $host['hn'], false);
$obj->XML->writeElement('hico', $host['hico']);
$obj->XML->writeElement('hnl', $host['hnl']);
$obj->XML->writeElement('hid', $host['hid']);
$obj->XML->writeElement('hcount', $host['hcount']);
$obj->XML->writeElement('hs', $host['hs']);
$obj->XML->writeElement('hc', $host['hc']);
$obj->XML->writeElement(
'h_details_uri',
$useDeprecatedPages
? 'main.php?p=20202&o=hd&host_name=' . $host['hn']
: $resourceController->buildHostDetailsUri($host['hid'])
);
$obj->XML->writeElement(
's_listing_uri',
$useDeprecatedPages
? 'main.php?o=svc&p=20201&statusFilter=&host_search=' . $host['hn']
: $resourceController->buildListingUri([
'filter' => json_encode([
'criterias' => [
'search' => 'h.name:^' . $host['hn'] . '$',
],
]),
])
);
foreach ($host['service'] as $service) {
$obj->XML->startElement('svc');
$obj->XML->writeElement('sn', $service['sn']);
$obj->XML->writeElement('snl', $service['snl']);
$obj->XML->writeElement('sc', $service['sc']);
$obj->XML->writeElement('svc_id', $service['svc_id']);
$obj->XML->writeElement(
's_details_uri',
$useDeprecatedPages
? 'main.php?o=svcd&p=202&host_name='
. $host['hn']
. '&service_description='
. $service['sn']
: $resourceController->buildServiceDetailsUri($host['hid'], $service['svc_id'])
);
$obj->XML->endElement();
}
$obj->XML->writeElement('chartIcon', returnSvg('www/img/icons/chart.svg', 'var(--icons-fill-color)', 18, 18));
$obj->XML->writeElement('viewIcon', returnSvg('www/img/icons/view.svg', 'var(--icons-fill-color)', 18, 18));
$obj->XML->endElement();
$count++;
}
$obj->XML->endElement();
}
$obj->XML->endElement();
// Send Header
$obj->header();
// Send XML
$obj->XML->output();
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/status/ServicesServiceGroups/xml/serviceSummaryBySGXML.php | centreon/www/include/monitoring/status/ServicesServiceGroups/xml/serviceSummaryBySGXML.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
*
*/
ini_set('display_errors', 'Off');
require_once realpath(__DIR__ . '/../../../../../../bootstrap.php');
include_once _CENTREON_PATH_ . 'www/class/centreonUtils.class.php';
include_once _CENTREON_PATH_ . 'www/class/centreonXMLBGRequest.class.php';
include_once _CENTREON_PATH_ . 'www/include/monitoring/status/Common/common-Func.php';
include_once _CENTREON_PATH_ . 'www/include/common/common-Func.php';
include_once _CENTREON_PATH_ . 'www/class/centreonService.class.php';
// Create XML Request Objects
CentreonSession::start(1);
$obj = new CentreonXMLBGRequest($dependencyInjector, session_id(), 1, 1, 0, 1);
$svcObj = new CentreonService($obj->DB);
if (! isset($obj->session_id) || ! CentreonSession::checkSession($obj->session_id, $obj->DB)) {
echo 'Bad Session ID';
exit();
}
// Set Default Poller
$obj->getDefaultFilters();
/**
* @var Centreon $centreon
*/
$centreon = $_SESSION['centreon'];
/**
* true: URIs will correspond to deprecated pages
* false: URIs will correspond to new page (Resource Status)
*/
$useDeprecatedPages = $centreon->user->doesShowDeprecatedPages();
// Check Arguments From GET tab
$o = isset($_GET['o']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_GET['o']) : 'h';
$p = filter_input(INPUT_GET, 'p', FILTER_VALIDATE_INT, ['options' => ['default' => 2]]);
$num = filter_input(INPUT_GET, 'num', FILTER_VALIDATE_INT, ['options' => ['default' => 0]]);
$limit = filter_input(INPUT_GET, 'limit', FILTER_VALIDATE_INT, ['options' => ['default' => 20]]);
// if instance value is not set, displaying all active pollers linked resources
$instance = filter_var($obj->defaultPoller ?? -1, FILTER_VALIDATE_INT);
$hSearch = isset($_GET['host_search']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_GET['host_search']) : '';
$sgSearch = isset($_GET['sg_search']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_GET['sg_search']) : '';
$sort_type = isset($_GET['sort_type']) ? HtmlAnalyzer::sanitizeAndRemoveTags($_GET['sort_type']) : 'host_name';
$order = isset($_GET['order']) && $_GET['order'] === 'DESC' ? 'DESC' : 'ASC';
$kernel = App\Kernel::createForWeb();
$resourceController = $kernel->getContainer()->get(
Centreon\Application\Controller\MonitoringResourceController::class
);
// saving bound values
$queryValues = [];
$queryValues2 = [];
// Backup poller selection
$obj->setInstanceHistory($instance);
/**
* Prepare pagination
*/
$s_search = '';
// Display service problems
if (str_ends_with($o, '_pb')) {
$s_search .= ' AND s.state != 0 AND s.state != 4 ';
}
// Display acknowledged services
if (str_ends_with($o, '_ack_1')) {
$s_search .= " AND s.acknowledged = '1' ";
} elseif (str_ends_with($o, '_ack_0')) {
// Display not acknowledged services
$s_search .= ' AND s.state != 0 AND s.state != 4 AND s.acknowledged = 0 ';
}
$query = 'SELECT SQL_CALC_FOUND_ROWS DISTINCT 1 AS REALTIME, sg.servicegroup_id, h.host_id
FROM servicegroups sg
INNER JOIN services_servicegroups sgm ON sg.servicegroup_id = sgm.servicegroup_id
INNER JOIN services s ON s.service_id = sgm.service_id
INNER JOIN hosts h ON sgm.host_id = h.host_id AND h.host_id = s.host_id '
. $obj->access->getACLHostsTableJoin($obj->DBC, 'h.host_id')
. $obj->access->getACLServicesTableJoin($obj->DBC, 's.service_id')
. ' WHERE 1 = 1 ';
// Servicegroup ACL
$query .= $obj->access->queryBuilder('AND', 'sg.servicegroup_id', $obj->access->getServiceGroupsString('ID'));
// Servicegroup search
if ($sgSearch != '') {
$query .= 'AND sg.name = :sgSearch ';
$queryValues['sgSearch'] = [
PDO::PARAM_STR => $sgSearch,
];
}
// Host search
$h_search = '';
if ($hSearch != '') {
$h_search .= ' AND h.name LIKE :hSearch ';
// as this partial request is used in two queries, we need to bound it two times using two arrays
// to avoid incoherent number of bound variables in the second query
$queryValues['hSearch'] = $queryValues2['hSearch'] = [
PDO::PARAM_STR => '%' . $hSearch . '%',
];
}
$query .= $h_search;
// Service search
$query .= $s_search;
// Poller search
if ($instance != -1) {
$query .= ' AND h.instance_id = :instance ';
$queryValues['instance'] = [
PDO::PARAM_INT => $instance,
];
}
$query .= 'ORDER BY sg.name ' . $order . ' LIMIT :numLimit, :limit';
$queryValues['numLimit'] = [
PDO::PARAM_INT => (int) ($num * $limit),
];
$queryValues['limit'] = [
PDO::PARAM_INT => (int) $limit,
];
$dbResult = $obj->DBC->prepare($query);
foreach ($queryValues as $bindId => $bindData) {
foreach ($bindData as $bindType => $bindValue) {
$dbResult->bindValue($bindId, $bindValue, $bindType);
}
}
$dbResult->execute();
$numRows = $obj->DBC->query('SELECT FOUND_ROWS() AS REALTIME')->fetchColumn();
/**
* Create XML Flow
*/
$obj->XML = new CentreonXML();
$obj->XML->startElement('reponse');
$obj->XML->startElement('i');
$obj->XML->writeElement('numrows', $numRows);
$obj->XML->writeElement('num', $num);
$obj->XML->writeElement('limit', $limit);
$obj->XML->writeElement('host_name', _('Hosts'), 0);
$obj->XML->writeElement('services', _('Services'), 0);
$obj->XML->writeElement('p', $p);
$obj->XML->writeElement('sk', $obj->colorService[0]);
$obj->XML->writeElement('sw', $obj->colorService[1]);
$obj->XML->writeElement('sc', $obj->colorService[2]);
$obj->XML->writeElement('su', $obj->colorService[3]);
$obj->XML->writeElement('sp', $obj->colorService[4]);
$obj->XML->writeElement('s', '1');
$obj->XML->endElement();
$buildParameter = function (string $id, string $name) {
return [
'id' => $id,
'name' => $name,
];
};
$buildServicesUri = function (string $hostname, array $statuses) use ($resourceController, $buildParameter) {
return $resourceController->buildListingUri([
'filter' => json_encode([
'criterias' => [
'search' => 'h.name:^' . $hostname . '$',
'resourceTypes' => [$buildParameter('service', 'Service')],
'statuses' => $statuses,
],
]),
]);
};
$okStatus = $buildParameter('OK', 'Ok');
$warningStatus = $buildParameter('WARNING', 'Warning');
$criticalStatus = $buildParameter('CRITICAL', 'Critical');
$unknownStatus = $buildParameter('UNKNOWN', 'Unknown');
$pendingStatus = $buildParameter('PENDING', 'Pending');
// Construct query for servicegroups search
$sg_search = '';
if ($numRows > 0) {
$sg_search .= 'AND (';
$servicegroups = [];
while ($row = $dbResult->fetch()) {
$servicesgroups[$row['servicegroup_id']][] = $row['host_id'];
}
$servicegroupsSql1 = [];
foreach ($servicesgroups as $key => $value) {
$hostsSql = [];
foreach ($value as $hostId) {
$hostsSql[] = $hostId;
}
$servicegroupsSql1[] = '(sg.servicegroup_id = ' . $key . ' AND h.host_id IN ('
. implode(',', $hostsSql) . ')) ';
}
$sg_search .= implode(' OR ', $servicegroupsSql1);
$sg_search .= ') ';
if ($sgSearch != '') {
$sg_search .= 'AND sg.name = :sgSearch';
$queryValues2['sgSearch'] = [
PDO::PARAM_STR => $sgSearch,
];
}
$query2 = 'SELECT SQL_CALC_FOUND_ROWS
1 AS REALTIME,
count(s.state) as count_state,
sg.name AS sg_name,
h.name AS host_name,
h.state AS host_state,
h.icon_image, h.host_id, s.state,
(CASE s.state WHEN 0 THEN 3 WHEN 2 THEN 0 WHEN 3 THEN 2 ELSE s.state END) AS tri
FROM servicegroups sg, services_servicegroups sgm, services s, hosts h
WHERE h.host_id = s.host_id AND s.host_id = sgm.host_id AND s.service_id=sgm.service_id
AND sg.servicegroup_id=sgm.servicegroup_id '
. $s_search
. $sg_search
. $h_search
. $obj->access->queryBuilder('AND', 'sg.servicegroup_id', $obj->access->getServiceGroupsString('ID'))
. $obj->access->queryBuilder('AND', 's.service_id', $obj->access->getServicesString('ID', $obj->DBC))
. ' GROUP BY sg_name,host_name,host_state,icon_image,host_id, s.state ORDER BY tri ASC ';
$dbResult = $obj->DBC->prepare($query2);
foreach ($queryValues2 as $bindId => $bindData) {
foreach ($bindData as $bindType => $bindValue) {
$dbResult->bindValue($bindId, $bindValue, $bindType);
}
}
$dbResult->execute();
$states = [0 => 'sk', 1 => 'sw', 2 => 'sc', 3 => 'su', 4 => 'sp'];
$sg_list = [];
while ($tab = $dbResult->fetch()) {
$sg_list[$tab['sg_name']][$tab['host_name']]['host_id'] = $tab['host_id'];
$sg_list[$tab['sg_name']][$tab['host_name']]['icon_image'] = $tab['icon_image'];
$sg_list[$tab['sg_name']][$tab['host_name']]['host_state'] = $tab['host_state'];
$sg_list[$tab['sg_name']][$tab['host_name']]['states'][$states[$tab['state']]] = $tab['count_state'];
}
$ct = 0;
foreach ($sg_list as $sg => $h) {
$count = 0;
$ct++;
$obj->XML->startElement('sg');
$obj->XML->writeElement('sgn', CentreonUtils::escapeSecure($sg));
$obj->XML->writeElement('o', $ct);
foreach ($h as $host_name => $hostInfos) {
$count++;
$obj->XML->startElement('h');
$obj->XML->writeAttribute('class', $obj->getNextLineClass());
$obj->XML->writeElement('hn', CentreonUtils::escapeSecure($host_name), false);
if ($hostInfos['icon_image']) {
$obj->XML->writeElement('hico', $hostInfos['icon_image']);
} else {
$obj->XML->writeElement('hico', 'none');
}
$obj->XML->writeElement('hnl', CentreonUtils::escapeSecure(urlencode($host_name)));
$obj->XML->writeElement('hcount', $count);
$obj->XML->writeElement('hid', $hostInfos['host_id']);
$obj->XML->writeElement('hs', _($obj->statusHost[$hostInfos['host_state']]));
$obj->XML->writeElement('hc', $obj->colorHost[$hostInfos['host_state']]);
$obj->XML->writeElement(
'h_details_uri',
$useDeprecatedPages
? 'main.php?p=20202&o=hd&host_name=' . $host_name
: $resourceController->buildHostDetailsUri($hostInfos['host_id'])
);
$serviceListingDeprecatedUri = 'main.php?p=20201&o=svc&host_search=' . $host_name;
$obj->XML->writeElement(
's_listing_uri',
$useDeprecatedPages
? $serviceListingDeprecatedUri . '$statusFilter='
: $resourceController->buildListingUri([
'filter' => json_encode([
'criterias' => [
'search' => 'h.name:^' . $host_name . '$',
],
]),
])
);
$obj->XML->writeElement(
's_listing_ok',
$useDeprecatedPages
? $serviceListingDeprecatedUri . '&statusFilter=ok'
: $buildServicesUri($host_name, [$okStatus])
);
$obj->XML->writeElement(
's_listing_warning',
$useDeprecatedPages
? $serviceListingDeprecatedUri . '&statusFilter=warning'
: $buildServicesUri($host_name, [$warningStatus])
);
$obj->XML->writeElement(
's_listing_critical',
$useDeprecatedPages
? $serviceListingDeprecatedUri . '&statusFilter=critical'
: $buildServicesUri($host_name, [$criticalStatus])
);
$obj->XML->writeElement(
's_listing_unknown',
$useDeprecatedPages
? $serviceListingDeprecatedUri . '&statusFilter=unknown'
: $buildServicesUri($host_name, [$unknownStatus])
);
$obj->XML->writeElement(
's_listing_pending',
$useDeprecatedPages
? $serviceListingDeprecatedUri . '&statusFilter=pending'
: $buildServicesUri($host_name, [$pendingStatus])
);
foreach ($hostInfos['states'] as $state => $count) {
$obj->XML->writeElement($state, $count);
}
$obj->XML->writeElement('chartIcon', returnSvg('www/img/icons/chart.svg', 'var(--icons-fill-color)', 18, 18));
$obj->XML->writeElement('viewIcon', returnSvg('www/img/icons/view.svg', 'var(--icons-fill-color)', 18, 18));
$obj->XML->endElement();
}
$obj->XML->endElement();
}
}
$obj->XML->endElement();
// Send Header
$obj->header();
// Send XML
$obj->XML->output();
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/recurrentDowntime/listDowntime.php | centreon/www/include/monitoring/recurrentDowntime/listDowntime.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($centreon)) {
exit();
}
include_once './class/centreonUtils.class.php';
include './include/common/autoNumLimit.php';
// initializing filters values
$search = HtmlAnalyzer::sanitizeAndRemoveTags(
$_POST['searchDT'] ?? $_GET['searchDT'] ?? ''
);
if (isset($_POST['Search'])) {
// saving chosen filters values
$centreon->historySearch[$url] = [];
$centreon->historySearch[$url]['search'] = $search;
} else {
// restoring saved values
$search = $centreon->historySearch[$url]['search'] ?? '';
}
$downtime->setSearch($search);
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate($path);
// Access level
$lvl_access = ($centreon->user->access->page($p) == 1) ? 'w' : 'r';
$tpl->assign('mode_access', $lvl_access);
// start header menu
$tpl->assign('headerMenu_name', _('Name'));
$tpl->assign('headerMenu_desc', _('Alias'));
$tpl->assign('headerMenu_status', _('Status'));
$tpl->assign('headerMenu_options', _('Options'));
// Nagios list
$rows = $downtime->getNbRows();
include './include/common/checkPagination.php';
$listDowntime = $downtime->getList($num, $limit, $type);
$form = new HTML_QuickFormCustom('select_form', 'POST', '?p=' . $p);
// Different style between each lines
$style = 'one';
$attrBtnSuccess = ['class' => 'btc bt_success', 'onClick' => "window.history.replaceState('', '', '?p=" . $p . "');"];
$form->addElement('submit', 'Search', _('Search'), $attrBtnSuccess);
// Fill a tab with a mutlidimensionnal Array we put in $tpl
$elemArr = [];
$centreonToken = createCSRFToken();
foreach ($listDowntime as $dt) {
$moptions = '';
$selectedElements = $form->addElement('checkbox', 'select[' . $dt['dt_id'] . ']');
if ($dt['dt_activate']) {
$moptions .= "<a href='main.php?p=" . $p . '&dt_id=' . $dt['dt_id'] . '&o=u&limit=' . $limit
. '&num=' . $num . '&search=' . $search . '¢reon_token=' . $centreonToken
. "'><img src='img/icons/disabled.png' "
. "class='ico-14 margin_right' border='0' alt='" . _('Disabled') . "'></a>";
} else {
$moptions .= "<a href='main.php?p=" . $p . '&dt_id=' . $dt['dt_id'] . '&o=e&limit=' . $limit
. '&num=' . $num . '&search=' . $search . '¢reon_token=' . $centreonToken
. "'><img src='img/icons/enabled.png' "
. "class='ico-14 margin_right' border='0' alt='" . _('Enabled') . "'></a>";
}
$moptions .= '<input onKeypress="if(event.keyCode > 31 && (event.keyCode < 45 || event.keyCode > 57))'
. ' event.returnValue = false; if(event.which > 31 && (event.which < 45 || event.which > 57))'
. " return false;\" maxlength=\"3\" size=\"3\" value='1' style=\"margin-bottom:0px;\" "
. "name='dupNbr[" . $dt['dt_id'] . "]'></input>";
$elemArr[] = ['MenuClass' => 'list_' . $style, 'RowMenu_select' => $selectedElements->toHtml(), 'RowMenu_name' => $dt['dt_name'], 'RowMenu_link' => 'main.php?p=' . $p . '&o=c&dt_id=' . $dt['dt_id'], 'RowMenu_desc' => $dt['dt_description'], 'RowMenu_status' => $dt['dt_activate'] ? _('Enabled') : _('Disabled'), 'RowMenu_options' => $moptions];
$style = $style != 'two' ? 'two' : 'one';
}
$tpl->assign('elemArr', $elemArr);
// Different messages we put in the template
$tpl->assign(
'msg',
['addL' => 'main.php?p=' . $p . '&o=a', 'addT' => _('Add'), 'delConfirm' => _('Do you confirm the deletion ?')]
);
// Toolbar select
?>
<script type="text/javascript">
function setO(_i) {
document.forms['form'].elements['o'].value = _i;
}
</SCRIPT>
<?php
foreach (['o1', 'o2'] as $option) {
$attrs1 = ['onchange' => 'javascript: '
. ' var bChecked = isChecked(); '
. " if (this.form.elements['" . $option . "'].selectedIndex != 0 && !bChecked) {"
. " alert('" . _('Please select one or more items') . "'); return false;} "
. "if (this.form.elements['" . $option
. "'].selectedIndex == 1 && confirm('" . _('Do you confirm the duplication ?') . "')) {"
. " setO(this.form.elements['" . $option . "'].value); submit();} "
. "else if (this.form.elements['" . $option
. "'].selectedIndex == 2 && confirm('" . _('Do you confirm the deletion ?') . "')) {"
. " setO(this.form.elements['" . $option . "'].value); submit();} "
. "else if (this.form.elements['" . $option
. "'].selectedIndex == 3 || this.form.elements['" . $option . "'].selectedIndex == 4) {"
. " setO(this.form.elements['" . $option . "'].value); submit();} "
. ''];
$form->addElement(
'select',
$option,
null,
[null => _('More actions...'), 'm' => _('Duplicate'), 'd' => _('Delete'), 'ms' => _('Enable'), 'mu' => _('Disable')],
$attrs1
);
$form->setDefaults([$option => null]);
$o1 = $form->getElement($option);
$o1->setValue(null);
$o1->setSelected(null);
}
$tpl->assign('limit', $limit);
$tpl->assign('searchDT', $search);
// Apply a template definition
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl);
$form->accept($renderer);
$tpl->assign('form', $renderer->toArray());
$tpl->display('listDowntime.html');
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/recurrentDowntime/formDowntime.php | centreon/www/include/monitoring/recurrentDowntime/formDowntime.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($centreon)) {
exit();
}
/**
* GetUserAclAllowedResources returns allowed resources for the user regarding resource type
*
* @param CentreonACL $userAcl
* @param string $resourceType
*/
function getUserAclAllowedResources(CentreonACL $userAcl, string $resourceType)
{
return match ($resourceType) {
'hosts' => $userAcl->getHostAclConf(null, 'broker'),
'servicegroups' => $userAcl->getServiceGroupAclConf(null, 'broker'),
'hostgroups' => $userAcl->getHostGroupAclConf(null, 'broker'),
};
}
/**
* Check resources access regarding selected resources
*
* @param CentreonACL $userAcl
* @param int[] $selectedResources
* @param string $resourceType
* @return bool
**/
function checkResourcesRelations(CentreonACL $userAcl, array $selectedResources, string $resourceType): bool
{
$allowedResources = getUserAclAllowedResources($userAcl, $resourceType);
$selectedResourceIds = array_map(
static fn (array $resource) => $resource['id'],
$selectedResources
);
$diff = array_diff($selectedResourceIds, array_keys($allowedResources));
if ($diff === []) {
return true;
}
foreach ($selectedResources as $resource) {
if (
in_array($resource['id'], $diff)
&& $resource['activated'] === '1'
) {
return false;
}
}
return true;
}
// QuickForm Rules
function testDowntimeNameExistence($downtimeName = null)
{
global $pearDB, $form;
$id = null;
if (isset($form)) {
$id = $form->getSubmitValue('dt_id');
}
$res = $pearDB->query("SELECT dt_id FROM downtime WHERE dt_name = '" . $pearDB->escape($downtimeName) . "'");
$d = $res->fetchRow();
$nbRes = $res->rowCount();
if ($nbRes && $d['dt_id'] == $id) {
return true;
}
return ! ($nbRes && $d['dt_id'] != $id);
}
if (($o == 'c' || $o == 'w') && isset($_GET['dt_id'])) {
$id = filter_var($_GET['dt_id'], FILTER_VALIDATE_INT);
} else {
$o = 'a';
}
// Var information to format the element
$attrsText = ['size' => '30'];
$attrsText2 = ['size' => '6'];
$attrsTextLong = ['size' => '70'];
$attrsAdvSelect_small = ['style' => 'width: 270px; height: 70px;'];
$attrsAdvSelect = ['style' => 'width: 270px; height: 100px;'];
$attrsAdvSelect_big = ['style' => 'width: 270px; height: 200px;'];
$attrsTextarea = ['rows' => '5', 'cols' => '40'];
$eTemplate = '<table><tr><td><div class="ams">{label_2}</div>{unselected}</td><td align="center">{add}<br />'
. '<br /><br />{remove}</td><td><div class="ams">{label_3}</div>{selected}</td></tr></table>';
$hostsRoute = './include/common/webServices/rest/internal.php?object=centreon_configuration_host&action=list';
$attrHosts = ['datasourceOrigin' => 'ajax', 'availableDatasetRoute' => $hostsRoute, 'multiple' => true, 'linkedObject' => 'centreonHost', 'showDisabled' => true];
$hostgroupsRoute = './include/common/webServices/rest/internal.php?object=centreon_configuration_hostgroup&action=list';
$attrHostgroups = ['datasourceOrigin' => 'ajax', 'availableDatasetRoute' => $hostgroupsRoute, 'multiple' => true, 'linkedObject' => 'centreonHostgroups', 'showDisabled' => true];
$servicesRoute = './include/common/webServices/rest/internal.php?object=centreon_configuration_service&action=list';
$attrServices = ['datasourceOrigin' => 'ajax', 'availableDatasetRoute' => $servicesRoute, 'multiple' => true, 'linkedObject' => 'centreonService', 'showDisabled' => true];
$servicegroupsRoute = './include/common/webServices/rest/internal.php'
. '?object=centreon_configuration_servicegroup&action=list';
$attrServicegroups = ['datasourceOrigin' => 'ajax', 'availableDatasetRoute' => $servicegroupsRoute, 'multiple' => true, 'linkedObject' => 'centreonServicegroups', 'showDisabled' => true];
// Init QuickFrom
$form = new HTML_QuickFormCustom('form_dt', 'post', "?p={$p}");
if ($o == 'a') {
$form->addElement('header', 'title', _('Add a downtime'));
} elseif ($o == 'c') {
$form->addElement('header', 'title', _('Modify a downtime'));
} elseif ($o == 'w') {
$form->addElement('header', 'title', _('View a downtime'));
}
$form->addElement('header', 'periods', _('Periods'));
// Tab 1
$form->addElement('header', 'information', _('General Information'));
$form->addElement('header', 'linkManagement', _('Links Management'));
$form->addElement('text', 'downtime_name', _('Name'), $attrsText);
$form->addElement('text', 'downtime_description', _('Alias'), $attrsTextLong);
$donwtime_activate[] = $form->createElement('radio', 'downtime_activate', null, _('Yes'), '1');
$donwtime_activate[] = $form->createElement('radio', 'downtime_activate', null, _('No'), '0');
$form->addGroup($donwtime_activate, 'downtime_activate', _('Enable'), ' ');
$form->setDefaults(['downtime_activate' => '1']);
$page = $form->addElement('hidden', 'p');
$page->setValue($p);
$redirect = $form->addElement('hidden', 'o');
$redirect->setValue($o);
$form->addElement('hidden', 'dt_id');
/*
* Tab 2
* Hosts
*/
$routeAttrHosts = './include/common/webServices/rest/internal.php?object=centreon_configuration_host'
. '&action=defaultValues&target=downtime&field=host_relation&id=' . $downtime_id;
$attrHost1 = array_merge(
$attrHosts,
['defaultDatasetRoute' => $routeAttrHosts]
);
$form->addElement('select2', 'host_relation', _('Linked with Hosts'), [], $attrHost1);
// Hostgroups
$routeAttrHostgroup = './include/common/webServices/rest/internal.php?object=centreon_configuration_hostgroup'
. '&action=defaultValues&target=downtime&field=hostgroup_relation&id=' . $downtime_id;
$attrHostgroup1 = array_merge(
$attrHostgroups,
['defaultDatasetRoute' => $routeAttrHostgroup],
);
$form->addElement('select2', 'hostgroup_relation', _('Linked with Host Groups'), [], $attrHostgroup1);
// Service
$routeAttrService = './include/common/webServices/rest/internal.php?object=centreon_configuration_service'
. '&action=defaultValues&target=downtime&field=svc_relation&id=' . $downtime_id;
$attrService1 = array_merge(
$attrServices,
['defaultDatasetRoute' => $routeAttrService]
);
$form->addElement('select2', 'svc_relation', _('Linked with Services'), [], $attrService1);
// Servicegroups
$routeAttrServicegroup = './include/common/webServices/rest/internal.php?object=centreon_configuration_servicegroup'
. '&action=defaultValues&target=downtime&field=svcgroup_relation&id=' . $downtime_id;
$attrServicegroup1 = array_merge(
$attrServicegroups,
['defaultDatasetRoute' => $routeAttrServicegroup]
);
$form->addElement('select2', 'svcgroup_relation', _('Linked with Service Groups'), [], $attrServicegroup1);
$form->addRule('downtime_name', _('Name'), 'required');
$form->registerRule('exist', 'callback', 'testDowntimeNameExistence');
$form->addRule('downtime_name', _('Name is already in use'), 'exist');
$form->setRequiredNote("<i class='red'>*</i> " . _('Required fields'));
if ($o == 'c' || $o == 'w') {
$infos = $downtime->getInfos((int) $id);
$relations = $downtime->getRelations((int) $id);
$extractRelationId = static fn (array $item): string => (string) ($item['id'] ?? '');
$default_dt = [
'dt_id' => $id,
'downtime_name' => $infos['name'],
'downtime_description' => $infos['description'],
'downtime_activate' => $infos['activate'],
'host_relation' => array_map($extractRelationId, $relations['hosts']),
'hostgroup_relation' => array_map($extractRelationId, $relations['hostgroups']),
'svc_relation' => array_map($extractRelationId, $relations['services']),
'svcgroup_relation' => array_map($extractRelationId, $relations['servicegroups']),
];
}
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate($path);
/**
* $o parameter possible values
*
* $o = w - Watch the recurrent downtime = no possible edit
* $o = c - Edit the recurrent downtime
* $o = a - Add a recurrent downtime
*/
if ($o == 'w') {
if (! $min && $centreon->user->access->page($p) != 2) {
$form->addElement('button', 'change', _('Modify'), ['onClick' => "javascript:window.location.href='?p=" . $p . '&o=c&dt_id=' . $id . "'", 'class' => 'btc bt_default']);
}
$form->setDefaults($default_dt);
$form->freeze();
} elseif ($o == 'c') {
/**
* Only search for ACL if the user is not admin
*/
$userId = $centreon->user->user_id;
$userIsAdmin = $centreon->user->admin;
if ($userIsAdmin !== '1') {
require_once _CENTREON_PATH_ . '/www/class/centreonACL.class.php';
$userAcl = new CentreonACL($userId, $userIsAdmin);
if (
! checkResourcesRelations($userAcl, $relations['hosts'], 'hosts')
|| ! checkResourcesRelations($userAcl, $relations['hostgroups'], 'hostgroups')
|| ! checkResourcesRelations($userAcl, $relations['servicegroups'], 'servicegroups')
) {
$form->addElement('text', 'msgacl', _('error'), 'error');
$form->freeze();
}
}
$subC = $form->addElement(
'button',
'submitC',
_('Save'),
['onClick' => 'validForm();', 'class' => 'btc bt_success']
);
$res = $form->addElement(
'button',
'reset',
_('Reset'),
['onClick' => 'history.go(0);', 'class' => 'btc bt_default']
);
$form->setDefaults($default_dt);
} elseif ($o == 'a') {
$subA = $form->addElement(
'button',
'submitA',
_('Save'),
['onClick' => 'validForm();', 'class' => 'btc bt_success']
);
$res = $form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']);
}
$tpl->assign('sort1', _('Downtime Configuration'));
$tpl->assign('sort2', _('Relations'));
$tpl->assign('periods', _('Periods'));
$tpl->assign('period', _('Period'));
$tpl->assign('add', _('Add new period'));
// prepare help texts
$helptext = '';
include_once 'help.php';
foreach ($help as $key => $text) {
$helptext .= '<span style="display:none" id="help:' . $key . '">' . $text . '</span>' . "\n";
}
$tpl->assign('helptext', $helptext);
$valid = false;
if ($form->validate()) {
$values = $form->getSubmitValues();
$valid = true;
foreach ($values['periods'] as $periods) {
$time_end_period = strtotime($periods['end_period']);
if ($periods['end_period'] == '24:00') {
$time_end_period = strtotime('00:00') + 3600 * 24; // Fix with 00:00 and 24 h for with before 5.3
}
if (strtotime($periods['start_period']) > $time_end_period) {
$valid = false;
$tpl->assign('period_err', _('The end time must be greater than the start time.'));
}
}
/** validate that at least one relation has been configured */
if (
(! isset($values['host_relation']) || count($values['host_relation']) === 0)
&& (! isset($values['hostgroup_relation']) || count($values['hostgroup_relation']) === 0)
&& (! isset($values['svc_relation']) || count($values['svc_relation']) === 0)
&& (! isset($values['svcgroup_relation']) || count($values['svcgroup_relation']) === 0)
) {
$valid = false;
$tpl->assign('msg_err', _('No relation set for this downtime'));
}
if ($valid) {
if ($values['o'] == 'a') {
$activate = $values['downtime_activate']['downtime_activate'];
$id = $downtime->add($values['downtime_name'], $values['downtime_description'], $activate);
if ($id !== false) {
foreach ($values['periods'] as $periods) {
$downtime->addPeriod($id, $periods);
}
if (isset($values['host_relation'])) {
$downtime->addRelations($id, $values['host_relation'], 'host');
}
if (isset($values['hostgroup_relation'])) {
$downtime->addRelations($id, $values['hostgroup_relation'], 'hostgrp');
}
if (isset($values['svc_relation'])) {
$downtime->addRelations($id, $values['svc_relation'], 'svc');
}
if (isset($values['svcgroup_relation'])) {
$downtime->addRelations($id, $values['svcgroup_relation'], 'svcgrp');
}
$o = 'w';
$form->addElement(
'button',
'change',
_('Modify'),
['onClick' => "javascript:window.location.href='?p=" . $p . '&o=c&dt_id=' . $id . "'"]
);
$form->freeze();
$valid = true;
}
} elseif ($values['o'] == 'c') {
$id = $values['dt_id'];
$activate = $values['downtime_activate']['downtime_activate'];
$downtime->modify($id, $values['downtime_name'], $values['downtime_description'], $activate);
$downtime->deletePeriods((int) $id);
foreach ($values['periods'] as $periods) {
$downtime->addPeriod($id, $periods);
}
$downtime->deleteRelations($id);
if (isset($values['host_relation'])) {
$downtime->addRelations($id, $values['host_relation'], 'host');
}
if (isset($values['hostgroup_relation'])) {
$downtime->addRelations($id, $values['hostgroup_relation'], 'hostgrp');
}
if (isset($values['svc_relation'])) {
$downtime->addRelations($id, $values['svc_relation'], 'svc');
}
if (isset($values['svcgroup_relation'])) {
$downtime->addRelations($id, $values['svcgroup_relation'], 'svcgrp');
}
$o = 'w';
$form->addElement(
'button',
'change',
_('Modify'),
['onClick' => "javascript:window.location.href='?p=" . $p . '&o=c&dt_id=' . $id . "'"]
);
$form->freeze();
$valid = true;
}
}
if ($valid) {
require_once $path . 'listDowntime.php';
}
if (! $valid) {
$form->setDefaults($values);
}
}
if (! $valid) {
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl, true);
$renderer->setRequiredTemplate('{$label} <i class="red">*</i>');
$renderer->setErrorTemplate('<i class="red">{$error}</i><br />{$html}');
if ($o == 'w') {
$tpl->assign('time_period', _('Time period'));
$tpl->assign('days', _('Days'));
$tpl->assign('seconds', _('Seconds'));
$tpl->assign('downtime_type', _('Downtime type'));
$tpl->assign('fixed', _('Fixed'));
$tpl->assign('flexible', _('Flexible'));
$tpl->assign('weekly_basis', _('Weekly basis'));
$tpl->assign('monthly_basis', _('Monthly basis'));
$tpl->assign('specific_date', _('Specific date'));
$tpl->assign('week_days', [1 => _('Monday'), 2 => _('Tuesday'), 3 => _('Wednesday'), 4 => _('Thursday'), 5 => _('Friday'), 6 => _('Saturday'), 7 => _('Sunday')]);
$tpl->assign('periods_tab', $downtime->getPeriods($id));
}
$tpl->assign('msg_err_norelation', addslashes(_('No relation set for this downtime')));
$form->accept($renderer);
$tpl->assign('o', $o);
$tpl->assign('p', $p);
$tpl->assign('form', $renderer->toArray());
$tpl->display('formDowntime.html');
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/recurrentDowntime/help.php | centreon/www/include/monitoring/recurrentDowntime/help.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
$help = [];
$help['mc_update'] = dgettext(
'help',
'Choose the update mode for the below field: incremental adds the selected values, replacement overwrites '
. 'the original values.'
);
// Host Configuration
$help['downtime_name'] = dgettext('help', 'The name of the recurrent downtime rule.');
$help['downtime_description'] = dgettext('help', 'Description of the downtime');
$help['downtime_activate'] = dgettext('help', 'Option to enable or disable this downtime');
$help['downtime_period'] = dgettext(
'help',
'This field give the possibility to configure the frequency of this downtime.'
);
$help['host_relation'] = dgettext(
'help',
'This field give you the possibility to select all hosts implied by this downtime'
);
$help['hostgroup_relation'] = dgettext(
'help',
'This field give you the possibility to select all hostgroups and all hosts contained into the selected '
. 'hostgroups implied by this downtime'
);
$help['svc_relation'] = dgettext(
'help',
'This field give you the possibility to select all services implied by this downtime'
);
$help['svcgroup_relation'] = dgettext(
'help',
'This field give you the possibility to select all servicegroups and all services contained into the '
. 'servicegroups implied by this downtime'
);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/recurrentDowntime/ajaxForms.php | centreon/www/include/monitoring/recurrentDowntime/ajaxForms.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($centreon)) {
return;
}
$period_tab = $_GET['period'] ?? 1;
$form = $_GET['period_form'] ?? 'general';
// Smarty template initialization
$path = './include/monitoring/recurrentDowntime/';
$tpl = SmartyBC::createSmartyTemplate($path, 'templates/');
$tpl->assign('period_tab', $period_tab);
$tpl->assign('days', _('Days'));
$tpl->assign('hours', _('Hours'));
$tpl->assign('minutes', _('Minutes'));
$tpl->assign('seconds', _('Seconds'));
$tpl->assign('downtime_type', _('Downtime type'));
$tpl->assign('fixed', _('Fixed'));
$tpl->assign('flexible', _('Flexible'));
switch ($form) {
case 'weekly_basis':
$tpl->assign('time_period', _('Time period'));
$tpl->assign('monday', _('Monday'));
$tpl->assign('tuesday', _('Tuesday'));
$tpl->assign('wednesday', _('Wednesday'));
$tpl->assign('thursday', _('Thursday'));
$tpl->assign('friday', _('Friday'));
$tpl->assign('saturday', _('Saturday'));
$tpl->assign('sunday', _('Sunday'));
$tmpl = 'weekly_basis.html';
break;
case 'monthly_basis':
$tpl->assign('time_period', _('Time period'));
$tpl->assign('nbDays', range(1, 31));
$tmpl = 'monthly_basis.html';
break;
case 'specific_date':
$tpl->assign('first_of_month', _('First of month'));
$tpl->assign('second_of_month', _('Second of month'));
$tpl->assign('third_of_month', _('Third of month'));
$tpl->assign('fourth_of_month', _('Fourth of month'));
$tpl->assign('last_of_month', _('Last of month'));
$tpl->assign('time_period', _('Time period'));
$tpl->assign('monday', _('Monday'));
$tpl->assign('tuesday', _('Tuesday'));
$tpl->assign('wednesday', _('Wednesday'));
$tpl->assign('thursday', _('Thursday'));
$tpl->assign('friday', _('Friday'));
$tpl->assign('saturday', _('Saturday'));
$tpl->assign('sunday', _('Sunday'));
$tmpl = 'specific_date.html';
break;
case 'general':
default:
$tpl->assign('weekly_basis', _('Weekly basis'));
$tpl->assign('monthly_basis', _('Monthly basis'));
$tpl->assign('specific_date', _('Specific date'));
$tmpl = 'general.html';
break;
}
$tpl->assign('o', '');
$tpl->assign('p', $p);
$tpl->display($tmpl);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/recurrentDowntime/ajaxPeriods.php | centreon/www/include/monitoring/recurrentDowntime/ajaxPeriods.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
*
*/
header('Content-Type: application/json');
header('Cache-Control: no-cache');
require_once __DIR__ . '/../../../../config/centreon.config.php';
require_once _CENTREON_PATH_ . '/www/class/centreonDB.class.php';
require_once _CENTREON_PATH_ . '/www/class/centreonDowntime.class.php';
$downtimeId = filter_input(INPUT_GET, 'dt_id', FILTER_VALIDATE_INT);
if (! empty($downtimeId)) {
$pearDB = new CentreonDB();
$downtime = new CentreonDowntime($pearDB);
$periods = $downtime->getPeriods($downtimeId);
} else {
$periods = [];
}
echo json_encode($periods);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/recurrentDowntime/downtime.php | centreon/www/include/monitoring/recurrentDowntime/downtime.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($centreon)) {
exit();
}
$downtime_id = filter_var(
$_GET['hg_id'] ?? $_POST['hg_id'] ?? null,
FILTER_VALIDATE_INT
);
$cG = $_GET['select'] ?? null;
$cP = $_POST['select'] ?? null;
$select = $cG ?: $cP;
$cG = $_GET['dupNbr'] ?? null;
$cP = $_POST['dupNbr'] ?? null;
$dupNbr = $cG ?: $cP;
$path = './include/monitoring/recurrentDowntime/';
require_once './class/centreonDowntime.class.php';
$downtime = new CentreonDowntime($pearDB);
require_once './include/common/common-Func.php';
if (isset($_POST['o1'], $_POST['o2'])) {
if ($_POST['o1'] != '') {
$o = $_POST['o1'];
}
if ($_POST['o2'] != '') {
$o = $_POST['o2'];
}
}
// Set the real page
if (isset($ret) && is_array($ret) && $ret['topology_page'] != '' && $p != $ret['topology_page']) {
$p = $ret['topology_page'];
}
if (isset($_GET['period_form']) || isset($_GET['period']) && $o == '') {
require_once $path . 'ajaxForms.php';
} else {
switch ($o) {
case 'a':
require_once $path . 'formDowntime.php';
break; // Add a downtime
case 'w':
require_once $path . 'formDowntime.php';
break; // Watch a downtime
case 'c':
require_once $path . 'formDowntime.php';
break; // Modify a downtime
case 'e':
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
if ($downtime_id) {
$downtime->enable($downtime_id);
}
} else {
unvalidFormMessage();
}
require_once $path . 'listDowntime.php';
break; // Activate a service
case 'ms':
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
$downtime->multiEnable($select ?? []);
} else {
unvalidFormMessage();
}
require_once $path . 'listDowntime.php';
break;
case 'u':
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
if ($downtime_id) {
$downtime->disable($downtime_id);
}
} else {
unvalidFormMessage();
}
require_once $path . 'listDowntime.php';
break; // Desactivate a service
case 'mu':
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
$downtime->multiDisable($select ?? []);
} else {
unvalidFormMessage();
}
require_once $path . 'listDowntime.php';
break;
case 'm':
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
$downtime->duplicate($select ?? [], $dupNbr);
} else {
unvalidFormMessage();
}
require_once $path . 'listDowntime.php';
break; // Duplicate n services
case 'd':
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
$downtime->multiDelete(isset($select) ? array_keys($select) : []);
} else {
unvalidFormMessage();
}
require_once $path . 'listDowntime.php';
break; // Delete n services
default:
require_once $path . 'listDowntime.php';
break;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/acknowlegement/serviceAcknowledge.php | centreon/www/include/monitoring/acknowlegement/serviceAcknowledge.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($centreon)) {
exit();
}
require_once './include/monitoring/common-Func.php';
require_once './class/centreonDB.class.php';
$pearDBndo = $pearDBO;
$host_name = $_GET['host_name'] ?? null;
$service_description = $_GET['service_description'] ?? null;
$cmd = $_GET['cmd'] ?? null;
$en = $_GET['en'] ?? 1;
// Smarty template initialization
$path = './include/monitoring/acknowlegement/';
$tpl = SmartyBC::createSmartyTemplate($path, './templates/');
if (! $is_admin) {
$lcaHostByName['LcaHost'] = $centreon->user->access->getHostsServicesName($pearDBndo);
}
// HOST LCA
if ($is_admin || (isset($lcaHostByName['LcaHost'][$host_name]))) {
// # Form begin
$form = new HTML_QuickFormCustom(
'select_form',
'POST',
'?p=' . $p . '&host_name=' . urlencode($host_name) . '&service_description=' . urlencode($service_description)
);
$form->addElement('header', 'title', _('Acknowledge a Service'));
$tpl->assign('hostlabel', _('Host Name'));
$tpl->assign('hostname', $host_name);
$tpl->assign('en', $en);
$tpl->assign('servicelabel', _('Service'));
$tpl->assign('servicedescription', $service_description);
$tpl->assign('authorlabel', _('Alias'));
$tpl->assign('authoralias', $centreon->user->get_alias());
$ckbx[] = $form->addElement('checkbox', 'notify', _('notify'));
if (isset($centreon->optGen['monitoring_ack_notify']) && $centreon->optGen['monitoring_ack_notify']) {
$ckbx[0]->setChecked(true);
}
$ckbx1[] = $form->addElement('checkbox', 'sticky', _('sticky'));
if (isset($centreon->optGen['monitoring_ack_sticky']) && $centreon->optGen['monitoring_ack_sticky']) {
$ckbx1[0]->setChecked(true);
}
$ckbx2[] = $form->addElement('checkbox', 'persistent', _('persistent'));
if (isset($centreon->optGen['monitoring_ack_persistent']) && $centreon->optGen['monitoring_ack_persistent']) {
$ckbx2[0]->setChecked(true);
}
$ckbx3[] = $form->addElement('checkbox', 'force_check', _('Force active check'));
if (isset($centreon->optGen['monitoring_ack_active_checks']) && $centreon->optGen['monitoring_ack_active_checks']) {
$ckbx3[0]->setChecked(true);
}
$form->addElement('hidden', 'host_name', $host_name);
$form->addElement('hidden', 'service_description', $service_description);
$form->addElement('hidden', 'author', $centreon->user->get_alias());
$form->addElement('hidden', 'cmd', $cmd);
$form->addElement('hidden', 'p', $p);
$form->addElement('hidden', 'en', $en);
$form->applyFilter('__ALL__', 'myTrim');
$textarea = $form->addElement('textarea', 'comment', _('comment'), ['rows' => '8', 'cols' => '80']);
$textarea->setValue(sprintf(_('Acknowledged by %s'), $centreon->user->get_alias()));
$form->addRule('comment', _('Comment is required'), 'required', '', 'client');
$form->setJsWarnings(_('Invalid information entered'), _('Please correct these fields'));
$form->addElement('submit', 'submit', ($en == 1) ? _('Add') : _('Delete'), ($en == 1) ? ['class' => 'btc bt_success'] : ['class' => 'btc bt_danger']);
$form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']);
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl);
$renderer->setRequiredTemplate('{$label} <font color="red" size="1">*</font>');
$renderer->setErrorTemplate('<font color="red">{$error}</font><br />{$html}');
$form->accept($renderer);
$tpl->assign('form', $renderer->toArray());
$tpl->display('serviceAcknowledge.ihtml');
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/acknowlegement/hostAcknowledge.php | centreon/www/include/monitoring/acknowlegement/hostAcknowledge.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($centreon)) {
exit();
}
require_once './include/monitoring/common-Func.php';
require_once './class/centreonDB.class.php';
// DB connexion
$pearDBndo = $pearDBO;
$host_name = isset($_GET['host_name']) ? htmlentities($_GET['host_name'], ENT_QUOTES, 'UTF-8') : null;
$cmd = isset($_GET['cmd']) ? htmlentities($_GET['cmd'], ENT_QUOTES, 'UTF-8') : null;
$en = isset($_GET['en']) ? htmlentities($_GET['en'], ENT_QUOTES, 'UTF-8') : 1;
// Smarty template initialization
$path = './include/monitoring/acknowlegement/';
$tpl = SmartyBC::createSmartyTemplate($path, './templates/');
if (! $is_admin) {
$lcaHostByName = $centreon->user->access->getHostsServicesName($pearDBndo);
}
if ($is_admin || (isset($lcaHostByName[$host_name]))) {
$form = new HTML_QuickFormCustom('select_form', 'POST', '?p=' . $p . '&host_name=' . urlencode($host_name));
$form->addElement('header', 'title', _('Acknowledge a host'));
$tpl->assign('hostlabel', _('Host Name'));
$tpl->assign('hostname', $host_name);
$tpl->assign('en', $en);
$tpl->assign('authorlabel', _('Alias'));
$tpl->assign('authoralias', $centreon->user->get_alias());
$ckbx[] = $form->addElement('checkbox', 'notify', _('Notify'));
if (isset($centreon->optGen['monitoring_ack_notify']) && $centreon->optGen['monitoring_ack_notify']) {
$ckbx[0]->setChecked(true);
}
$ckbx1[] = $form->addElement('checkbox', 'persistent', _('Persistent'));
if (isset($centreon->optGen['monitoring_ack_persistent']) && $centreon->optGen['monitoring_ack_persistent']) {
$ckbx1[0]->setChecked(true);
}
$ckbx2[] = $form->addElement('checkbox', 'ackhostservice', _('Acknowledge services attached to hosts'));
if (isset($centreon->optGen['monitoring_ack_svc']) && $centreon->optGen['monitoring_ack_svc']) {
$ckbx2[0]->setChecked(true);
}
$ckbx3[] = $form->addElement('checkbox', 'sticky', _('Sticky'));
if (isset($centreon->optGen['monitoring_ack_sticky']) && $centreon->optGen['monitoring_ack_sticky']) {
$ckbx3[0]->setChecked(true);
}
$form->addElement('hidden', 'host_name', $host_name);
$form->addElement('hidden', 'author', $centreon->user->get_alias());
$form->addElement('hidden', 'cmd', $cmd);
$form->addElement('hidden', 'p', $p);
$form->addElement('hidden', 'en', $en);
$textarea = $form->addElement('textarea', 'comment', _('Comment'), ['rows' => '8', 'cols' => '80']);
$textarea->setValue(sprintf(_('Acknowledged by %s'), $centreon->user->get_alias()));
$form->addRule('comment', _('Comment is required'), 'required', '', 'client');
$form->setJsWarnings(_('Invalid information entered'), _('Please correct these fields'));
$form->addElement('submit', 'submit', ($en == 1) ? _('Add') : _('Delete'));
$form->addElement('reset', 'reset', _('Reset'));
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl);
$renderer->setRequiredTemplate('{$label} <font color="red" size="1">*</font>');
$renderer->setErrorTemplate('<font color="red">{$error}</font><br />{$html}');
$form->accept($renderer);
$tpl->assign('form', $renderer->toArray());
$tpl->assign('o', 'hd');
$tpl->display('hostAcknowledge.ihtml');
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/acknowlegement/xml/broker/makeXMLForAck.php | centreon/www/include/monitoring/acknowlegement/xml/broker/makeXMLForAck.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');
include_once _CENTREON_PATH_ . 'www/class/centreonDuration.class.php';
include_once _CENTREON_PATH_ . 'www/class/centreonGMT.class.php';
include_once _CENTREON_PATH_ . 'www/class/centreonXML.class.php';
include_once _CENTREON_PATH_ . 'www/class/centreonDB.class.php';
include_once _CENTREON_PATH_ . 'www/class/centreonSession.class.php';
include_once _CENTREON_PATH_ . 'www/class/centreon.class.php';
include_once _CENTREON_PATH_ . 'www/class/centreonLang.class.php';
include_once _CENTREON_PATH_ . 'www/include/common/common-Func.php';
session_start();
$oreon = $_SESSION['centreon'];
$db = new CentreonDB();
$dbb = new CentreonDB('centstorage');
$centreonLang = new CentreonLang(_CENTREON_PATH_, $oreon);
$centreonLang->bindLang();
$sid = session_id();
if (isset($sid)) {
$res = $db->prepare('SELECT * FROM session WHERE session_id = :sid');
$res->bindValue(':sid', $sid, PDO::PARAM_STR);
$res->execute();
if (! $session = $res->fetch()) {
get_error('bad session id');
}
} else {
get_error('need session id !');
}
// sanitize host and service id from request;
$hostId = filter_var($_GET['hid'] ?? false, FILTER_VALIDATE_INT);
$svcId = filter_var($_GET['svc_id'] ?? false, FILTER_VALIDATE_INT);
// check if a mandatory valid hostId is given
if ($hostId === false) {
get_error('bad host Id');
}
// Init GMT class
$centreonGMT = new CentreonGMT();
$centreonGMT->getMyGMTFromSession($sid);
// Start Buffer
$xml = new CentreonXML();
$xml->startElement('response');
$xml->startElement('label');
$xml->writeElement('author', _('Author'));
$xml->writeElement('entrytime', _('Entry Time'));
$xml->writeElement('persistent', _('Persistent'));
$xml->writeElement('sticky', _('Sticky'));
$xml->writeElement('comment', _('Comment'));
$xml->endElement();
// Retrieve info
if ($svcId === false) {
$res = $dbb->prepare(
'SELECT author, entry_time, comment_data, persistent_comment, sticky
FROM acknowledgements
WHERE host_id = :hostId
AND service_id = 0
ORDER BY entry_time DESC
LIMIT 1'
);
$res->bindValue(':hostId', $hostId, PDO::PARAM_INT);
$res->execute();
} else {
$res = $dbb->prepare(
'SELECT author, entry_time, comment_data, persistent_comment, sticky
FROM acknowledgements
WHERE host_id = :hostId
AND service_id = :svcId
ORDER BY entry_time DESC
LIMIT 1'
);
$res->bindValue(':hostId', $hostId, PDO::PARAM_INT);
$res->bindValue(':svcId', $svcId, PDO::PARAM_INT);
$res->execute();
}
$rowClass = 'list_one';
while ($row = $res->fetch()) {
$row['comment_data'] = strip_tags($row['comment_data']);
$xml->startElement('ack');
$xml->writeAttribute('class', $rowClass);
$xml->writeElement('author', $row['author']);
$xml->writeElement('entrytime', $row['entry_time']);
$xml->writeElement('comment', $row['comment_data']);
$xml->writeElement('persistent', $row['persistent_comment'] ? _('Yes') : _('No'));
$xml->writeElement('sticky', $row['sticky'] ? _('Yes') : _('No'));
$xml->endElement();
$rowClass = $rowClass === 'list_one' ? 'list_two' : 'list_one';
}
// End buffer
$xml->endElement();
header('Content-type: text/xml; charset=utf-8');
header('Cache-Control: no-cache, must-revalidate');
// Print Buffer
$xml->output();
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/objectDetails/hostDetails.php | centreon/www/include/monitoring/objectDetails/hostDetails.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($centreon)) {
exit();
}
include_once './class/centreonUtils.class.php';
include_once './class/centreonDB.class.php';
include_once './class/centreonHost.class.php';
include_once './class/centreonConfigEngine.php';
// Create Object env
$hostObj = new CentreonHost($pearDB);
// ACL Actions
$GroupListofUser = [];
$GroupListofUser = $centreon->user->access->getAccessGroups();
// Init Table status
$tab_status_service = ['0' => 'OK', '1' => 'WARNING', '2' => 'CRITICAL', '3' => 'UNKNOWN', '4' => 'PENDING'];
$tab_host_status = [0 => 'UP', 1 => 'DOWN', 2 => 'UNREACHABLE'];
$tab_host_statusid = ['UP' => 0, 'DOWN' => 1, 'UNREACHABLE' => 2];
$tab_color_host = ['up' => 'host_up', 'down' => 'host_down', 'unreachable' => 'host_unreachable'];
$tab_color_service = ['OK' => 'service_ok', 'WARNING' => 'service_warning', 'CRITICAL' => 'service_critical', 'UNKNOWN' => 'service_unknown', 'PENDING' => 'pending'];
$en_acknowledge_text = ['1' => _('Delete Problem Acknowledgement'), '0' => _('Acknowledge Host Problem')];
$en_acknowledge = ['1' => '0', '0' => '1'];
$en_inv = ['1' => '1', '0' => '0'];
$en_inv_text = ['1' => _('Disable'), '0' => _('Enable')];
$color_onoff = ['1' => 'host_up', '0' => 'host_down'];
$color_onoff_inv = ['0' => 'host_up', '1' => 'host_up'];
$en_disable = ['1' => _('Enabled'), '0' => _('Disabled')];
$img_en = ['0' => "'./img/icons/enabled.png'", '1' => "'./img/icons/disabled.png'"];
$tab_status_type = ['1' => 'HARD', '0' => 'SOFT'];
$allActions = false;
if (count($GroupListofUser) > 0 && $is_admin == 0) {
$authorized_actions = [];
$authorized_actions = $centreon->user->access->getActions();
}
if (isset($_GET['host_name']) && $_GET['host_name']) {
$host_name = $_GET['host_name'];
if (isset($_REQUEST['cmd'])) {
$host_name = mb_convert_encoding($host_name, 'ISO-8859-1');
}
} else {
foreach ($_GET['select'] as $key => $value) {
$host_name = $key;
}
}
// ACL
$haveAccess = 0;
if (! $is_admin) {
$DBRESULT = $pearDBO->query("SELECT host_id
FROM centreon_acl
WHERE host_id = '" . getMyHostId($host_name) . "'
AND group_id
IN (" . $centreon->user->access->getAccessGroupsString() . ')');
if ($DBRESULT->rowCount()) {
$haveAccess = 1;
}
}
if (! $is_admin && ! $haveAccess) {
include_once 'alt_error.php';
} else {
$tab_status = [];
$en = ['0' => _('No'), '1' => _('Yes')];
// Smarty template initialization
$path = './include/monitoring/objectDetails/';
$tpl = SmartyBC::createSmartyTemplate($path, './template/');
// Get GMT
$centreon->CentreonGMT->getMyGMTFromSession(session_id(), $pearDB);
// Host Group List
$host_id = getMyHostID($host_name);
if (! is_null($host_id)) {
// Get HG relations
$DBRESULT = $pearDB->query("SELECT DISTINCT hostgroup_hg_id
FROM hostgroup_relation
WHERE host_host_id = '" . $host_id . "'");
for ($i = 0; $hg = $DBRESULT->fetchRow(); $i++) {
$hostGroups[] = getMyHostGroupName($hg['hostgroup_hg_id']);
}
$DBRESULT->closeCursor();
// Get service categories
$hostIds = [$host_id];
$hostTemplates = $hostObj->getTemplateChain($host_id);
foreach ($hostTemplates as $hostTemplate) {
$hostIds[] = $hostTemplate['host_id'];
}
$DBRESULT = $pearDB->query("SELECT DISTINCT hc.*
FROM hostcategories hc
INNER JOIN hostcategories_relation hcr
ON hc.hc_id = hcr.hostcategories_hc_id
AND hcr.host_host_id IN ('" . implode("','", $hostIds) . "') ");
while ($hc = $DBRESULT->fetchRow()) {
$hostCategorie[] = $hc['hc_name'];
}
$DBRESULT->closeCursor();
// Get notifications contacts
$retrievedNotificationsInfos = getNotifiedInfosForHost($host_id, $dependencyInjector);
$contacts = $retrievedNotificationsInfos['contacts'];
$contactGroups = $retrievedNotificationsInfos['contactGroups'];
// Get services informations on the current Host
$rq = 'SELECT DISTINCT s.state AS current_state,'
. ' s.output as plugin_output,'
. ' s.check_attempt as current_attempt,'
. ' s.last_update as status_update_time,'
. ' s.last_state_change as last_state_change,'
. ' s.last_check,'
. ' s.notify AS notifications_enabled,'
. ' s.next_check,'
. ' s.acknowledged,'
. ' s.passive_checks,'
. ' s.active_checks,'
. ' s.event_handler_enabled,'
. ' s.flapping AS is_flapping,'
. ' s.latency as check_latency,'
. ' s.execution_time as check_execution_time,'
. ' s.last_notification as last_notification,'
. ' s.service_id as service_id,'
. ' h.name AS host_name,'
. ' h.host_id AS host_id,'
. ' s.scheduled_downtime_depth as in_downtime,'
. ' s.description as service_description'
. ' FROM services s, hosts h' . ((! $is_admin) ? ', centreon_acl acl' : '')
. ' WHERE s.host_id = h.host_id AND h.host_id = ' . $host_id . ' '
. ' AND h.enabled = 1 '
. ' AND s.enabled = 1 '
. ((! $is_admin) ? ' AND acl.host_id = s.host_id AND acl.service_id = s.service_id AND group_id IN ('
. $centreon->user->access->getAccessGroupsString() . ')' : '')
. ' ORDER BY current_state DESC, service_description ASC';
$DBRESULT = $pearDBO->query($rq);
$services = [];
$class = 'list_one';
$graphs = [];
while ($row = $DBRESULT->fetchRow()) {
$row['last_check'] = $centreon->CentreonGMT->getDate(_('Y/m/d - H:i:s'), $row['last_check']);
$row['current_state'] = $tab_status_service[$row['current_state']];
$row['status_class'] = $tab_color_service[$row['current_state']];
$row['line_class'] = $class;
// Split the plugin_output
$outputLines = explode(
"\n",
htmlentities($row['plugin_output'], ENT_QUOTES, 'UTF-8')
);
$row['short_output'] = $outputLines[0];
$row['hnl'] = CentreonUtils::escapeSecure(urlencode($row['host_name']));
$row['sdl'] = CentreonUtils::escapeSecure(urlencode($row['service_description']));
$row['svc_id'] = $row['service_id'];
/**
* Get Service Graph index
*/
if (! isset($graphs[$row['host_id']]) || ! isset($graphs[$row['host_id']][$row['service_id']])) {
$request2 = "SELECT service_id, id
FROM index_data, metrics
WHERE metrics.index_id = index_data.id
AND host_id = '" . $row['host_id'] . "'
AND service_id = '" . $row['service_id'] . "'
AND index_data.hidden = '0'";
$DBRESULT2 = $pearDBO->query($request2);
while ($dataG = $DBRESULT2->fetchRow()) {
if (! isset($graphs[$row['host_id']])) {
$graphs[$row['host_id']] = [];
}
$graphs[$row['host_id']][$dataG['service_id']] = $dataG['id'];
}
if (! isset($graphs[$row['host_id']])) {
$graphs[$row['host_id']] = [];
}
}
$row['svc_index'] = (
$graphs[$row['host_id']][$row['service_id']] ?? 0
);
$duration = '';
if ($row['last_state_change'] > 0 && time() > $row['last_state_change']) {
$duration = CentreonDuration::toString(time() - $row['last_state_change']);
} elseif ($row['last_state_change'] > 0) {
$duration = ' - ';
}
$row['duration'] = $duration;
$class = ($class == 'list_one') ? 'list_two' : 'list_one';
// Set Data
$services[] = $row;
}
$DBRESULT->closeCursor();
// Get host informations
$rq2 = 'SELECT state AS current_state, h.name, alias, h.address, host_id, '
. ' acknowledged AS problem_has_been_acknowledged, '
. ' passive_checks AS passive_checks_enabled,'
. ' active_checks AS active_checks_enabled,'
. ' notify AS notifications_enabled,'
. ' execution_time as check_execution_time,'
. ' latency as check_latency,'
. ' perfdata as performance_data,'
. ' check_attempt as current_attempt,'
. ' max_check_attempts, '
. ' state_type,'
. ' check_type,'
. ' last_notification,'
. ' next_host_notification AS next_notification,'
. ' flapping AS is_flapping,'
. ' h.flap_detection AS flap_detection_enabled,'
. ' event_handler_enabled,'
. ' obsess_over_host,'
. ' notification_number AS current_notification_number,'
. ' percent_state_change,'
. ' scheduled_downtime_depth,'
. ' last_state_change,'
. ' output as plugin_output,'
. ' last_check,'
. ' last_notification,'
. ' next_check,'
. ' h.address,'
. ' h.name AS host_name, '
. ' notes_url, '
. ' notes, '
. ' alias, '
. ' action_url, '
. ' h.timezone, '
. ' h.instance_id, '
. ' i.name as instance_name '
. ' FROM hosts h, instances i '
. " WHERE h.host_id = {$host_id} AND h.instance_id = i.instance_id "
. ' AND h.enabled = 1 ';
$DBRESULT = $pearDBO->query($rq2);
$data = $DBRESULT->fetchRow();
$host_status[$host_name] = [
'current_state' => '',
'name' => '',
'alias' => '',
'address' => '',
'host_id' => '',
'problem_has_been_acknowledged' => '',
'passive_checks_enabled' => '',
'active_checks_enabled' => '',
'notifications_enabled' => '',
'check_execution_time' => '',
'check_latency' => '',
'performance_data' => '',
'current_attempt' => '',
'max_check_attempts' => '',
'state_type' => '',
'check_type' => '',
'last_notification' => '',
'next_notification' => '',
'is_flapping' => '',
'flap_detection_enabled' => '',
'event_handler_enabled' => '',
'obsess_over_host' => '',
'current_notification_number' => '',
'percent_state_change' => '',
'scheduled_downtime_depth' => '',
'last_state_change' => '',
'plugin_output' => '',
'last_check' => '',
'next_check' => '',
'host_name' => '',
'notes_url' => '',
'notes' => '',
'action_url' => '',
'timezone' => '',
'instance_id' => '',
'instance_name' => '',
'comments' => '',
];
if (is_array($data)) {
$host_status[$host_name] = $data;
// Get host timezone
if (empty($host_status[$host_name]['timezone'])) {
$instanceObj = new CentreonConfigEngine($pearDB);
$host_status[$host_name]['timezone'] = $instanceObj->getTimezone(
$host_status[$host_name]['instance_id']
);
} else {
$host_status[$host_name]['timezone'] = substr($host_status[$host_name]['timezone'], 1);
}
$host_status[$host_name]['plugin_output'] = htmlentities(
$host_status[$host_name]['plugin_output'],
ENT_QUOTES,
'UTF-8'
);
$host_status[$host_name]['current_state'] = $tab_host_status[$data['current_state']] ?? '';
if (isset($host_status[$host_name]['notes_url']) && $host_status[$host_name]['notes_url']) {
$host_status[$host_name]['notes_url'] = str_replace(
'$HOSTNAME$',
$data['host_name'],
$data['notes_url']
);
$host_status[$host_name]['notes_url'] = str_replace(
'$HOSTADDRESS$',
$data['address'],
$data['notes_url']
);
$host_status[$host_name]['notes_url'] = str_replace(
'$HOSTALIAS$',
$data['alias'],
$data['notes_url']
);
}
if (isset($host_status[$host_name]['notes']) && $host_status[$host_name]['notes']) {
$host_status[$host_name]['notes'] = str_replace('$HOSTNAME$', $data['host_name'], $data['notes']);
$host_status[$host_name]['notes'] = str_replace('$HOSTADDRESS$', $data['address'], $data['notes']);
$host_status[$host_name]['notes'] = str_replace('$HOSTALIAS$', $data['alias'], $data['notes']);
}
if (isset($host_status[$host_name]['action_url']) && $host_status[$host_name]['action_url']) {
$host_status[$host_name]['action_url'] = str_replace(
'$HOSTNAME$',
$data['host_name'],
$data['action_url']
);
$host_status[$host_name]['action_url'] = str_replace(
'$HOSTADDRESS$',
$data['address'],
$data['action_url']
);
$host_status[$host_name]['action_url'] = str_replace(
'$HOSTALIAS$',
$data['alias'],
$data['action_url']
);
}
}
$url_id = null;
// Get comments for hosts
$tabCommentHosts = [];
$rq2 = 'SELECT cmt.entry_time as comment_time, cmt.comment_id, cmt.author AS author_name,
cmt.data AS comment_data, cmt.persistent AS is_persistent, h.name AS host_name '
. ' FROM comments cmt, hosts h '
. " WHERE cmt.host_id = '" . $host_id . "'
AND h.host_id = cmt.host_id
AND cmt.type = 1
AND cmt.expires = 0
AND (cmt.deletion_time IS NULL OR cmt.deletion_time = 0)
ORDER BY cmt.entry_time DESC";
$DBRESULT = $pearDBO->query($rq2);
for ($i = 0; $data = $DBRESULT->fetchRow(); $i++) {
$tabCommentHosts[$i] = $data;
$tabCommentHosts[$i]['is_persistent'] = $en[$tabCommentHosts[$i]['is_persistent']];
}
// We escaped all unauthorized HTML tags for comments
foreach ($tabCommentHosts as $index => $commentHost) {
$tabCommentHosts[$index]['comment_data']
= CentreonUtils::escapeAllExceptSelectedTags(
$commentHost['comment_data'],
['a', 'hr', 'br']
);
}
$DBRESULT->closeCursor();
unset($data);
// Get Graphs Listing
$graphLists = [];
$query = 'SELECT DISTINCT i.id, i.host_name, i.service_description, i.host_id, i.service_id '
. ' FROM index_data i, metrics m, hosts h, services s' . ((! $is_admin) ? ', centreon_acl acl' : '')
. ' WHERE m.index_id = i.id '
. " AND i.host_id = '{$host_id}' "
. ' AND i.host_id = h.host_id '
. ' AND h.enabled = 1 '
. ' AND i.host_id = s.host_id '
. ' AND i.service_id = s.service_id '
. ' AND s.enabled = 1 '
. ((! $is_admin) ? ' AND acl.host_id = i.host_id AND acl.service_id = i.service_id AND group_id IN ('
. $centreon->user->access->getAccessGroupsString() . ')' : '')
. ' ORDER BY i.service_description ASC';
$DBRESULT = $pearDBO->query($query);
while ($g = $DBRESULT->fetchRow()) {
$graphLists[$g['host_id'] . '_' . $g['service_id']] = $g['host_name'] . ';' . $g['service_description'];
}
$host_status[$host_name]['status_class']
= $tab_color_host[strtolower($host_status[$host_name]['current_state'])] ?? '';
if (! $host_status[$host_name]['next_check']) {
$host_status[$host_name]['next_check'] = '';
}
if (! $host_status[$host_name]['last_notification']) {
$host_status[$host_name]['last_notification'] = '';
}
if (! $host_status[$host_name]['next_notification']) {
$host_status[$host_name]['next_notification'] = '';
}
! $host_status[$host_name]['last_state_change']
? $host_status[$host_name]['duration'] = ''
: $host_status[$host_name]['duration']
= CentreonDuration::toString(time() - $host_status[$host_name]['last_state_change']);
if (! $host_status[$host_name]['last_state_change']) {
$host_status[$host_name]['last_state_change'] = '';
}
if ($host_status[$host_name]['problem_has_been_acknowledged']) {
$host_status[$host_name]['current_state'] .= ' <b>(' . _('ACKNOWLEDGED') . ')</b>';
}
if (! empty($host_status[$host_name]['state_type'])) {
$host_status[$host_name]['state_type'] = $tab_status_type[$host_status[$host_name]['state_type']];
}
if (! empty($host_status[$host_name]['is_flapping'])) {
$host_status[$host_name]['is_flapping'] = $en[$host_status[$host_name]['is_flapping']];
}
if (
isset($host_status[$host_name]['scheduled_downtime_depth'])
&& $host_status[$host_name]['scheduled_downtime_depth']
) {
$host_status[$host_name]['scheduled_downtime_depth'] = 1;
}
if (isset($hostDB)) {
$host_status[$host_name]['comments'] = $hostDB['host_comment'];
}
if (isset($tab_host_service[$host_name]) && count($tab_host_service[$host_name])) {
foreach ($tab_host_service[$host_name] as $key_name => $s) {
if (! isset($tab_status[$service_status[$host_name . '_' . $key_name]['current_state']])) {
$tab_status[$service_status[$host_name . '_' . $key_name]['current_state']] = 0;
}
$tab_status[$service_status[$host_name . '_' . $key_name]['current_state']]++;
}
}
$status = null;
if (isset($tab_status)) {
foreach ($tab_status as $key => $value) {
$status .= '&value[' . $key . ']=' . $value;
}
}
$tpl->assign('m_mon_host', _('Host'));
$tpl->assign('m_mon_host_info', _('Status Details'));
$tpl->assign('m_mon_host_poller', _('Poller'));
$tpl->assign('m_mon_host_poller_name', _('Name'));
$tpl->assign('m_mon_host_services', _('Services'));
$tpl->assign('header_service_description', _('Services'));
$tpl->assign('header_service_status', _('Status'));
$tpl->assign('header_service_duration', _('Duration'));
$tpl->assign('header_service_output', _('Ouput'));
$tpl->assign('m_mon_host_status', _('Host Status'));
$tpl->assign('m_mon_host_status_info', _('Status information'));
$tpl->assign('m_mon_performance_data', _('Performance Data'));
$tpl->assign('m_mon_current_attempt', _('Current Attempt'));
$tpl->assign('m_mon_state_type', _('State Type'));
$tpl->assign('m_mon_host_last_check', _('Last Check'));
$tpl->assign('m_mon_state_type', _('State Type'));
$tpl->assign('m_mon_next_check', _('Next Check'));
$tpl->assign('m_mon_check_latency', _('Latency'));
$tpl->assign('m_mon_check_execution_time', _('Execution Time'));
$tpl->assign('m_mon_last_change', _('Last State Change'));
$tpl->assign('m_mon_current_state_duration', _('Current State Duration'));
$tpl->assign('m_mon_last_notification', _('Last Notification'));
$tpl->assign('m_mon_next_notification', _('Next Notification'));
$tpl->assign('m_mon_notification_nb', _('Current Notification Number'));
$tpl->assign('m_mon_host_flapping', _('Is This Host Flapping?'));
$tpl->assign('m_mon_percent_state_change', _('Percent State Change'));
$tpl->assign('m_mon_downtime_sc', _('In Scheduled Downtime?'));
$tpl->assign('m_mon_last_update', _('Last Update'));
$tpl->assign('cmt_host_name', _('Host Name'));
$tpl->assign('cmt_entry_time', _('Entry Time'));
$tpl->assign('cmt_author', _('Author'));
$tpl->assign('cmt_comment', _('Comments'));
$tpl->assign('cmt_persistent', _('Persistent'));
$tpl->assign('cmt_actions', _('Actions'));
$tpl->assign('options', _('Options'));
$tpl->assign('hosts_command', _('Host Commands'));
$tpl->assign('m_mon_SCH_downtime', _('Schedule downtime for this host'));
$tpl->assign('m_mon_add_comment', _('Add Comment for this host'));
$tpl->assign('m_mon_disable_not_all_services', _('Disable all service notifications on this host'));
$tpl->assign('m_mon_enable_not_all_services', _('Enable all service notifications on this host'));
$tpl->assign('m_mon_SCH_immediate_check', _('Schedule an immediate check of all services on this host'));
$tpl->assign(
'm_mon_SCH_immediate_check_f',
_('Schedule an immediate check of all services on this host (forced)')
);
$tpl->assign('m_mon_diable_check_all_svc', _('Disable all service checks on this host'));
$tpl->assign('m_mon_enable_check_all_svc', _('Enable all service checks on this host'));
$tpl->assign('m_mon_acknowledge', _('Acknowledge problem'));
$tpl->assign('seconds', _('seconds'));
$tpl->assign('links', _('Links'));
$tpl->assign('notifications', _('Notifications'));
$tpl->assign('notified', _('Notified'));
$tpl->assign('m_mon_host_comment', _('Comments'));
$tpl->assign('m_mon_obsess_over_host', _('Obsess Over Host'));
$tpl->assign('m_mon_check_this_host', _('Active Checks'));
$tpl->assign('m_mon_host_checks_active', _('Active Checks'));
$tpl->assign('m_mon_host_checks_passive', _('Passive Checks'));
$tpl->assign('m_mon_passive_check_this_host', _('Passive Checks'));
$tpl->assign('m_mon_host_notification', _('Notifications'));
$tpl->assign('m_mon_notify_this_host', _('Notifications'));
$tpl->assign('m_mon_event_handler', _('Event Handler'));
$tpl->assign('m_mon_ed_event_handler', _('Event Handler'));
$tpl->assign('m_mon_ed_flapping_detect', _('Flap Detection'));
$tpl->assign('m_mon_flap_detection', _('Flap Detection'));
$tpl->assign('m_mon_services_en_acknowledge', _('Acknowledged'));
$tpl->assign('m_mon_submit_passive', _('Submit result for this host'));
// Strings are used by javascript command handler
$str_check_host_enable = _('Enable Active Checks');
$str_check_host_disable = _('Disable Active Checks');
$str_passive_check_host_enable = _('Enable Passive Checks');
$str_passive_check_host_disable = _('Disable Passive Checks');
$str_notif_host_enable = _('Enable Host Notifications');
$str_notif_host_disable = _('Disable Host Notifications');
$str_handler_host_enable = _('Enable Event Handler');
$str_handler_host_disable = _('Disable Event Handler');
$str_flap_host_enable = _('Enable Flap Detection');
$str_flap_host_disable = _('Disable Flap Detection');
$str_obsess_host_enable = _('Enable Obsess Over Host');
$str_obsess_host_disable = _('Disable Obsess Over Host');
// Add Tips
$tpl->assign('lnk_all_services', sprintf(_('View status of all services on host %s'), $host_name));
$tpl->assign('lnk_host_graphs', sprintf(_('View graphs for host %s'), $host_name));
$tpl->assign('lnk_host_config', sprintf(_('Configure host %s'), $host_name));
$tpl->assign('lnk_host_reports', sprintf(_('View report for host %s'), $host_name));
$tpl->assign('lnk_host_logs', sprintf(_('View logs for host %s'), $host_name));
/*
* if user is admin, allActions is true,
* else we introduce all actions allowed for user
*/
if (isset($authorized_actions)) {
$tpl->assign('aclAct', $authorized_actions);
}
$tpl->assign('p', $p);
$tpl->assign('en', $en);
$tpl->assign('en_inv', $en_inv);
$tpl->assign('en_inv_text', $en_inv_text);
$tpl->assign('img_en', $img_en);
$tpl->assign('color_onoff', $color_onoff);
$tpl->assign('color_onoff_inv', $color_onoff_inv);
$tpl->assign('en_disable', $en_disable);
$tpl->assign('status', $status);
$tpl->assign('en_acknowledge_text', $en_acknowledge_text);
$tpl->assign('en_acknowledge', $en_acknowledge);
$tpl->assign('admin', $is_admin);
$tpl->assign('lcaTopo', $centreon->user->access->topology);
if (isset($hostDB)) {
$tpl->assign('h', CentreonUtils::escapeSecure($hostDB));
}
$tpl->assign('url_id', $url_id);
$tpl->assign('host_id', $host_id);
$tpl->assign('graphs', $graphLists);
$tpl->assign('m_mon_ticket', 'Open Ticket');
$tpl->assign('start', time() - 3600 * 12);
$tpl->assign('end', time());
// Hostgroups Display
$tpl->assign('hostgroups_label', _('Member of Host Groups'));
$tpl->assign('hostgroups', []);
if (isset($hostGroups)) {
$tpl->assign('hostgroups', CentreonUtils::escapeSecure($hostGroups));
}
$tpl->assign('hostcategorie_label', _('Host Categories'));
$tpl->assign('hostcategorie', []);
if (isset($hostCategorie)) {
$tpl->assign('hostcategorie', $hostCategorie);
}
$tpl->assign('hosts_services', $services);
// Contactgroups Display
$tpl->assign('contactgroups_label', _('Contact groups notified for this host'));
$tpl->assign('contactgroups', []);
if (isset($contactGroups)) {
$tpl->assign('contactgroups', CentreonUtils::escapeSecure($contactGroups));
}
// Contacts Display
$tpl->assign('contacts_label', _('Contacts notified for this host'));
$tpl->assign('contacts', []);
if (isset($contacts)) {
$tpl->assign('contacts', CentreonUtils::escapeSecure($contacts));
}
$tpl->assign('tab_comments_host', []);
if (isset($tabCommentHosts)) {
$tpl->assign(
'tab_comments_host',
array_map(
['CentreonUtils', 'escapeSecure'],
$tabCommentHosts
)
);
}
$tpl->assign('host_data', $host_status[$host_name]);
// Ext informations
$notesurl = getMyHostExtendedInfoField($host_id, 'ehi_notes_url');
$notesurl = $hostObj->replaceMacroInString($host_id, $notesurl);
if (isset($host_status[$host_name]['instance_name'])) {
$notesurl = str_replace('$INSTANCENAME$', $host_status[$host_name]['instance_name'], $notesurl);
}
$notesurl = str_replace('$HOSTSTATE$', $host_status[$host_name]['current_state'], $notesurl);
$notesurl = str_replace(
'$HOSTSTATEID$',
$tab_host_statusid[$host_status[$host_name]['current_state']] ?? '',
$notesurl
);
$tpl->assign('h_ext_notes_url', CentreonUtils::escapeSecure($notesurl));
$tpl->assign('h_ext_notes', CentreonUtils::escapeSecure(getMyHostExtendedInfoField($host_id, 'ehi_notes')));
$tpl->assign('h_ext_notes_url_lang', _('URL Notes'));
$tpl->assign('h_ext_action_url_lang', _('Action URL'));
$actionurl = getMyHostExtendedInfoField($host_id, 'ehi_action_url');
$actionurl = $hostObj->replaceMacroInString($host_id, $actionurl);
if (isset($host_status[$host_name]['instance_name'])) {
$actionurl = str_replace('$INSTANCENAME$', $host_status[$host_name]['instance_name'], $actionurl);
}
$actionurl = str_replace('$HOSTSTATE$', $host_status[$host_name]['current_state'], $actionurl);
$actionurl = str_replace(
'$HOSTSTATEID$',
$tab_host_statusid[$host_status[$host_name]['current_state']] ?? '',
$actionurl
);
$tpl->assign('h_ext_action_url', CentreonUtils::escapeSecure($actionurl));
if (isset($hostDB)) {
$tpl->assign('h_ext_icon_image', getMyHostExtendedInfoField($hostDB['host_id'], 'ehi_icon_image'));
$tpl->assign('h_ext_icon_image_alt', getMyHostExtendedInfoField($hostDB['host_id'], 'ehi_icon_image_alt'));
}
// Check if central or remote server
$DBRESULT = $pearDB->query("SELECT `value` FROM `informations` WHERE `key` = 'isRemote'");
$result = $DBRESULT->fetchRow();
if ($result === false) {
$isRemote = false;
} else {
$isRemote = array_map('myDecode', $result);
$isRemote = ($isRemote['value'] === 'yes') ? true : false;
}
$DBRESULT->closeCursor();
$tpl->assign('isRemote', $isRemote);
/**
* Build the host detail URI that will be used in the
* deprecated banner
*/
$kernel = App\Kernel::createForWeb();
$resourceController = $kernel->getContainer()->get(
Centreon\Application\Controller\MonitoringResourceController::class
);
$deprecationMessage = _('[Page deprecated] This page will be removed in the next major version. Please use the new page: ');
$resourcesStatusLabel = _('Resources Status');
$redirectionUrl = $resourceController->buildHostDetailsUri($host_id);
$tpl->display('hostDetails.ihtml');
} else {
echo "<div class='msg' align='center'>"
. _('This host no longer exists in Centreon configuration. Please reload the configuration.') . '</div>';
}
}
?>
<script>
<?php
$tFM = 0;
$time = time();
require_once _CENTREON_PATH_ . 'www/include/monitoring/status/Common/commonJS.php';
?>
</script>
<?php if (! is_null($host_id)) { ?>
<?php require_once _CENTREON_PATH_ . 'www/class/centreonMsg.class.php'; ?>
<script type="text/javascript">
var glb_confirm = '<?php echo _('Submit command?'); ?>';
var command_sent = '<?php echo _('Command sent'); ?>';
var command_failure = "<?php echo _('Failed to execute command'); ?>";
var host_id = '<?php echo $hostObj->getHostId($host_name); ?>';
var labels = new Array();
display_deprecated_banner();
labels['host_checks'] = new Array(
"<?php echo $str_check_host_enable; ?>",
"<?php echo $str_check_host_disable; ?>",
"<?php echo $img_en[0]; ?>",
"<?php echo $img_en[1]; ?>"
);
labels['host_notifications'] = new Array(
"<?php echo $str_notif_host_enable; ?>",
"<?php echo $str_notif_host_disable; ?>",
"<?php echo $img_en[0]; ?>",
"<?php echo $img_en[1]; ?>"
);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | true |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/objectDetails/serviceDetails.php | centreon/www/include/monitoring/objectDetails/serviceDetails.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\Domain\Monitoring\Exception\MonitoringServiceException;
if (! isset($centreon)) {
exit();
}
include_once './class/centreonUtils.class.php';
include_once './class/centreonDB.class.php';
include_once './class/centreonHost.class.php';
include_once './class/centreonService.class.php';
include_once './class/centreonMeta.class.php';
// We initialize the kernel of Symfony to retrieve its container.
include_once $centreon_path . 'config/bootstrap.php';
$kernel = new App\Kernel('prod', false);
$kernel->boot();
$container = $kernel->getContainer();
$monitoringService = $container->get(Centreon\Domain\Monitoring\Interfaces\MonitoringServiceInterface::class);
$contactService = $container->get(Centreon\Domain\Contact\Interfaces\ContactServiceInterface::class);
$contact = $contactService->findBySession(session_id());
if ($contact !== null) {
$monitoringService->filterByContact($contact);
}
// Create Object env
$hostObj = new CentreonHost($pearDB);
$svcObj = new CentreonService($pearDB);
$metaObj = new CentreonMeta($pearDB);
// ACL Actions
$GroupListofUser = [];
$GroupListofUser = $centreon->user->access->getAccessGroups();
$allActions = false;
// Get list of actions allowed for user
$authorized_actions = [
'service_schedule_check' => '',
'service_schedule_forced_check' => '',
'service_schedule_downtime' => '',
'service_comment' => '',
'service_submit_result' => '',
'service_checks' => '',
'service_passive_checks' => '',
'service_notifications' => '',
'service_event_handler' => '',
'service_flap_detection' => '',
'global_service_obsess' => '',
'service_acknowledgement' => '',
'service_disacknowledgement' => '',
];
if (count($GroupListofUser) > 0 && $is_admin == 0) {
$authorized_actions = $centreon->user->access->getActions();
}
if (
! empty($_GET['host_name'])
&& ! empty($_GET['service_description'])
) {
$host_name = $_GET['host_name'];
$svc_description = $_GET['service_description'];
} else {
foreach ($_GET['select'] as $key => $value) {
$tab_data = preg_split("/\;/", $key);
}
$host_name = $tab_data[0];
$svc_description = $tab_data[1];
}
// Check if host is found
$host_id = getMyHostID($host_name);
if (! is_null($host_id)) {
$can_display = 1;
$service_id = getMyServiceID($svc_description, $host_id);
if (! isset($service_id)) {
$service_id = getMyServiceIDStorage($svc_description, $host_id);
}
// Define if the service is a metaservice
$isMetaservice = 'false';
$meta_id = $service_id;
if ($host_name == '_Module_Meta') {
$isMetaservice = 'true';
if (preg_match('/meta_(\d+)/', $svc_description, $matches)) {
$meta_id = $matches[1];
}
}
if (! $is_admin) {
$lcaHost['LcaHost'] = $centreon->user->access->getHostServicesName($pearDBO, $host_name);
if (! isset($lcaHost['LcaHost'][$service_id])) {
$can_display = 0;
}
}
if ($can_display == 0) {
include_once '../errors/alt_error.php';
} else {
// Get Hostgroup List
$hgrStatement = $pearDB->prepare('SELECT DISTINCT hostgroup_hg_id FROM hostgroup_relation '
. 'WHERE host_host_id = :hostId '
. $centreon->user->access->queryBuilder(
'AND',
'host_host_id',
$centreon->user->access->getHostsString('ID', $pearDBO)
));
$hgrStatement->bindValue(':hostId', (int) $host_id, PDO::PARAM_INT);
$hgrStatement->execute();
for ($i = 0; $hg = $hgrStatement->fetch(PDO::FETCH_ASSOC); $i++) {
$hostGroups[] = getMyHostGroupName($hg['hostgroup_hg_id']);
}
if (isset($service_id) && $service_id) {
$proc_warning = getMyServiceMacro($service_id, 'PROC_WARNING');
$proc_critical = getMyServiceMacro($service_id, 'PROC_CRITICAL');
}
// Get notifications contacts
$retrievedNotificationsInfos = getNotifiedInfosForService($service_id, $host_id, $dependencyInjector);
$contacts = $retrievedNotificationsInfos['contacts'];
$contactGroups = $retrievedNotificationsInfos['contactGroups'];
// Get servicegroups list
if (isset($service_id, $host_id)) {
$sgStatement = $pearDB->prepare('SELECT DISTINCT sg.sg_name FROM servicegroup sg, servicegroup_relation sgr '
. 'WHERE sgr.servicegroup_sg_id = sg.sg_id AND sgr.host_host_id = :hostId '
. ' AND sgr.service_service_id = :serviceId '
. $centreon->user->access->queryBuilder(
'AND',
'sgr.host_host_id',
$centreon->user->access->getHostsString('ID', $pearDBO)
));
$sgStatement->bindValue(':hostId', (int) $host_id, PDO::PARAM_INT);
$sgStatement->bindValue(':serviceId', (int) $service_id, PDO::PARAM_INT);
$sgStatement->execute();
while ($row = $sgStatement->fetch(PDO::FETCH_ASSOC)) {
$serviceGroups[] = $row['sg_name'];
}
}
// Get service category
$tab_sc = getMyServiceCategories($service_id);
if (is_array($tab_sc)) {
foreach ($tab_sc as $sc_id) {
$serviceCategories[] = getMyCategorieName($sc_id);
}
}
$tab_status = [];
// Get all service information
$rq = 'SELECT s.service_id, '
. ' s.state AS current_state,'
. ' s.output as plugin_output, '
. ' s.output as plugin_output2,'
. ' s.check_attempt as current_attempt,'
. ' s.last_update as status_update_time,'
. ' s.last_state_change,'
. ' s.last_check,'
. ' s.last_time_ok,'
. ' s.last_time_warning,'
. ' s.last_time_critical,'
. ' s.last_time_unknown,'
. ' s.notify AS notifications_enabled,'
. ' s.next_check,'
. ' s.acknowledged AS problem_has_been_acknowledged,'
. ' s.passive_checks AS passive_checks_enabled,'
. ' s.active_checks AS active_checks_enabled,'
. ' s.event_handler_enabled,'
. ' s.perfdata as performance_data,'
. ' s.flapping AS is_flapping,'
. ' s.scheduled_downtime_depth,'
. ' s.percent_state_change,'
. ' s.notification_number AS current_notification_number,'
. ' s.obsess_over_service,'
. ' s.check_type,'
. ' s.check_command,'
. ' s.state_type,'
. ' s.latency as check_latency,'
. ' s.execution_time as check_execution_time,'
. ' s.flap_detection AS flap_detection_enabled,'
. ' s.last_notification as last_notification,'
. ' h.name AS host_name,'
. ' s.description as service_description, '
. ' s.display_name, '
. ' s.notes_url, '
. ' s.notes, '
. ' s.action_url, '
. ' i.name as instance_name '
. ' FROM services s, hosts h, instances i '
. ' WHERE h.host_id = s.host_id '
. ' AND h.host_id LIKE :hostId '
. ' AND s.service_id LIKE :serviceId '
. ' AND h.instance_id = i.instance_id'
. ' AND h.enabled = 1 '
. ' AND s.enabled = 1 ';
$shiStatement = $pearDBO->prepare($rq);
$shiStatement->bindValue(':hostId', (int) $host_id, PDO::PARAM_INT);
$shiStatement->bindValue(':serviceId', (int) $service_id, PDO::PARAM_INT);
$shiStatement->execute();
$tab_status_service = [0 => 'OK', 1 => 'WARNING', 2 => 'CRITICAL', 3 => 'UNKNOWN', 4 => 'PENDING'];
$tab_class_service = ['ok' => 'service_ok', 'warning' => 'service_warning', 'critical' => 'service_critical', 'unknown' => 'service_unknown', 'pending' => 'pending'];
$service_status = [
'service_id' => '',
'current_state' => '',
'plugin_output' => '',
'plugin_output2' => '',
'current_attempt' => '',
'status_update_time' => '',
'last_state_change' => '',
'last_check' => '',
'last_time_ok' => '',
'last_time_warning' => '',
'last_time_critical' => '',
'last_time_unknown' => '',
'notifications_enabled' => '',
'next_check' => '',
'problem_has_been_acknowledged' => '',
'passive_checks_enabled' => '',
'active_checks_enabled' => '',
'event_handler_enabled' => '',
'performance_data' => '',
'is_flapping' => '',
'scheduled_downtime_depth' => '',
'percent_state_change' => '',
'current_notification_number' => '',
'obsess_over_service' => '',
'check_type' => '',
'check_command' => '',
'state_type' => '',
'check_latency' => '',
'check_execution_time' => '',
'flap_detection_enabled' => '',
'last_notification' => '',
'host_name' => '',
'service_description' => '',
'display_name' => '',
'notes_url' => '',
'notes' => '',
'action_url' => '',
'instance_name' => '',
'command_line' => '',
'current_stateid' => '',
'status_color' => '',
'status_class' => '',
'notification' => '',
'next_notification' => '',
'long_plugin_output' => '',
'duration' => '',
];
while ($data = $shiStatement->fetch(PDO::FETCH_ASSOC)) {
if (isset($data['performance_data'])) {
$data['performance_data'] = $data['performance_data'];
}
if ($data['current_state'] === null || ! in_array($data['current_state'], array_keys($tab_status_service))) {
$data['current_state'] = 4; // default to PENDING
}
if ($data['service_description'] == $svc_description) {
$service_status = $data;
}
if (! isset($tab_status[$tab_status_service[$data['current_state']]])) {
$tab_status[$tab_status_service[$data['current_state']]] = 0;
}
$tab_status[$tab_status_service[$data['current_state']]]++;
}
if ($is_admin || isset($authorized_actions['service_display_command'])) {
$commandLine = '';
try {
$commandLine = $monitoringService->findCommandLineOfService(
(int) $host_id,
(int) $service_status['service_id']
);
} catch (MonitoringServiceException $ex) {
$commandLine = 'Error: ' . $ex->getMessage();
}
$service_status['command_line'] = $commandLine;
}
$service_status['current_stateid'] = $service_status['current_state'];
if ($service_status['current_state'] !== '') {
$service_status['current_state'] = $tab_status_service[$service_status['current_state']];
}
// Get Host informations
$hStatement = $pearDB->prepare('SELECT * FROM host WHERE host_id = :hostId');
$hStatement->bindValue(':hostId', (int) $host_id, PDO::PARAM_INT);
$hStatement->execute();
$host = $hStatement->fetch(PDO::FETCH_ASSOC);
if ($isMetaservice == 'true') {
$metaParameters = $metaObj->getParameters($meta_id, ['max_check_attempts']);
$total_current_attempts = $metaParameters['max_check_attempts'];
} else {
$total_current_attempts = getMyServiceField($service_id, 'service_max_check_attempts');
}
// Smarty template initialization
$path = './include/monitoring/objectDetails/';
$tpl = SmartyBC::createSmartyTemplate($path, './template/');
$en = ['0' => _('No'), '1' => _('Yes')];
// Get comments for service
$tabCommentServices = [];
if (isset($host_id, $service_id)) {
$rq2 = ' SELECT DISTINCT cmt.entry_time as entry_time, cmt.comment_id, '
. 'cmt.author AS author_name, cmt.data AS comment_data, cmt.persistent AS is_persistent, '
. 'h.name AS host_name, s.description AS service_description '
. ' FROM comments cmt, hosts h, services s '
. ' WHERE h.host_id = ' . $pearDBO->escape($host_id)
. ' AND h.host_id = s.host_id '
. 'AND s.service_id = ' . $pearDBO->escape($service_id)
. ' AND h.host_id = cmt.host_id '
. 'AND s.service_id = cmt.service_id '
. 'AND cmt.expires = 0 '
. 'AND (cmt.deletion_time IS NULL OR cmt.deletion_time = 0) '
. 'ORDER BY cmt.entry_time DESC';
$DBRESULT = $pearDBO->query($rq2);
for ($i = 0; $data = $DBRESULT->fetchRow(); $i++) {
$tabCommentServices[$i] = $data;
$tabCommentServices[$i]['host_name'] = $data['host_name'];
$tabCommentServices[$i]['service_description'] = $data['service_description'];
$tabCommentServices[$i]['comment_data']
= CentreonUtils::escapeAllExceptSelectedTags(
$data['comment_data'],
['a', 'hr', 'br']
);
$tabCommentServices[$i]['is_persistent'] = $en[$tabCommentServices[$i]['is_persistent']];
}
$DBRESULT->closeCursor();
unset($data);
}
$en_acknowledge_text = ['1' => _('Delete Problem Acknowledgement'), '0' => _('Acknowledge Service Problem')];
$en_acknowledge = ['1' => '0', '0' => '1'];
$en_disable = ['1' => _('Enabled'), '0' => _('Disabled')];
$en_inv = ['1' => '1', '0' => '0'];
$en_inv_text = ['1' => _('Disable'), '0' => _('Enable')];
$color_onoff = ['1' => '#88b917', '0' => '#e00b3d'];
$color_onoff_inv = ['0' => '#F7FAFF', '1' => '#E7C9FF'];
$img_en = ['0' => "'./img/icons/enabled.png'", '1' => "'./img/icons/disabled.png'"];
// Ajust data for beeing displayed in template
$centreon->CentreonGMT->getMyGMTFromSession(session_id(), $pearDB);
$service_status['command_line'] = str_replace(' -', "\n\t-", $service_status['command_line']);
$service_status['performance_data'] = CentreonUtils::escapeAll(
str_replace(' \'', "\n'", $service_status['performance_data'])
);
if ($service_status['current_state'] !== '') {
$service_status['status_class'] = $tab_class_service[strtolower($service_status['current_state'])];
}
! $service_status['check_latency']
? $service_status['check_latency'] = '< 1 second'
: $service_status['check_latency'] = $service_status['check_latency'] . ' seconds';
! $service_status['check_execution_time']
? $service_status['check_execution_time'] = '< 1 second'
: $service_status['check_execution_time'] = $service_status['check_execution_time'] . ' seconds';
if (! $service_status['last_notification']) {
$service_status['notification'] = '';
}
if (isset($service_status['next_notification']) && ! $service_status['next_notification']) {
$service_status['next_notification'] = '';
} elseif (! isset($service_status['next_notification'])) {
$service_status['next_notification'] = 'N/A';
}
$service_status['long_plugin_output'] = '';
$service_status['plugin_output2'] = str_replace("\n", '\n', $service_status['plugin_output2']);
$outputTmp = explode('\n', $service_status['plugin_output2']);
if ($outputTmp !== []) {
$i = 0;
while (isset($outputTmp[$i])) {
if (! $i) {
$service_status['plugin_output'] = htmlentities($outputTmp[$i], ENT_QUOTES, 'UTF-8') . '<br />';
} else {
$service_status['long_plugin_output']
.= htmlentities($outputTmp[$i], ENT_QUOTES, 'UTF-8') . '<br />';
}
$i++;
}
}
$service_status['plugin_output'] = str_replace("'", '', $service_status['plugin_output']);
$service_status['plugin_output'] = str_replace('"', '', $service_status['plugin_output']);
$service_status['plugin_output'] = str_replace('\\n', '<br>', $service_status['plugin_output']);
$service_status['plugin_output'] = str_replace('\n', '<br>', $service_status['plugin_output']);
// Added for long_plugin_output <gavinw>
if (isset($service_status['long_plugin_output'])) {
$service_status['long_plugin_output'] = str_replace('<b>', '', $service_status['long_plugin_output']);
$service_status['long_plugin_output'] = str_replace('</b>', '', $service_status['long_plugin_output']);
$service_status['long_plugin_output'] = str_replace('<br>', '', $service_status['long_plugin_output']);
$service_status['long_plugin_output'] = str_replace("'", '', $service_status['long_plugin_output']);
$service_status['long_plugin_output'] = str_replace('"', '', $service_status['long_plugin_output']);
$service_status['long_plugin_output'] = str_replace('\n', '<br />', $service_status['long_plugin_output']);
}
if (isset($service_status['notes_url']) && $service_status['notes_url']) {
$service_status['notes_url'] = str_replace('$HOSTNAME$', $host_name, $service_status['notes_url']);
$service_status['notes_url'] = str_replace(
'$SERVICEDESC$',
$svc_description,
$service_status['notes_url']
);
$service_status['notes_url'] = str_replace(
'$SERVICESTATE$',
$service_status['current_state'],
$service_status['notes_url']
);
$service_status['notes_url'] = str_replace(
'$SERVICESTATEID$',
$service_status['current_stateid'],
$service_status['notes_url']
);
if ($host_id) {
$service_status['notes_url'] = str_replace(
'$HOSTALIAS$',
$hostObj->getHostAlias($host_id),
$service_status['notes_url']
);
$service_status['notes_url'] = str_replace(
'$HOSTADDRESS$',
$hostObj->getHostAddress($host_id),
$service_status['notes_url']
);
}
}
if (isset($service_status['action_url']) && $service_status['action_url']) {
$service_status['action_url'] = str_replace('$HOSTNAME$', $host_name, $service_status['action_url']);
$service_status['action_url'] = str_replace(
'$SERVICEDESC$',
$svc_description,
$service_status['action_url']
);
$service_status['action_url'] = str_replace(
'$SERVICESTATE$',
$service_status['current_state'],
$service_status['action_url']
);
$service_status['action_url'] = str_replace(
'$SERVICESTATEID$',
$service_status['current_stateid'],
$service_status['action_url']
);
if ($host_id) {
$service_status['action_url'] = str_replace(
'$HOSTALIAS$',
$hostObj->getHostAlias($host_id),
$service_status['action_url']
);
$service_status['action_url'] = str_replace(
'$HOSTADDRESS$',
$hostObj->getHostAddress($host_id),
$service_status['action_url']
);
}
}
$service_status['plugin_output'] = $service_status['plugin_output'];
$service_status['plugin_output'] = str_replace("'", '', $service_status['plugin_output']);
$service_status['plugin_output'] = str_replace('"', '', $service_status['plugin_output']);
$service_status['plugin_output'] = str_replace('\\n', '<br>', $service_status['plugin_output']);
$service_status['plugin_output'] = str_replace('\n', '<br>', $service_status['plugin_output']);
// Added for long_plugin_output <gavinw>
if (isset($service_status['long_plugin_output'])) {
$service_status['long_plugin_output'] = str_replace('<b>', '', $service_status['long_plugin_output']);
$service_status['long_plugin_output'] = str_replace('</b>', '', $service_status['long_plugin_output']);
$service_status['long_plugin_output'] = str_replace('<br>', '', $service_status['long_plugin_output']);
$service_status['long_plugin_output'] = str_replace("'", '', $service_status['long_plugin_output']);
$service_status['long_plugin_output'] = str_replace('"', '', $service_status['long_plugin_output']);
$service_status['long_plugin_output'] = str_replace('\n', '<br />', $service_status['long_plugin_output']);
}
if (isset($service_status['notes_url']) && $service_status['notes_url']) {
$service_status['notes_url'] = str_replace('$HOSTNAME$', $host_name, $service_status['notes_url']);
$service_status['notes_url'] = str_replace(
'$SERVICEDESC$',
$svc_description,
$service_status['notes_url']
);
if ($host_id) {
$service_status['notes_url'] = str_replace(
'$HOSTALIAS$',
$hostObj->getHostAlias($host_id),
$service_status['notes_url']
);
$service_status['notes_url'] = str_replace(
'$HOSTADDRESS$',
$hostObj->getHostAddress($host_id),
$service_status['notes_url']
);
}
}
if (isset($service_status['action_url']) && $service_status['action_url']) {
$service_status['action_url'] = str_replace('$HOSTNAME$', $host_name, $service_status['action_url']);
$service_status['action_url'] = str_replace(
'$SERVICEDESC$',
$svc_description,
$service_status['action_url']
);
if ($host_id) {
$service_status['action_url'] = str_replace(
'$HOSTALIAS$',
$hostObj->getHostAlias($host_id),
$service_status['action_url']
);
$service_status['action_url'] = str_replace(
'$HOSTADDRESS$',
$hostObj->getHostAddress($host_id),
$service_status['action_url']
);
}
}
$service_status['duration'] = '';
if (isset($service_status['last_time_' . strtolower($service_status['current_state'])])) {
! $service_status['last_state_change']
? $service_status['duration']
= CentreonDuration::toString($service_status['last_time_' . strtolower($service_status['current_state'])])
: $service_status['duration']
= centreonDuration::toString(time() - $service_status['last_state_change']);
}
if (! $service_status['last_state_change']) {
$service_status['last_state_change'] = '';
}
$service_status['is_flapping']
? $service_status['is_flapping'] = $en[$service_status['is_flapping']]
: $service_status['is_flapping'] = 'N/A';
if ($service_status['problem_has_been_acknowledged']) {
$service_status['current_state'] .= ' <b>(' . _('ACKNOWLEDGED') . ')</b>';
}
if (isset($service_status['scheduled_downtime_depth']) && $service_status['scheduled_downtime_depth']) {
$service_status['scheduled_downtime_depth'] = 1;
}
$status = null;
foreach ($tab_status as $key => $value) {
$status .= '&value[' . $key . ']=' . $value;
}
$query = 'SELECT id FROM `index_data`, `metrics` WHERE host_name = :host_name'
. ' AND service_description = :svc_description AND id = index_id LIMIT 1';
$statement = $pearDBO->prepare($query);
$statement->bindValue(':host_name', $host_name, PDO::PARAM_STR);
$statement->bindValue(':svc_description', $svc_description, PDO::PARAM_STR);
$statement->execute();
$index_data = 0;
if ($statement->rowCount()) {
$row = $statement->fetchRow();
$index_data = $row['id'];
}
// Assign translations
if ($isMetaservice == 'false') {
$tpl->assign('m_mon_services', _('Service'));
} else {
$tpl->assign('m_mon_services', _('Meta Service'));
}
$tpl->assign('m_mon_status_info', _('Status Details'));
$tpl->assign('m_mon_on_host', _('on host'));
$tpl->assign('m_mon_services_status', _('Service Status'));
$tpl->assign('m_mon_host_status_info', _('Status information'));
$tpl->assign('m_mon_host_long_info', _('Extended status information'));
$tpl->assign('m_mon_performance_data', _('Performance Data'));
$tpl->assign('m_mon_services_attempt', _('Current Attempt'));
$tpl->assign('m_mon_services_state', _('State Type'));
$tpl->assign('m_mon_last_check_type', _('Last Check Type'));
$tpl->assign('m_mon_host_last_check', _('Last Check'));
$tpl->assign('m_mon_services_active_check', _('Next Scheduled Active Check'));
$tpl->assign('m_mon_services_latency', _('Latency'));
$tpl->assign('m_mon_services_duration', _('Check Duration'));
$tpl->assign('m_mon_last_change', _('Last State Change'));
$tpl->assign('m_mon_current_state_duration', _('Current State Duration'));
$tpl->assign('m_mon_last_notification_serv', _('Last Service Notification'));
$tpl->assign('m_mon_notification_nb', _('Current Notification Number'));
$tpl->assign('m_mon_services_flapping', _('Is This Service Flapping?'));
$tpl->assign('m_mon_percent_state_change', _('Percent State Change'));
$tpl->assign('m_mon_downtime_sc', _('In Scheduled Downtime?'));
$tpl->assign('m_mon_last_update', _('Last Update'));
$tpl->assign('m_mon_tools', _('Tools'));
$tpl->assign('m_mon_service_command', _('Service Commands'));
$tpl->assign('m_mon_check_this_service', _('Checks for this service'));
$tpl->assign('m_mon_schedule', _('Re-schedule the next check for this service'));
$tpl->assign('m_mon_schedule_force', _('Re-schedule the next check for this service (forced)'));
$tpl->assign('m_mon_submit_passive', _('Submit result for this service'));
$tpl->assign('m_mon_schedule_downtime', _('Schedule downtime for this service'));
$tpl->assign('m_mon_schedule_comment', _('Add a comment for this service'));
$tpl->assign('m_mon_obsessing', _('Obsess Over Service'));
$tpl->assign('m_comment_for_service', _('All Comments for this service'));
$tpl->assign('cmt_host_name', _('Host Name'));
$tpl->assign('cmt_service_descr', _('Services'));
$tpl->assign('cmt_entry_time', _('Entry Time'));
$tpl->assign('cmt_author', _('Author'));
$tpl->assign('cmt_comment', _('Comments'));
$tpl->assign('cmt_persistent', _('Persistent'));
$tpl->assign('secondes', _('seconds'));
$tpl->assign('m_mon_ticket', 'Open Ticket');
$tpl->assign('links', _('Links'));
$tpl->assign('notifications', _('Notifications'));
$tpl->assign('m_mon_service_command_line', _('Executed Check Command Line'));
$tpl->assign('m_mon_services_en_check_active', _('Active Checks'));
$tpl->assign('m_mon_services_en_check_passif', _('Passive Checks'));
$tpl->assign('m_mon_accept_passive', _('Passive Checks'));
$tpl->assign('m_mon_notification_service', _('Service Notifications'));
$tpl->assign('m_mon_services_en_notification', _('Service Notifications'));
$tpl->assign('m_mon_services_en_acknowledge', _('Acknowledged'));
$tpl->assign('m_mon_event_handler', _('Event Handler'));
$tpl->assign('m_mon_flap_detection', _('Flap Detection'));
$tpl->assign('m_mon_services_en_flap', _('Flap Detection'));
$str_check_svc_enable = _('Enable Active Checks');
$str_check_svc_disable = _('Disable Active Checks');
$str_passive_svc_enable = _('Enable Passive Checks');
$str_passive_svc_disable = _('Disable Passive Checks');
$str_notif_svc_enable = _('Enable Service Notifications');
$str_notif_svc_disable = _('Disable Service Notifications');
$str_handler_svc_enable = _('Enable Event Handler');
$str_handler_svc_disable = _('Disable Event Handler');
$str_flap_svc_enable = _('Enable Flap Detection');
$str_flap_svc_disable = _('Disable Flap Detection');
$str_obsess_svc_enable = _('Enable Obsess Over Service');
$str_obsess_svc_disable = _('Disable Obsess Over Service');
/*
* if user is admin, allActions is true,
* else we introduce all actions allowed for user
*/
if (isset($authorized_actions)) {
$tpl->assign('aclAct', $authorized_actions);
}
$serviceDescriptionDisplay = $svc_description;
$hostNameDisplay = $host_name;
if ($isMetaservice == 'true') {
$tpl->assign('meta_id', $meta_id);
$hostNameDisplay = '';
$serviceDescriptionDisplay = $service_status['display_name'];
}
$tpl->assign('is_meta', $isMetaservice);
$tpl->assign('p', $p);
$tpl->assign('o', $o);
$tpl->assign('en', $en);
$tpl->assign('en_inv', $en_inv);
$tpl->assign('en_inv_text', $en_inv_text);
$tpl->assign('img_en', $img_en);
$tpl->assign('color_onoff', $color_onoff);
$tpl->assign('color_onoff_inv', $color_onoff_inv);
$tpl->assign('en_disable', $en_disable);
$tpl->assign('total_current_attempt', $total_current_attempts);
$tpl->assign('en_acknowledge_text', $en_acknowledge_text);
$tpl->assign('en_acknowledge', $en_acknowledge);
$tpl->assign('actpass', ['0' => _('Active'), '1' => _('Passive')]);
$tpl->assign('harsof', ['0' => _('SOFT'), '1' => _('HARD')]);
$tpl->assign('status', $status);
$tpl->assign('h', CentreonUtils::escapeSecure($host));
$tpl->assign('admin', $is_admin);
$tpl->assign('lcaTopo', $centreon->user->access->topology);
$tpl->assign('count_comments_svc', count($tabCommentServices));
$tpl->assign('tab_comments_svc', $tabCommentServices);
$tpl->assign('host_id', $host_id);
$tpl->assign('service_id', $service_id);
$centreonGraph = new CentreonGraph($centreon->user->user_id, null, 0, null);
if (isset($host_id, $service_id)) {
$tpl->assign('flag_graph', $centreonGraph->statusGraphExists($host_id, $service_id));
}
$tpl->assign('service_data', $service_status);
$tpl->assign('host_display_name', CentreonUtils::escapeSecure($hostNameDisplay));
$tpl->assign('host_name', CentreonUtils::escapeSecure($host_name));
$tpl->assign('svc_display_name', CentreonUtils::escapeSecure($serviceDescriptionDisplay));
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | true |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/objectDetails/xml/hostSendCommand.php | centreon/www/include/monitoring/objectDetails/xml/hostSendCommand.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
require_once realpath(__DIR__ . '/../../../../../config/centreon.config.php');
require_once _CENTREON_PATH_ . '/www/class/centreonExternalCommand.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/centreonACL.class.php';
require_once _CENTREON_PATH_ . '/www/class/centreonSession.class.php';
require_once _CENTREON_PATH_ . '/www/class/centreonUtils.class.php';
require_once _CENTREON_PATH_ . '/www/class/centreon.class.php';
require_once _CENTREON_PATH_ . '/www/class/centreonXML.class.php';
require_once _CENTREON_PATH_ . '/www/class/HtmlAnalyzer.php';
CentreonSession::start(1);
$centreon = $_SESSION['centreon'];
if (! isset($_SESSION['centreon'], $_POST['host_id'], $_POST['cmd'], $_POST['actiontype'])) {
exit();
}
$pearDB = new CentreonDB();
$hostObj = new CentreonHost($pearDB);
$hostId = filter_var(
$_POST['host_id'] ?? false,
FILTER_VALIDATE_INT
);
$pollerId = $hostObj->getHostPollerId($hostId);
$cmd = HtmlAnalyzer::sanitizeAndRemoveTags($_POST['cmd'] ?? '');
$cmd = CentreonUtils::escapeSecure($cmd, CentreonUtils::ESCAPE_ILLEGAL_CHARS);
$actionType = (int) $_POST['actiontype'];
$pearDB = new CentreonDB();
if ($sessionId = session_id()) {
$res = $pearDB->prepare('SELECT * FROM `session` WHERE `session_id` = :sid');
$res->bindValue(':sid', $sessionId, PDO::PARAM_STR);
$res->execute();
if (! $session = $res->fetch(PDO::FETCH_ASSOC)) {
exit();
}
} else {
exit();
}
/* If admin variable equals 1 it means that user admin
* otherwise it means that it is a simple user under ACL
*/
$isAdmin = (int) $centreon->user->access->admin;
if ($isAdmin === 0) {
if (! $centreon->user->access->checkAction($cmd)) {
exit();
}
if (! $centreon->user->access->checkHost($hostId)) {
exit();
}
}
$command = new CentreonExternalCommand($centreon);
$commandList = $command->getExternalCommandList();
$sendCommand = $commandList[$cmd][$actionType];
$sendCommand .= ';' . $hostObj->getHostName($hostId) . ';' . time();
$command->setProcessCommand($sendCommand, $pollerId);
$returnType = $actionType ? 1 : 0;
$result = $command->write();
$buffer = new CentreonXML();
$buffer->startElement('root');
$buffer->writeElement('result', $result);
$buffer->writeElement('cmd', $cmd);
$buffer->writeElement('actiontype', $returnType);
$buffer->endElement();
header('Content-type: text/xml; charset=utf-8');
header('Cache-Control: no-cache, must-revalidate');
$buffer->output();
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/monitoring/objectDetails/xml/serviceSendCommand.php | centreon/www/include/monitoring/objectDetails/xml/serviceSendCommand.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
require_once realpath(__DIR__ . '/../../../../../config/centreon.config.php');
require_once _CENTREON_PATH_ . '/www/class/centreonExternalCommand.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/centreonACL.class.php';
require_once _CENTREON_PATH_ . '/www/class/centreonSession.class.php';
require_once _CENTREON_PATH_ . '/www/class/centreonUtils.class.php';
require_once _CENTREON_PATH_ . '/www/class/centreon.class.php';
require_once _CENTREON_PATH_ . '/www/class/centreonXML.class.php';
require_once _CENTREON_PATH_ . '/www/class/HtmlAnalyzer.php';
CentreonSession::start(1);
$centreon = $_SESSION['centreon'];
if (! isset($_SESSION['centreon'], $_POST['host_id'], $_POST['service_id'], $_POST['cmd'], $_POST['actiontype'])) {
exit();
}
$pearDB = new CentreonDB();
$hostObj = new CentreonHost($pearDB);
$svcObj = new CentreonService($pearDB);
$hostId = filter_var(
$_POST['host_id'] ?? false,
FILTER_VALIDATE_INT
);
$serviceId = filter_var(
$_POST['service_id'] ?? false,
FILTER_VALIDATE_INT
);
$pollerId = $hostObj->getHostPollerId($hostId);
$cmd = HtmlAnalyzer::sanitizeAndRemoveTags($_POST['cmd'] ?? '');
$cmd = CentreonUtils::escapeSecure($cmd, CentreonUtils::ESCAPE_ILLEGAL_CHARS);
$actionType = (int) $_POST['actiontype'];
$pearDB = new CentreonDB();
if ($sessionId = session_id()) {
$res = $pearDB->prepare('SELECT * FROM `session` WHERE `session_id` = :sid');
$res->bindValue(':sid', $sessionId, PDO::PARAM_STR);
$res->execute();
if (! $session = $res->fetch(PDO::FETCH_ASSOC)) {
exit();
}
} else {
exit();
}
/* If admin variable equals 1 it means that user admin
* otherwise it means that it is a simple user under ACL
*/
$isAdmin = (int) $centreon->user->access->admin;
if ($centreon->user->access->admin === 0) {
if (! $centreon->user->access->checkAction($cmd)) {
exit();
}
if (! $centreon->user->access->checkHost($hostId)) {
exit();
}
if (! $centreon->user->access->checkService($serviceId)) {
exit();
}
}
$command = new CentreonExternalCommand($centreon);
$commandList = $command->getExternalCommandList();
$sendCommand = $commandList[$cmd][$actionType];
$sendCommand .= ';' . $hostObj->getHostName($hostId) . ';' . $svcObj->getServiceDesc($serviceId) . ';' . time();
$command->setProcessCommand($sendCommand, $pollerId);
$returnType = $actionType ? 1 : 0;
$result = $command->write();
$buffer = new CentreonXML();
$buffer->startElement('root');
$buffer->writeElement('result', $result);
$buffer->writeElement('cmd', $cmd);
$buffer->writeElement('actiontype', $returnType);
$buffer->endElement();
header('Content-type: text/xml; charset=utf-8');
header('Cache-Control: no-cache, must-revalidate');
$buffer->output();
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/core/pathway/pathway.php | centreon/www/include/core/pathway/pathway.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($centreon)) {
exit();
}
if (isset($url)) {
/**
* If url is defined we can use it to retrieve the associated page number
* to show the right tree in case when we have just the topology parent
* and we need to show breadcrumb for the first menu found (processed by
* main.php).
*/
$statementSelect = $pearDB->prepare(
'SELECT topology_url FROM topology WHERE topology_page = :topology_page'
);
$statementSelect->bindValue(':topology_page', $p, PDO::PARAM_INT);
if ($statementSelect->execute()) {
$result = $statementSelect->fetch(PDO::FETCH_ASSOC);
if ($result !== false && $result['topology_url'] != $url) {
/**
* If urls are not equal we can retrieve the topology page number
* associated to this url because there is multiple topology page
* number with the same URL.
*/
$statement = $pearDB->prepare(
'SELECT topology_page FROM topology '
. 'WHERE topology_url = :url'
);
$statement->bindValue(':url', $url, PDO::PARAM_STR);
if (
$statement->execute()
&& $result = $statement->fetch(PDO::FETCH_ASSOC)
) {
$p = $result['topology_page'];
}
}
}
}
/**
* Recursive query to retrieve tree details from child to parent
*/
$pdoStatement = $pearDB->prepare(
'SELECT `topology_url`, `topology_url_opt`, `topology_parent`,
`topology_name`, `topology_page`, `is_react`
FROM topology where topology_page IN
(SELECT :topology_page
UNION
SELECT * FROM (
SELECT @pv:=(
SELECT topology_parent
FROM topology
WHERE topology_page = @pv
) AS topology_parent FROM topology
JOIN
(SELECT @pv:=:topology_page) tmp
) a
WHERE topology_parent IS NOT NULL)
ORDER BY topology_page ASC'
);
$pdoStatement->bindValue(':topology_page', (int) $p, PDO::PARAM_INT);
$breadcrumbData = [];
$basePath = '/' . trim(explode('main.get.php', $_SERVER['REQUEST_URI'])[0], '/');
$basePath = htmlspecialchars($basePath, ENT_QUOTES, 'UTF-8');
if ($pdoStatement->execute()) {
while ($result = $pdoStatement->fetch(PDO::FETCH_ASSOC)) {
$isNameAlreadyInserted = array_search(
$result['topology_name'],
array_column($breadcrumbData, 'name')
);
if ($isNameAlreadyInserted) {
/**
* We don't show two items with the same name. So we remove the first
* item with the same name (in tree with duplicate topology name,
* the first has no url)
*/
$breadcrumbDataArrayNames = array_column($breadcrumbData, 'name');
$topologyNameSearch = array_search($result['topology_name'], $breadcrumbDataArrayNames);
$breadcrumbTopologyResults = array_slice($breadcrumbData, $topologyNameSearch);
$topology = array_pop($breadcrumbTopologyResults);
unset($breadcrumbData[$topology['page']]);
}
$breadcrumbData[$result['topology_page']] = [
'is_react' => $result['is_react'],
'name' => $result['topology_name'],
'url' => $result['topology_url'],
'opt' => $result['topology_url_opt'],
'page' => $result['topology_page'],
];
}
}
?>
<div class="pathway">
<?php
if ($centreon->user->access->page($p)) {
$flag = '';
foreach ($breadcrumbData as $page => $details) {
echo $flag;
?>
<a href="<?= $details['is_react'] ? "{$basePath}{$details['url']}" : "main.php?p={$page}{$details['opt']}"; ?>"
<?= $details['is_react'] ? ' isreact="isreact"' : ''; ?> class="pathWay"><?= _($details['name']); ?></a>
<?php
$flag = '<span class="pathWayBracket" > > </span>';
}
if (isset($_GET['host_id'])) {
echo '<span class="pathWayBracket" > > </span>';
echo HtmlSanitizer::createFromString(getMyHostName((int) $_GET['host_id']))->sanitize()->getString();
}
}
?>
</div>
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/core/errors/alt_error.php | centreon/www/include/core/errors/alt_error.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($centreon)) {
exit();
}
echo "<div class='msg' align='center'>" . _('You are not allowed to reach this page') . '</div>';
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/core/footer/footerPart.php | centreon/www/include/core/footer/footerPart.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($centreon)) {
exit;
}
require_once './class/centreonData.class.php';
if (! $min) {
?>
<!-- Footer -->
<?php
}
?>
<script type="text/javascript">
// Centreon ToolTips
var centreonTooltip = new CentreonToolTip();
centreonTooltip.setTitle('<?php echo _('Help'); ?>');
var svg = "<?php displaySvg('www/img/icons/question.svg', 'var(--help-tool-tip-icon-fill-color)', 18, 18); ?>"
centreonTooltip.setSource(svg);
centreonTooltip.render();
function myToggleAll(duration, toggle) {
if (toggle) {
//var i = document.getElementsByTagName("html")[0];
var i = document.documentElement;
if (
document.fullscreenElement ||
document.webkitFullscreenElement ||
document.mozFullScreenElement ||
document.msFullscreenElement
) {
jQuery(
"#actionBar, .pathWayBracket, .imgPathWay, .pathWay, hr, #QuickSearch, #menu1_bgcolor, " +
"#footer, #menu_1, #Tmenu , #menu_2, #menu_3, #header, .toHideInFullscreen"
).removeClass('tohide');
jQuery("#fullscreenIcon").attr("src", "./img/icons/fullscreen.png");
jQuery('#contener').css({
'height': 'calc(100% - 170px)'
});
jQuery('#Tcontener').css({
'margin-bottom': '0px'
});
if (document.exitFullscreen) {
document.exitFullscreen();
} else if (document.msExitFullscreen) {
document.msExitFullscreen();
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if (document.webkitExitFullscreen) {
document.webkitExitFullscreen();
}
} else {
jQuery(
"#actionBar, .pathWayBracket, .imgPathWay, .pathWay, hr, #QuickSearch, #menu1_bgcolor," +
" #footer, #menu_1, #Tmenu , #menu_2, #menu_3, #header, .toHideInFullscreen"
).addClass('tohide');
jQuery("#fullscreenIcon").attr("src", "./img/icons/fullscreen_off.png");
jQuery('#contener').css({
'height': '100%'
});
jQuery('#Tcontener').css({
'margin-bottom': '0px'
});
// go full-screen
if (i.requestFullscreen) {
i.requestFullscreen();
} else if (i.webkitRequestFullscreen) {
i.webkitRequestFullscreen();
} else if (i.mozRequestFullScreen) {
i.mozRequestFullScreen();
} else if (i.msRequestFullscreen) {
i.msRequestFullscreen();
}
}
}
}
document.addEventListener('webkitfullscreenchange', exitHandler, false);
document.addEventListener('mozfullscreenchange', exitHandler, false);
document.addEventListener('fullscreenchange', exitHandler, false);
document.addEventListener('MSFullscreenChange', exitHandler, false);
function exitHandler() {
var state = document.fullScreen ||
document.mozFullScreen ||
document.webkitIsFullScreen ||
document.msFullscreenElement;
var event = state ? 'FullscreenOn' : 'FullscreenOff';
if (event === 'FullscreenOff') {
jQuery("#fullscreenIcon").attr("src", "./img/icons/fullscreen.png");
jQuery(
"#actionBar, .pathWayBracket, .imgPathWay, .pathWay, hr, #QuickSearch, #menu1_bgcolor, " +
"#footer, #menu_1, #Tmenu , #menu_2, #menu_3, #header, .toHideInFullscreen"
).removeClass('tohide');
}
}
</script>
<?php
if ((isset($_GET['mini']) && $_GET['mini'] == 1)
|| (isset($_SESSION['fullScreen'], $_SESSION['fullScreen']['value']) && $_SESSION['fullScreen']['value'])) {
?>
<script type="text/javascript">
myToggleAll(0, false);
</script>
<?php
} elseif (! $centreon->user->showDiv('footer')) {
?>
<script type="text/javascript">
new Effect.toggle('footer', 'blind', {
duration: 0
});
</script>
<?php
}
// Create Data Flow
$cdata = CentreonData::getInstance();
$jsdata = $cdata->getJsData();
foreach ($jsdata as $k => $val) {
echo '<span class="data hide" id="' . $k . '" data-' . $k . '="' . $val . '"></span>';
}
?>
<script src="./include/common/javascript/pendo.js" async></script>
<script type='text/javascript'>
jQuery(function() {
initWholePage();
// convert URIs to links
jQuery(".containsURI").each(function() {
jQuery(this).linkify();
});
});
/*
* Init whole page
*/
function initWholePage() {
setQuickSearchPosition();
jQuery().centreon_notify({
refresh_rate: <?php echo $centreon->optGen['AjaxTimeReloadMonitoring'] * 1000; ?>
});
}
/*
* set quick search position
*/
function setQuickSearchPosition() {
if (jQuery('QuickSearch')) {
if (jQuery('header').is(':visible')) {
jQuery('QuickSearch').css({
top: '86px'
});
} else {
jQuery('QuickSearch').css({
top: '3px'
});
}
}
jQuery(".timepicker").timepicker();
jQuery(".datepicker").datepicker();
}
<?php
$featureToAsk = $centreonFeature->toAsk($centreon->user->get_id());
if (count($featureToAsk) === 1) {
?>
var testingFeature = jQuery('<div/>')
.html(
'<h3>Feature testing</h3>' +
'<div style="margin: 2px;">Would you like to activate the feature flipping:' +
'<?php echo $featureToAsk[0]['name']; ?> ?</div>' +
'<div style="margin: 2px; font-weight: bold;">Description: </div>' +
'<div style="margin: 2px;"> <?php echo $featureToAsk[0]['description']; ?>.</div>' +
'<div style="margin: 2px;">Please, give us your feedback on ' +
'<a href="https://centreon.github.io">Slack</a> ' +
'or <a href="https://github.com/centreon/centreon/issues">Github</a>.</div>' +
'<div style="margin: 2px; font-weight: bold;">Legacy version: </div>' +
'<div style="margin: 2px;">You can switch back to the legacy version in my account page. ' +
'<div style="margin-top: 8px; text-align: center;">' +
'<button class="btc bt_success" onclick="featureEnable()" id="btcActivateFf" >Activate</button>' +
' <button class="btc bt_default" onclick="featureDisable()" id="btcDisableFf">No</button>' +
'</div>'
)
.css('position', 'relative');
function validateFeature(name, version, enabled) {
jQuery.ajax({
url: './api/internal.php?object=centreon_featuretesting&action=enabled',
type: 'POST',
data: JSON.stringify({
name: name,
version: version,
enabled: enabled
}),
dataType: 'json',
success: function() {
location.reload()
}
})
}
function featureEnable() {
validateFeature(
"<?php echo $featureToAsk[0]['name']; ?>",
"<?php echo $featureToAsk[0]['version']; ?>",
true
);
testingFeature.centreonPopin("close");
}
function featureDisable() {
validateFeature(
"<?php echo $featureToAsk[0]['name']; ?>",
"<?php echo $featureToAsk[0]['version']; ?>",
true
);
testingFeature.centreonPopin("close");
}
testingFeature.centreonPopin({
isModal: true,
open: true
})
<?php
}
?>
// send an event to parent for change in iframe URL
function parentHrefUpdate(href) {
let parentHref = window.parent.location.href;
href = href.replace('main.get.php', 'main.php');
if (parentHref.localeCompare(href) === 0) {
return;
}
href = '/' + href.split(window.location.host + '/')[1];
if (parentHref.localeCompare(href) === 0) {
return;
}
var event = new CustomEvent('react.href.update', {
detail: {
href: href
}
});
window.parent.dispatchEvent(event);
}
// send event when url changed
jQuery(document).ready(function() {
parentHrefUpdate(location.href);
});
// send event when hash changed
jQuery(window).bind('hashchange', function() {
parentHrefUpdate(location.href);
});
jQuery('body').delegate(
'a',
'click',
function(e) {
var href = jQuery(this).attr('href');
var isReact = jQuery(this).attr('isreact');
var isHandled = jQuery(this).is('[onload]') ||
jQuery(this).is('[onclick]') ||
(href.match(/^javascript:/) !== null);
// if it's a relative path, we can use the default redirection
if (!href.match(/^\.\/(?!main(?:\.get)?\.php)/) && isHandled === false && !isReact) {
e.preventDefault();
// Manage centreon links
// # allows to manage backboneJS links + jQuery form tabs
if (href.match(/^\#|^\?|main\.php|main\.get\.php/)) {
// If we open link a new tab, we want to keep the header
if (jQuery(this).attr('target') === '_blank') {
href = href.replace('main.get.php', 'main.php');
window.open(href);
// If it's an internal link, we remove header to avoid inception
} else {
// isMobile is declared in the menu.js file
if (typeof isMobile === 'undefined' || isMobile !== true) {
href = href.replace('main.php', 'main.get.php');
}
window.location.href = href;
}
// Manage external links (ie: www.google.com)
// we always open it in a new tab
} else {
window.open(href);
}
} else if (isReact) {
e.preventDefault();
window.top.history.pushState("", "", href);
window.top.history.pushState("", "", href);
window.top.history.go(-1);
}
}
);
</script>
</body>
</html>
<?php
// Close all DB handler
if (isset($pearDB) && is_object($pearDB)) {
$pearDB = null;
}
if (isset($pearDBO) && is_object($pearDBO)) {
$pearDBO = null;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/core/header/header.php | centreon/www/include/core/header/header.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! defined('SMARTY_DIR')) {
define('SMARTY_DIR', realpath('../vendor/smarty/smarty/libs/') . '/');
}
// Bench
function microtime_float(): bool
{
[$usec, $sec] = explode(' ', microtime());
return (float) $usec + (float) $sec;
}
set_time_limit(60);
$time_start = microtime_float();
$advanced_search = 0;
// Include
include_once realpath(__DIR__ . '/../../../../bootstrap.php');
require_once "{$classdir}/centreonDB.class.php";
require_once "{$classdir}/centreonLang.class.php";
require_once "{$classdir}/centreonSession.class.php";
require_once "{$classdir}/centreon.class.php";
require_once "{$classdir}/centreonFeature.class.php";
/*
* Create DB Connection
* - centreon
* - centstorage
*/
$pearDB = new CentreonDB();
$pearDBO = new CentreonDB('centstorage');
$centreonSession = new CentreonSession();
CentreonSession::start();
// Check session and drop all expired sessions
if (! $centreonSession->updateSession($pearDB)) {
CentreonSession::stop();
}
$args = '&redirect=' . urlencode(http_build_query($_GET));
// check centreon session
// if session is not valid and autologin token is not given, then redirect to login page
if (! isset($_SESSION['centreon'])) {
if (! isset($_GET['autologin'])) {
include __DIR__ . '/../../../index.html';
} else {
$args = null;
foreach ($_GET as $key => $value) {
$args ? $args .= '&' . $key . '=' . $value : $args = $key . '=' . $value;
}
header('Location: index.php?' . $args . '');
}
}
// Define Oreon var alias
if (isset($_SESSION['centreon'])) {
$oreon = $_SESSION['centreon'];
$centreon = $_SESSION['centreon'];
}
if (! isset($centreon) || ! is_object($centreon)) {
exit();
}
// Init different elements we need in a lot of pages
unset($centreon->optGen);
$centreon->initOptGen($pearDB);
if (! $p) {
$rootMenu = getFirstAllowedMenu($centreon->user->access->topologyStr, $centreon->user->default_page);
if ($rootMenu && $rootMenu['topology_url'] && $rootMenu['is_react']) {
header("Location: .{$rootMenu['topology_url']}");
} elseif ($rootMenu) {
$p = $rootMenu['topology_page'];
$tab = preg_split("/\=/", $rootMenu['topology_url_opt']);
if (isset($tab[1])) {
$o = $tab[1];
}
}
}
// Cut Page ID
$level1 = null;
$level2 = null;
$level3 = null;
$level4 = null;
switch (strlen($p)) {
case 1:
$level1 = $p;
break;
case 3:
$level1 = substr($p, 0, 1);
$level2 = substr($p, 1, 2);
$level3 = substr($p, 3, 2);
break;
case 5:
$level1 = substr($p, 0, 1);
$level2 = substr($p, 1, 2);
$level3 = substr($p, 3, 2);
break;
case 6:
$level1 = substr($p, 0, 2);
$level2 = substr($p, 2, 2);
$level3 = substr($p, 3, 2);
break;
case 7:
$level1 = substr($p, 0, 1);
$level2 = substr($p, 1, 2);
$level3 = substr($p, 3, 2);
$level4 = substr($p, 5, 2);
break;
default:
$level1 = $p;
break;
}
// Update Session Table For last_reload and current_page row
$page = '' . $level1 . $level2 . $level3 . $level4;
if (empty($page)) {
$page = null;
}
$sessionStatement = $pearDB->prepare(
'UPDATE `session`
SET `current_page` = :currentPage
WHERE `session_id` = :sessionId'
);
$sessionStatement->bindValue(':currentPage', $page, PDO::PARAM_INT);
$sessionStatement->bindValue(':sessionId', session_id(), PDO::PARAM_STR);
$sessionStatement->execute();
// Init Language
$centreonLang = new CentreonLang(_CENTREON_PATH_, $centreon);
$centreonLang->bindLang();
$centreonLang->bindLang('help');
$centreon->user->access->getActions();
/**
* Initialize features flipping
*/
$centreonFeature = new CentreonFeature($pearDB);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/core/header/htmlHeader.php | centreon/www/include/core/header/htmlHeader.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($centreon)) {
exit();
}
// generate version URI parameter to clean css cache at each new version
$versionParam = isset($centreon->informations) && isset($centreon->informations['version'])
? '?version=' . $centreon->informations['version']
: '';
echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
$variablesThemeCSS = 'Centreon-Light';
$userId = (int) $centreon->user->user_id;
$statement = $pearDB->prepare('SELECT contact_theme FROM contact WHERE contact_id = :contactId');
$statement->bindValue(':contactId', $userId, PDO::PARAM_INT);
$statement->execute();
if ($result = $statement->fetch(PDO::FETCH_ASSOC)) {
switch ($result['contact_theme']) {
case 'light':
$variablesThemeCSS = 'Generic-theme';
break;
case 'dark':
$variablesThemeCSS = 'Centreon-Dark';
break;
default:
throw new Exception('Unknown contact theme : ' . $result['contact_theme']);
}
}
?>
<!DOCTYPE html>
<html lang="<?php echo $centreon->user->lang; ?>">
<title>Centreon - IT & Network Monitoring</title>
<link rel="shortcut icon" href="./img/favicon.ico"/>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name="Generator" content="Centreon - Copyright (C) 2005 - 2021 Open Source Matters. All rights reserved."/>
<meta name="robots" content="index, nofollow"/>
<?php if (isset($isMobile) && $isMobile) { ?>
<link href="./Themes/Generic-theme/MobileMenu/css/material_icons.css" rel="stylesheet" type="text/css"/>
<link href="./Themes/Generic-theme/MobileMenu/css/menu.css" rel="stylesheet" type="text/css"/>
<?php } ?>
<link href="./include/common/javascript/jquery/plugins/jpaginator/jPaginator.css" rel="stylesheet" type="text/css"/>
<!-- Theme selection -->
<link
href="./Themes/Generic-theme/style.css<?php echo $versionParam; ?>"
rel="stylesheet"
type="text/css"
/>
<link
href="./Themes/Generic-theme/centreon-loading.css<?php echo $versionParam; ?>"
rel="stylesheet"
type="text/css"
/>
<link
href="./Themes/Generic-theme/responsive-style.css<?php echo $versionParam; ?>"
rel="stylesheet"
type="text/css"
/>
<link
href="./Themes/Generic-theme/color.css<?php echo $versionParam; ?>"
rel="stylesheet"
type="text/css"
/>
<link
href="./Themes/Generic-theme/jquery-ui/jquery-ui.css<?php echo $versionParam; ?>"
rel="stylesheet"
type="text/css"
/>
<link
href="./Themes/Generic-theme/jquery-ui/jquery-ui-centreon.css<?php echo $versionParam; ?>"
rel="stylesheet"
type="text/css"
/>
<link
href="./include/common/javascript/jquery/plugins/timepicker/jquery.ui.timepicker.css"
rel="stylesheet"
type="text/css"
media="screen"
/>
<link
href="./include/common/javascript/jquery/plugins/select2/css/select2.css"
rel="stylesheet"
type="text/css"
media="screen"
/>
<link href="./include/common/javascript/jquery/plugins/colorbox/colorbox.css" rel="stylesheet" type="text/css"/>
<link href="./include/common/javascript/jquery/plugins/qtip/jquery-qtip.css" rel="stylesheet" type="text/css"/>
<!-- graph css -->
<link href="./include/common/javascript/charts/c3.min.css" type="text/css" rel="stylesheet" />
<link href="./include/views/graphs/javascript/centreon-status-chart.css" type="text/css" rel="stylesheet" />
<link
href="./Themes/<?php echo $variablesThemeCSS === 'Generic-theme' ? $variablesThemeCSS . '/Variables-css/'
: $variablesThemeCSS . '/'; ?>variables.css<?php echo $versionParam; ?>"
rel="stylesheet"
type="text/css"
/>
<?php
// == Declare CSS for modules
foreach ($centreon->modules as $moduleName => $infos) {
if (file_exists(__DIR__ . '/../../../www/modules/' . $moduleName . '/static/css/styles.css')) {
echo '<link '
. "href='./modules/" . $moduleName . "/static/css/styles.css' "
. "rel='stylesheet' type='text/css' "
. "/>\n";
}
}
if (! isset($_REQUEST['iframe']) || (isset($_REQUEST['iframe']) && $_REQUEST['iframe'] != 1)) {
?>
<script type="text/javascript" src="./include/common/javascript/jquery/jquery.min.js"></script>
<script type="text/javascript" src="./include/common/javascript/jquery/plugins/toggleClick/jquery.toggleClick.js">
</script>
<script type="text/javascript" src="./include/common/javascript/jquery/plugins/select2/js/select2.full.min.js">
</script>
<script type="text/javascript" src="./include/common/javascript/centreon/centreon-select2.js"></script>
<script type="text/javascript" src="./include/common/javascript/jquery/jquery-ui.js"></script>
<script type="text/javascript" src="./include/common/javascript/jquery/jquery-ui-tabs-rotate.js"></script>
<script type="text/javascript" src="./include/common/javascript/jquery/plugins/colorbox/jquery.colorbox-min.js">
</script>
<script type="text/javascript" src="./include/common/javascript/jquery/plugins/jeditable/jquery.jeditable-min.js">
</script>
<script type="text/javascript" src="./include/common/javascript/jquery/plugins/timepicker/jquery.ui.timepicker.js">
</script>
<script type="text/javascript" src="./include/common/javascript/jquery/plugins/noty/jquery.noty.js"></script>
<script type="text/javascript" src="./include/common/javascript/jquery/plugins/noty/themes/default.js"></script>
<script type="text/javascript" src="./include/common/javascript/jquery/plugins/noty/layouts/bottomRight.js">
</script>
<script type="text/javascript" src="./include/common/javascript/jquery/plugins/buzz/buzz.min.js"></script>
<script type='text/javascript' src='./include/common/javascript/visibility.min.js'></script>
<script type="text/javascript" src="./include/common/javascript/centreon/notifier.js"></script>
<script type="text/javascript" src="./include/common/javascript/centreon/multiselectResizer.js"></script>
<script type="text/javascript" src="./include/common/javascript/centreon/popin.js"></script>
<script type="text/javascript" src="./include/common/javascript/jquery/plugins/jquery.nicescroll.min.js"></script>
<script type="text/javascript" src="./include/common/javascript/jquery/plugins/jpaginator/jPaginator.js"></script>
<script type="text/javascript" src="./include/common/javascript/clipboard.min.js"></script>
<script type='text/javascript' src='./include/common/javascript/changetab.js'></script>
<script type='text/javascript' src='./include/common/javascript/linkify/linkify.min.js'></script>
<script type='text/javascript' src='./include/common/javascript/linkify/linkify-jquery.min.js'></script>
<?php
}
?>
<script type="text/javascript" src="./class/centreonToolTip.js"></script>
<!-- graph js -->
<script src="./include/common/javascript/charts/d3.min.js"></script>
<script src="./include/common/javascript/charts/c3.min.js"></script>
<script src="./include/common/javascript/charts/d3-timeline.js"></script>
<script src="./include/views/graphs/javascript/centreon-graph.js"></script>
<script src="./include/views/graphs/javascript/centreon-c3.js"></script>
<script src="./include/common/javascript/numeral.min.js"></script>
<script src="./include/views/graphs/javascript/centreon-status-chart.js"></script>
<script src="./include/common/javascript/moment-with-locales.min.2.29.4.js"></script>
<script src="./include/common/javascript/moment-timezone-with-data.min.js"></script>
<?php if (isset($isMobile) && $isMobile) { ?>
<script type="text/javascript">
var text_back = '<?= gettext('Back'); ?>'
</script>
<script src="./Themes/Generic-theme/MobileMenu/js/menu.js"></script>
<?php } ?>
<?php
global $search, $search_service;
$searchStr = '';
if (isset($_GET['search'])) {
$searchStr .= 'search_host=' . htmlentities($_GET['search'], ENT_QUOTES, 'UTF-8');
}
if (isset($centreon->historySearch[$url]) && ! isset($_GET['search'])) {
if (! is_array($centreon->historySearch[$url])) {
$searchStr .= 'search_host=' . $centreon->historySearch[$url];
} elseif (isset($centreon->historySearch[$url]['search'])) {
$searchStr .= 'search_host=' . $centreon->historySearch[$url]['search'];
}
}
$searchStrSVC = '';
if (isset($_GET['search_service'])) {
$searchStrSVC = 'search_service=' . htmlentities($_GET['search_service'], ENT_QUOTES, 'UTF-8');
if ($searchStr == '') {
$searchStrSVC = '&' . $searchStrSVC;
}
$search_service = htmlentities($_GET['search_service'], ENT_QUOTES, 'UTF-8');
} elseif (isset($centreon->historySearchService[$url]) && ! isset($_GET['search_service'])) {
$search_service = $centreon->historySearchService[$url];
$searchStr .= 'search_service=' . $centreon->historySearchService[$url];
}
// include javascript
$res = null;
$query = 'SELECT DISTINCT PathName_js, init FROM topology_JS WHERE id_page = ? AND (o = ? OR o IS NULL)';
$sth = $pearDB->prepare($query);
$sth->execute([$p, $o]);
while ($topology_js = $sth->fetch()) {
if ($topology_js['PathName_js'] != './include/common/javascript/ajaxMonitoring.js') {
if ($topology_js['PathName_js'] != '') {
echo "<script type='text/javascript' src='" . $topology_js['PathName_js'] . "'></script>\n";
}
}
}
$DBRESULT = null;
// init javascript
$sid = session_id();
$tS = $centreon->optGen['AjaxTimeReloadStatistic'] * 1000;
$tM = $centreon->optGen['AjaxTimeReloadMonitoring'] * 1000;
?>
<script src="./include/common/javascript/centreon/dateMoment.js" type="text/javascript"></script>
<script src="./include/common/javascript/centreon/centreon-localStorage.js" type="text/javascript"></script>
<script src="./include/common/javascript/datepicker/localizedDatepicker.js"></script>
<script type='text/javascript'>
jQuery(function () {
<?php
$res = null;
$query = "SELECT DISTINCT PathName_js, init FROM topology_JS WHERE id_page = '"
. $p . "' AND (o = '" . $o . "' OR o IS NULL)";
$DBRESULT = $pearDB->query($query);
while ($topology_js = $DBRESULT->fetch()) {
if ($topology_js['init'] == 'initM') {
if ($o != 'hd' && $o != 'svcd') {
$obis = $o;
if (isset($_GET['problem'])) {
$obis .= '_pb';
}
if (isset($_GET['acknowledge'])) {
$obis .= '_ack_' . $_GET['acknowledge'];
}
echo "\tsetTimeout('initM({$tM}, \"{$obis}\")', 0);";
}
} elseif ($topology_js['init']) {
echo 'if (typeof ' . $topology_js['init'] . " == 'function') {";
echo $topology_js['init'] . '();';
echo '}';
}
}
?>
check_session(<?php echo $tM; ?>);
});
</script>
<script src="./include/common/javascript/xslt.js" type="text/javascript"></script>
</head>
<body>
<?php if (! isset($_REQUEST['iframe']) || (isset($_REQUEST['iframe']) && $_REQUEST['iframe'] != 1)) { ?>
<script type="text/javascript" src="./lib/wz_tooltip/wz_tooltip.js"></script>
<?php } ?>
<div style="display:none" id="header"></div>
<?php
// Showing the mobile menu if it's a mobile browser
if (isset($isMobile) && $isMobile) {
require _CENTREON_PATH_ . 'www/include/common/mobile_menu.php';
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/api/internal.php | centreon/www/api/internal.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 _CENTREON_PATH_ . 'www/class/centreonSession.class.php';
require_once _CENTREON_PATH_ . 'www/class/centreon.class.php';
require_once _CENTREON_PATH_ . '/www/class/centreonDB.class.php';
require_once __DIR__ . '/class/webService.class.php';
require_once __DIR__ . '/interface/di.interface.php';
error_reporting(-1);
ini_set('display_errors', 0);
$pearDB = new CentreonDB();
CentreonSession::start(1);
if (! isset($_SESSION['centreon'])) {
CentreonWebService::sendResult('Unauthorized', 401);
}
$pearDB = new CentreonDB();
// Define Centreon var alias
if (isset($_SESSION['centreon']) && CentreonSession::checkSession(session_id(), $pearDB)) {
$oreon = $_SESSION['centreon'];
$centreon = $_SESSION['centreon'];
}
if (! isset($centreon) || ! is_object($centreon)) {
CentreonWebService::sendResult('Unauthorized', 401);
}
CentreonWebService::router($dependencyInjector, $centreon->user, true);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/api/external.php | centreon/www/api/external.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
*
*/
ini_set('error_reporting', E_ALL & ~E_NOTICE & ~E_STRICT);
ini_set('display_errors', 'Off');
require_once __DIR__ . '/../../bootstrap.php';
require_once __DIR__ . '/../class/centreon.class.php';
require_once __DIR__ . '/class/webService.class.php';
$pearDB = $dependencyInjector['configuration_db'];
$user = null;
// get user information if a token is provided
if (isset($_SERVER['HTTP_CENTREON_AUTH_TOKEN'])) {
try {
$contactStatement = $pearDB->prepare(
<<<'SQL'
SELECT c.*
FROM security_authentication_tokens sat, contact c
WHERE c.contact_id = sat.user_id
AND sat.token = :token
AND sat.is_revoked = 0
SQL
);
$contactStatement->bindValue(':token', $_SERVER['HTTP_CENTREON_AUTH_TOKEN'], PDO::PARAM_STR);
$contactStatement->execute();
if ($userInfos = $contactStatement->fetch()) {
$centreon = new Centreon($userInfos);
$user = $centreon->user;
}
} catch (PDOException $e) {
CentreonWebService::sendResult('Database error', 500);
}
}
CentreonWebService::router($dependencyInjector, $user, false);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/api/index.php | centreon/www/api/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 __DIR__ . '/../../bootstrap.php';
require_once _CENTREON_PATH_ . 'www/class/centreon.class.php';
require_once __DIR__ . '/class/webService.class.php';
require_once __DIR__ . '/interface/di.interface.php';
use Core\Security\Authentication\Domain\Exception\AuthenticationException;
error_reporting(-1);
ini_set('display_errors', 0);
$pearDB = $dependencyInjector['configuration_db'];
$kernel = App\Kernel::createForWeb();
// Test if the call is for authenticate
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_GET['action']) && $_GET['action'] == 'authenticate') {
if (isset($_POST['username']) === false || isset($_POST['password']) === false) {
CentreonWebService::sendResult('Bad parameters', 400);
}
$credentials = [
'login' => $_POST['username'],
'password' => $_POST['password'],
];
$authenticateApiUseCase = $kernel->getContainer()->get(
Centreon\Domain\Authentication\UseCase\AuthenticateApi::class
);
$request = new Centreon\Domain\Authentication\UseCase\AuthenticateApiRequest(
$credentials['login'],
$credentials['password']
);
$response = new Centreon\Domain\Authentication\UseCase\AuthenticateApiResponse();
try {
$authenticateApiUseCase->execute($request, $response);
} catch (AuthenticationException $ex) {
CentreonWebService::sendResult('Authentication failed', 401);
}
$userAccessesStatement = $pearDB->prepare(
'SELECT contact_admin, reach_api, reach_api_rt FROM contact WHERE contact_alias = :alias'
);
$userAccessesStatement->bindValue(':alias', $credentials['login'], PDO::PARAM_STR);
$userAccessesStatement->execute();
if (($userAccess = $userAccessesStatement->fetch(PDO::FETCH_ASSOC)) !== false) {
if (
! (int) $userAccess['contact_admin']
&& (int) $userAccess['reach_api'] === 0
&& (int) $userAccess['reach_api_rt'] === 0
) {
CentreonWebService::sendResult('Unauthorized', 403);
}
}
if (! empty($response->getApiAuthentication()['security']['token'])) {
CentreonWebService::sendResult(['authToken' => $response->getApiAuthentication()['security']['token']]);
} else {
CentreonWebService::sendResult('Invalid credentials', 401);
}
}
// Test authentication
if (isset($_SERVER['HTTP_CENTREON_AUTH_TOKEN']) === false) {
CentreonWebService::sendResult('Unauthorized', 403);
}
// Create the default object
try {
$contactStatement = $pearDB->prepare(
'SELECT c.*
FROM security_authentication_tokens sat, contact c
WHERE c.contact_id = sat.user_id
AND sat.token = :token'
);
$contactStatement->bindValue(':token', $_SERVER['HTTP_CENTREON_AUTH_TOKEN'], PDO::PARAM_STR);
$contactStatement->execute();
} catch (PDOException $e) {
CentreonWebService::sendResult('Database error', 500);
}
$userInfos = $contactStatement->fetch();
if (is_null($userInfos)) {
CentreonWebService::sendResult('Unauthorized', 401);
}
$centreon = new Centreon($userInfos);
$oreon = $centreon;
CentreonWebService::router($dependencyInjector, $centreon->user);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/api/exceptions.php | centreon/www/api/exceptions.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 RestException
*/
class RestException extends Exception
{
/**
* RestException constructor
*
* @param string $message
* @param int $code
* @param Throwable|null $previous
*/
public function __construct($message = '', $code = 0, $previous = null)
{
parent::__construct($message, $code, $previous);
}
}
/**
* Class
*
* @class RestBadRequestException
*/
class RestBadRequestException extends RestException
{
/** @var int */
protected $code = 400;
/**
* RestBadRequestException constructor
*
* @param string $message
* @param int $code
* @param Throwable|null $previous
*/
public function __construct($message = '', $code = 0, $previous = null)
{
parent::__construct($message, $this->code, $previous);
}
}
/**
* Class
*
* @class RestUnauthorizedException
*/
class RestUnauthorizedException extends RestException
{
/** @var int */
protected $code = 401;
/**
* RestUnauthorizedException constructor
*
* @param string $message
* @param int $code
* @param Throwable|null $previous
*/
public function __construct($message = '', $code = 0, $previous = null)
{
parent::__construct($message, $this->code, $previous);
}
}
/**
* Class
*
* @class RestForbiddenException
*/
class RestForbiddenException extends RestException
{
/** @var int */
protected $code = 403;
/**
* RestForbiddenException constructor
*
* @param string $message
* @param int $code
* @param Throwable|null $previous
*/
public function __construct($message = '', $code = 0, $previous = null)
{
parent::__construct($message, $this->code, $previous);
}
}
/**
* Class
*
* @class RestNotFoundException
*/
class RestNotFoundException extends RestException
{
/** @var int */
protected $code = 404;
/**
* RestNotFoundException constructor
*
* @param string $message
* @param int $code
* @param Throwable|null $previous
*/
public function __construct($message = '', $code = 0, $previous = null)
{
parent::__construct($message, $this->code, $previous);
}
}
/**
* Class
*
* @class RestMethodNotAllowedException
*/
class RestMethodNotAllowedException extends RestException
{
/** @var int */
protected $code = 405;
/**
* RestMethodNotAllowedException constructor
*
* @param string $message
* @param int $code
* @param Throwable|null $previous
*/
public function __construct($message = '', $code = 0, $previous = null)
{
parent::__construct($message, $this->code, $previous);
}
}
/**
* Class
*
* @class RestConflictException
*/
class RestConflictException extends RestException
{
/** @var int */
protected $code = 409;
/**
* RestConflictException constructor
*
* @param string $message
* @param int $code
* @param Throwable|null $previous
*/
public function __construct($message = '', $code = 0, $previous = null)
{
parent::__construct($message, $this->code, $previous);
}
}
/**
* Class
*
* @class RestInternalServerErrorException
*/
class RestInternalServerErrorException extends RestException
{
/** @var int */
protected $code = 500;
/**
* RestInternalServerErrorException constructor
*
* @param string $message
* @param int $code
* @param Throwable|null $previous
*/
public function __construct($message = '', $code = 0, $previous = null)
{
parent::__construct($message, $this->code, $previous);
}
}
/**
* Class
*
* @class RestBadGatewayException
*/
class RestBadGatewayException extends RestException
{
/** @var int */
protected $code = 502;
/**
* RestBadGatewayException constructor
*
* @param string $message
* @param int $code
* @param Throwable|null $previous
*/
public function __construct($message = '', $code = 0, $previous = null)
{
parent::__construct($message, $this->code, $previous);
}
}
/**
* Class
*
* @class RestServiceUnavailableException
*/
class RestServiceUnavailableException extends RestException
{
/** @var int */
protected $code = 503;
/**
* RestServiceUnavailableException constructor
*
* @param string $message
* @param int $code
* @param Throwable|null $previous
*/
public function __construct($message = '', $code = 0, $previous = null)
{
parent::__construct($message, $this->code, $previous);
}
}
/**
* Class
*
* @class RestGatewayTimeOutException
*/
class RestGatewayTimeOutException extends RestException
{
/** @var int */
protected $code = 504;
/**
* RestGatewayTimeOutException constructor
*
* @param string $message
* @param int $code
* @param Throwable|null $previous
*/
public function __construct($message = '', $code = 0, $previous = null)
{
parent::__construct($message, $this->code, $previous);
}
}
/**
* Class
*
* @class RestPartialContent
*/
class RestPartialContent extends RestException
{
/** @var int */
protected $code = 206;
/**
* RestPartialContent constructor
*
* @param string $message
* @param int $code
* @param Throwable|null $previous
*/
public function __construct($message = '', $code = 0, $previous = null)
{
parent::__construct($message, $this->code, $previous);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/api/trait/diAndUtilis.trait.php | centreon/www/api/trait/diAndUtilis.trait.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 CentreonLegacy\Core\Utils\Factory;
use Pimple\Container;
/**
* Trait
*
* @class CentreonWebServiceDiAndUtilisTrait
*/
trait CentreonWebServiceDiAndUtilisTrait
{
/** @var Container */
private $dependencyInjector;
/** @var Factory */
private $utils;
/**
* @param Container $dependencyInjector
*
* @return void
*/
public function finalConstruct(Container $dependencyInjector): void
{
$this->dependencyInjector = $dependencyInjector;
$utilsFactory = new Factory($dependencyInjector);
$this->utils = $utilsFactory->newUtils();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/api/interface/di.interface.php | centreon/www/api/interface/di.interface.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;
/**
* Interface
*
* @class CentreonWebServiceDiInterface
*/
interface CentreonWebServiceDiInterface
{
/**
* @param Container $dependencyInjector
*/
public function finalConstruct(Container $dependencyInjector);
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/api/class/centreon_monitoring_externalcmd.class.php | centreon/www/api/class/centreon_monitoring_externalcmd.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/centreonExternalCommand.class.php';
require_once __DIR__ . '/centreon_configuration_objects.class.php';
/**
* Class
*
* @class CentreonMonitoringExternalcmd
*/
class CentreonMonitoringExternalcmd extends CentreonConfigurationObjects
{
/** @var CentreonDB */
protected $pearDBMonitoring;
/** @var string */
protected $centcore_file;
/**
* CentreonMonitoringExternalcmd constructor
*/
public function __construct()
{
parent::__construct();
$this->pearDBMonitoring = new CentreonDB('centstorage');
if (is_dir(_CENTREON_VARLIB_ . '/centcore')) {
$this->centcore_file = _CENTREON_VARLIB_ . '/centcore/' . microtime(true) . '-externalcommand.cmd';
} else {
$this->centcore_file = _CENTREON_VARLIB_ . '/centcore.cmd';
}
}
/**
* @throws PDOException
* @throws RestBadRequestException
* @throws RestException
* @throws RestUnauthorizedException
* @return array
*/
public function postSend()
{
global $centreon;
if (
isset($this->arguments['commands'])
&& is_array($this->arguments['commands'])
&& count($this->arguments['commands'])
) {
// Get poller Listing
$query = 'SELECT id '
. 'FROM nagios_server '
. 'WHERE ns_activate = "1"';
$dbResult = $this->pearDB->query($query);
$pollers = [];
while ($row = $dbResult->fetch(PDO::FETCH_ASSOC)) {
$pollers[$row['id']] = 1;
}
$externalCommand = new CentreonExternalCommand();
$availableCommands = [];
/**
* We need to make the concordance between the data saved in the database
* and the action provided by the user.
*/
foreach ($externalCommand->getExternalCommandList() as $key => $cmd) {
foreach ($cmd as $c) {
$availableCommands[$c] = $key;
}
}
$isAdmin = $centreon->user->admin;
/**
* If user is not admin we need to retrieve its ACL
*/
if (! $isAdmin) {
$userAcl = new CentreonACL($centreon->user->user_id, $isAdmin);
}
if ($fh = @fopen($this->centcore_file, 'a+')) {
foreach ($this->arguments['commands'] as $command) {
$commandSplitted = explode(';', $command['command']);
$action = $commandSplitted[0];
if (! $isAdmin) {
if (preg_match('/HOST(_SVC)?/', $action, $matches)) {
if (! isset($commandSplitted[1])) {
throw new RestBadRequestException(_('Host not found'));
}
$query = 'SELECT acl.host_id
FROM centreon_acl acl, hosts h
WHERE acl.host_id = h.host_id
AND acl.service_id IS NULL
AND h.name = ?
AND acl.group_id IN (' . $userAcl->getAccessGroupsString() . ')';
$result = $this->pearDBMonitoring->prepare($query);
$result->execute([$commandSplitted[1]]);
if ($result->fetch() === false) {
throw new RestBadRequestException(_('Host not found'));
}
} elseif (preg_match('/(?!HOST_)SVC/', $action, $matches)) {
if (! isset($commandSplitted[1]) || ! isset($commandSplitted[2])) {
throw new RestBadRequestException(_('Service not found'));
}
$query = 'SELECT acl.service_id
FROM centreon_acl acl, hosts h, services s
WHERE h.host_id = s.host_id
AND acl.host_id = s.host_id
AND acl.service_id = s.service_id
AND h.name = :hostName
AND s.description = :serviceDescription
AND acl.group_id IN (' . $userAcl->getAccessGroupsString() . ')';
$statement = $this->pearDBMonitoring->prepare($query);
$statement->bindValue(':hostName', $commandSplitted[1], PDO::PARAM_STR);
$statement->bindValue(':serviceDescription', $commandSplitted[2], PDO::PARAM_STR);
$statement->execute();
if ($statement->fetch() === false) {
throw new RestBadRequestException(_('Service not found'));
}
}
}
// checking that action provided exists
if (! array_key_exists($action, $availableCommands)) {
throw new RestBadRequestException('Action ' . $action . ' not supported');
}
if (! $isAdmin) {
// Checking that the user has rights to do the action provided
if ($userAcl->checkAction($availableCommands[$action]) === 0) {
throw new RestUnauthorizedException(
'User is not allowed to execute ' . $action . ' action'
);
}
}
if (isset($pollers[$command['poller_id']])) {
fwrite(
$fh,
'EXTERNALCMD:' . $command['poller_id'] . ':['
. $command['timestamp'] . '] ' . $command['command'] . "\n"
);
}
}
fclose($fh);
return ['success' => true];
}
throw new RestException('Cannot open Centcore file');
} else {
throw new RestBadRequestException('Bad arguments - Cannot find command list');
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/api/class/centreon_administration_aclgroup.class.php | centreon/www/api/class/centreon_administration_aclgroup.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__ . '/centreon_configuration_objects.class.php';
/**
* Class
*
* @class CentreonAdministrationAclgroup
*/
class CentreonAdministrationAclgroup extends CentreonConfigurationObjects
{
public const ADMIN_ACL_GROUP = 'customer_admin_acl';
/**
* @throws PDOException
* @throws RestBadRequestException
* @return array
*/
public function getList()
{
global $centreon;
$queryValues = [];
$filterAclgroup = [];
$isUserAdmin = $this->isUserAdmin();
/**
* Determine if the connected user is an admin (or not). User is admin if
* - he is configured as being an admin (onPrem) - is_admin = true
* - he belongs to the customer_admin_acl acl_group (cloud).
*/
if (! $isUserAdmin) {
$acl = new CentreonACL($centreon->user->user_id, $centreon->user->admin);
$filterAclgroup[] = ' ag.acl_group_id IN (' . $acl->getAccessGroupsString() . ') ';
}
$query = filter_var($this->arguments['q'] ?? '', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
if ($query !== '') {
$filterAclgroup[] = ' (ag.acl_group_name LIKE :aclGroup OR ag.acl_group_alias LIKE :aclGroup) ';
$queryValues['aclGroup'] = '%' . $query . '%';
}
$limit = array_key_exists('page_limit', $this->arguments)
? filter_var($this->arguments['page_limit'], FILTER_VALIDATE_INT)
: null;
$page = array_key_exists('page', $this->arguments)
? filter_var($this->arguments['page'], FILTER_VALIDATE_INT)
: null;
$useResourceAccessManagement = filter_var(
$this->arguments['use_ram'] ?? false,
FILTER_VALIDATE_BOOL
);
$allHostGroupsFilter = filter_var(
$this->arguments['all_hostgroups_filter'] ?? false,
FILTER_VALIDATE_BOOL
);
$allServiceGroupsFilter = filter_var(
$this->arguments['all_servicegroups_filter'] ?? false,
FILTER_VALIDATE_BOOL
);
if ($limit === false) {
throw new RestBadRequestException('Error, limit must be an integer greater than zero');
}
if ($page === false) {
throw new RestBadRequestException('Error, page must be an integer greater than zero');
}
$range = '';
if (
$page !== null
&& $limit !== null
) {
$range = ' LIMIT :offset, :limit';
$queryValues['offset'] = (int) (($page - 1) * $limit);
$queryValues['limit'] = $limit;
}
$query = <<<'SQL_WRAP'
SELECT SQL_CALC_FOUND_ROWS
ag.acl_group_id,
ag.acl_group_name
FROM acl_groups ag
SQL_WRAP;
$query .= ! $isUserAdmin
? <<<'SQL'
INNER JOIN acl_res_group_relations argr
ON argr.acl_group_id = ag.acl_group_id
INNER JOIN acl_resources ar
ON ar.acl_res_id = argr.acl_res_id
SQL
: '';
$whereCondition = '';
// In cloud environment we only want to return ACL defines through Resource Access Management page
if ($useResourceAccessManagement === true) {
$whereCondition = ' WHERE ag.cloud_specific = 1';
}
if ($filterAclgroup !== []) {
$whereCondition .= empty($whereCondition) ? ' WHERE ' : ' AND ';
$whereCondition .= implode(' AND ', $filterAclgroup);
}
$query .= $whereCondition;
$query .= ' GROUP BY ag.acl_group_id';
if ($allHostGroupsFilter && ! $isUserAdmin) {
$query .= <<<'SQL'
HAVING SUM(CASE ar.all_hostgroups WHEN '1' THEN 1 ELSE 0 END) = 0
SQL;
}
if ($allServiceGroupsFilter && ! $isUserAdmin) {
$query .= <<<'SQL'
HAVING SUM(CASE ar.all_servicegroups WHEN '1' THEN 1 ELSE 0 END) = 0
SQL;
}
$query .= ' ORDER BY ag.acl_group_name ' . $range;
$statement = $this->pearDB->prepare($query);
if (isset($queryValues['aclGroup'])) {
$statement->bindValue(':aclGroup', $queryValues['aclGroup'], PDO::PARAM_STR);
}
if (isset($queryValues['offset'])) {
$statement->bindValue(':offset', $queryValues['offset'], PDO::PARAM_INT);
$statement->bindValue(':limit', $queryValues['limit'], PDO::PARAM_INT);
}
$statement->execute();
$aclGroupList = [];
while ($data = $statement->fetch()) {
$aclGroupList[] = [
'id' => $data['acl_group_id'],
'text' => $data['acl_group_name'],
];
}
return [
'items' => $aclGroupList,
'total' => (int) $this->pearDB->numberRows(),
];
}
/**
* @return bool
*/
private function isUserAdmin(): bool
{
global $centreon;
if ($centreon->user->admin) {
return true;
}
// Get user's ACL groups
$acl = new CentreonACL($centreon->user->user_id, $centreon->user->admin);
return in_array(self::ADMIN_ACL_GROUP, $acl->getAccessGroups(), true);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/api/class/centreon_configuration_hostgroup.class.php | centreon/www/api/class/centreon_configuration_hostgroup.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 __DIR__ . '/centreon_configuration_objects.class.php';
/**
* Class
*
* @class CentreonConfigurationHostgroup
*/
class CentreonConfigurationHostgroup extends CentreonConfigurationObjects
{
/** @var CentreonDB */
protected $pearDBMonitoring;
/**
* CentreonConfigurationHostgroup constructor
*/
public function __construct()
{
parent::__construct();
$this->pearDBMonitoring = new CentreonDB('centstorage');
}
/**
* @throws PDOException
* @throws RestBadRequestException
* @return array
*/
public function getList()
{
global $centreon;
$userId = $centreon->user->user_id;
$isAdmin = $centreon->user->admin;
$aclHostGroups = '';
$queryValues = [];
// Get ACL if user is not admin
if (
! $isAdmin
&& $centreon->user->access->hasAccessToAllHostGroups === false
) {
$acl = new CentreonACL($userId, $isAdmin);
$aclHostGroups .= ' AND hg.hg_id IN (' . $acl->getHostGroupsString() . ') ';
}
$query = filter_var(
$this->arguments['q'] ?? '',
FILTER_SANITIZE_FULL_SPECIAL_CHARS
);
$limit = array_key_exists('page_limit', $this->arguments)
? filter_var($this->arguments['page_limit'], FILTER_VALIDATE_INT)
: null;
$page = array_key_exists('page', $this->arguments)
? filter_var($this->arguments['page'], FILTER_VALIDATE_INT)
: null;
if ($limit === false) {
throw new RestBadRequestException('Error, limit must be an integer greater than zero');
}
if ($page === false) {
throw new RestBadRequestException('Error, page must be an integer greater than zero');
}
$queryValues['hostGroupName'] = $query !== '' ? '%' . $query . '%' : '%%';
$range = '';
if (
$page !== null
&& $limit !== null
) {
$range = ' LIMIT :offset, :limit';
$queryValues['offset'] = (int) (($page - 1) * $limit);
$queryValues['limit'] = $limit;
}
$request = <<<SQL
SELECT SQL_CALC_FOUND_ROWS DISTINCT
hg.hg_name,
hg.hg_id,
hg.hg_activate
FROM hostgroup hg
WHERE hg.hg_name LIKE :hostGroupName {$aclHostGroups}
ORDER BY hg.hg_name
{$range}
SQL;
$statement = $this->pearDB->prepare($request);
$statement->bindValue(':hostGroupName', $queryValues['hostGroupName'], PDO::PARAM_STR);
if (isset($queryValues['offset'])) {
$statement->bindValue(':offset', $queryValues['offset'], PDO::PARAM_INT);
$statement->bindValue(':limit', $queryValues['limit'], PDO::PARAM_INT);
}
$statement->execute();
$hostGroupList = [];
while ($record = $statement->fetch()) {
$hostGroupList[] = [
'id' => htmlentities($record['hg_id']),
'text' => $record['hg_name'],
'status' => (bool) $record['hg_activate'],
];
}
return [
'items' => $hostGroupList,
'total' => (int) $this->pearDB->numberRows(),
];
}
/**
* @throws PDOException
* @throws RestBadRequestException
* @return array
*/
public function getHostList()
{
global $centreon;
$userId = $centreon->user->user_id;
$isAdmin = $centreon->user->admin;
$queryValues = [];
// Get ACL if user is not admin
if (! $isAdmin) {
$acl = new CentreonACL($userId, $isAdmin);
if ($centreon->user->access->hasAccessToAllHostGroups === false) {
$filters[] = ' hg.hg_id IN (' . $acl->getHostGroupsString() . ') ';
}
$filters[] = ' h.host_id IN (' . $acl->getHostsString($this->pearDBMonitoring) . ') ';
}
// Handle search by host group ids
$hostGroupIdsString = filter_var($this->arguments['hgid'] ?? '', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
$whereCondition = '';
if ($hostGroupIdsString !== '') {
$hostGroupIds = array_values(explode(',', $hostGroupIdsString));
foreach ($hostGroupIds as $key => $hostGroupId) {
if (! is_numeric($hostGroupId)) {
throw new RestBadRequestException('Error, host group id must be numerical');
}
$queryValues[':hostGroupId' . $key] = (int) $hostGroupId;
}
$whereCondition .= ' WHERE hg.hg_id IN (' . implode(',', $queryValues) . ')';
}
// Handle pagination and limit
$limit = array_key_exists('page_limit', $this->arguments)
? filter_var($this->arguments['page_limit'], FILTER_VALIDATE_INT)
: null;
$page = array_key_exists('page', $this->arguments)
? filter_var($this->arguments['page'], FILTER_VALIDATE_INT)
: null;
if ($limit === false) {
throw new RestBadRequestException('Error, limit must be an integer greater than zero');
}
if ($page === false) {
throw new RestBadRequestException('Error, page must be an integer greater than zero');
}
$range = '';
if (
$page !== null
&& $limit !== null
) {
$range = ' LIMIT :offset, :limit';
$queryValues['offset'] = (int) (($page - 1) * $limit);
$queryValues['limit'] = $limit;
}
$request = <<<'SQL_WRAP'
SELECT SQL_CALC_FOUND_ROWS DISTINCT
h.host_name,
h.host_id
FROM hostgroup hg
INNER JOIN hostgroup_relation hgr
ON hg.hg_id = hgr.hostgroup_hg_id
INNER JOIN host h
ON h.host_id = hgr.host_host_id
SQL_WRAP;
if ($filters !== []) {
$whereCondition .= empty($whereCondition) ? ' WHERE ' : ' AND ';
$whereCondition .= implode(' AND ', $filters);
}
$request .= $whereCondition . $range;
$statement = $this->pearDB->prepare($request);
foreach ($queryValues as $key => $value) {
$statement->bindValue($key, $value, PDO::PARAM_INT);
}
$statement->execute();
$hostList = [];
while ($record = $statement->fetch()) {
$hostList[] = [
'id' => htmlentities($record['host_id']),
'text' => $record['host_name'],
];
}
return [
'items' => $hostList,
'total' => (int) $this->pearDB->numberRows(),
];
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/api/class/centreon_realtime_hosts.class.php | centreon/www/api/class/centreon_realtime_hosts.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
*
*/
declare(strict_types=1);
require_once _CENTREON_PATH_ . '/www/class/centreonDB.class.php';
require_once __DIR__ . '/centreon_configuration_objects.class.php';
require_once __DIR__ . '/centreon_realtime_base.class.php';
/**
* Class
*
* @class CentreonRealtimeHosts
*/
class CentreonRealtimeHosts extends CentreonRealtimeBase
{
/** @var CentreonDB */
protected $aclObj;
/** @var int */
protected $admin;
// parameters
/** @var int */
protected $limit;
/** @var int */
protected $number;
/** @var string */
protected $status;
/** @var array|null */
protected $hostgroup;
/** @var string|null */
protected $search;
/** @var */
protected $searchHost;
/** @var string|null */
protected $viewType;
/** @var string|null */
protected $sortType;
/** @var string|null */
protected $order;
/** @var string|null */
protected $instance;
/** @var string|null */
protected $criticality;
/** @var string */
protected $fieldList;
/**
* CentreonConfigurationService constructor
*/
public function __construct()
{
global $centreon;
parent::__construct();
// Init ACL
if (! $centreon->user->admin) {
$this->admin = 0;
$this->aclObj = new CentreonACL($centreon->user->user_id, $centreon->user->admin);
} else {
$this->admin = 1;
}
}
/**
* @throws PDOException
* @throws RestBadRequestException
* @return array
*/
public function getList()
{
$this->setHostFilters();
$this->setHostFieldList();
return $this->getHostState();
}
/**
* @throws PDOException
* @throws RestBadRequestException
* @return array
*/
public function getHostState()
{
$queryValues = [];
$tables = 'instances i, '
. (! $this->admin ? 'centreon_acl, ' : '')
. ($this->hostgroup ? 'hosts_hostgroups hhg, hostgroups hg, ' : '')
. ($this->criticality ? 'customvariables cvs, ' : '')
. '`hosts` h';
$criticalityConditions = '';
if ($this->criticality) {
$criticalityConditions = <<<'SQL'
AND h.host_id = cvs.host_id
AND cvs.name = 'CRITICALITY_LEVEL'
AND (cvs.service_id IS NULL OR cvs.service_id = 0)
AND cvs.value = :criticality
SQL;
$queryValues['criticality'] = (string) $this->criticality;
}
$nonAdminConditions = '';
if (! $this->admin) {
$nonAdminConditions .= ' AND h.host_id = centreon_acl.host_id ';
$nonAdminConditions .= $this->aclObj->queryBuilder(
'AND',
'centreon_acl.group_id',
$this->aclObj->getAccessGroupsString()
);
}
$viewTypeConditions = '';
if ($this->viewType === 'unhandled') {
$viewTypeConditions = <<<'SQL'
AND h.state = 1
AND h.state_type = '1'
AND h.acknowledged = 0
AND h.scheduled_downtime_depth = 0
SQL;
} elseif ($this->viewType === 'problems') {
$viewTypeConditions = ' AND (h.state <> 0 AND h.state <> 4) ';
}
$statusConditions = '';
if ($this->status === 'up') {
$statusConditions = ' AND h.state = 0 ';
} elseif ($this->status === 'down') {
$statusConditions = ' AND h.state = 1 ';
} elseif ($this->status === 'unreachable') {
$statusConditions = ' AND h.state = 2 ';
} elseif ($this->status === 'pending') {
$statusConditions = ' AND h.state = 4 ';
}
$hostGroupConditions = '';
if ($this->hostgroup) {
$explodedValues = '';
foreach (explode(',', $this->hostgroup) as $hgId => $hgValue) {
if (! is_numeric($hgValue)) {
throw new RestBadRequestException('Error, host group id must be numerical');
}
$explodedValues .= ':hostgroup' . $hgId . ',';
$queryValues['hostgroup'][$hgId] = (int) $hgValue;
}
$explodedValues = rtrim($explodedValues, ',');
$hostGroupConditions = <<<SQL
AND h.host_id = hhg.host_id
AND hg.hostgroup_id IN ({$explodedValues})
AND hhg.hostgroup_id = hg.hostgroup_id
SQL;
}
$instanceConditions = '';
if ($this->instance !== -1 && ! empty($this->instance)) {
if (! is_numeric($this->instance)) {
throw new RestBadRequestException('Error, instance id must be numerical');
}
$instanceConditions = ' AND h.instance_id = :instanceId ';
$queryValues['instanceId'] = (int) $this->instance;
}
$order = '';
if (
! isset($this->arguments['fields'])
|| is_null($this->arguments['fields'])
|| in_array($this->sortType, explode(',', $this->arguments['fields']), true)
) {
$q = 'ASC';
if (isset($this->order) && mb_strtoupper($this->order) === 'DESC') {
$q = 'DESC';
}
switch ($this->sortType) {
case 'id':
$order = " ORDER BY h.host_id {$q}, h.name";
break;
case 'alias':
$order = " ORDER BY h.alias {$q}, h.name";
break;
case 'address':
$order = " ORDER BY IFNULL(inet_aton(h.address), h.address) {$q}, h.name ";
break;
case 'state':
$order = " ORDER BY h.state {$q}, h.name ";
break;
case 'last_state_change':
$order = " ORDER BY h.last_state_change {$q}, h.name ";
break;
case 'last_hard_state_change':
$order = " ORDER BY h.last_hard_state_change {$q}, h.name ";
break;
case 'acknowledged':
$order = "ORDER BY h.acknowledged {$q}, h.name";
break;
case 'last_check':
$order = " ORDER BY h.last_check {$q}, h.name ";
break;
case 'check_attempt':
$order = " ORDER BY h.check_attempt {$q}, h.name ";
break;
case 'max_check_attempts':
$order = " ORDER BY h.max_check_attempts {$q}, h.name";
break;
case 'instance_name':
$order = " ORDER BY i.name {$q}, h.name";
break;
case 'output':
$order = " ORDER BY h.output {$q}, h.name ";
break;
case 'criticality':
$order = " ORDER BY criticality {$q}, h.name ";
break;
case 'name':
default:
$order = " ORDER BY h.name {$q}";
break;
}
}
// Get Host status
$query = <<<SQL
SELECT SQL_CALC_FOUND_ROWS DISTINCT {$this->fieldList}
FROM {$tables}
LEFT JOIN hosts_hosts_parents hph
ON hph.parent_id = h.host_id
LEFT JOIN `customvariables` cv
ON (cv.host_id = h.host_id
AND (cv.service_id IS NULL OR cv.service_id = 0)
AND cv.name = 'CRITICALITY_LEVEL')
WHERE h.name NOT LIKE '\_Module\_%'
AND h.instance_id = i.instance_id
{$criticalityConditions}
{$nonAdminConditions}
AND (h.name LIKE :searchName OR h.alias LIKE :searchAlias OR h.address LIKE :searchAddress)
{$viewTypeConditions}
{$statusConditions}
{$hostGroupConditions}
{$instanceConditions}
AND h.enabled = 1
{$order}
LIMIT :offset,:limit
SQL;
$queryValues['searchName'] = '%' . (string) $this->search . '%';
$queryValues['searchAlias'] = '%' . (string) $this->search . '%';
$queryValues['searchAddress'] = '%' . (string) $this->search . '%';
$queryValues['offset'] = (int) ($this->number * $this->limit);
$queryValues['limit'] = (int) $this->limit;
$stmt = $this->realTimeDb->prepare($query);
if ($this->criticality) {
$stmt->bindParam(':criticality', $queryValues['criticality'], PDO::PARAM_STR);
}
$stmt->bindParam(':searchName', $queryValues['searchName'], PDO::PARAM_STR);
$stmt->bindParam(':searchAlias', $queryValues['searchAlias'], PDO::PARAM_STR);
$stmt->bindParam(':searchAddress', $queryValues['searchAddress'], PDO::PARAM_STR);
if (isset($queryValues['hostgroup'])) {
foreach ($queryValues['hostgroup'] as $hgId => $hgValue) {
$stmt->bindValue(':hostgroup' . $hgId, $hgValue, PDO::PARAM_INT);
}
}
if (isset($queryValues['instanceId'])) {
$stmt->bindParam(':instanceId', $queryValues['instanceId'], PDO::PARAM_INT);
}
$stmt->bindParam(':offset', $queryValues['offset'], PDO::PARAM_INT);
$stmt->bindParam(':limit', $queryValues['limit'], PDO::PARAM_INT);
$stmt->execute();
$dataList = [];
while ($data = $stmt->fetch()) {
$dataList[] = $data;
}
return $dataList;
}
/**
* Set a list of filters send by the request.
*
* @throws RestBadRequestException
*/
protected function setHostFilters(): void
{
// Pagination Elements
$this->limit = $this->arguments['limit'] ?? 30;
$this->number = $this->arguments['number'] ?? 0;
if (! is_numeric($this->number) || ! is_numeric($this->limit)) {
throw new RestBadRequestException('Error, limit must be numerical');
}
// Filters
if (isset($this->arguments['status'])) {
$statusList = ['up', 'down', 'unreachable', 'pending', 'all'];
if (in_array(mb_strtolower($this->arguments['status']), $statusList, true)) {
$this->status = $this->arguments['status'];
} else {
throw new RestBadRequestException('Bad status parameter');
}
} else {
$this->status = null;
}
$this->hostgroup = $this->arguments['hostgroup'] ?? null;
$this->search = $this->arguments['search'] ?? null;
$this->instance = $this->arguments['instance'] ?? null;
$this->criticality = $this->arguments['criticality'] ?? null;
// view properties
$this->viewType = $this->arguments['viewType'] ?? null;
if (isset($this->arguments['order'])) {
if (
mb_strtolower($this->arguments['order']) === 'asc'
|| mb_strtolower($this->arguments['order']) === 'desc'
) {
$this->order = $this->arguments['order'];
} else {
throw new RestBadRequestException('Bad order parameter');
}
} else {
$this->order = null;
}
$this->sortType = $this->arguments['sortType'] ?? null;
}
/**
* Get selected fields by the request.
*
* @return array
*/
protected function getFieldContent()
{
$tab = explode(',', $this->arguments['fields']);
$fieldList = [];
foreach ($tab as $key) {
$fieldList[trim($key)] = 1;
}
return $fieldList;
}
/**
* Set Filters.
*/
protected function setHostFieldList(): void
{
$fields = [];
if (! isset($this->arguments['fields'])) {
$fields['h.host_id as id'] = 'host_id';
$fields['h.name'] = 'name';
$fields['h.alias'] = 'alias';
$fields['h.address'] = 'address';
$fields['h.state'] = 'state';
$fields['h.state_type'] = 'state_type';
$fields['h.output'] = 'output';
$fields['h.max_check_attempts'] = 'max_check_attempts';
$fields['h.check_attempt'] = 'check_attempt';
$fields['h.last_check'] = 'last_check';
$fields['h.last_state_change'] = 'last_state_change';
$fields['h.last_hard_state_change'] = 'last_hard_state_change';
$fields['h.acknowledged'] = 'acknowledged';
$fields['i.name as instance_name'] = 'instance';
$fields['cv.value as criticality'] = 'criticality';
} else {
$fieldList = $this->getFieldContent();
if (isset($fieldList['id'])) {
$fields['h.host_id as id'] = 'host_id';
}
if (isset($fieldList['name'])) {
$fields['h.name'] = 'name';
}
if (isset($fieldList['alias'])) {
$fields['h.alias'] = 'alias';
}
if (isset($fieldList['address'])) {
$fields['h.address'] = 'address';
}
if (isset($fieldList['state'])) {
$fields['h.state'] = 'state';
}
if (isset($fieldList['state_type'])) {
$fields['h.state_type'] = 'state_type';
}
if (isset($fieldList['output'])) {
$fields['h.output'] = 'output';
}
if (isset($fieldList['max_check_attempts'])) {
$fields['h.max_check_attempts'] = 'max_check_attempts';
}
if (isset($fieldList['check_attempt'])) {
$fields['h.check_attempt'] = 'check_attempt';
}
if (isset($fieldList['last_check'])) {
$fields['h.last_check'] = 'last_check';
}
if (isset($fieldList['next_check'])) {
$fields['h.next_check'] = 'next_check';
}
if (isset($fieldList['last_state_change'])) {
$fields['h.last_state_change'] = 'last_state_change';
}
if (isset($fieldList['last_hard_state_change'])) {
$fields['h.last_hard_state_change'] = 'last_hard_state_change';
}
if (isset($fieldList['acknowledged'])) {
$fields['h.acknowledged'] = 'acknowledged';
}
if (isset($fieldList['instance'])) {
$fields['i.name as instance_name'] = 'instance';
}
if (isset($fieldList['instance_id'])) {
$fields['i.instance_id as instance_id'] = 'instance_id';
}
if (isset($fieldList['criticality'])) {
$fields['cv.value as criticality'] = 'criticality';
}
if (isset($fieldList['passive_checks'])) {
$fields['h.passive_checks'] = 'passive_checks';
}
if (isset($fieldList['active_checks'])) {
$fields['h.active_checks'] = 'active_checks';
}
if (isset($fieldList['notify'])) {
$fields['h.notify'] = 'notify';
}
if (isset($fieldList['action_url'])) {
$fields['h.action_url'] = 'action_url';
}
if (isset($fieldList['notes_url'])) {
$fields['h.notes_url'] = 'notes_url';
}
if (isset($fieldList['notes'])) {
$fields['h.notes'] = 'notes';
}
if (isset($fieldList['icon_image'])) {
$fields['h.icon_image'] = 'icon_image';
}
if (isset($fieldList['icon_image_alt'])) {
$fields['h.icon_image_alt'] = 'icon_image_alt';
}
if (isset($fieldList['scheduled_downtime_depth'])) {
$fields['h.scheduled_downtime_depth'] = 'scheduled_downtime_depth';
}
if (isset($fieldList['flapping'])) {
$fields['h.flapping'] = 'flapping';
}
}
// Build Field List
$this->fieldList = '';
foreach ($fields as $key => $value) {
if ($this->fieldList !== '') {
$this->fieldList .= ', ';
}
$this->fieldList .= $key;
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/api/class/centreon_datepicker_i18n.class.php | centreon/www/api/class/centreon_datepicker_i18n.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 CentreonDatepickerI18n
* @description Webservice that allow to load the datepicker library from user's language if the file exists.
*/
class CentreonDatepickerI18n extends CentreonWebService
{
/**
* Used to search and load the right datepicker library if it exists.
*
* @return string|null
*/
public function getDatepickerLibrary()
{
$data = $this->arguments['data'];
$path = __DIR__ . '/../../include/common/javascript/datepicker/';
// check if the fullLocale library exist
$datepickerFileToFound = 'datepicker-' . substr($data, 0, 5) . '.js';
$valid = file_exists($path . $datepickerFileToFound);
// if not found, then check if the shortLocale library exist
if ($valid !== true) {
$datepickerFileToFound = 'datepicker-' . substr($data, 0, 2) . '.js';
$valid = file_exists($path . $datepickerFileToFound);
}
// sending result
return ($valid === true) ? $datepickerFileToFound : null;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/api/class/centreon_configuration_contactgroup.class.php | centreon/www/api/class/centreon_configuration_contactgroup.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/centreonContactgroup.class.php';
require_once _CENTREON_PATH_ . '/www/class/centreonLDAP.class.php';
require_once __DIR__ . '/centreon_configuration_objects.class.php';
/**
* Class
*
* @class CentreonConfigurationContactgroup
*/
class CentreonConfigurationContactgroup extends CentreonConfigurationObjects
{
/**
* CentreonConfigurationContactgroup constructor
*/
public function __construct()
{
parent::__construct();
}
/**
* @throws PDOException
* @throws RestBadRequestException
* @return array
*/
public function getList()
{
global $centreon;
if (isset($this->arguments['page_limit'], $this->arguments['page'])) {
if (
! is_numeric($this->arguments['page'])
|| ! is_numeric($this->arguments['page_limit'])
|| $this->arguments['page_limit'] < 1
) {
throw new RestBadRequestException('Error, limit must be an integer greater than zero');
}
$limit = ($this->arguments['page'] - 1) * $this->arguments['page_limit'];
$offset = $this->arguments['page_limit'];
$range = $limit . ',' . $offset;
} else {
$range = '';
}
$filterContactgroup = [];
$ldapFilter = '';
if (isset($this->arguments['q'])) {
$filterContactgroup['cg_name'] = ['LIKE', '%' . $this->arguments['q'] . '%'];
$filterContactgroup['cg_alias'] = ['OR', 'LIKE', '%' . $this->arguments['q'] . '%'];
$ldapFilter = $this->arguments['q'];
}
$cg = new CentreonContactgroup($this->pearDB);
$acl = new CentreonACL($centreon->user->user_id);
$aclCgs = $acl->getContactGroupAclConf(
['fields' => ['cg_id', 'cg_name', 'cg_type', 'ar_name'], 'get_row' => null, 'keys' => ['cg_id'], 'conditions' => $filterContactgroup, 'order' => ['cg_name'], 'pages' => $range, 'total' => true],
false
);
$contactgroupList = [];
foreach ($aclCgs['items'] as $id => $contactgroup) {
// If we query local contactgroups and the contactgroup type is ldap, we skip it
if (
isset($this->arguments['type'])
&& ($this->arguments['type'] === 'local')
&& ($contactgroup['cg_type'] === 'ldap')
) {
--$aclCgs['total'];
continue;
}
$sText = $contactgroup['cg_name'];
if ($contactgroup['cg_type'] == 'ldap') {
$sText .= ' (LDAP : ' . $contactgroup['ar_name'] . ')';
}
$id = $contactgroup['cg_id'];
$contactgroupList[] = ['id' => $id, 'text' => $sText];
}
// get Ldap contactgroups
// If we don't query local contactgroups, we can return an array with ldap contactgroups
if (! isset($this->arguments['type']) || $this->arguments['type'] !== 'local') {
$ldapCgs = [];
if (isset($this->arguments['page_limit'], $this->arguments['page'])) {
$maxItem = $this->arguments['page_limit'] * $this->arguments['page'];
if ($aclCgs['total'] <= $maxItem) {
$ldapCgs = $cg->getLdapContactgroups($ldapFilter);
}
} else {
$ldapCgs = $cg->getLdapContactgroups($ldapFilter);
}
foreach ($ldapCgs as $key => $value) {
$sTemp = $value;
if (! $this->uniqueKey($sTemp, $contactgroupList)) {
$contactgroupList[] = ['id' => $key, 'text' => $value];
}
}
}
return ['items' => $contactgroupList, 'total' => $aclCgs['total']];
}
/**
* @param $val
* @param array $array
*
* @return bool
*/
protected function uniqueKey($val, &$array)
{
if (! empty($val) && count($array) > 0) {
foreach ($array as $key => $value) {
if ($value['text'] == $val) {
return true;
}
}
}
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/api/class/webService.class.php | centreon/www/api/class/webService.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
*
*/
if (! (class_exists('centreonDB') || class_exists('\\centreonDB')) && defined('_CENTREON_PATH_')) {
require_once _CENTREON_PATH_ . '/www/class/centreonDB.class.php';
}
use Centreon\Infrastructure\Webservice\WebserviceAutorizePublicInterface;
use Centreon\Infrastructure\Webservice\WebserviceAutorizeRestApiInterface;
use Pimple\Container;
/**
* Class
*
* @class CentreonWebService
*/
class CentreonWebService
{
public const RESULT_HTML = 'html';
public const RESULT_JSON = 'json';
/** @var CentreonDB|null */
protected $pearDB = null;
/** @var array */
protected $arguments = [];
/** @var null */
protected $token = null;
/** @var */
protected static $webServicePaths;
/**
* CentreonWebService constructor
*/
public function __construct()
{
$this->loadDb();
$this->loadArguments();
$this->loadToken();
}
/**
* Authorize to access to the action
*
* @param string $action The action name
* @param CentreonUser $user The current user
* @param bool $isInternal If the api is call in internal
* @return bool If the user has access to the action
*/
public function authorize($action, $user, $isInternal = false)
{
return (bool) ($isInternal || ($user && $user->admin));
}
/**
* Send json return
*
* @param mixed $data
* @param int $code
* @param string|null $format
*
* @return void
*/
public static function sendResult($data, $code = 200, $format = null): void
{
switch ($code) {
case 500:
header('HTTP/1.1 500 Internal Server Error');
break;
case 502:
header('HTTP/1.1 502 Bad Gateway');
break;
case 503:
header('HTTP/1.1 503 Service Unavailable');
break;
case 504:
header('HTTP/1.1 504 Gateway Time-out');
break;
case 400:
header('HTTP/1.1 400 Bad Request');
break;
case 401:
header('HTTP/1.1 401 Unauthorized');
break;
case 403:
header('HTTP/1.1 403 Forbidden');
break;
case 404:
header('HTTP/1.1 404 Object not found');
break;
case 405:
header('HTTP/1.1 405 Method not allowed');
break;
case 409:
header('HTTP/1.1 409 Conflict');
break;
case 206:
header('HTTP/1.1 206 Partial content');
$data = json_decode($data, true);
break;
}
switch ($format) {
case static::RESULT_HTML:
header('Content-type: text/html');
echo $data;
break;
case static::RESULT_JSON:
case null:
header('Content-type: application/json;charset=utf-8');
echo json_encode($data, JSON_UNESCAPED_UNICODE);
break;
}
exit();
}
/**
* Route the webservice to the good method
*
* @param Container $dependencyInjector
* @param CentreonUser $user The current user
* @param bool $isInternal If the Rest API call is internal
*
* @throws PDOException
*/
public static function router(Container $dependencyInjector, $user, $isInternal = false): void
{
global $pearDB;
// Test if route is defined
if (isset($_GET['object']) === false || isset($_GET['action']) === false) {
static::sendResult('Bad parameters', 400);
}
$resultFormat = 'json';
if (isset($_GET['resultFormat'])) {
$resultFormat = $_GET['resultFormat'];
}
$methodPrefix = strtolower($_SERVER['REQUEST_METHOD']);
$object = $_GET['object'];
$action = $methodPrefix . ucfirst($_GET['action']);
// Generate path for WebService
self::$webServicePaths = glob(_CENTREON_PATH_ . '/www/api/class/*.class.php');
$res = $pearDB->query('SELECT name FROM modules_informations');
while ($row = $res->fetch()) {
self::$webServicePaths = array_merge(
self::$webServicePaths,
glob(_CENTREON_PATH_ . '/www/modules/' . $row['name'] . '/webServices/rest/*.class.php')
);
}
self::$webServicePaths = array_merge(
self::$webServicePaths,
glob(_CENTREON_PATH_ . '/www/widgets/*/webServices/rest/*.class.php')
);
$isService = $dependencyInjector['centreon.webservice']->has($object);
if ($isService === true) {
$webService = [
'class' => $dependencyInjector['centreon.webservice']->get($object),
];
// Initialize the language translator
$dependencyInjector['translator'];
// Use the web service if has been initialized or initialize it
if (isset($dependencyInjector[$webService['class']])) {
$wsObj = $dependencyInjector[$webService['class']];
} else {
$wsObj = new $webService['class']();
$wsObj->setDi($dependencyInjector);
}
} else {
$webService = self::webservicePath($object);
/**
* Either we retrieve an instance of this web service that has been
* created in the dependency injector, or we create a new one.
*/
if (isset($dependencyInjector[$webService['class']])) {
$wsObj = $dependencyInjector[$webService['class']];
} else {
// Initialize the webservice
require_once $webService['path'];
$wsObj = new $webService['class']();
}
}
if ($wsObj instanceof CentreonWebServiceDiInterface) {
$wsObj->finalConstruct($dependencyInjector);
}
if (method_exists($wsObj, $action) === false) {
static::sendResult('Method not found', 404);
}
// Execute the action
try {
if (! static::isWebserviceAllowed($wsObj, $action, $user, $isInternal)) {
static::sendResult('Forbidden', 403, static::RESULT_JSON);
}
static::updateTokenTtl();
$data = $wsObj->{$action}();
$wsObj::sendResult($data, 200, $resultFormat);
} catch (RestException $e) {
$wsObj::sendResult($e->getMessage(), $e->getCode());
} catch (Exception $e) {
$wsObj::sendResult($e->getMessage(), 500);
}
}
/**
* Load database
*
* @return void
*/
protected function loadDb()
{
$this->pearDB ??= new CentreonDB();
}
/**
* Load arguments compared http method
*
* @return void
*/
protected function loadArguments()
{
switch ($_SERVER['REQUEST_METHOD']) {
case 'GET':
$httpParams = $_GET;
unset($httpParams['action'], $httpParams['object']);
$this->arguments = $httpParams;
break;
case 'POST':
case 'PUT':
case 'PATCH':
$this->arguments = $this->parseBody();
break;
case 'DELETE':
break;
default:
static::sendResult('Bad request', 400);
break;
}
}
/**
* Parse the body for get arguments
* The body must be JSON format
* @return array
*/
protected function parseBody()
{
try {
$httpParams = json_decode(file_get_contents('php://input'), true);
} catch (Exception $e) {
static::sendResult('Bad parameters', 400);
}
return $httpParams;
}
/**
* Load the token for class if exists
*
* @return void
*/
protected function loadToken()
{
if (isset($_SERVER['HTTP_CENTREON_AUTH_TOKEN'])) {
$this->token = $_SERVER['HTTP_CENTREON_AUTH_TOKEN'];
}
}
/**
* Get webservice
*
* @param string $object
*
* @return array|mixed
*/
protected static function webservicePath($object = '')
{
$webServiceClass = [];
foreach (self::$webServicePaths as $webServicePath) {
if (str_contains($webServicePath, $object . '.class.php')) {
require_once $webServicePath;
$explodedClassName = explode('_', $object);
$className = '';
foreach ($explodedClassName as $partClassName) {
$className .= ucfirst(strtolower($partClassName));
}
if (class_exists($className)) {
$webServiceClass = ['path' => $webServicePath, 'class' => $className];
}
}
}
if ($webServiceClass === []) {
static::sendResult('Method not found', 404);
}
return $webServiceClass;
}
/**
* Update the ttl for a token if the authentication is by token
* Does not update the manual tokens
*
* @return void
*/
protected static function updateTokenTtl()
{
global $pearDB;
if (isset($_SERVER['HTTP_CENTREON_AUTH_TOKEN'])) {
try {
$stmt = $pearDB->prepare(
'UPDATE security_token st
INNER JOIN security_authentication_tokens sat
ON st.id = sat.provider_token_id AND sat.token_type = \'auto\'
SET st.expiration_date = (
SELECT UNIX_TIMESTAMP(NOW() + INTERVAL (`value` * 60) SECOND)
FROM `options`
wHERE `key` = \'session_expire\'
)
WHERE st.token = :token'
);
$stmt->bindValue(':token', $_SERVER['HTTP_CENTREON_AUTH_TOKEN'], PDO::PARAM_STR);
$stmt->execute();
} catch (Exception $e) {
static::sendResult('Internal error', 500);
}
}
}
/**
* Check webservice authorization
*
* @param WebserviceAutorizePublicInterface|WebserviceAutorizeRestApiInterface $webservice
* @param string $action The action name
* @param CentreonUser|null $user The current user
* @param bool $isInternal If the api is call from internal
*
* @return bool if the webservice is allowed for the current user
*/
private static function isWebserviceAllowed($webservice, $action, $user, $isInternal): bool
{
$allowed = false;
// skip checks if public interface is implemented
if ($webservice instanceof WebserviceAutorizePublicInterface) {
$allowed = true;
} else {
$allowed = $webservice->authorize($action, $user, $isInternal);
}
return $allowed;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/api/class/centreon_configuration_graphcurve.class.php | centreon/www/api/class/centreon_configuration_graphcurve.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 __DIR__ . '/centreon_configuration_objects.class.php';
/**
* Class
*
* @class CentreonConfigurationGraphcurve
*/
class CentreonConfigurationGraphcurve extends CentreonConfigurationObjects
{
/**
* CentreonConfigurationGraphcurve constructor
*/
public function __construct()
{
parent::__construct();
}
/**
* @throws RestBadRequestException|PDOException
* @return array
*/
public function getList()
{
$queryValues = [];
// Check for select2 'q' argument
$queryValues['name'] = isset($this->arguments['q']) === false ? '%%' : '%' . (string) $this->arguments['q'] . '%';
$query = 'SELECT SQL_CALC_FOUND_ROWS DISTINCT compo_id, name '
. 'FROM giv_components_template '
. 'WHERE name LIKE :name '
. 'ORDER BY name ';
if (isset($this->arguments['page_limit'], $this->arguments['page'])) {
if (
! is_numeric($this->arguments['page'])
|| ! is_numeric($this->arguments['page_limit'])
|| $this->arguments['page_limit'] < 1
) {
throw new RestBadRequestException('Error, limit must be an integer greater than zero');
}
$offset = ($this->arguments['page'] - 1) * $this->arguments['page_limit'];
$query .= 'LIMIT :offset, :limit';
$queryValues['offset'] = (int) $offset;
$queryValues['limit'] = (int) $this->arguments['page_limit'];
}
$stmt = $this->pearDB->prepare($query);
$stmt->bindParam(':name', $queryValues['name'], PDO::PARAM_STR);
if (isset($queryValues['offset'])) {
$stmt->bindParam(':offset', $queryValues['offset'], PDO::PARAM_INT);
$stmt->bindParam(':limit', $queryValues['limit'], PDO::PARAM_INT);
}
$stmt->execute();
$graphCurveList = [];
while ($data = $stmt->fetch()) {
$graphCurveList[] = ['id' => $data['compo_id'], 'text' => $data['name']];
}
return ['items' => $graphCurveList, 'total' => (int) $this->pearDB->numberRows()];
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/api/class/centreon_performance_service.class.php | centreon/www/api/class/centreon_performance_service.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/centreonACL.class.php';
require_once _CENTREON_PATH_ . '/www/class/centreonHook.class.php';
require_once __DIR__ . '/centreon_configuration_objects.class.php';
/**
* Class
*
* @class CentreonPerformanceService
*/
class CentreonPerformanceService extends CentreonConfigurationObjects
{
/** @var array */
public $arguments;
/** @var CentreonDB */
protected $pearDBMonitoring;
/**
* CentreonPerformanceService constructor
*/
public function __construct()
{
$this->pearDBMonitoring = new CentreonDB('centstorage');
}
/**
* @throws PDOException
* @throws RestBadRequestException
* @return array
*/
public function getList()
{
global $centreon, $conf_centreon;
$this->setArguments();
$userId = $centreon->user->user_id;
$isAdmin = $centreon->user->admin;
$additionalTables = '';
$additionalValues = [];
$additionalCondition = '';
$bindParams = [];
$excludeAnomalyDetection = false;
// Get ACL if user is not admin
$acl = null;
if (! $isAdmin) {
$acl = new CentreonACL($userId, $isAdmin);
}
$bindParams[':fullName'] = isset($this->arguments['q']) === false ? '%%' : '%' . (string) $this->arguments['q'] . '%';
if (isset($this->arguments['e']) && strcmp('anomaly', $this->arguments['e']) == 0) {
$excludeAnomalyDetection = true;
}
$query = 'SELECT SQL_CALC_FOUND_ROWS DISTINCT 1 AS REALTIME, 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, services s ' . (! $isAdmin ? ', centreon_acl acl ' : '');
if (isset($this->arguments['hostgroup'])) {
$additionalTables .= ',hosts_hostgroups hg ';
}
if (isset($this->arguments['servicegroup'])) {
$additionalTables .= ',services_servicegroups sg ';
}
$query .= $additionalTables
. 'WHERE i.id = m.index_id '
. 'AND s.enabled = 1 '
. 'AND i.service_id = s.service_id '
. 'AND i.host_name NOT LIKE "\_Module\_%" '
. 'AND CONCAT(i.host_name, " - ", i.service_description) LIKE :fullName ';
if (! $isAdmin) {
$query .= 'AND acl.host_id = i.host_id '
. 'AND acl.service_id = i.service_id '
. 'AND acl.group_id IN (' . $acl->getAccessGroupsString() . ') ';
}
if ($excludeAnomalyDetection) {
$additionalCondition .= 'AND s.service_id NOT IN (SELECT service_id
FROM `' . $conf_centreon['db'] . '`.mod_anomaly_service) ';
}
if (isset($this->arguments['hostgroup'])) {
$additionalCondition .= 'AND (hg.host_id = i.host_id '
. 'AND hg.hostgroup_id IN (';
$params = [];
foreach ($this->arguments['hostgroup'] as $k => $v) {
if (! is_numeric($v)) {
throw new RestBadRequestException('Error, host group id must be numerical');
}
$params[':hgId' . $v] = (int) $v;
}
$bindParams = array_merge($bindParams, $params);
$additionalCondition .= implode(',', array_keys($params)) . ')) ';
}
if (isset($this->arguments['servicegroup'])) {
$additionalCondition .= 'AND (sg.host_id = i.host_id AND sg.service_id = i.service_id '
. 'AND sg.servicegroup_id IN (';
$params = [];
foreach ($this->arguments['servicegroup'] as $k => $v) {
if (! is_numeric($v)) {
throw new RestBadRequestException('Error, service group id must be numerical');
}
$params[':sgId' . $v] = (int) $v;
}
$bindParams = array_merge($bindParams, $params);
$additionalCondition .= implode(',', array_keys($params)) . ')) ';
}
if (isset($this->arguments['host'])) {
$additionalCondition .= 'AND i.host_id IN (';
$params = [];
foreach ($this->arguments['host'] as $k => $v) {
if (! is_numeric($v)) {
throw new RestBadRequestException('Error, host id must be numerical');
}
$params[':hostId' . $v] = (int) $v;
}
$bindParams = array_merge($bindParams, $params);
$additionalCondition .= implode(',', array_keys($params)) . ') ';
}
$query .= $additionalCondition . ') ';
if (isset($acl)) {
$virtualObject = $this->getVirtualServicesCondition(
$additionalTables,
$additionalCondition,
$additionalValues,
$acl
);
$virtualServicesCondition = $virtualObject['query'];
$virtualValues = $virtualObject['value'];
} else {
$virtualObject = $this->getVirtualServicesCondition(
$additionalTables,
$additionalCondition,
$additionalValues
);
$virtualServicesCondition = $virtualObject['query'];
$virtualValues = $virtualObject['value'];
}
$query .= $virtualServicesCondition . ') as t_union '
. 'WHERE fullname LIKE :fullName '
. 'GROUP BY host_id, service_id, fullname, index_id '
. 'ORDER BY fullname ';
if (isset($this->arguments['page_limit'], $this->arguments['page'])) {
if (
! is_numeric($this->arguments['page'])
|| ! is_numeric($this->arguments['page_limit'])
|| $this->arguments['page_limit'] < 1
) {
throw new RestBadRequestException('Error, limit must be an integer greater than zero');
}
$offset = ($this->arguments['page'] - 1) * $this->arguments['page_limit'];
$query .= 'LIMIT :offset, :limit';
$bindParams[':offset'] = (int) $offset;
$bindParams[':limit'] = (int) $this->arguments['page_limit'];
}
$stmt = $this->pearDBMonitoring->prepare($query);
$stmt->bindValue(':fullName', $bindParams[':fullName'], PDO::PARAM_STR);
unset($bindParams[':fullName']);
foreach ($bindParams as $k => $v) {
$stmt->bindValue($k, $v, PDO::PARAM_INT);
}
if (isset($virtualValues['metaService'])) {
foreach ($virtualValues['metaService'] as $k => $v) {
$stmt->bindValue(':' . $k, $v, PDO::PARAM_INT);
}
}
if (isset($virtualValues['virtualService'])) {
foreach ($virtualValues['virtualService'] as $k => $v) {
$stmt->bindValue(':' . $k, $v, PDO::PARAM_INT);
}
}
$stmt->execute();
$serviceList = [];
while ($data = $stmt->fetch()) {
$serviceCompleteName = $data['fullname'];
$serviceCompleteId = $data['host_id'] . '-' . $data['service_id'];
$serviceList[] = ['id' => htmlentities($serviceCompleteId), 'text' => $serviceCompleteName];
}
return ['items' => $serviceList, 'total' => (int) $this->pearDBMonitoring->query('SELECT FOUND_ROWS() AS REALTIME')->fetchColumn()];
}
/**
* @param $additionalTables
* @param $additionalCondition
* @param $additionalValues
* @param CentreonACL|null $aclObj
* @throws RestBadRequestException
* @return array
*/
private function getVirtualServicesCondition(
$additionalTables,
$additionalCondition,
$additionalValues,
$aclObj = null,
) {
global $centreon;
$userId = $centreon->user->user_id;
$isAdmin = $centreon->user->admin;
// Get ACL if user is not admin
$acl = null;
if (! $isAdmin) {
$acl = new CentreonACL($userId, $isAdmin);
}
// First, get virtual services for metaservices
$metaServiceCondition = '';
$metaValues = $additionalValues;
if (isset($aclObj)) {
$metaServices = $aclObj->getMetaServices();
$virtualServices = [];
foreach ($metaServices as $metaServiceId => $metaServiceName) {
$virtualServices[] = 'meta_' . $metaServiceId;
}
if ($virtualServices !== []) {
$metaServiceCondition = 'AND s.description IN (';
$explodedValues = '';
foreach ($virtualServices as $k => $v) {
$explodedValues .= ':meta' . $k . ',';
$metaValues['metaService']['meta' . $k] = (string) $v;
}
$explodedValues = rtrim($explodedValues, ',');
$metaServiceCondition .= $explodedValues . ') ';
}
}
$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 ' . (! $isAdmin ? ', centreon_acl acl ' : '')
. $additionalTables
. 'WHERE i.id = m.index_id '
. 'AND s.enabled = 1 '
. $additionalCondition
. $metaServiceCondition
. 'AND i.service_id = s.service_id ';
if (! $isAdmin) {
$virtualServicesCondition .= 'AND acl.host_id = i.host_id '
. 'AND acl.service_id = i.service_id '
. 'AND acl.group_id IN (' . $acl->getAccessGroupsString() . ') ';
}
$virtualServicesCondition .= ') ';
// Then, get virtual services for modules if not in anomaly detection context
$allVirtualServiceIds = [];
if (($this->arguments['e'] ?? null) !== 'anomaly') {
$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 '
. $additionalTables
. 'WHERE i.id = m.index_id '
. 'AND s.enabled = 1 '
. $additionalCondition
. 'AND s.service_id IN (';
$explodedValues = '';
foreach ($virtualServiceIds as $k => $v) {
if (! is_numeric($v)) {
throw new RestBadRequestException('Error, virtual service id must be numerical');
}
$explodedValues .= ':vService' . $v . ',';
$metaValues['virtualService']['vService' . $v] = (int) $v;
}
$explodedValues = rtrim($explodedValues, ',');
$virtualServicesCondition .= $explodedValues . ') '
. 'AND i.service_id = s.service_id '
. ') ';
}
}
}
return ['query' => $virtualServicesCondition, 'value' => $metaValues];
}
private function setArguments(): void
{
$this->arguments = $_GET;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/api/class/centreon_configuration_servicegroup.class.php | centreon/www/api/class/centreon_configuration_servicegroup.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 __DIR__ . '/centreon_configuration_objects.class.php';
/**
* Class
*
* @class CentreonConfigurationServicegroup
*/
class CentreonConfigurationServicegroup extends CentreonConfigurationObjects
{
/** @var CentreonDB */
protected $pearDBMonitoring;
/**
* CentreonConfigurationServicegroup constructor
*/
public function __construct()
{
$this->pearDBMonitoring = new CentreonDB('centstorage');
parent::__construct();
}
/**
* @throws PDOException
* @throws RestBadRequestException
* @return array
*/
public function getList()
{
global $centreon;
$isAdmin = $centreon->user->admin;
$userId = $centreon->user->user_id;
$queryValues = [];
$aclServicegroups = '';
$query = filter_var(
$this->arguments['q'] ?? '',
FILTER_SANITIZE_FULL_SPECIAL_CHARS
);
$limit = array_key_exists('page_limit', $this->arguments)
? filter_var($this->arguments['page_limit'], FILTER_VALIDATE_INT)
: null;
$page = array_key_exists('page', $this->arguments)
? filter_var($this->arguments['page'], FILTER_VALIDATE_INT)
: null;
if ($limit === false) {
throw new RestBadRequestException('Error, limit must be an integer greater than zero');
}
if ($page === false) {
throw new RestBadRequestException('Error, page must be an integer greater than zero');
}
$queryValues['serviceGroupName'] = $query !== '' ? '%' . $query . '%' : '%%';
$range = '';
if (
$page !== null
&& $limit !== null
) {
$range = ' LIMIT :offset, :limit';
$queryValues['offset'] = (int) (($page - 1) * $limit);
$queryValues['limit'] = $limit;
}
// Get ACL if user is not admin or does not have access to all servicegroups
if (
! $isAdmin
&& $centreon->user->access->hasAccessToAllServiceGroups === false
) {
$acl = new CentreonACL($userId, $isAdmin);
$aclServicegroups .= ' AND sg_id IN (' . $acl->getServiceGroupsString('ID') . ') ';
}
$request = <<<SQL
SELECT SQL_CALC_FOUND_ROWS DISTINCT
sg.sg_id,
sg.sg_name,
sg.sg_activate
FROM servicegroup sg
WHERE sg_name LIKE :serviceGroupName {$aclServicegroups}
ORDER BY sg.sg_name
{$range}
SQL;
$statement = $this->pearDB->prepare($request);
$statement->bindValue(':serviceGroupName', $queryValues['serviceGroupName'], PDO::PARAM_STR);
if (isset($queryValues['offset'])) {
$statement->bindParam(':offset', $queryValues['offset'], PDO::PARAM_INT);
$statement->bindParam(':limit', $queryValues['limit'], PDO::PARAM_INT);
}
$statement->execute();
$serviceGroups = [];
while ($record = $statement->fetch(PDO::FETCH_ASSOC)) {
$serviceGroups[] = [
'id' => htmlentities($record['sg_id']),
'text' => $record['sg_name'],
'status' => (bool) $record['sg_activate'],
];
}
return [
'items' => $serviceGroups,
'total' => (int) $this->pearDB->numberRows(),
];
}
/**
* @throws PDOException
* @throws RestBadRequestException
* @return array
*/
public function getServiceList()
{
global $centreon;
$isAdmin = $centreon->user->admin;
$userId = $centreon->user->user_id;
$queryValues = [];
$serviceGroupIdsString = filter_var($this->arguments['sgid'] ?? '', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
$whereCondition = '';
// Handle the search by service groups IDs
if ($serviceGroupIdsString !== '') {
$serviceGroupIds = array_values(explode(',', $serviceGroupIdsString));
foreach ($serviceGroupIds as $key => $serviceGroupId) {
if (! is_numeric($serviceGroupId)) {
throw new RestBadRequestException('Error, service group id must be numerical');
}
$queryValues[':serviceGroupId' . $key] = (int) $serviceGroupId;
}
$whereCondition .= ' WHERE sg.sg_id IN (' . implode(',', array_keys($queryValues)) . ')';
}
$filters = [];
// Get ACL if user is not admin
if (! $isAdmin) {
$acl = new CentreonACL($userId, $isAdmin);
if ($centreon->user->access->hasAccessToAllServiceGroups === false) {
$filters[] = ' sg.sg_id IN (' . $acl->getServiceGroupsString() . ') ';
}
$filters[] = ' s.service_id IN (' . $acl->getServicesString($this->pearDBMonitoring) . ') ';
}
$request = <<<'SQL_WRAP'
SELECT SQL_CALC_FOUND_ROWS DISTINCT
s.service_id,
s.service_description,
h.host_name,
h.host_id
FROM servicegroup sg
INNER JOIN servicegroup_relation sgr
ON sgr.servicegroup_sg_id = sg.sg_id
INNER JOIN service s
ON s.service_id = sgr.service_service_id
INNER JOIN host_service_relation hsr
ON hsr.service_service_id = s.service_id
INNER JOIN host h ON h.host_id = hsr.host_host_id
SQL_WRAP;
if ($filters !== []) {
$whereCondition .= empty($whereCondition) ? ' WHERE ' : ' AND ';
$whereCondition .= implode(' AND ', $filters);
}
// Handle pagination and limit
$limit = array_key_exists('page_limit', $this->arguments)
? filter_var($this->arguments['page_limit'], FILTER_VALIDATE_INT)
: null;
$page = array_key_exists('page', $this->arguments)
? filter_var($this->arguments['page'], FILTER_VALIDATE_INT)
: null;
if ($limit === false) {
throw new RestBadRequestException('Error, limit must be an integer greater than zero');
}
if ($page === false) {
throw new RestBadRequestException('Error, page must be an integer greater than zero');
}
$range = '';
if (
$page !== null
&& $limit !== null
) {
$range = ' LIMIT :offset, :limit';
$queryValues['offset'] = (int) (($page - 1) * $limit);
$queryValues['limit'] = $limit;
}
$request .= $whereCondition . $range;
$statement = $this->pearDB->prepare($request);
foreach ($queryValues as $key => $value) {
$statement->bindValue($key, $value, PDO::PARAM_INT);
}
$statement->execute();
$serviceList = [];
while ($record = $statement->fetch(PDO::FETCH_ASSOC)) {
$serviceList[] = [
'id' => $record['host_id'] . '_' . $record['service_id'],
'text' => $record['host_name'] . ' - ' . $record['service_description'],
];
}
return [
'items' => $serviceList,
'total' => (int) $this->pearDB->numberRows(),
];
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/api/class/centreon_metric.class.php | centreon/www/api/class/centreon_metric.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\Enum\QueryParameterTypeEnum;
use Adaptation\Database\Connection\ValueObject\QueryParameter;
require_once _CENTREON_PATH_ . '/www/class/centreonDB.class.php';
require_once _CENTREON_PATH_ . '/www/class/centreonGraphNg.class.php';
require_once _CENTREON_PATH_ . '/www/class/centreonGraphService.class.php';
require_once _CENTREON_PATH_ . '/www/class/centreonGraphPoller.class.php';
require_once _CENTREON_PATH_ . '/www/class/centreonGraphStatus.class.php';
require_once _CENTREON_PATH_ . '/www/include/common/sqlCommonFunction.php';
require_once __DIR__ . '/webService.class.php';
/**
* Class
*
* @class CentreonMetric
*/
class CentreonMetric extends CentreonWebService
{
/** @var CentreonDB */
protected $pearDBMonitoring;
/** @var string[] */
protected $statusColors = [
'ok' => '#88b917',
'warning' => '#ff9a13',
'critical' => '#e00b3d',
'unknown' => 'gray',
];
/**
* CentreonMetric constructor
*/
public function __construct()
{
parent::__construct();
$this->pearDBMonitoring = new CentreonDB('centstorage');
}
/**
* Get metric list
*
* @throws Exception
* @return array
*/
public function getList()
{
global $centreon;
$queryValues = [];
$queryValues['name'] = isset($this->arguments['q']) ? '%' . (string) $this->arguments['q'] . '%' : '%%';
$query = 'SELECT DISTINCT(`metric_name`)
COLLATE utf8_bin as "metric_name", index_id FROM `metrics` as m, index_data i
WHERE metric_name LIKE :name ';
/**
* If ACLs on, then only return metrics linked to services that the user can see.
*/
if (! $centreon->user->admin) {
$acl = new CentreonACL($centreon->user->user_id, $centreon->user->admin);
$query .= ' AND m.index_id = i.id AND i.service_id IN ('
. $acl->getServicesString('ID', $this->pearDBMonitoring) . ') ';
}
$query .= ' ORDER BY `metric_name` COLLATE utf8_general_ci ';
$stmt = $this->pearDBMonitoring->prepare($query);
$stmt->bindParam(':name', $queryValues['name'], PDO::PARAM_STR);
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception('An error occured');
}
$metrics = [];
while ($row = $stmt->fetch()) {
$metrics[] = ['id' => $row['metric_name'], 'text' => $row['metric_name']];
}
return $metrics;
}
/**
* Get last metrics value by services or/and metrics
*
* @throws RestBadRequestException
* @throws RestForbiddenException
* @throws RestNotFoundException
* @return array | null if arguments are not set
*/
public function getLastMetricsData()
{
if (! isset($this->arguments['services']) && ! isset($this->arguments['metrics'])) {
self::sendResult([]);
}
return $this->lastMetricsData(
$this->arguments['services'] ?? '',
$this->arguments['metrics'] ?? ''
);
}
/**
* Get metrics data by service or/and metrics
*
* @throws RestBadRequestException
* @throws RestForbiddenException
* @throws RestNotFoundException
* @return array | null if arguments are not set
*/
public function getMetricsData()
{
if (! isset($this->arguments['services']) && ! isset($this->arguments['metrics'])) {
self::sendResult([]);
}
return $this->metricsData(
$this->arguments['services'] ?? '',
$this->arguments['metrics'] ?? ''
);
}
/**
* Get metrics datas for a service
*
* @throws RestBadRequestException
* @throws RestForbiddenException
* @throws RestNotFoundException
* @return array
*/
public function getMetricsDataByService()
{
if (! isset($this->arguments['ids'])) {
self::sendResult([]);
}
// Get the list of service ID
$ids = explode(',', $this->arguments['ids']);
$result = [];
if (isset($this->arguments['type']) && $this->arguments['type'] === 'ng') {
foreach ($ids as $id) {
$result[] = $this->serviceDatasNg($id);
}
} else {
foreach ($ids as $id) {
$result[] = $this->serviceDatas($id);
}
}
return $result;
}
/**
* Get metrics datas for a metric
*
* @throws RestBadRequestException
* @throws RestForbiddenException
* @throws RestNotFoundException
* @return array
*/
public function getMetricsDataByMetric()
{
if (! isset($this->arguments['ids'])) {
self::sendResult([]);
}
// Get the list of service ID
$ids = explode(',', $this->arguments['ids']);
$result = [];
if (isset($this->arguments['type']) && $this->arguments['type'] === 'ng') {
foreach ($ids as $id) {
[$hostId, $serviceId, $metricId] = explode('_', $id);
$hostId = (int) $hostId;
$serviceId = (int) $serviceId;
$metricId = (int) $metricId;
$result[] = $this->serviceDatasNg($hostId . '_' . $serviceId, $metricId);
}
} else {
foreach ($ids as $id) {
[$hostId, $serviceId, $metricId] = explode('_', $id);
$hostId = (int) $hostId;
$serviceId = (int) $serviceId;
$metricId = (int) $metricId;
$result[] = $this->serviceDatas($hostId . '_' . $serviceId, $metricId);
}
}
return $result;
}
/**
* Get the status for a service
*
* @throws PDOException
* @throws RestBadRequestException
* @throws RestForbiddenException
* @throws RestNotFoundException
* @throws RuntimeException
* @return array
*/
public function getStatusByService()
{
global $centreon;
$userId = $centreon->user->user_id;
$isAdmin = $centreon->user->admin;
// Get ACL if user is not admin
if (! $isAdmin) {
$acl = new CentreonACL($userId, $isAdmin);
$aclGroups = $acl->getAccessGroupsString();
}
// Validate options
if (
! isset($this->arguments['start']) || ! is_numeric($this->arguments['start'])
|| ! isset($this->arguments['end']) || ! is_numeric($this->arguments['end'])
) {
throw new RestBadRequestException('Bad parameters');
}
$start = $this->arguments['start'];
$end = $this->arguments['end'];
// Get the numbers of points
$rows = 200;
if (isset($this->arguments['rows'])) {
if (! is_numeric($this->arguments['rows'])) {
throw new RestBadRequestException('Bad parameters');
}
$rows = $this->arguments['rows'];
}
if ($rows < 10) {
throw new RestBadRequestException('The rows must be greater as 10');
}
if (! isset($this->arguments['ids'])) {
self::sendResult([]);
}
// Get the list of service ID
$ids = explode(',', $this->arguments['ids']);
$result = [];
foreach ($ids as $id) {
[$hostId, $serviceId] = explode('_', $id);
if (
! is_numeric($hostId)
|| ! is_numeric($serviceId)
) {
throw new RestBadRequestException('Bad parameters');
}
// Check ACL is not admin
if (! $isAdmin) {
$query = 'SELECT service_id '
. 'FROM centreon_acl '
. 'WHERE host_id = :hostId '
. 'AND service_id = :serviceId '
. 'AND group_id IN (' . $aclGroups . ')';
$stmt = $this->pearDBMonitoring->prepare($query);
$stmt->bindParam(':hostId', $hostId, PDO::PARAM_INT);
$stmt->bindParam(':serviceId', $serviceId, PDO::PARAM_INT);
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception('An error occured');
}
if ($stmt->rowCount() === 0) {
throw new RestForbiddenException('Access denied');
}
}
// Prepare graph
try {
// Get index data
$indexData = CentreonGraphStatus::getIndexId($hostId, $serviceId, $this->pearDBMonitoring);
$graph = new CentreonGraphStatus($indexData, $start, $end);
} catch (Exception $e) {
throw new RestNotFoundException('Graph not found');
}
$statusData = $graph->getData();
// Get comments for this services
$comments = [];
$query = 'SELECT `value` FROM `options` WHERE `key` = "display_comment_chart"';
$res = $this->pearDB->query($query);
$row = $res->fetch();
if ($row && $row['value'] === '1') {
$queryComment = 'SELECT `entry_time`, `author`, `data` '
. 'FROM comments '
. 'WHERE host_id = :hostId '
. 'AND service_id = :serviceId '
. 'AND type = 2 '
. 'AND entry_type = 1 '
. 'AND deletion_time IS NULL '
. 'AND :start < entry_time '
. 'AND :end > entry_time';
$stmt = $this->pearDBMonitoring->prepare($queryComment);
$stmt->bindParam(':hostId', $hostId, PDO::PARAM_INT);
$stmt->bindParam(':serviceId', $serviceId, PDO::PARAM_INT);
$stmt->bindParam(':start', $start, PDO::PARAM_INT);
$stmt->bindParam(':end', $end, PDO::PARAM_INT);
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception('An error occured');
}
while ($row = $stmt->fetch()) {
$comments[] = ['author' => $row['author'], 'comment' => $row['data'], 'time' => $row['entry_time']];
}
}
$result[] = ['service_id' => $id, 'data' => ['status' => $statusData, 'comments' => $comments], 'size' => $rows];
}
return $result;
}
/**
* Get metrics Data by poller
*
* @throws RestBadRequestException
* @throws RestNotFoundException
* @throws RuntimeException
* @return array
*/
public function getMetricsDataByPoller()
{
global $centreon;
$userId = $centreon->user->user_id;
$isAdmin = $centreon->user->admin;
// Get ACL if user is not admin
if (! $isAdmin) {
$acl = new CentreonACL($userId, $isAdmin);
}
// Validate options
if (
! isset($this->arguments['ids'])
|| ! isset($this->arguments['start'])
|| ! is_numeric($this->arguments['start'])
|| ! isset($this->arguments['end'])
|| ! is_numeric($this->arguments['end'])
) {
throw new RestBadRequestException('Bad parameters');
}
$explodedId = explode('-', $this->arguments['ids']);
$id = $explodedId[0];
$graphName = $explodedId[1];
$start = $this->arguments['start'];
$end = $this->arguments['end'];
// Get the numbers of points
$rows = 200;
if (isset($this->arguments['rows'])) {
if (! is_numeric($this->arguments['rows'])) {
throw new RestBadRequestException('Bad parameters');
}
$rows = $this->arguments['rows'];
}
if ($rows < 10) {
throw new RestBadRequestException('The rows must be greater as 10');
}
// Init graph object
try {
$graphPollerObject = new CentreonGraphPoller(
$this->pearDB,
$this->pearDBMonitoring
);
$graphPollerObject->setPoller($id, $graphName);
} catch (Exception $e) {
throw new RestNotFoundException('Graph not found');
}
$result = $graphPollerObject->getGraph($start, $end);
return [$result];
}
/**
* Authorize to access to the action
*
* @param string $action The action name
* @param array $user The current user
* @param bool $isInternal If the api is call in internal
*
* @return bool If the user has access to the action
*/
public function authorize($action, $user, $isInternal = false)
{
return (bool) (
parent::authorize($action, $user, $isInternal)
|| ($user && $user->hasAccessRestApiRealtime())
);
}
/**
* @throws PDOException
* @throws RestBadRequestException
* @return array
*/
protected function getListByService()
{
global $centreon;
$queryValues = [];
$queryValues['name'] = isset($this->arguments['q']) ? '%' . (string) $this->arguments['q'] . '%' : '%%';
$query = 'SELECT SQL_CALC_FOUND_ROWS m.metric_id,
CONCAT(h.name," - ", s.description, " - ", m.metric_name) AS fullname
FROM metrics m, hosts h, services s, index_data i
WHERE m.index_id = i.id
AND h.host_id = i.host_id
AND s.service_id = i.service_id
AND h.enabled = 1
AND s.enabled = 1
AND CONCAT(h.name," - ", s.description, " - ", m.metric_name) LIKE :name ';
if (! $centreon->user->admin) {
$acl = new CentreonACL($centreon->user->user_id, $centreon->user->admin);
$query .= 'AND s.service_id IN (' . $acl->getServicesString('ID', $this->pearDBMonitoring) . ') ';
}
$query .= ' ORDER BY fullname COLLATE utf8_general_ci ';
if (isset($this->arguments['page_limit'], $this->arguments['page'])) {
if (
! is_numeric($this->arguments['page'])
|| ! is_numeric($this->arguments['page_limit'])
|| $this->arguments['page_limit'] < 1
) {
throw new RestBadRequestException('400 Bad Request, limit error');
}
$offset = ($this->arguments['page'] - 1) * $this->arguments['page_limit'];
$query .= 'LIMIT :offset,:limit';
$queryValues['offset'] = (int) $offset;
$queryValues['limit'] = (int) $this->arguments['page_limit'];
}
$stmt = $this->pearDBMonitoring->prepare($query);
$stmt->bindParam(':name', $queryValues['name'], PDO::PARAM_STR);
if (isset($queryValues['offset'])) {
$stmt->bindParam(':offset', $queryValues['offset'], PDO::PARAM_INT);
$stmt->bindParam(':limit', $queryValues['limit'], PDO::PARAM_INT);
}
$stmt->execute();
$metrics = [];
while ($row = $stmt->fetch()) {
$metrics[] = ['id' => $row['metric_id'], 'text' => $row['fullname']];
}
return ['items' => $metrics, 'total' => (int) $this->pearDBMonitoring->numberRows()];
}
/**
* @throws PDOException
* @throws RestBadRequestException
* @return array
*/
protected function getListOfMetricsByService()
{
$queryValues = [];
if (isset($this->arguments['id'])) {
$tmp = explode('-', $this->arguments['id']);
$queryValues['host_id'] = (int) $tmp[0];
$queryValues['service_id'] = (int) $tmp[1];
} else {
throw new RestBadRequestException('400 Bad Request, invalid service id');
}
$nameArg = HtmlAnalyzer::sanitizeAndRemoveTags($this->arguments['q'] ?? false);
$queryValues['name'] = $nameArg !== false ? '%' . $nameArg . '%' : '%%';
$query = 'SELECT SQL_CALC_FOUND_ROWS m.metric_id, '
. 'm.metric_name AS name '
. 'FROM metrics m, hosts h, services s, index_data i '
. 'WHERE m.index_id = i.id '
. 'AND h.host_id = i.host_id '
. 'AND s.service_id = i.service_id '
. 'AND h.enabled = 1 '
. 'AND s.enabled = 1 '
. 'AND m.metric_name LIKE :name '
. 'AND h.host_id = :host_id AND s.service_id = :service_id '
. 'ORDER BY m.metric_name ';
if (isset($this->arguments['page_limit'], $this->arguments['page'])) {
if (
! is_numeric($this->arguments['page'])
|| ! is_numeric($this->arguments['page_limit'])
|| $this->arguments['page_limit'] < 1
) {
throw new RestBadRequestException('400 Bad Request, limit error');
}
$offset = ($this->arguments['page'] - 1) * $this->arguments['page_limit'];
$query .= 'LIMIT :offset,:limit';
$queryValues['offset'] = (int) $offset;
$queryValues['limit'] = (int) $this->arguments['page_limit'];
}
$stmt = $this->pearDBMonitoring->prepare($query);
$stmt->bindParam(':name', $queryValues['name'], PDO::PARAM_STR);
$stmt->bindParam(':host_id', $queryValues['host_id'], PDO::PARAM_INT);
$stmt->bindParam(':service_id', $queryValues['service_id'], PDO::PARAM_INT);
if (isset($queryValues['offset'])) {
$stmt->bindParam(':offset', $queryValues['offset'], PDO::PARAM_INT);
$stmt->bindParam(':limit', $queryValues['limit'], PDO::PARAM_INT);
}
$stmt->execute();
$metrics = [];
while ($row = $stmt->fetch()) {
$metrics[] = ['id' => $row['metric_id'], 'text' => $row['name']];
}
return ['items' => $metrics, 'total' => (int) $this->pearDBMonitoring->numberRows()];
}
/**
* Get last data for metrics (by services and/or metrics)
*
* @param string $services List of services (like hostId_serviceId,hostId2_serviceId2,...)
* @param string $metrics List of metrics (like metricId,metricId2,...)
*
* @throws PDOException
* @return array
*/
protected function lastMetricsData($services, $metrics)
{
global $centreon;
$userId = $centreon->user->user_id;
$isAdmin = $centreon->user->admin;
$aclGroups = null;
$query = '';
$filterHostIds = [];
$filterServiceIds = [];
$filterMetricIds = [];
if (is_string($services) && strlen($services) > 0) {
foreach (explode(',', $services) as $service) {
[$hostId, $serviceId] = explode('_', $service);
if (! is_numeric($hostId) || ! is_numeric($serviceId)) {
continue;
}
$filterHostIds[':host' . $hostId] = $hostId;
$filterServiceIds[':service' . $serviceId] = $serviceId;
}
if ($filterHostIds !== [] && $filterServiceIds !== []) {
$query = '
SELECT i.host_id, i.service_id, m.*
FROM index_data i, metrics m
WHERE i.host_id IN (' . implode(',', array_keys($filterHostIds)) . ')
AND i.service_id IN (' . implode(',', array_keys($filterServiceIds)) . ')
AND i.id = m.index_id';
}
}
if (is_string($metrics) && strlen($metrics) > 0) {
foreach (explode(',', $metrics) as $metricId) {
if (! is_numeric($metricId)) {
continue;
}
$filterMetricIds[':metric' . $metricId] = $metricId;
}
if ($filterMetricIds !== []) {
if ($query !== '') {
$query .= ' UNION ';
}
$query .= '
SELECT i.host_id, i.service_id, m.*
FROM metrics m, index_data i
WHERE m.metric_id IN (' . implode(',', array_keys($filterMetricIds)) . ')
AND m.index_id = i.id';
}
}
if ($query === '') {
throw new Exception('No metrics found');
}
// Get ACL if user is not admin
if (! $isAdmin) {
$acl = new CentreonACL($userId, $isAdmin);
$aclGroups = $acl->getAccessGroupsString();
$query = '
SELECT ms.* FROM (' . $query . ') as ms, centreon_acl ca
WHERE EXISTS (
SELECT 1
FROM centreon_acl ca
WHERE ca.host_id = ms.host_id
AND ca.service_id = ms.service_id
AND ca.group_id IN (' . $aclGroups . '))';
}
$stmt = $this->pearDBMonitoring->prepare($query);
foreach ([$filterHostIds, $filterServiceIds, $filterMetricIds] as $filterParams) {
foreach ($filterParams as $param => $value) {
$stmt->bindValue($param, $value, PDO::PARAM_INT);
}
}
$stmt->execute();
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
/**
* Get data for metrics (by services and/or metrics)
*
* @param string $services List of services (like hostId_serviceId,hostId2_serviceId2,...)
* @param string $metrics List of metrics (like metricId,metricId2,...)
*
* @throws PDOException
* @throws RestBadRequestException
* @throws RestNotFoundException
* @return array
*/
protected function metricsData($services, $metrics)
{
global $centreon;
$selectedMetrics = $this->manageMetricsDataArguments($services, $metrics);
$multipleServices = count(array_keys($selectedMetrics)) > 1 ? true : false;
// Prepare graph
try {
$graph = new CentreonGraphNg($centreon->user->user_id);
$graph->setMultipleServices($multipleServices);
foreach ($selectedMetrics as $service => $metrics) {
[$hostId, $serviceId] = explode('_', $service);
if (count(array_keys($metrics)) <= 0) {
$graph->addServiceMetrics($hostId, $serviceId);
} else {
$graph->addServiceCustomMetrics($hostId, $serviceId, $metrics);
}
}
} catch (Exception $e) {
throw new RestNotFoundException('Graph not found');
}
$result = $graph->getGraph($this->arguments['start'], $this->arguments['end']);
if (! $multipleServices && count($selectedMetrics) > 0) {
// Get extra information (downtime/acknowledgment)
$result['acknowledge'] = [];
$result['downtime'] = [];
[$hostId, $serviceId] = explode('_', array_key_first($selectedMetrics));
$result['acknowledge'] = $this->getAcknowledgements(
(int) $hostId,
(int) $serviceId,
(int) $this->arguments['start'],
(int) $this->arguments['end']
);
$result['downtime'] = $this->getDowntimePeriods(
(int) $hostId,
(int) $serviceId,
(int) $this->arguments['start'],
(int) $this->arguments['end']
);
}
return $result;
}
/**
* Get data for a service can be filtered by metric (new backend)
*
* @param string $id The service id like hostId_serviceId
* @param int $metric The metric id
*
* @throws Exception
* @throws RestBadRequestException
* @throws RestForbiddenException
* @throws RestNotFoundException
* @return array
*/
protected function serviceDatasNg(string $id, ?int $metric = null)
{
global $centreon;
$userId = $centreon->user->user_id;
$isAdmin = $centreon->user->admin;
if (
! isset($this->arguments['start']) || ! is_numeric($this->arguments['start'])
|| ! isset($this->arguments['end']) || ! is_numeric($this->arguments['end'])
) {
throw new RestBadRequestException('Bad parameters');
}
$start = $this->arguments['start'];
$end = $this->arguments['end'];
if (! preg_match('/^(\d+)_(\d+)$/', $id, $matches)) {
throw new RestBadRequestException('Bad parameters');
}
[, $hostId, $serviceId] = $matches;
if (
! is_numeric($hostId)
|| ! is_numeric($serviceId)
) {
throw new RestBadRequestException('Bad parameters');
}
if (! $isAdmin) {
try {
$acl = new CentreonAclLazy($userId);
$accessGroups = $acl->getAccessGroups();
if ($accessGroups->isEmpty()) {
throw new RestForbiddenException('Access denied');
}
$queryParameters = [
QueryParameter::int('serviceId', (int) $serviceId),
QueryParameter::int('hostId', (int) $hostId),
];
['parameters' => $aclParameters, 'placeholderList' => $bindQuery] = createMultipleBindParameters(
$accessGroups->getIds(),
'access_group_id',
QueryParameterTypeEnum::INTEGER,
);
$request = <<<SQL
SELECT
1 AS REALTIME,
host_id
FROM
centreon_acl
WHERE
host_id = :hostId
AND service_id = :serviceId
AND group_id IN ({$bindQuery})
SQL;
$result = $this->pearDBMonitoring->fetchAllAssociative(
$request,
QueryParameters::create([...$queryParameters, ...$aclParameters]),
);
if ($result === []) {
throw new RestForbiddenException(sprintf('You are not allowed to see graphs for service identified by ID %d', $serviceId));
}
} catch (Exception $exception) {
CentreonLog::create()->error(
logTypeId: CentreonLog::TYPE_BUSINESS_LOG,
message: 'Error fetching metrics data for service: ' . $exception->getMessage(),
customContext: [
'hostId' => $hostId,
'serviceId' => $serviceId,
],
exception: $exception
);
throw $exception;
}
}
// Prepare graph
try {
$graph = new CentreonGraphNg($userId);
if (is_null($metric)) {
$graph->addServiceMetrics($hostId, $serviceId);
} else {
$graph->addMetric($metric);
}
} catch (Exception $exception) {
CentreonLog::create()->error(
logTypeId: CentreonLog::TYPE_BUSINESS_LOG,
message: sprintf('Graph not found for metric %s: %s', $metric ?? '', $exception->getMessage()),
exception: $exception
);
throw new RestNotFoundException('Graph not found');
}
$result = $graph->getGraph($this->arguments['start'], $this->arguments['end']);
// Get extra information (downtime/acknowledgment)
$result['acknowledge'] = [];
$result['downtime'] = [];
$request = <<<'SQL'
SELECT `value` FROM `options` WHERE `key` = "display_downtime_chart"
SQL;
$record = $this->pearDB->fetchOne($request);
if ((int) $record === 1) {
$result['acknowledge'] = $this->getAcknowlegePeriods($hostId, $serviceId, $start, $end);
$result['downtime'] = $this->getDowntimePeriods($hostId, $serviceId, $start, $end);
}
return $result;
}
/**
* Get data for a service can be filtered by metric
*
* @param string $id The service id like hostId_serviceId
* @param int $metric The metric id
*
* @throws Exception
* @throws RestBadRequestException
* @throws RestForbiddenException
* @throws RestNotFoundException
* @return array
*/
protected function serviceDatas($id, $metric = null)
{
global $centreon;
$userId = $centreon->user->user_id;
$isAdmin = $centreon->user->admin;
// Get ACL if user is not admin
if (! $isAdmin) {
$acl = new CentreonACL($userId, $isAdmin);
$aclGroups = $acl->getAccessGroupsString();
}
if (
! isset($this->arguments['start'])
|| ! is_numeric($this->arguments['start'])
|| ! isset($this->arguments['end'])
|| ! is_numeric($this->arguments['end'])
) {
throw new RestBadRequestException('Bad parameters');
}
$start = $this->arguments['start'];
$end = $this->arguments['end'];
// Get the numbers of points
$rows = 200;
if (isset($this->arguments['rows'])) {
if (! is_numeric($this->arguments['rows'])) {
throw new RestBadRequestException('Bad parameters');
}
$rows = $this->arguments['rows'];
}
if ($rows < 10) {
throw new RestBadRequestException('The rows must be greater as 10');
}
[$hostId, $serviceId] = explode('_', $id);
if (
! is_numeric($hostId)
|| ! is_numeric($serviceId)
) {
throw new RestBadRequestException('Bad parameters');
}
// Check ACL is not admin
if (! $isAdmin) {
$query = 'SELECT service_id '
. 'FROM centreon_acl '
. 'WHERE host_id = :hostId '
. 'AND service_id = :serviceId '
. 'AND group_id IN (' . $aclGroups . ')';
$stmt = $this->pearDBMonitoring->prepare($query);
$stmt->bindParam(':hostId', $hostId, PDO::PARAM_INT);
$stmt->bindParam(':serviceId', $serviceId, PDO::PARAM_INT);
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception('An error occured');
}
if ($stmt->rowCount() === 0) {
throw new RestForbiddenException('Access denied');
}
}
// Prepare graph
try {
// Get index data
$indexData = CentreonGraphService::getIndexId($hostId, $serviceId, $this->pearDBMonitoring);
$graph = new CentreonGraphService($indexData, $userId);
} catch (Exception $e) {
throw new RestNotFoundException('Graph not found');
}
if (! is_null($metric)) {
$graph->setMetricList($metric);
}
$graph->setRRDOption('start', $start);
$graph->setRRDOption('end', $end);
$graph->setTemplate();
$graph->initCurveList();
$graph->createLegend();
$serviceData = $graph->getData($rows);
// Replace NaN
$counter = count($serviceData);
for ($i = 0; $i < $counter; $i++) {
if (isset($serviceData[$i]['data'])) {
$times = array_keys($serviceData[$i]['data']);
$values = array_map(
[$this, 'convertNaN'],
array_values($serviceData[$i]['data'])
);
}
$serviceData[$i]['data'] = $values;
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | true |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/api/class/centreon_submit_results.class.php | centreon/www/api/class/centreon_submit_results.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 __DIR__ . '/webService.class.php';
/**
* Class
*
* @class CentreonSubmitResults
* @description Class for provide the webservice for submit a status for a service or host
*/
class CentreonSubmitResults extends CentreonWebService
{
/** @var string The path to the centcore pipe file */
protected $centcoreFile;
/** @var bool If the file pipe is open */
protected $pipeOpened = false;
/** @var mixed The file descriptor of the centcore pipe */
protected $fh;
/** @var CentreonDB The database connection to centreon_storage (realtime database) */
protected $pearDBC;
/** @var array The cache for relation between hosts and pollers */
protected $pollerHosts = [];
/** @var array The cache for relation between hosts and services */
protected $hostServices;
/** @var array The list of accepted status */
protected $acceptedStatus = ['host' => [0, 1, 2, 'up', 'down', 'unknown'], 'service' => [0, 1, 2, 3, 'ok', 'warning', 'critical', 'unknown']];
/** @var array The match between status string and number */
protected $convertStatus = ['host' => ['up' => 0, 'down' => 1, 'unknown' => 2], 'service' => ['ok' => 0, 'warning' => 1, 'critical' => 2, 'unknown' => 3]];
/** @var string The rejex for validate perfdata */
protected $perfDataRegex = "/(('([^'=]+)'|([^'= ]+))=[0-9\.-]+[a-zA-Z%\/]*(;[0-9\.-]*){0,4}[ ]?)+/";
/**
* CentreonSubmitResults constructor
*/
public function __construct()
{
parent::__construct();
if (is_dir(_CENTREON_VARLIB_ . '/centcore')) {
$this->centcoreFile = _CENTREON_VARLIB_ . '/centcore/' . microtime(true) . '-externalcommand.cmd';
} else {
$this->centcoreFile = _CENTREON_VARLIB_ . '/centcore.cmd';
}
$this->pearDBC = new CentreonDB('centstorage');
$this->getPollers();
}
/**
* Entry point for submit a passive check result
*
* @throws PDOException
* @throws RestBadRequestException
* @throws RestPartialContent
* @return array[]
*/
public function postSubmit()
{
$this->getHostServiceInfo();
$results = [];
$hasError = false;
if (isset($this->arguments['results']) && is_array($this->arguments['results'])) {
if ($this->arguments['results'] !== []) {
if ($this->pipeOpened === false) {
$this->openPipe();
}
foreach ($this->arguments['results'] as $data) {
try {
// Validate the list of arguments
// Required fields
if (! isset($data['host']) || $data['host'] === ''
|| ! isset($data['status']) || ! isset($data['updatetime']) || ! isset($data['output'])) {
throw new RestBadRequestException('Missing argument.');
}
// Validate is the host and service exists in poller
if (! isset($this->pollerHosts['name'][$data['host']])) {
throw new RestNotFoundException('The host is not present.');
}
if (isset($data['service']) && $data['service'] !== ''
&& ! $this->hostServices[$data['host']][$data['service']]) {
throw new RestNotFoundException('The service is not present.');
}
// Validate status format
$status = strtolower($data['status']);
if (is_numeric($status)) {
$status = (int) $status;
}
if (isset($data['service']) && $data['service'] !== '') {
if (! in_array($status, $this->acceptedStatus['service'], true)) {
throw new RestBadRequestException('Bad status word.');
}
if (! is_numeric($status)) {
$status = $this->convertStatus['service'][$status];
}
} else {
if (! in_array($status, $this->acceptedStatus['host'], true)) {
throw new RestBadRequestException('Bad status word.');
}
if (! is_numeric($status)) {
$status = $this->convertStatus['host'][$status];
}
}
$data['status'] = $status;
// Validate timestamp format
if (! is_numeric($data['updatetime'])) {
throw new RestBadRequestException('The timestamp is not a integer.');
}
if (isset($data['perfdata'])) {
if ($data['perfdata'] !== '' && ! preg_match($this->perfDataRegex, $data['perfdata'])) {
throw new RestBadRequestException('The format of performance data is not valid.');
}
} else {
$data['perfdata'] = '';
}
// Execute the command
if (! $this->sendResults($data)) {
throw new RestInternalServerErrorException('Error during send command to CentCore.');
}
$results[] = [
'code' => 202,
'message' => 'The status send to the engine',
];
} catch (Exception $error) {
$hasError = true;
$results[] = ['code' => $error->getCode(), 'message' => $error->getMessage()];
}
}
$this->closePipe();
}
if ($hasError) {
throw new RestPartialContent(json_encode(['results' => $results]));
}
return ['results' => $results];
}
throw new RestBadRequestException('Bad arguments - Cannot find result list');
}
/**
* Authorize to access to the action
*
* @param string $action The action name
* @param CentreonUser $user The current user
* @param bool $isInternal If the api is call in internal
* @return bool If the user has access to the action
*/
public function authorize($action, $user, $isInternal = false)
{
return (bool) (
parent::authorize($action, $user, $isInternal)
|| ($user && $user->hasAccessRestApiRealtime())
);
}
/**
* Load the cache for pollers/hosts
*
* @throws PDOException
* @return void
*/
private function getPollers(): void
{
if (! isset($this->pollerHosts) || count($this->pollerHosts) === 0) {
$query = 'SELECT h.host_id, h.host_name, ns.nagios_server_id AS poller_id '
. 'FROM host h, ns_host_relation ns '
. 'WHERE host_host_id = host_id '
. 'AND h.host_activate = "1" '
. 'AND h.host_register = "1"';
$dbResult = $this->pearDB->query($query);
$this->pollerHosts = ['name' => [], 'id' => []];
while ($row = $dbResult->fetchRow()) {
$this->pollerHosts['id'][$row['host_id']] = $row['poller_id'];
$this->pollerHosts['name'][$row['host_name']] = $row['poller_id'];
}
$dbResult->free();
}
}
/**
* Load the cache for hosts/services
*
* @throws PDOException
* @return void
*/
private function getHostServiceInfo(): void
{
if (! isset($this->hostServices)) {
$query = 'SELECT name, description '
. 'FROM hosts h, services s '
. 'WHERE h.host_id = s.host_id '
. 'AND h.enabled = 1 '
. 'AND s.enabled = 1 ';
$dbResult = $this->pearDBC->query($query);
$this->hostServices = [];
while ($row = $dbResult->fetchRow()) {
if (! isset($this->hostServices[$row['name']])) {
$this->hostServices[$row['name']] = [];
}
$this->hostServices[$row['name']][$row['description']] = 1;
}
$dbResult->free();
}
}
/**
* Open the centcore pipe file
*
* @throws RestBadRequestException
* @return void
*/
private function openPipe(): void
{
if ($this->fh = @fopen($this->centcoreFile, 'a+')) {
$this->pipeOpened = true;
} else {
throw new RestBadRequestException("Can't open centcore pipe");
}
}
/**
* Close the centcore pipe file
*
* @return void
*/
private function closePipe(): void
{
fclose($this->fh);
$this->pipeOpened = false;
}
/**
* Write into the centcore pipe filr
*
* @param $string
*
* @return bool
*/
private function writeInPipe($string)
{
if ($this->pipeOpened === false) {
return false;
}
if ($string != '') {
fwrite($this->fh, $string . "\n");
}
return true;
}
/**
* Send the data to CentCore
*
* @param array $data
*
* @throws RestBadRequestException
* @return bool
*/
private function sendResults($data)
{
if (! isset($this->pollerHosts['name'][$data['host']])) {
throw new RestBadRequestException("Can't find poller_id for host: " . $data['host']);
}
if (isset($data['service']) && $data['service'] !== '') {
// Services update
$command = $data['host'] . ';' . $data['service'] . ';' . $data['status'] . ';'
. $data['output'] . '|' . $data['perfdata'];
// send data
return $this->writeInPipe('EXTERNALCMD:' . $this->pollerHosts['name'][$data['host']]
. ':[' . $data['updatetime'] . '] PROCESS_SERVICE_CHECK_RESULT;' . $command);
}
// Host Update
$command = $data['host'] . ';' . $data['status'] . ';' . $data['output'] . '|' . $data['perfdata'];
// send data
return $this->writeInPipe('EXTERNALCMD:' . $this->pollerHosts['name'][$data['host']]
. ':[' . $data['updatetime'] . '] PROCESS_HOST_CHECK_RESULT;' . $command);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/api/class/centreon_configuration_hostcategory.class.php | centreon/www/api/class/centreon_configuration_hostcategory.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 __DIR__ . '/centreon_configuration_objects.class.php';
/**
* Class
*
* @class CentreonConfigurationHostcategory
*/
class CentreonConfigurationHostcategory extends CentreonConfigurationObjects
{
/** @var CentreonDB */
protected $pearDBMonitoring;
/**
* CentreonConfigurationHostcategory constructor
*/
public function __construct()
{
parent::__construct();
$this->pearDBMonitoring = new CentreonDB('centstorage');
}
/**
* @throws PDOException
* @throws RestBadRequestException
* @return array
*/
public function getList()
{
global $centreon;
$queryValues = [];
$userId = $centreon->user->user_id;
$isAdmin = $centreon->user->admin;
$aclHostCategories = '';
// Get ACL if user is not admin
if (! $isAdmin) {
$acl = new CentreonACL($userId, $isAdmin);
$aclHostCategoryIds = $acl->getHostCategoriesString('ID');
if ($aclHostCategoryIds != "''") {
$aclHostCategories .= 'AND hc.hc_id IN (' . $aclHostCategoryIds . ') ';
}
}
/* Check for select2
't' argument
'a' or empty = category and severitiy
'c' = catagory only
's' = severity only */
if (isset($this->arguments['t'])) {
$selectList = ['a', 'c', 's'];
if (in_array(strtolower($this->arguments['t']), $selectList)) {
$t = $this->arguments['t'];
} else {
throw new RestBadRequestException('Error, type must be numerical');
}
} else {
$t = '';
}
// Check for select2 'q' argument
$queryValues['hcName'] = isset($this->arguments['q']) ? '%' . (string) $this->arguments['q'] . '%' : '%%';
$queryHostCategory = 'SELECT SQL_CALC_FOUND_ROWS DISTINCT hc.hc_name, hc.hc_id '
. 'FROM hostcategories hc '
. 'WHERE hc.hc_name LIKE :hcName '
. $aclHostCategories;
if (! empty($t) && $t == 'c') {
$queryHostCategory .= 'AND level IS NULL ';
}
if (! empty($t) && $t == 's') {
$queryHostCategory .= 'AND level IS NOT NULL ';
}
$queryHostCategory .= 'ORDER BY hc.hc_name ';
if (isset($this->arguments['page_limit'], $this->arguments['page'])) {
if (
! is_numeric($this->arguments['page'])
|| ! is_numeric($this->arguments['page_limit'])
|| $this->arguments['page_limit'] < 1
) {
throw new RestBadRequestException('Error, limit must be an integer greater than zero');
}
$offset = ($this->arguments['page'] - 1) * $this->arguments['page_limit'];
$queryHostCategory .= 'LIMIT :offset, :limit';
$queryValues['offset'] = (int) $offset;
$queryValues['limit'] = (int) $this->arguments['page_limit'];
}
$stmt = $this->pearDB->prepare($queryHostCategory);
$stmt->bindParam(':hcName', $queryValues['hcName'], PDO::PARAM_STR);
if (isset($queryValues['offset'])) {
$stmt->bindParam(':offset', $queryValues['offset'], PDO::PARAM_INT);
$stmt->bindParam(':limit', $queryValues['limit'], PDO::PARAM_INT);
}
$stmt->execute();
$hostCategoryList = [];
while ($data = $stmt->fetch()) {
$hostCategoryList[] = ['id' => htmlentities($data['hc_id']), 'text' => $data['hc_name']];
}
return ['items' => $hostCategoryList, 'total' => (int) $this->pearDB->numberRows()];
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/api/class/centreon_ceip.class.php | centreon/www/api/class/centreon_ceip.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 App\Kernel;
use Centreon\Domain\Log\Logger;
use Centreon\LegacyContainer;
use CentreonLicense\Infrastructure\Service\LicenseService;
use CentreonLicense\ServiceProvider;
use Core\Common\Infrastructure\FeatureFlags;
use Pimple\Exception\UnknownIdentifierException;
use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException;
use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
require_once __DIR__ . '/../../../bootstrap.php';
require_once __DIR__ . '/../../class/centreonDB.class.php';
require_once __DIR__ . '/../../class/centreonUUID.class.php';
require_once __DIR__ . '/../../class/centreonStatistics.class.php';
require_once __DIR__ . '/../../include/common/common-Func.php';
require_once __DIR__ . '/webService.class.php';
/**
* Class
*
* @class CentreonCeip
*/
class CentreonCeip extends CentreonWebService
{
/** @var string */
private $uuid;
/** @var CentreonUser */
private $user;
/** @var Logger */
private Logger $logger;
/** @var FeatureFlags */
private FeatureFlags $featureFlags;
/**
* CentreonCeip constructor
*
* @throws LogicException
* @throws ServiceCircularReferenceException
* @throws ServiceNotFoundException
*/
public function __construct()
{
parent::__construct();
global $centreon;
$this->user = $centreon->user;
// Generate UUID
$this->uuid = (string) (new CentreonUUID($this->pearDB))->getUUID();
$kernel = Kernel::createForWeb();
$this->logger = $kernel->getContainer()->get(Logger::class)
?? throw new LogicException('Logger not found in container');
$this->featureFlags = $kernel->getContainer()->get(FeatureFlags::class)
?? throw new LogicException('FeatureFlags not found in container');
}
/**
* Get CEIP Account and User info.
*
* @throws PDOException
* @return array<string,mixed> with Account/User info
*/
public function getCeipInfo(): array
{
return $this->isCeipActive()
? [
'visitor' => $this->getVisitorInformation(),
'account' => $this->getAccountInformation(),
'excludeAllText' => true,
'agents' => $this->getAgentInformation(),
'ceip' => true,
]
// Don't compute data if CEIP is disabled
: [
'ceip' => false,
];
}
/**
* Fetch Agents info.
*
* @throws PDOException
* @return array{
* poller_id: int,
* nb_agents: int
* }
*/
private function getAgentInformation(): array
{
$agents = [];
try {
$query = <<<'SQL'
SELECT `poller_id`, `enabled`, `infos`
FROM `centreon_storage`.`agent_information`
SQL;
$statement = $this->pearDB->executeStatement($query);
$rows = $this->pearDB->fetchAllAssociative($statement);
foreach ($rows as $row) {
/** @var array{poller_id:int,enabled:int,infos:string} $row */
if ((bool) $row['enabled'] === false) {
continue;
}
$decodedInfos = json_decode($row['infos'], true);
if (! is_array($decodedInfos)) {
CentreonLog::create()->error(
logTypeId: CentreonLog::TYPE_BUSINESS_LOG,
message: "Invalid JSON format in agent_information table for poller_id {$row['poller_id']}",
customContext: ['agent_data' => $row]
);
continue;
}
$agents[] = [
'poller_id' => $row['poller_id'],
'nb_agents' => array_sum(array_map(static fn (array $info): int => $info['nb_agent'] ?? 0, $decodedInfos)),
];
}
} catch (Throwable $exception) {
CentreonLog::create()->error(
logTypeId: CentreonLog::TYPE_BUSINESS_LOG,
message: $exception->getMessage(),
customContext: ['context' => $exception]
);
}
return $agents;
}
/**
* Get the type of the Centreon server.
*
* @throws PDOException
* @return array{
* type: 'central'|'remote',
* platform: 'on_premise'|'centreon_cloud',
* } the type of the server
*/
private function getServerType(): array
{
// Default parameters
$instanceInformation = [
'type' => 'central',
'platform' => 'on_premise',
];
$sql = "SELECT * FROM `informations` WHERE `key` IN ('isRemote', 'is_cloud')";
$result = $this->pearDB?->query($sql) ?: null;
while (is_array($row = $result?->fetch())) {
/** @var array{key:string, value:string} $row */
if ($row['key'] === 'is_cloud' && $row['value'] === 'yes') {
$instanceInformation['platform'] = 'centreon_cloud';
}
if ($row['key'] === 'isRemote' && $row['value'] === 'yes') {
$instanceInformation['type'] = 'remote';
}
}
return $instanceInformation;
}
/**
* Get visitor information.
*
* @return array<string,mixed> with visitor information
*/
private function getVisitorInformation(): array
{
$locale = $this->user->get_lang();
if (isCloudPlatform()) {
// Get the user role for the Centreon Cloud platform
// Get list of ACL Groups linked to this user
$grouplistStr = $this->user->access->getAccessGroupsString('NAME');
// Check main ACL Group
if (preg_match('/customer_admin_acl/', $grouplistStr)) {
$role = 'Administrator';
} elseif (preg_match('/customer_editor_acl/', $grouplistStr)) {
$role = 'Editor';
} elseif (preg_match('/customer_user_acl/', $grouplistStr)) {
$role = 'User';
} else {
$role = 'User';
}
$dependencyInjector = LegacyContainer::getInstance();
$licenseService = $dependencyInjector['lm.license'];
if ($licenseService->isTrial()) {
$email = $this->user->email;
}
} else {
// Get the user role for the Centreon on-premises platform
$role = $this->user->admin
? 'admin'
: 'user';
// If user have access to monitoring configuration, it's an operator
if (strcmp($role, 'admin') !== 0 && $this->user->access->page('601') > 0) {
$role = 'editor';
}
}
$visitorInformation = [
'id' => mb_substr($this->uuid, 0, 6) . '-' . $this->user->user_id,
'locale' => $locale,
'role' => $role,
];
if (isset($email)) {
$visitorInformation['email'] = $email;
}
return $visitorInformation;
}
/**
* Get account information.
*
* @return array<string,mixed> with account information
*/
private function getAccountInformation(): array
{
// Get Centreon statistics
$centreonStats = new CentreonStatistics($this->logger);
$configUsage = $centreonStats->getPlatformInfo();
// Get Licences information
$licenseInfo = $this->getLicenseInformation();
// Get Version of Centreon
$centreonVersion = $this->getCentreonVersion();
// Get Instance information
$instanceInformation = $this->getServerType();
// Get LACCESS
$laccess = $this->getLaccess();
$accountInformation = [
'id' => $this->uuid,
'name' => $licenseInfo['companyName'],
'serverType' => $instanceInformation['type'],
'platformType' => $instanceInformation['platform'],
'platformEnvironment' => $licenseInfo['platformEnvironment'],
'licenseType' => $licenseInfo['licenseType'],
'versionMajor' => $centreonVersion['major'],
'versionMinor' => $centreonVersion['minor'],
'nb_hosts' => (int) $configUsage['nb_hosts'],
'nb_services' => (int) $configUsage['nb_services'],
'nb_servers' => $configUsage['nb_central'] + $configUsage['nb_remotes'] + $configUsage['nb_pollers'],
'enabled_features_tags' => $this->featureFlags->getEnabled() ?: [],
];
if (isset($licenseInfo['hosts_limitation'])) {
$accountInformation['hosts_limitation'] = $licenseInfo['hosts_limitation'];
}
if (isset($licenseInfo['fingerprint'])) {
$accountInformation['fingerprint'] = $licenseInfo['fingerprint'];
}
if (! empty($laccess) && isset($licenseInfo['mode']) && $licenseInfo['mode'] !== 'offline') {
$accountInformation['LACCESS'] = $laccess;
}
return $accountInformation;
}
/**
* Get license information such as company name and license type.
*
* @return array<string,string> with license info
*/
private function getLicenseInformation(): array
{
/**
* Getting License information.
*/
$dependencyInjector = LegacyContainer::getInstance();
$productLicense = 'Open Source';
if (
! class_exists('\\CentreonLicense\\ServiceProvider', false)
|| ! $dependencyInjector->offsetExists('lm.license')
) {
return [
'companyName' => '',
'licenseType' => $productLicense,
'platformEnvironment' => 'demo',
];
}
$licenseClientName = '';
try {
$fingerprintService = $dependencyInjector[ServiceProvider::LM_FINGERPRINT];
$centreonModules = ['epp', 'bam', 'map', 'mbi'];
/** @var LicenseService $licenseObject */
$licenseObject = $dependencyInjector['lm.license'];
/** @var array<array-key, array<array-key, string|array<array-key, string>>> $licenseInformation */
$licenseInformation = [];
foreach ($centreonModules as $module) {
$licenseObject->setProduct($module);
$isLicenseValid = $licenseObject->validate();
if ($isLicenseValid && ! empty($licenseObject->getData())) {
/**
* @var array<
* array-key,
* array<array-key, array<array-key, string|array<array-key, string>>>> $licenseInformation
*/
$licenseInformation[$module] = $licenseObject->getData();
/** @var string $licenseClientName */
$licenseClientName = $licenseInformation[$module]['client']['name'];
$hostsLimitation = $licenseInformation[$module]['licensing']['hosts'];
$licenseMode = $licenseInformation[$module]['platform']['mode'] ?? null;
$licenseStart = DateTime::createFromFormat(
'Y-m-d',
$licenseInformation[$module]['licensing']['start']
) ?: throw new Exception('Invalid date format');
$licenseEnd = DateTime::createFromFormat(
'Y-m-d',
$licenseInformation[$module]['licensing']['end']
) ?: throw new Exception('Invalid date format');
$licenseDurationInDays = (int) ($licenseEnd->diff($licenseStart)->days ?? 0);
if ($module === 'epp') {
$productLicense = 'IT Edition';
if ($licenseInformation[$module]['licensing']['type'] === 'IT100') {
$productLicense = 'IT-100 Edition';
} elseif ((int) $hostsLimitation === -1 && $licenseDurationInDays > 90) {
$productLicense = 'MSP Edition';
$fingerprint = $fingerprintService->calculateFingerprint();
}
}
if (in_array($module, ['mbi', 'bam', 'map'], true)) {
$productLicense = 'Business Edition';
$fingerprint = $fingerprintService->calculateFingerprint();
if ((int) $hostsLimitation === -1 && $licenseDurationInDays > 90) {
$productLicense = 'MSP Edition';
}
break;
}
$environment = $licenseInformation[$module]['platform']['environment'];
}
}
} catch (UnknownIdentifierException) {
// The licence does not exist, 99.99% chance we are on Open source. No need to log.
} catch (Throwable $exception) {
CentreonLog::create()->error(
logTypeId: CentreonLog::TYPE_BUSINESS_LOG,
message: $exception->getMessage(),
customContext: ['context' => $exception]
);
}
$licenseInformation = [
'companyName' => $licenseClientName,
'licenseType' => $productLicense,
'platformEnvironment' => $environment ?? 'demo',
];
if (isset($hostsLimitation)) {
$licenseInformation['hosts_limitation'] = $hostsLimitation;
}
if (isset($fingerprint)) {
$licenseInformation['fingerprint'] = $fingerprint;
}
if (isset($licenseMode)) {
$licenseInformation['mode'] = $licenseMode;
}
return $licenseInformation;
}
/**
* Get the major and minor versions of Centreon web.
*
* @throws PDOException
* @return array{major: string, minor: string} with major and minor versions
*/
private function getCentreonVersion(): array
{
$sql = "SELECT informations.value FROM informations WHERE informations.key = 'version'";
$minor = (string) $this->sqlFetchValue($sql);
$major = mb_substr($minor, 0, (int) mb_strrpos($minor, '.', 0));
return compact('major', 'minor');
}
/**
* Get CEIP status.
*
* @throws PDOException
* @return bool the status of CEIP
*/
private function isCeipActive(): bool
{
$sql = "SELECT `value` FROM `options` WHERE `key` = 'send_statistics' LIMIT 1";
return $this->sqlFetchValue($sql) === '1';
}
/**
* Get LACCESS to complete the connection between Pendo and Salesforce.
*
* @throws PDOException
* @return string LACCESS value from options table
*/
private function getLaccess(): string
{
$sql = "SELECT `value` FROM `options` WHERE `key` = 'impCompanyToken' LIMIT 1";
$impCompanyToken = (string) $this->sqlFetchValue($sql);
if ($impCompanyToken === '') {
return '';
}
$decodedToken = json_decode($impCompanyToken, true);
if (is_array($decodedToken) && is_string($decodedToken['token'] ?? null)) {
return $decodedToken['token'];
}
CentreonLog::create()->error(
logTypeId: CentreonLog::TYPE_BUSINESS_LOG,
message: "Invalid JSON format in options table for key 'impCompanyToken'",
customContext: ['context' => $impCompanyToken]
);
return '';
}
/**
* Helper to retrieve the first value of a SQL query.
*
* @param string $sql
* @param array{string, mixed, int} ...$binds List of [':field', $value, \PDO::PARAM_STR]
*
* @return string|float|int|null
*/
private function sqlFetchValue(string $sql, array ...$binds): string|float|int|null
{
try {
$statement = $this->pearDB?->prepare($sql) ?: null;
foreach ($binds as $args) {
$statement?->bindValue(...$args);
}
$statement?->execute();
$row = $statement?->fetch(PDO::FETCH_NUM);
$value = is_array($row) && isset($row[0]) ? $row[0] : null;
return is_string($value) || is_int($value) || is_float($value) ? $value : null;
} catch (PDOException $exception) {
CentreonLog::create()->error(
logTypeId: CentreonLog::TYPE_BUSINESS_LOG,
message: $exception->getMessage(),
customContext: ['context' => $exception]
);
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/api/class/centreon_ldap_synchro.class.php | centreon/www/api/class/centreon_ldap_synchro.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/centreonLog.class.php';
/**
* Class
*
* @class CentreonLdapSynchro
* @description Webservice to request LDAP data synchronization for a selected contact.
*/
class CentreonLdapSynchro extends CentreonWebService
{
/** @var CentreonDB */
protected $pearDB;
/** @var CentreonLog */
protected $centreonLog;
/**
* Constructor
*/
public function __construct()
{
parent::__construct();
$this->pearDB = new CentreonDB();
$this->centreonLog = new CentreonLog();
}
/**
* Used to request a data synchronization of a contact from the contact page
* Using the contact ID or the session PHPSESSID value
*
* Each instance of Centreon using this contact account will be killed
*
* Method POST
*
* @throws PDOException
* @return bool
*/
public function postRequestLdapSynchro(): bool
{
$result = false;
$contactId = filter_var(
$_POST['contactId'] ?? false,
FILTER_VALIDATE_INT
);
if (! $this->isLdapEnabled()) {
return $result;
}
if ($contactId === false) {
$this->centreonLog->insertLog(
3, // ldap.log
'LDAP MANUAL SYNC : Error - Chosen contact id is not consistent.'
);
return $result;
}
$this->pearDB->beginTransaction();
try {
$resUser = $this->pearDB->prepare(
'SELECT `contact_id`, `contact_name` FROM `contact`
WHERE `contact_id` = :contactId'
);
$resUser->bindValue(':contactId', $contactId, PDO::PARAM_INT);
$resUser->execute();
$contact = $resUser->fetch();
// requiring a manual synchronization at next login of the contact
$stmtRequiredSync = $this->pearDB->prepare(
'UPDATE contact
SET `contact_ldap_required_sync` = "1"
WHERE contact_id = :contactId'
);
$stmtRequiredSync->bindValue(':contactId', $contact['contact_id'], PDO::PARAM_INT);
$stmtRequiredSync->execute();
// checking if the contact is currently connected to Centreon
$activeSession = $this->pearDB->prepare(
'SELECT session_id FROM `session` WHERE user_id = :contactId'
);
$activeSession->bindValue(':contactId', $contact['contact_id'], PDO::PARAM_INT);
$activeSession->execute();
// disconnecting every session using this contact data
$logoutContact = $this->pearDB->prepare(
'DELETE FROM session WHERE session_id = :userSessionId'
);
while ($rowSession = $activeSession->fetch()) {
$logoutContact->bindValue(':userSessionId', $rowSession['session_id'], PDO::PARAM_STR);
$logoutContact->execute();
}
$this->pearDB->commit();
$this->centreonLog->insertLog(
3,
'LDAP MANUAL SYNC : Successfully planned LDAP synchronization for ' . $contact['contact_name']
);
$result = true;
} catch (PDOException $e) {
$this->centreonLog->insertLog(
2, // sql-error.log
'LDAP MANUAL SYNC : Error - unable to read or update the contact data in the DB.'
);
$this->pearDB->rollBack();
}
return $result;
}
/**
* Checking if LDAP is enabled
*
* @throws PDOException
* @return bool
*/
private function isLdapEnabled()
{
// checking if at least one LDAP configuration is still enabled
$ldapEnable = $this->pearDB->query(
"SELECT `value` FROM `options` WHERE `key` = 'ldap_auth_enable'"
);
$row = $ldapEnable->fetch();
if ($row['value'] !== '1') {
$this->centreonLog->insertLog(
3,
'LDAP MANUAL SYNC : Error - No enabled LDAP configuration found.'
);
return false;
}
return true;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/api/class/centreon_home_customview.class.php | centreon/www/api/class/centreon_home_customview.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__ . '/webService.class.php';
require_once _CENTREON_PATH_ . 'www/class/centreonCustomView.class.php';
/**
* Class
*
* @class CentreonHomeCustomview
*/
class CentreonHomeCustomview extends CentreonWebService
{
/**
* CentreonHomeCustomview constructor
*/
public function __construct()
{
parent::__construct();
}
/**
* @throws PDOException
* @return array
*/
public function getListSharedViews()
{
global $centreon;
$views = [];
$q = [];
if (isset($this->arguments['q']) && $this->arguments['q'] != '') {
$q[] = '%' . $this->arguments['q'] . '%';
}
$query = 'SELECT custom_view_id, name FROM ('
. 'SELECT cv.custom_view_id, cv.name FROM custom_views cv '
. 'INNER JOIN custom_view_user_relation cvur ON cv.custom_view_id = cvur.custom_view_id '
. 'WHERE (cvur.user_id = ' . $centreon->user->user_id . ' '
. 'OR cvur.usergroup_id IN ( '
. 'SELECT contactgroup_cg_id '
. 'FROM contactgroup_contact_relation '
. 'WHERE contact_contact_id = ' . $centreon->user->user_id . ' '
. ') '
. ') '
. 'UNION '
. 'SELECT cv2.custom_view_id, cv2.name FROM custom_views cv2 '
. 'WHERE cv2.public = 1 ) as d '
. 'WHERE d.custom_view_id NOT IN ('
. 'SELECT cvur2.custom_view_id FROM custom_view_user_relation cvur2 '
. 'WHERE cvur2.user_id = ' . $centreon->user->user_id . ' '
. 'AND cvur2.is_consumed = 1) '
. ($q !== [] ? 'AND d.name like ? ' : '')
. 'ORDER BY name';
$stmt = $this->pearDB->prepare($query);
$stmt->execute($q);
while ($row = $stmt->fetch()) {
$views[] = ['id' => $row['custom_view_id'], 'text' => $row['name']];
}
return ['items' => $views, 'total' => count($views)];
}
/**
* @throws RestBadRequestException
* @return array
*/
public function getLinkedUsers()
{
// Check for select2 'q' argument
if (isset($this->arguments['q'])) {
if (! is_numeric($this->arguments['q'])) {
throw new RestBadRequestException('Error, custom view id must be numerical');
}
$customViewId = $this->arguments['q'];
} else {
$customViewId = 0;
}
global $centreon;
$viewObj = new CentreonCustomView($centreon, $this->pearDB);
return $viewObj->getUsersFromViewId($customViewId);
}
/**
* @throws RestBadRequestException
* @return array
*/
public function getLinkedUsergroups()
{
// Check for select2 'q' argument
if (isset($this->arguments['q'])) {
if (! is_numeric($this->arguments['q'])) {
throw new RestBadRequestException('Error, custom view id must be numerical');
}
$customViewId = $this->arguments['q'];
} else {
$customViewId = 0;
}
global $centreon;
$viewObj = new CentreonCustomView($centreon, $this->pearDB);
return $viewObj->getUsergroupsFromViewId($customViewId);
}
/**
* Get the list of views
*
* @throws Exception
* @return array
*/
public function getListViews()
{
global $centreon;
$viewObj = new CentreonCustomView($centreon, $this->pearDB);
$tabs = [];
$tabsDb = $viewObj->getCustomViews();
foreach ($tabsDb as $key => $tab) {
$tabs[] = ['default' => false, 'name' => $tab['name'], 'custom_view_id' => $tab['custom_view_id'], 'public' => $tab['public'], 'nbCols' => $tab['layout']];
}
return ['current' => $viewObj->getCurrentView(), 'tabs' => $tabs];
}
/**
* Get the list of preferences
* @throws Exception
* @return false|string
*/
public function getPreferences()
{
if (
filter_var(($widgetId = $this->arguments['widgetId'] ?? false), FILTER_VALIDATE_INT) === false
|| filter_var(($viewId = $this->arguments['viewId'] ?? false), FILTER_VALIDATE_INT) === false
) {
throw new InvalidArgumentException('Bad argument format');
}
require_once _CENTREON_PATH_ . 'www/class/centreonWidget.class.php';
require_once _CENTREON_PATH_ . 'www/class/centreonWidget/Params/Boolean.class.php';
require_once _CENTREON_PATH_ . 'www/class/centreonWidget/Params/Hidden.class.php';
require_once _CENTREON_PATH_ . 'www/class/centreonWidget/Params/List.class.php';
require_once _CENTREON_PATH_ . 'www/class/centreonWidget/Params/Password.class.php';
require_once _CENTREON_PATH_ . 'www/class/centreonWidget/Params/Range.class.php';
require_once _CENTREON_PATH_ . 'www/class/centreonWidget/Params/Text.class.php';
require_once _CENTREON_PATH_ . 'www/class/centreonWidget/Params/Compare.class.php';
require_once _CENTREON_PATH_ . 'www/class/centreonWidget/Params/Sort.class.php';
require_once _CENTREON_PATH_ . 'www/class/centreonWidget/Params/Date.class.php';
$smartyDir = __DIR__ . '/../../../vendor/smarty/smarty/';
require_once $smartyDir . 'libs/Smarty.class.php';
global $centreon;
$action = 'setPreferences';
$viewObj = new CentreonCustomView($centreon, $this->pearDB);
$widgetObj = new CentreonWidget($centreon, $this->pearDB);
$title = '';
$defaultTab = [];
$widgetTitle = $widgetObj->getWidgetTitle($widgetId);
$title = $widgetTitle != '' ? sprintf(_('Widget Preferences for %s'), $widgetTitle) : _('Widget Preferences');
$info = $widgetObj->getWidgetDirectory($widgetObj->getWidgetType($widgetId));
$title .= ' [' . $info . ']';
$defaultTab['custom_view_id'] = $viewId;
$defaultTab['widget_id'] = $widgetId;
$defaultTab['action'] = $action;
$url = $widgetObj->getUrl($widgetId);
// Smarty template Init
$libDir = __DIR__ . '/../../../GPL_LIB';
$tpl = new SmartyBC();
$tpl->setTemplateDir(_CENTREON_PATH_ . '/www/include/home/customViews/');
$tpl->setCompileDir($libDir . '/SmartyCache/compile');
$tpl->setConfigDir($libDir . '/SmartyCache/config');
$tpl->setCacheDir($libDir . '/SmartyCache/cache');
$tpl->addPluginsDir($libDir . '/smarty-plugins');
$tpl->loadPlugin('smarty_function_eval');
$tpl->setForceCompile(true);
$tpl->setAutoLiteral(false);
$form = new HTML_QuickFormCustom('Form', 'post', '?p=103');
$form->addElement('header', 'title', $title);
$form->addElement('header', 'information', _('General Information'));
// Prepare list of installed modules and have widget connectors
$loadConnectorPaths = [];
// Add core path
$loadConnectorPaths[] = _CENTREON_PATH_ . 'www/class/centreonWidget/Params/Connector';
$query = 'SELECT name FROM modules_informations ORDER BY name';
$res = $this->pearDB->query($query);
while ($module = $res->fetchRow()) {
$dirPath = _CENTREON_PATH_ . 'www/modules/' . $module['name'] . '/widgets/Params/Connector';
if (is_dir($dirPath)) {
$loadConnectorPaths[] = $dirPath;
}
}
try {
$permission = $viewObj->checkPermission($viewId);
$params = $widgetObj->getParamsFromWidgetId($widgetId, $permission);
foreach ($params as $paramId => $param) {
if ($param['is_connector']) {
$paramClassFound = false;
foreach ($loadConnectorPaths as $path) {
$filename = $path . '/' . ucfirst($param['ft_typename'] . '.class.php');
if (is_file($filename)) {
require_once $filename;
$paramClassFound = true;
break;
}
}
if ($paramClassFound === false) {
throw new Exception('No connector found for ' . $param['ft_typename']);
}
$className = 'CentreonWidgetParamsConnector' . ucfirst($param['ft_typename']);
} else {
$className = 'CentreonWidgetParams' . ucfirst($param['ft_typename']);
}
if (class_exists($className)) {
$currentParam = call_user_func(
[$className, 'factory'],
$this->pearDB,
$form,
$className,
$centreon->user->user_id
);
$param['custom_view_id'] = $viewId;
$param['widget_id'] = $widgetId;
$currentParam->init($param);
$currentParam->setValue($param);
$params[$paramId]['trigger'] = $currentParam->getTrigger();
} else {
throw new Exception('No class name found');
}
}
} catch (Exception $e) {
echo $e->getMessage() . '<br/>';
}
$tpl->assign('params', $params);
/**
* Submit button
*/
$form->addElement(
'button',
'submit',
_('Apply'),
['class' => 'btc bt_success', 'onClick' => 'submitData();']
);
$form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']);
$form->addElement('hidden', 'custom_view_id');
$form->addElement('hidden', 'widget_id');
$form->addElement('hidden', 'action');
$form->setDefaults($defaultTab);
// Apply a template definition
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($template, true);
$renderer->setRequiredTemplate('{$label} <i class="red">*</i>');
$renderer->setErrorTemplate('<i class="red">{$error}</i><br />{$html}');
$form->accept($renderer);
$tpl->assign('form', $renderer->toArray());
$tpl->assign('viewId', $viewId);
$tpl->assign('widgetId', $widgetId);
$tpl->assign('url', $url);
return $tpl->fetch('widgetParam.html');
}
/**
* Get preferences by widget id
*
* @throws Exception When missing argument
* @return array The widget preferences
*/
public function getPreferencesByWidgetId()
{
global $centreon;
if (! isset($this->arguments['widgetId'])) {
throw new Exception('Missing argument : widgetId');
}
$widgetId = $this->arguments['widgetId'];
$widgetObj = new CentreonWidget($centreon, $this->pearDB);
return $widgetObj->getWidgetPreferences($widgetId);
}
/**
* Authorize to access to the action
*
* @param string $action The action name
* @param CentreonUser $user The current user
* @param bool $isInternal If the api is call in internal
* @return bool If the user has access to the action
*/
public function authorize($action, $user, $isInternal = false)
{
return (bool) (
parent::authorize($action, $user, $isInternal)
|| ($user && $user->hasAccessRestApiConfiguration())
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/api/class/centreon_monitoring_poller.class.php | centreon/www/api/class/centreon_monitoring_poller.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 __DIR__ . '/centreon_configuration_objects.class.php';
/**
* Class
*
* @class CentreonMonitoringPoller
*/
class CentreonMonitoringPoller extends CentreonConfigurationObjects
{
/** @var CentreonDB */
protected $pearDBMonitoring;
/**
* CentreonMonitoringPoller constructor
*/
public function __construct()
{
$this->pearDBMonitoring = new CentreonDB('centstorage');
parent::__construct();
}
/**
* @throws Exception
* @return array
*/
public function getList()
{
global $centreon;
$queryValues = [];
// Check for select2 'q' argument
$queryValues['name'] = isset($this->arguments['q']) ? '%' . (string) $this->arguments['q'] . '%' : '%%';
$queryPoller = 'SELECT SQL_CALC_FOUND_ROWS DISTINCT instance_id, name FROM instances '
. 'WHERE name LIKE :name AND deleted=0 ';
if (! $centreon->user->admin) {
$acl = new CentreonACL($centreon->user->user_id, $centreon->user->admin);
$queryPoller .= 'AND instances.instance_id IN ('
. $acl->getPollerString('ID', $this->pearDBMonitoring) . ') ';
}
$queryPoller .= ' ORDER BY name ';
if (isset($this->arguments['page_limit'], $this->arguments['page'])) {
if (
! is_numeric($this->arguments['page'])
|| ! is_numeric($this->arguments['page_limit'])
|| $this->arguments['page_limit'] < 1
) {
throw new RestBadRequestException('Error, limit must be an integer greater than zero');
}
$offset = ($this->arguments['page'] - 1) * $this->arguments['page_limit'];
$queryPoller .= 'LIMIT :offset,:limit';
$queryValues['offset'] = (int) $offset;
$queryValues['limit'] = (int) $this->arguments['page_limit'];
}
$stmt = $this->pearDBMonitoring->prepare($queryPoller);
$stmt->bindParam(':name', $queryValues['name'], 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');
}
$pollerList = [];
while ($data = $stmt->fetch()) {
$pollerList[] = ['id' => $data['instance_id'], 'text' => $data['name']];
}
return ['items' => $pollerList, 'total' => (int) $this->pearDBMonitoring->numberRows()];
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/api/class/centreon_configuration_contact.class.php | centreon/www/api/class/centreon_configuration_contact.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 __DIR__ . '/centreon_configuration_objects.class.php';
/**
* Class
*
* @class CentreonConfigurationContact
*/
class CentreonConfigurationContact extends CentreonConfigurationObjects
{
/**
* CentreonConfigurationContact constructor
*/
public function __construct()
{
parent::__construct();
}
/**
* @throws RestBadRequestException
* @return array
*/
public function getList()
{
global $centreon;
if (isset($this->arguments['page_limit'], $this->arguments['page'])) {
if (
! is_numeric($this->arguments['page'])
|| ! is_numeric($this->arguments['page_limit'])
|| $this->arguments['page_limit'] < 1
) {
throw new RestBadRequestException('Error, limit must be an integer greater than zero');
}
$limit = ($this->arguments['page'] - 1) * $this->arguments['page_limit'];
$offset = $this->arguments['page_limit'];
$range = $limit . ',' . $offset;
} else {
$range = '';
}
$filterContact = ['contact_register' => '1'];
if (isset($this->arguments['q'])) {
$filterContact['contact_name'] = ['LIKE', '%' . $this->arguments['q'] . '%'];
$filterContact['contact_alias'] = ['OR', 'LIKE', '%' . $this->arguments['q'] . '%'];
}
$acl = new CentreonACL($centreon->user->user_id);
$contacts = $acl->getContactAclConf(
['fields' => ['contact_id', 'contact_name'], 'get_row' => 'contact_name', 'keys' => ['contact_id'], 'conditions' => $filterContact, 'order' => ['contact_name'], 'pages' => $range, 'total' => true]
);
$contactList = [];
foreach ($contacts['items'] as $id => $contactName) {
$contactList[] = ['id' => $id, 'text' => $contactName];
}
return ['items' => $contactList, 'total' => $contacts['total']];
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/api/class/centreon_menu.class.php | centreon/www/api/class/centreon_menu.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 CentreonLegacy\Core\Menu\Menu;
use Pimple\Container;
require_once __DIR__ . '/webService.class.php';
/**
* Class
*
* @class CentreonMenu
*/
class CentreonMenu extends CentreonWebService implements CentreonWebServiceDiInterface
{
/** @var CentreonDB */
public $pearDB;
/** @var Container */
private $dependencyInjector;
/**
* Get the init menu on loading page
*
* Argument:
* page -> int - The current page
*
* Method: GET
*
* @throws RestUnauthorizedException
* @return array
*/
public function getMenu()
{
if (! isset($_SESSION['centreon'])) {
throw new RestUnauthorizedException('Session does not exists.');
}
/**
* Initialize the language translator
*/
$this->dependencyInjector['translator'];
$menu = new Menu($this->pearDB, $_SESSION['centreon']->user);
return $menu->getMenu();
}
/**
* Define the dependency injector
*
* @param Container $dependencyInjector
*
* @return void
*/
public function finalConstruct(Container $dependencyInjector): void
{
$this->dependencyInjector = $dependencyInjector;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/api/class/centreon_configuration_service_severity.class.php | centreon/www/api/class/centreon_configuration_service_severity.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 __DIR__ . '/centreon_configuration_objects.class.php';
/**
* Class
*
* @class CentreonConfigurationServiceSeverity
* @description Configure the selection of multiple host severity (select2 filter)
*/
class CentreonConfigurationServiceSeverity extends CentreonConfigurationObjects
{
/**
* CentreonConfigurationServicecategory constructor
*/
public function __construct()
{
parent::__construct();
}
/**
* @throws Exception
* @return array
*/
public function getList()
{
$queryValues = [];
// Check for select2 'q' argument
$queryValues['name'] = isset($this->arguments['q']) !== false ? '%' . (string) $this->arguments['q'] . '%' : '%%';
$queryContact = 'SELECT SQL_CALC_FOUND_ROWS DISTINCT sc_id, sc_name FROM service_categories
WHERE sc_name LIKE :name
AND level IS NOT NULL
ORDER BY sc_name ';
if (isset($this->arguments['page_limit'], $this->arguments['page'])) {
if (
! is_numeric($this->arguments['page'])
|| ! is_numeric($this->arguments['page_limit'])
|| $this->arguments['page_limit'] < 1
) {
throw new RestBadRequestException('Error, limit must be an integer greater than zero');
}
$offset = ($this->arguments['page'] - 1) * $this->arguments['page_limit'];
$queryContact .= 'LIMIT :offset,:limit';
$queryValues['offset'] = (int) $offset;
$queryValues['limit'] = (int) $this->arguments['page_limit'];
}
$stmt = $this->pearDB->prepare($queryContact);
$stmt->bindParam(':name', $queryValues['name'], PDO::PARAM_STR);
if (isset($queryValues['offset'])) {
$stmt->bindParam(':offset', $queryValues['offset'], PDO::PARAM_INT);
$stmt->bindParam(':limit', $queryValues['limit'], PDO::PARAM_INT);
}
$stmt->execute();
$serviceList = [];
while ($data = $stmt->fetch()) {
$serviceList[] = ['id' => $data['sc_id'], 'text' => $data['sc_name']];
}
return ['items' => $serviceList, 'total' => (int) $this->pearDB->numberRows()];
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/api/class/centreon_configuration_meta.class.php | centreon/www/api/class/centreon_configuration_meta.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 __DIR__ . '/centreon_configuration_objects.class.php';
/**
* Class
*
* @class CentreonConfigurationMeta
*/
class CentreonConfigurationMeta extends CentreonConfigurationObjects
{
/**
* CentreonConfigurationMeta constructor
*/
public function __construct()
{
parent::__construct();
}
/**
* @throws PDOException
* @throws RestBadRequestException
* @return array
*/
public function getList()
{
global $centreon;
$userId = $centreon->user->user_id;
$isAdmin = $centreon->user->admin;
$aclMetaServices = '';
$queryValues = [];
// Get ACL if user is not admin
if (! $isAdmin) {
$acl = new CentreonACL($userId, $isAdmin);
$aclMetaServices .= 'AND meta_id IN (' . $acl->getMetaServiceString() . ') ';
}
// Check for select2 'q' argument
$queryValues['name'] = isset($this->arguments['q']) ? '%' . (string) $this->arguments['q'] . '%' : '%%';
$queryMeta = 'SELECT SQL_CALC_FOUND_ROWS DISTINCT meta_id, meta_name, meta_activate FROM meta_service '
. 'WHERE meta_name LIKE :name '
. $aclMetaServices
. 'ORDER BY meta_name ';
if (isset($this->arguments['page_limit'], $this->arguments['page'])) {
if (
! is_numeric($this->arguments['page'])
|| ! is_numeric($this->arguments['page_limit'])
|| $this->arguments['page_limit'] < 1
) {
throw new RestBadRequestException('Error, limit must be an integer greater than zero');
}
$offset = ($this->arguments['page'] - 1) * $this->arguments['page_limit'];
$queryMeta .= 'LIMIT :offset,:limit';
$queryValues['offset'] = (int) $offset;
$queryValues['limit'] = (int) $this->arguments['page_limit'];
}
$stmt = $this->pearDB->prepare($queryMeta);
$stmt->bindParam(':name', $queryValues['name'], PDO::PARAM_STR);
if (isset($queryValues['offset'])) {
$stmt->bindParam(':offset', $queryValues['offset'], PDO::PARAM_INT);
$stmt->bindParam(':limit', $queryValues['limit'], PDO::PARAM_INT);
}
$stmt->execute();
$metaList = [];
while ($data = $stmt->fetch()) {
$metaList[] = ['id' => $data['meta_id'], 'text' => $data['meta_name'], 'status' => (bool) $data['meta_activate']];
}
return ['items' => $metaList, 'total' => (int) $this->pearDB->numberRows()];
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/api/class/centreon_configuration_poller.class.php | centreon/www/api/class/centreon_configuration_poller.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 __DIR__ . '/centreon_configuration_objects.class.php';
/**
* Class
*
* @class CentreonConfigurationPoller
*/
class CentreonConfigurationPoller extends CentreonConfigurationObjects
{
/** @var CentreonDB */
protected $pearDB;
/**
* CentreonConfigurationPoller constructor
*/
public function __construct()
{
$this->pearDB = new CentreonDB('centreon');
parent::__construct();
}
/**
* @throws PDOException
* @throws RestBadRequestException
* @return array
*/
public function getList()
{
global $centreon;
$userId = $centreon->user->user_id;
$isAdmin = $centreon->user->admin;
$queryValues = [];
// Get ACL if user is not admin
if (! $isAdmin) {
$acl = new CentreonACL($userId, $isAdmin);
}
// Check for select2 'q' argument
$queryValues['name'] = isset($this->arguments['q']) ? '%' . (string) $this->arguments['q'] . '%' : '%%';
$queryPoller = 'SELECT SQL_CALC_FOUND_ROWS DISTINCT ns.id, ns.name FROM nagios_server ns ';
if (isset($this->arguments['t'])) {
if ($this->arguments['t'] == 'remote') {
$queryPoller .= 'JOIN remote_servers rs ON ns.id = rs.server_id ';
// Exclude selected master Remote Server
if (isset($this->arguments['e'])) {
$queryPoller .= 'WHERE ns.id <> :masterId ';
$queryValues['masterId'] = (int) $this->arguments['e'];
}
} elseif ($this->arguments['t'] == 'poller') {
$queryPoller .= 'LEFT JOIN remote_servers rs ON ns.id = rs.server_id '
. 'WHERE rs.ip IS NULL '
. "AND ns.localhost = '0' ";
} elseif ($this->arguments['t'] == 'central') {
$queryPoller .= "WHERE ns.localhost = '0' ";
}
} else {
$queryPoller .= '';
}
if (stripos($queryPoller, 'WHERE') === false) {
$queryPoller .= 'WHERE ns.name LIKE :name ';
} else {
$queryPoller .= 'AND ns.name LIKE :name ';
}
$queryPoller .= 'AND ns.ns_activate = "1" ';
if (! $isAdmin) {
$queryPoller .= $acl->queryBuilder('AND', 'id', $acl->getPollerString('ID', $this->pearDB));
}
$queryPoller .= 'ORDER BY name ';
if (isset($this->arguments['page_limit'], $this->arguments['page'])) {
if (
! is_numeric($this->arguments['page'])
|| ! is_numeric($this->arguments['page_limit'])
|| $this->arguments['page_limit'] < 1
) {
throw new RestBadRequestException('Error, limit must be an integer greater than zero');
}
$offset = ($this->arguments['page'] - 1) * $this->arguments['page_limit'];
$queryPoller .= 'LIMIT :offset, :limit';
$queryValues['offset'] = (int) $offset;
$queryValues['limit'] = (int) $this->arguments['page_limit'];
}
$stmt = $this->pearDB->prepare($queryPoller);
$stmt->bindParam(':name', $queryValues['name'], PDO::PARAM_STR);
// bind exluded master Remote Server
if (isset($this->arguments['t'])
&& $this->arguments['t'] == 'remote'
&& isset($this->arguments['e'])
) {
$stmt->bindParam(':masterId', $queryValues['masterId'], PDO::PARAM_STR);
}
if (isset($queryValues['offset'])) {
$stmt->bindParam(':offset', $queryValues['offset'], PDO::PARAM_INT);
$stmt->bindParam(':limit', $queryValues['limit'], PDO::PARAM_INT);
}
$stmt->execute();
$pollerList = [];
while ($data = $stmt->fetch()) {
$pollerList[] = ['id' => $data['id'], 'text' => $data['name']];
}
return ['items' => $pollerList, 'total' => (int) $this->pearDB->numberRows()];
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/api/class/centreon_configuration_manufacturer.class.php | centreon/www/api/class/centreon_configuration_manufacturer.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 __DIR__ . '/centreon_configuration_objects.class.php';
/**
* Class
*
* @class CentreonConfigurationManufacturer
*/
class CentreonConfigurationManufacturer extends CentreonConfigurationObjects
{
/**
* CentreonConfigurationManufacturer constructor
*/
public function __construct()
{
parent::__construct();
}
/**
* @throws Exception
* @throws RestBadRequestException
* @return array
*/
public function getList()
{
$queryValues = [];
// Check for select2 'q' argument
$queryValues['name'] = isset($this->arguments['q']) ? '%' . (string) $this->arguments['q'] . '%' : '%%';
$query = 'SELECT SQL_CALC_FOUND_ROWS DISTINCT id, name FROM traps_vendor '
. 'WHERE name LIKE :name '
. 'ORDER BY name ';
if (isset($this->arguments['page_limit'], $this->arguments['page'])) {
if (
! is_numeric($this->arguments['page'])
|| ! is_numeric($this->arguments['page_limit'])
|| $this->arguments['page_limit'] < 1
) {
throw new RestBadRequestException('Error, limit must be an integer greater than zero');
}
$offset = ($this->arguments['page'] - 1) * $this->arguments['page_limit'];
$query .= 'LIMIT :offset, :limit';
$queryValues['offset'] = (int) $offset;
$queryValues['limit'] = (int) $this->arguments['page_limit'];
}
$stmt = $this->pearDB->prepare($query);
$stmt->bindParam(':name', $queryValues['name'], PDO::PARAM_STR);
if (isset($queryValues['offset'])) {
$stmt->bindParam(':offset', $queryValues['offset'], PDO::PARAM_INT);
$stmt->bindParam(':limit', $queryValues['limit'], PDO::PARAM_INT);
}
$stmt->execute();
$manufacturerList = [];
while ($data = $stmt->fetch()) {
$manufacturerList[] = ['id' => $data['id'], 'text' => $data['name']];
}
return ['items' => $manufacturerList, 'total' => (int) $this->pearDB->numberRows()];
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/api/class/centreon_realtime_base.class.php | centreon/www/api/class/centreon_realtime_base.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 __DIR__ . '/webService.class.php';
/**
* Class
*
* @class CentreonRealtimeBase
*/
class CentreonRealtimeBase extends CentreonWebService
{
/** @var CentreonDB */
protected $realTimeDb;
/**
* CentreonConfigurationObjects constructor
*/
public function __construct()
{
parent::__construct();
$this->realTimeDb = new CentreonDB('centstorage');
}
/**
* @throws RestBadRequestException
* @return array
*/
public function getDefaultValues()
{
// Get Object targeted
if (isset($this->arguments['id']) && ! empty($this->arguments['id'])) {
$id = $this->arguments['id'];
} else {
throw new RestBadRequestException('Bad parameters id');
}
// Get Object targeted
if (isset($this->arguments['field'])) {
$field = $this->arguments['field'];
} else {
throw new RestBadRequestException('Bad parameters field');
}
// Get Object targeted
if (isset($this->arguments['target'])) {
$target = ucfirst($this->arguments['target']);
} else {
throw new RestBadRequestException('Bad parameters target');
}
$defaultValuesParameters = [];
$targetedFile = _CENTREON_PATH_ . "/www/class/centreon{$target}.class.php";
if (file_exists($targetedFile)) {
require_once $targetedFile;
$calledClass = 'Centreon' . $target;
$defaultValuesParameters = $calledClass::getDefaultValuesParameters($field);
}
if (count($defaultValuesParameters) == 0) {
throw new RestBadRequestException('Bad parameters count');
}
if (isset($defaultValuesParameters['type']) && $defaultValuesParameters['type'] === 'simple') {
if (isset($defaultValuesParameters['reverse']) && $defaultValuesParameters['reverse']) {
$selectedValues = $this->retrieveSimpleValues(
['table' => $defaultValuesParameters['externalObject']['table'], 'id' => $defaultValuesParameters['currentObject']['id']],
$id,
$defaultValuesParameters['externalObject']['id']
);
} else {
$selectedValues = $this->retrieveSimpleValues($defaultValuesParameters['currentObject'], $id, $field);
}
} elseif (isset($defaultValuesParameters['type']) && $defaultValuesParameters['type'] === 'relation') {
$selectedValues = $this->retrieveRelatedValues($defaultValuesParameters['relationObject'], $id);
} else {
throw new RestBadRequestException('Bad parameters');
}
// Manage final data
$finalDatas = [];
if (count($selectedValues) > 0) {
$finalDatas = $this->retrieveExternalObjectDatas(
$defaultValuesParameters['externalObject'],
$selectedValues
);
}
return $finalDatas;
}
/**
* Authorize to access to the action
*
* @param string $action The action name
* @param CentreonUser $user The current user
* @param bool $isInternal If the api is call in internal
* @return bool If the user has access to the action
*/
public function authorize($action, $user, $isInternal = false)
{
return (bool) (
parent::authorize($action, $user, $isInternal)
|| ($user && $user->hasAccessRestApiRealtime())
);
}
/**
* @param $externalObject
* @param $values
*
* @throws PDOException
* @return array
*/
protected function retrieveExternalObjectDatas($externalObject, $values)
{
$tmpValues = [];
if (isset($externalObject['object'])) {
$classFile = $externalObject['object'] . '.class.php';
include_once _CENTREON_PATH_ . "/www/class/{$classFile}";
$calledClass = ucfirst($externalObject['object']);
$externalObjectInstance = new $calledClass($this->pearDB);
$options = [];
if (isset($externalObject['objectOptions'])) {
$options = $externalObject['objectOptions'];
}
try {
$tmpValues = $externalObjectInstance->getObjectForSelect2($values, $options);
} catch (Exception $e) {
echo $e->getMessage();
}
} else {
$explodedValues = '';
$queryValues = [];
if (! empty($values)) {
foreach ($values as $key => $value) {
$explodedValues .= ':object' . $key . ',';
$queryValues['object'][$key] = $value;
}
$explodedValues = rtrim($explodedValues, ',');
}
$query = "SELECT {$externalObject['id']}, {$externalObject['name']} "
. "FROM {$externalObject['table']} "
. "WHERE {$externalObject['comparator']} "
. "IN ({$explodedValues})";
$stmt = $this->pearDB->prepare($query);
if (isset($queryValues['object'])) {
foreach ($queryValues['object'] as $key => $value) {
$stmt->bindValue(':object' . $key, $value);
}
}
$stmt->execute();
while ($row = $stmt->fetch()) {
$tmpValues[] = ['id' => $row[$externalObject['id']], 'text' => $row[$externalObject['name']]];
}
}
return $tmpValues;
}
/**
* @param $currentObject
* @param $id
* @param $field
* @return array
*/
protected function retrieveSimpleValues($currentObject, $id, $field)
{
$tmpValues = [];
$fields = [];
$fields[] = $field;
if (isset($currentObject['additionalField'])) {
$fields[] = $currentObject['additionalField'];
}
// Getting Current Values
$queryValuesRetrieval = 'SELECT ' . implode(', ', $fields) . ' '
. 'FROM ' . $currentObject['table'] . ' '
. 'WHERE ' . $currentObject['id'] . ' = :objectId';
$stmt = $this->pearDB->prepare($queryValuesRetrieval);
$stmt->bindParam(':objectId', $id, PDO::PARAM_INT);
while ($row = $stmt->fetch()) {
$tmpValue = $row[$field];
if (isset($currentObject['additionalField'])) {
$tmpValue .= '-' . $row[$currentObject['additionalField']];
}
$tmpValues[] = $tmpValue;
}
return $tmpValues;
}
/**
* @param $relationObject
* @param $id
* @return array
*/
protected function retrieveRelatedValues($relationObject, $id)
{
$tmpValues = [];
$fields = [];
$fields[] = $relationObject['field'];
if (isset($relationObject['additionalField'])) {
$fields[] = $relationObject['additionalField'];
}
$queryValuesRetrieval = 'SELECT ' . implode(', ', $fields) . ' '
. 'FROM ' . $relationObject['table'] . ' '
. 'WHERE ' . $relationObject['comparator'] . ' = :comparatorId';
$stmt = $this->pearDB->prepare($queryValuesRetrieval);
$stmt->bindParam(':comparatorId', $id, PDO::PARAM_INT);
while ($row = $stmt->fetch()) {
if (! empty($row[$relationObject['field']])) {
$tmpValue = $row[$relationObject['field']];
if (isset($relationObject['additionalField'])) {
$tmpValue .= '-' . $row[$relationObject['additionalField']];
}
$tmpValues[] = $tmpValue;
}
}
return $tmpValues;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/api/class/centreon_wiki.class.php | centreon/www/api/class/centreon_wiki.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/centreon-knowledge/wikiApi.class.php';
require_once __DIR__ . '/webService.class.php';
/**
* Class
*
* @class CentreonWiki
*/
class CentreonWiki extends CentreonWebService
{
/**
* CentreonWiki constructor
*/
public function __construct()
{
parent::__construct();
}
/**
* @return array
*/
public function postDeletePage()
{
$wikiApi = new WikiApi();
$result = $wikiApi->deletePage($this->arguments['title']);
return ['result' => $result];
}
/**
* Authorize to access to the action
*
* @param string $action The action name
* @param CentreonUser $user The current user
* @param bool $isInternal If the api is call in internal
* @return bool If the user has access to the action
*/
public function authorize($action, $user, $isInternal = false)
{
return (bool) (
parent::authorize($action, $user, $isInternal)
|| ($user && $user->hasAccessRestApiConfiguration())
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/api/class/centreon_configuration_timezone.class.php | centreon/www/api/class/centreon_configuration_timezone.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 __DIR__ . '/centreon_configuration_objects.class.php';
/**
* Class
*
* @class CentreonConfigurationTimezone
*/
class CentreonConfigurationTimezone extends CentreonConfigurationObjects
{
/**
* CentreonConfigurationTimezone constructor
*/
public function __construct()
{
parent::__construct();
}
/**
* @throws PDOException
* @throws RestBadRequestException
* @return array
*/
public function getList()
{
$queryValues = [];
// Check for select2 'q' argument
$queryValues['name'] = isset($this->arguments['q']) ? '%' . (string) $this->arguments['q'] . '%' : '%%';
$queryTimezone = 'SELECT SQL_CALC_FOUND_ROWS DISTINCT timezone_id, timezone_name FROM timezone '
. 'WHERE timezone_name LIKE :name '
. 'ORDER BY timezone_name ';
if (isset($this->arguments['page_limit'], $this->arguments['page'])) {
if (
! is_numeric($this->arguments['page'])
|| ! is_numeric($this->arguments['page_limit'])
|| $this->arguments['page_limit'] < 1
) {
throw new RestBadRequestException('Error, limit must be an integer greater than zero');
}
$offset = ($this->arguments['page'] - 1) * $this->arguments['page_limit'];
$queryTimezone .= 'LIMIT :offset,:limit';
$queryValues['offset'] = (int) $offset;
$queryValues['limit'] = (int) $this->arguments['page_limit'];
}
$stmt = $this->pearDB->prepare($queryTimezone);
$stmt->bindParam(':name', $queryValues['name'], PDO::PARAM_STR);
if (isset($queryValues['offset'])) {
$stmt->bindParam(':offset', $queryValues['offset'], PDO::PARAM_INT);
$stmt->bindParam(':limit', $queryValues['limit'], PDO::PARAM_INT);
}
$stmt->execute();
$timezoneList = [];
while ($data = $stmt->fetch()) {
$timezoneList[] = ['id' => $data['timezone_id'], 'text' => $data['timezone_name']];
}
return ['items' => $timezoneList, 'total' => (int) $this->pearDB->numberRows()];
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/api/class/centreon_proxy.class.php | centreon/www/api/class/centreon_proxy.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__ . '/webService.class.php';
require_once _CENTREON_PATH_ . '/www/class/centreonRestHttp.class.php';
/**
* Class
*
* @class CentreonProxy
*/
class CentreonProxy extends CentreonWebService
{
/**
* @return array
*/
public function postCheckConfiguration()
{
$proxyAddress = $this->arguments['url'];
$proxyPort = $this->arguments['port'];
try {
$testUrl = 'https://api.imp.centreon.com/api/pluginpack/pluginpack';
$restHttpLib = new CentreonRestHttp();
$restHttpLib->setProxy($proxyAddress, $proxyPort);
$restHttpLib->call($testUrl);
$outcome = true;
$message = _('Connection Successful');
} catch (Exception $e) {
$outcome = false;
$message = _('Could not establish connection to Centreon IMP servers (') . $e->getMessage() . ')';
}
return ['outcome' => $outcome, 'message' => $message];
}
/**
* Authorize to access to the action
*
* @param string $action The action name
* @param array $user The current user
* @param bool $isInternal If the api is call in internal
* @return bool If the user has access to the action
*/
public function authorize($action, $user, $isInternal = false)
{
return $isInternal;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/api/class/centreon_clapi.class.php | centreon/www/api/class/centreon_clapi.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 CentreonClapi\CentreonAPI;
use CentreonClapi\CentreonClapiException;
use CentreonClapi\CentreonObject;
use Pimple\Container;
require_once __DIR__ . '/../../include/common/csvFunctions.php';
require_once __DIR__ . '/webService.class.php';
define('_CLAPI_LIB_', _CENTREON_PATH_ . '/lib');
define('_CLAPI_CLASS_', _CENTREON_PATH_ . '/www/class/centreon-clapi');
set_include_path(implode(PATH_SEPARATOR, [_CENTREON_PATH_ . '/lib', _CENTREON_PATH_ . '/www/class/centreon-clapi', get_include_path()]));
require_once _CENTREON_PATH_ . '/www/class/centreon-clapi/centreonAPI.class.php';
/**
* Class wrapper for CLAPI to expose in REST
*/
class CentreonClapi extends CentreonWebService implements CentreonWebServiceDiInterface
{
/** @var Container */
private $dependencyInjector;
/**
* @param Container $dependencyInjector
*
* @return void
*/
public function finalConstruct(Container $dependencyInjector): void
{
$this->dependencyInjector = $dependencyInjector;
}
/**
* Post
*
* @global Centreon $centreon
* @global array $conf_centreon
* @throws RestBadRequestException
* @throws RestNotFoundException
* @throws RestConflictException
* @throws RestInternalServerErrorException
* @return array
*/
public function postAction()
{
global $centreon;
global $conf_centreon;
$dbConfig['host'] = $conf_centreon['hostCentreon'];
$dbConfig['username'] = $conf_centreon['user'];
$dbConfig['password'] = $conf_centreon['password'];
$dbConfig['dbname'] = $conf_centreon['db'];
if (isset($conf_centreon['port'])) {
$dbConfig['port'] = $conf_centreon['port'];
} elseif ($p = strstr($dbConfig['host'], ':')) {
$p = substr($p, 1);
if (is_numeric($p)) {
$dbConfig['port'] = $p;
}
}
$db = $this->dependencyInjector['configuration_db'];
$db_storage = $this->dependencyInjector['realtime_db'];
$username = $centreon->user->alias;
CentreonClapi\CentreonUtils::setUserName($username);
if (isset($this->arguments['action']) === false) {
throw new RestBadRequestException('Bad parameters');
}
// Prepare options table
$action = $this->arguments['action'];
$options = [];
if (isset($this->arguments['object'])) {
$options['o'] = $this->arguments['object'];
}
if (isset($this->arguments['values'])) {
if (is_array($this->arguments['values'])) {
$options['v'] = join(';', $this->arguments['values']);
} else {
$options['v'] = $this->arguments['values'];
}
}
// Load and execute clapi option
try {
$clapi = new CentreonAPI(
$username,
'',
$action,
_CENTREON_PATH_,
$options,
$this->dependencyInjector
);
ob_start();
$retCode = $clapi->launchAction(false);
$contents = ob_get_contents();
ob_end_clean();
} catch (CentreonClapiException $e) {
$message = $e->getMessage();
if (str_starts_with($message, CentreonObject::UNKNOWN_METHOD)) {
throw new RestNotFoundException($message);
}
if (str_starts_with($message, CentreonObject::MISSINGPARAMETER)) {
throw new RestBadRequestException($message);
}
if (str_starts_with($message, CentreonObject::MISSINGNAMEPARAMETER)) {
throw new RestBadRequestException($message);
}
if (str_starts_with($message, CentreonObject::OBJECTALREADYEXISTS)) {
throw new RestConflictException($message);
}
if (str_starts_with($message, CentreonObject::OBJECT_NOT_FOUND)) {
throw new RestNotFoundException($message);
}
if (str_starts_with($message, CentreonObject::NAMEALREADYINUSE)) {
throw new RestConflictException($message);
}
if (str_starts_with($message, CentreonObject::UNKNOWNPARAMETER)) {
throw new RestBadRequestException($message);
}
if (str_starts_with($message, CentreonObject::OBJECTALREADYLINKED)) {
throw new RestConflictException($message);
}
if (str_starts_with($message, CentreonObject::OBJECTNOTLINKED)) {
throw new RestBadRequestException($message);
}
throw new RestInternalServerErrorException($message);
}
if ($retCode != 0) {
$contents = trim($contents);
if (preg_match('/^Object ([\w\d ]+) not found in Centreon API.$/', $contents)) {
throw new RestBadRequestException($contents);
}
throw new RestInternalServerErrorException($contents);
}
if (preg_match("/^.*;.*(?:\n|$)/", $contents)) {
$result = csvToArray($contents, true);
if ($result === false) {
throw new RestInternalServerErrorException($contents);
}
$lastRecord = end($result);
if ($lastRecord && str_starts_with($lastRecord[0] ?? '', 'Return code end :')) {
array_pop($result);
}
} else {
$result = [];
foreach (explode("\n", $contents) as &$line) {
if (trim($line) !== '' && ! str_starts_with($line, 'Return code end :')) {
$result[] = $line;
}
}
}
$return = [];
$return['result'] = $result;
return $return;
}
/**
* Authorize to access to the action
*
* @param string $action The action name
* @param CentreonUser $user The current user
* @param bool $isInternal If the api is call in internal
* @return bool If the user has access to the action
*/
public function authorize($action, $user, $isInternal = false)
{
return (bool) (
parent::authorize($action, $user, $isInternal)
|| ($user && $user->is_admin())
);
}
/**
* Removes carriage returns from $item if string
*
* @param $item
*
* @return void
*/
private function clearCarriageReturns(&$item): void
{
$item = (is_string($item)) ? str_replace(["\n", "\t", "\r", '<br/>'], '', $item) : $item;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/api/class/centreon_configuration_servicecategory.class.php | centreon/www/api/class/centreon_configuration_servicecategory.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 __DIR__ . '/centreon_configuration_objects.class.php';
/**
* Class
*
* @class CentreonConfigurationServicecategory
*/
class CentreonConfigurationServicecategory extends CentreonConfigurationObjects
{
/**
* CentreonConfigurationServicecategory constructor
*/
public function __construct()
{
parent::__construct();
}
/**
* @throws Exception
* @return array
*/
public function getList()
{
$queryValues = [];
// Check for select2 'q' argument
$queryValues['name'] = isset($this->arguments['q']) !== false ? '%' . (string) $this->arguments['q'] . '%' : '%%';
/*
* Check for select2 't' argument
* 'a' or empty = category and severitiy
* 'c' = category only
* 's' = severity only
*/
if (isset($this->arguments['t'])) {
$selectList = ['a', 'c', 's'];
if (in_array(strtolower($this->arguments['t']), $selectList)) {
$t = $this->arguments['t'];
} else {
throw new RestBadRequestException('Error, Bad type');
}
} else {
$t = '';
}
$queryContact = 'SELECT SQL_CALC_FOUND_ROWS DISTINCT sc_id, sc_name FROM service_categories '
. 'WHERE sc_name LIKE :name ';
if ($t == 'c') {
$queryContact .= 'AND level IS NULL ';
}
if ($t == 's') {
$queryContact .= 'AND level IS NOT NULL ';
}
$queryContact .= 'ORDER BY sc_name ';
if (isset($this->arguments['page_limit'], $this->arguments['page'])) {
if (
! is_numeric($this->arguments['page'])
|| ! is_numeric($this->arguments['page_limit'])
|| $this->arguments['page_limit'] < 1
) {
throw new RestBadRequestException('Error, limit must be an integer greater than zero');
}
$offset = ($this->arguments['page'] - 1) * $this->arguments['page_limit'];
$queryContact .= 'LIMIT :offset,:limit';
$queryValues['offset'] = (int) $offset;
$queryValues['limit'] = (int) $this->arguments['page_limit'];
}
$stmt = $this->pearDB->prepare($queryContact);
$stmt->bindParam(':name', $queryValues['name'], PDO::PARAM_STR);
if (isset($queryValues['offset'])) {
$stmt->bindParam(':offset', $queryValues['offset'], PDO::PARAM_INT);
$stmt->bindParam(':limit', $queryValues['limit'], PDO::PARAM_INT);
}
$stmt->execute();
$serviceList = [];
while ($data = $stmt->fetch()) {
$serviceList[] = ['id' => $data['sc_id'], 'text' => $data['sc_name']];
}
return ['items' => $serviceList, 'total' => (int) $this->pearDB->numberRows()];
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/api/class/centreon_configuration_broker.class.php | centreon/www/api/class/centreon_configuration_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 __DIR__ . '/centreon_configuration_objects.class.php';
/**
* Class
*
* @class CentreonConfigurationBroker
*/
class CentreonConfigurationBroker extends CentreonConfigurationObjects
{
/**
* @throws Exception
* @return false|string
*/
public function getBlock()
{
if (! isset($this->arguments['page'])
|| ! isset($this->arguments['position'])
|| ! isset($this->arguments['blockId'])
|| ! isset($this->arguments['tag'])
) {
throw new Exception('Missing argument');
}
$page = filter_var((int) $this->arguments['page'], FILTER_VALIDATE_INT);
$position = filter_var((int) $this->arguments['position'], FILTER_VALIDATE_INT);
$blockId = HtmlAnalyzer::sanitizeAndRemoveTags((string) $this->arguments['blockId']);
$tag = HtmlAnalyzer::sanitizeAndRemoveTags((string) $this->arguments['tag']);
if (empty($tag) || empty($blockId) || $page === false || $position === false) {
throw new InvalidArgumentException('Invalid Parameters');
}
$cbObj = new CentreonConfigCentreonBroker($this->pearDB);
$form = $cbObj->quickFormById($blockId, $page, $position, 'new_' . rand(100, 1000));
$helps = [];
[$tagId, $typeId] = explode('_', $blockId);
$typeName = $cbObj->getTypeName($typeId);
$fields = $cbObj->getBlockInfos($typeId);
$helps[] = ['name' => $tag . '[' . $position . '][name]', 'desc' => _('The name of block configuration')];
$helps[] = ['name' => $tag . '[' . $position . '][type]', 'desc' => _('The type of block configuration')];
$cbObj->nbSubGroup = 1;
textdomain('help');
foreach ($fields as $field) {
$fieldname = '';
if ($field['group'] !== '') {
$fieldname .= $cbObj->getParentGroups($field['group']);
}
$fieldname .= $field['fieldname'];
$helps[] = ['name' => $tag . '[' . $position . '][' . $fieldname . ']', 'desc' => _($field['description'])];
}
textdomain('messages');
// Smarty template Init
$libDir = __DIR__ . '/../../../GPL_LIB';
$tpl = new SmartyBC();
$tpl->setTemplateDir(_CENTREON_PATH_ . '/www/include/configuration/configCentreonBroker/');
$tpl->setCompileDir($libDir . '/SmartyCache/compile');
$tpl->setConfigDir($libDir . '/SmartyCache/config');
$tpl->setCacheDir($libDir . '/SmartyCache/cache');
$tpl->addPluginsDir($libDir . '/smarty-plugins');
$tpl->loadPlugin('smarty_function_eval');
$tpl->setForceCompile(true);
$tpl->setAutoLiteral(false);
// Apply a template definition
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl);
$renderer->setRequiredTemplate('{$label} <font color="red" size="1">*</font>');
$renderer->setErrorTemplate('<font color="red">{$error}</font><br />{$html}');
$form->accept($renderer);
$tpl->assign('formBlock', $renderer->toArray());
$tpl->assign('typeName', $typeName);
$tpl->assign('tagBlock', $tag);
$tpl->assign('posBlock', $position);
$tpl->assign('helps', $helps);
return $tpl->fetch('blockConfig.ihtml');
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/api/class/centreon_administration_widget.class.php | centreon/www/api/class/centreon_administration_widget.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/centreonDBInstance.class.php';
require_once _CENTREON_PATH_ . '/www/class/centreonWidget.class.php';
require_once __DIR__ . '/webService.class.php';
require_once __DIR__ . '/../interface/di.interface.php';
require_once __DIR__ . '/../trait/diAndUtilis.trait.php';
/**
* Class
*
* @class CentreonAdministrationWidget
*/
class CentreonAdministrationWidget extends CentreonWebService implements CentreonWebServiceDiInterface
{
use CentreonWebServiceDiAndUtilisTrait;
/**
* @throws RestBadRequestException
* @return array
*/
public function getListInstalled()
{
global $centreon;
// Check for select2 'q' argument
$q = isset($this->arguments['q']) === false ? '' : $this->arguments['q'];
if (isset($this->arguments['page_limit'], $this->arguments['page'])) {
if (
! is_numeric($this->arguments['page'])
|| ! is_numeric($this->arguments['page_limit'])
|| $this->arguments['page_limit'] < 1
) {
throw new RestBadRequestException('Error, limit must be an integer greater than zero');
}
$limit = ($this->arguments['page'] - 1) * $this->arguments['page_limit'];
$range = [(int) $limit, (int) $this->arguments['page_limit']];
} else {
$range = [];
}
$widgetObj = new CentreonWidget($centreon, $this->pearDB);
return $widgetObj->getWidgetModels($q, $range);
}
/**
* Authorize to access to the action
*
* @param string $action The action name
* @param CentreonUser $user The current user
* @param bool $isInternal If the api is call in internal
* @return bool If the user has access to the action
*/
public function authorize($action, $user, $isInternal = false)
{
return (bool) (
parent::authorize($action, $user, $isInternal)
|| ($user && $user->hasAccessRestApiConfiguration())
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/api/class/centreon_configuration_objects.class.php | centreon/www/api/class/centreon_configuration_objects.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 __DIR__ . '/webService.class.php';
/**
* Class
*
* @class CentreonConfigurationObjects
*/
class CentreonConfigurationObjects extends CentreonWebService
{
/**
* CentreonConfigurationObjects constructor
*/
public function __construct()
{
parent::__construct();
}
/**
* @throws RestBadRequestException
* @return array
*/
public function getDefaultValues()
{
// Get Object targeted
if (isset($this->arguments['id']) && ! empty($this->arguments['id'])) {
$id = $this->arguments['id'];
} else {
throw new RestBadRequestException('Bad parameters id');
}
// Get Object targeted
if (isset($this->arguments['field'])) {
$field = $this->arguments['field'];
} else {
throw new RestBadRequestException('Bad parameters field');
}
// Get Object targeted
if (isset($this->arguments['target']) && preg_match('/^[a-zA-Z]+$/', $this->arguments['target'])) {
$target = ucfirst($this->arguments['target']);
} else {
throw new RestBadRequestException('Bad parameters target');
}
$defaultValuesParameters = [];
$targetedFile = _CENTREON_PATH_ . '/www/class/centreon' . $target . '.class.php';
if (file_exists($targetedFile)) {
require_once $targetedFile;
$calledClass = 'Centreon' . $target;
$defaultValuesParameters = $calledClass::getDefaultValuesParameters($field);
}
if (count($defaultValuesParameters) == 0) {
throw new RestBadRequestException('Bad parameters count');
}
if (isset($defaultValuesParameters['type']) && $defaultValuesParameters['type'] === 'simple') {
if (isset($defaultValuesParameters['reverse']) && $defaultValuesParameters['reverse']) {
$selectedValues = $this->retrieveSimpleValues(
['table' => $defaultValuesParameters['externalObject']['table'], 'id' => $defaultValuesParameters['currentObject']['id']],
$id,
$defaultValuesParameters['externalObject']['id']
);
} else {
$selectedValues = $this->retrieveSimpleValues($defaultValuesParameters['currentObject'], $id, $field);
}
} elseif (isset($defaultValuesParameters['type']) && $defaultValuesParameters['type'] === 'relation') {
$selectedValues = $this->retrieveRelatedValues($defaultValuesParameters['relationObject'], $id);
} else {
throw new RestBadRequestException('Bad parameters');
}
// Manage final data
$finalDatas = [];
if (count($selectedValues) > 0) {
$finalDatas = $this->retrieveExternalObjectDatas(
$defaultValuesParameters['externalObject'],
$selectedValues
);
}
return $finalDatas;
}
/**
* Authorize to access to the action
*
* @param string $action The action name
* @param CentreonUser $user The current user
* @param bool $isInternal If the api is call in internal
* @return bool If the user has access to the action
*/
public function authorize($action, $user, $isInternal = false)
{
return (bool) (
parent::authorize($action, $user, $isInternal)
|| ($user && $user->hasAccessRestApiConfiguration())
);
}
/**
* @param array $externalObject
* @param array $values
* @throws Exception
* @return array
*/
protected function retrieveExternalObjectDatas($externalObject, $values)
{
$tmpValues = [];
if (isset($externalObject['object'])) {
$classFile = $externalObject['object'] . '.class.php';
include_once _CENTREON_PATH_ . "/www/class/{$classFile}";
$calledClass = ucfirst($externalObject['object']);
$externalObjectInstance = new $calledClass($this->pearDB);
$options = [];
if (isset($externalObject['objectOptions'])) {
$options = $externalObject['objectOptions'];
}
try {
$tmpValues = $externalObjectInstance->getObjectForSelect2($values, $options);
} catch (Exception $e) {
echo $e->getMessage();
}
} else {
$explodedValues = '';
if (! empty($values)) {
$counter = count($values);
for ($i = 1; $i <= $counter; $i++) {
$explodedValues .= '?,';
}
$explodedValues = rtrim($explodedValues, ',');
}
$query = "SELECT {$externalObject['id']}, {$externalObject['name']} "
. "FROM {$externalObject['table']} "
. "WHERE {$externalObject['comparator']} "
. "IN ({$explodedValues})";
if (! empty($externalObject['additionalComparator'])) {
$query .= $this->processAdditionalComparator($externalObject['additionalComparator']);
}
$stmt = $this->pearDB->prepare($query);
$dbResult = $stmt->execute($values);
if (! $dbResult) {
throw new Exception('An error occured');
}
while ($row = $stmt->fetch()) {
$tmpValues[] = ['id' => $row[$externalObject['id']], 'text' => $row[$externalObject['name']]];
}
}
return $tmpValues;
}
/**
* @param array $additonalComparator
* @return string
*/
protected function processAdditionalComparator($additonalComparator)
{
$additonalQueryComparator = '';
foreach ($additonalComparator as $field => $value) {
if (is_null($value)) {
$additonalQueryComparator .= 'AND ' . $field . ' IS NULL ';
} else {
$additonalQueryComparator .= 'AND ' . $field . ' = ' . $value;
}
}
return $additonalQueryComparator;
}
/**
* @param $currentObject
* @param $id
* @param $field
*
* @throws PDOException
* @throws RestBadRequestException
* @return array
*/
protected function retrieveSimpleValues($currentObject, $id, $field)
{
if (! is_numeric($id)) {
throw new RestBadRequestException('Error, id must be numerical');
}
$tmpValues = [];
$fields = [];
$fields[] = $field;
if (isset($currentObject['additionalField'])) {
$fields[] = $currentObject['additionalField'];
}
// Getting Current Values
$queryValuesRetrieval = 'SELECT ' . implode(', ', $fields) . ' '
. 'FROM ' . $currentObject['table'] . ' '
. 'WHERE ' . $currentObject['id'] . ' = :id';
$stmt = $this->pearDB->prepare($queryValuesRetrieval);
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();
while ($row = $stmt->fetch()) {
$tmpValue = $row[$field];
if (isset($currentObject['additionalField'])) {
$tmpValue .= '-' . $row[$currentObject['additionalField']];
}
$tmpValues[] = $tmpValue;
}
return $tmpValues;
}
/**
* @param $relationObject
* @param $id
*
* @throws PDOException
* @return array
*/
protected function retrieveRelatedValues($relationObject, $id)
{
$tmpValues = [];
$fields = [];
$fields[] = $relationObject['field'];
if (isset($relationObject['additionalField'])) {
$fields[] = $relationObject['additionalField'];
}
$queryValuesRetrieval = 'SELECT ' . implode(', ', $fields) . ' '
. 'FROM ' . $relationObject['table'] . ' '
. 'WHERE ' . $relationObject['comparator'] . ' = :id';
$stmt = $this->pearDB->prepare($queryValuesRetrieval);
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();
while ($row = $stmt->fetch()) {
if (! empty($row[$relationObject['field']])) {
$tmpValue = $row[$relationObject['field']];
if (isset($relationObject['additionalField'])) {
$tmpValue .= '-' . $row[$relationObject['additionalField']];
}
$tmpValues[] = $tmpValue;
}
}
return $tmpValues;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/api/class/centreon_topcounter.class.php | centreon/www/api/class/centreon_topcounter.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__ . '/webService.class.php';
require_once __DIR__ . '/../../class/centreonDB.class.php';
require_once __DIR__ . '/../../class/centreonContact.class.php';
/**
* Class
*
* @class CentreonTopCounter
*/
class CentreonTopCounter extends CentreonWebService
{
/** @var CentreonDB */
protected $pearDBMonitoring;
/** @var int */
protected $timeUnit = 60;
/** @var int */
protected $refreshTime;
/** @var bool */
protected $hasAccessToTopCounter = false;
/** @var bool */
protected $hasAccessToPollers = false;
/** @var bool */
protected $hasAccessToProfile = false;
/** @var bool */
protected $soundNotificationsEnabled = false;
/** @var Centreon */
protected $centreon;
/**
* CentreonTopCounter constructor
* @throws Exception
*/
public function __construct()
{
global $centreon;
$this->centreon = $centreon;
parent::__construct();
$this->pearDBMonitoring = new CentreonDB('centstorage');
// get refresh interval from database
$this->initRefreshInterval();
$this->checkAccess();
}
/**
* The current time of the server
*
* Method GET
*
* @return array
*/
public function getClock()
{
$locale = $this->centreon->user->lang === 'browser'
? null
: $this->centreon->user->lang;
return ['time' => time(), 'locale' => $locale, 'timezone' => $this->centreon->CentreonGMT->getActiveTimezone($this->centreon->user->gmt)];
}
/**
* If the user must be disconnected
*
* Method GET
*
* @throws CentreonDbException
* @return bool[]
*/
public function getAutologout()
{
$logout = true;
if (isset($_SESSION['centreon'])) {
$query = $this->pearDB->prepare('SELECT user_id FROM session WHERE session_id = ?');
$res = $this->pearDB->execute($query, [session_id()]);
if ($res->rowCount()) {
$logout = false;
}
}
return ['autologout' => $logout];
}
/**
* Get the user information
*
* Method PUT
*
* @throws PDOException
* @return void
*/
public function putAutoLoginToken(): void
{
$userId = $this->arguments['userId'];
$autoLoginKey = $this->arguments['token'];
$query = 'UPDATE contact SET contact_autologin_key = :autoKey WHERE contact_id = :userId';
$stmt = $this->pearDB->prepare($query);
$stmt->bindParam(':autoKey', $autoLoginKey, PDO::PARAM_STR);
$stmt->bindParam(':userId', $userId, PDO::PARAM_INT);
$res = $stmt->execute();
if (! $res) {
throw new Exception('Error while update autologinKey ' . $autoLoginKey);
}
/**
* Update user object
*/
$this->centreon->user->setToken($autoLoginKey);
}
/**
* Get the user information
*
* Method GET
*
* @throws RestInternalServerErrorException
* @throws RestUnauthorizedException
* @return array
*/
public function getUser()
{
$locale = $this->centreon->user->lang === 'browser'
? null
: $this->centreon->user->lang;
$autoLoginKey = null;
$this->soundNotificationsEnabled = isset($_SESSION['disable_sound']) ? ! $_SESSION['disable_sound'] : true;
// Is the autologin feature enabled ?
try {
$res = $this->pearDB->query(
'SELECT value FROM options WHERE options.key = "enable_autologin"'
);
} catch (Exception $e) {
throw new RestInternalServerErrorException('Error getting the user.');
}
$rowEnableShortcut = $res->fetch();
// Do we need to display the autologin shortcut ?
try {
$res = $this->pearDB->query(
'SELECT value FROM options WHERE options.key = "display_autologin_shortcut"'
);
} catch (Exception $e) {
throw new RestInternalServerErrorException('Error getting the user.');
}
$rowEnableAutoLogin = $res->fetch();
// If the autologin feature is enabled then fetch the autologin key
// And display the shortcut if the option is enabled
if (
isset($rowEnableAutoLogin['value'], $rowEnableShortcut['value'])
&& $rowEnableAutoLogin['value'] === '1'
&& $rowEnableShortcut['value'] === '1'
) {
// Get autologinkey
try {
$res = $this->pearDB->prepare(
'SELECT contact_autologin_key FROM contact WHERE contact_id = :userId'
);
$res->bindValue(':userId', (int) $this->centreon->user->user_id, PDO::PARAM_INT);
$res->execute();
} catch (Exception $e) {
throw new RestInternalServerErrorException('Error getting the user.');
}
if ($res->rowCount() === 0) {
throw new RestUnauthorizedException('User does not exist.');
}
$row = $res->fetch();
$autoLoginKey = $row['contact_autologin_key'] ?? null;
}
return [
'userId' => $this->centreon->user->user_id,
'fullname' => $this->centreon->user->name,
'username' => $this->centreon->user->alias,
'locale' => $locale,
'timezone' => $this->centreon->CentreonGMT->getActiveTimezone($this->centreon->user->gmt),
'hasAccessToProfile' => $this->hasAccessToProfile,
'autologinkey' => $autoLoginKey,
'soundNotificationsEnabled' => $this->soundNotificationsEnabled,
'password_remaining_time' => $this->getPasswordRemainingTime(),
];
}
/**
* Get the pollers status
*
* Method GET
*
* @throws RestInternalServerErrorException
* @throws RestUnauthorizedException
* @return array
*/
public function getPollersStatus()
{
if (! $this->hasAccessToPollers) {
throw new RestUnauthorizedException("You're not authorized to access poller datas");
}
$pollers = $this->pollersStatusList();
$result = ['latency' => ['warning' => 0, 'critical' => 0], 'stability' => ['warning' => 0, 'critical' => 0], 'database' => ['warning' => 0, 'critical' => 0], 'total' => count($pollers), 'refreshTime' => $this->refreshTime];
foreach ($pollers as $poller) {
if ($poller['stability'] === 1) {
$result['stability']['warning']++;
} elseif ($poller['stability'] === 2) {
$result['stability']['critical']++;
}
if ($poller['database']['state'] === 1) {
$result['database']['warning']++;
} elseif ($poller['database']['state'] === 2) {
$result['database']['critical']++;
}
if ($poller['latency']['state'] === 1) {
$result['latency']['warning']++;
} elseif ($poller['latency']['state'] === 2) {
$result['latency']['critical']++;
}
}
return $result;
}
/**
* Get the list of pollers by status type
*
* Method GET
*
* @throws RestBadRequestException
* @throws RestInternalServerErrorException
* @return array
*/
public function getPollers()
{
$listType = ['configuration', 'stability', 'database', 'latency'];
if (! isset($this->arguments['type']) || ! in_array($this->arguments['type'], $listType)) {
throw new RestBadRequestException('Missing type argument or bad type name.');
}
$result = [
'type' => $this->arguments['type'],
'pollers' => [],
'total' => 0,
'refreshTime' => $this->refreshTime,
];
if ($this->arguments['type'] === 'configuration') {
$pollers = $this->pollersList();
$changeStateServers = [];
foreach ($pollers as $poller) {
$changeStateServers[$poller['id']] = $poller['lastRestart'];
}
$changeStateServers = getChangeState($changeStateServers);
foreach ($pollers as $poller) {
if ($poller['updated']) {
$result['pollers'][] = ['id' => $poller['id'], 'name' => $poller['name'], 'status' => 1, 'information' => ''];
}
}
} else {
$type = $this->arguments['type'];
$pollers = $this->pollersStatusList();
foreach ($pollers as $poller) {
$state = 0;
$info = '';
if ($type === 'stability') {
$state = $poller['stability'];
} else {
$state = $poller[$type]['state'];
$info = $poller[$type]['time'];
}
if ($state > 0) {
$result['pollers'][] = ['id' => $poller['id'], 'name' => $poller['name'], 'status' => $state, 'information' => $info];
}
}
}
$result['total'] = count($pollers);
return $result;
}
/**
* Get the list of pollers with problems
*
* Method GET
*
* @throws RestInternalServerErrorException
* @throws RestUnauthorizedException
* @return array
*/
public function getPollersListIssues()
{
if (! $this->hasAccessToPollers) {
throw new RestUnauthorizedException(_("You're not authorized to access poller data"));
}
$pollers = $this->pollersStatusList();
$result = ['issues' => ['latency' => ['warning' => ['poller' => [], 'total' => 0], 'critical' => ['poller' => [], 'total' => 0], 'total' => 0], 'stability' => ['warning' => ['poller' => [], 'total' => 0], 'critical' => ['poller' => [], 'total' => 0], 'total' => 0], 'database' => ['warning' => ['poller' => [], 'total' => 0], 'critical' => ['poller' => [], 'total' => 0], 'total' => 0]], 'total' => count($pollers), 'refreshTime' => $this->refreshTime];
$staWar = 0;
$staCri = 0;
$datWar = 0;
$datCri = 0;
$latWar = 0;
$latCri = 0;
foreach ($pollers as $poller) {
// stability
if ($poller['stability'] === 1) {
$result['issues']['stability']['warning']['poller'][] = ['id' => $poller['id'], 'name' => $poller['name'], 'since' => ''];
$staWar++;
} elseif ($poller['stability'] === 2) {
$result['issues']['stability']['critical']['poller'][] = ['id' => $poller['id'], 'name' => $poller['name'], 'since' => ''];
$staCri++;
}
// database
if ($poller['database']['state'] === 1) {
$result['issues']['database']['warning']['poller'][] = ['id' => $poller['id'], 'name' => $poller['name'], 'since' => $poller['database']['time']];
$datWar++;
} elseif ($poller['database']['state'] === 2) {
$result['issues']['database']['critical']['poller'][] = ['id' => $poller['id'], 'name' => $poller['name'], 'since' => $poller['database']['time']];
$datCri++;
}
// latency
if ($poller['latency']['state'] === 1) {
$result['issues']['latency']['warning']['poller'][] = ['id' => $poller['id'], 'name' => $poller['name'], 'since' => $poller['latency']['time']];
$latWar++;
} elseif ($poller['latency']['state'] === 2) {
$result['issues']['latency']['critical']['poller'][] = ['id' => $poller['id'], 'name' => $poller['name'], 'since' => $poller['latency']['time']];
$latCri++;
}
}
// total and unset empty
$staTotal = $staWar + $staCri;
if ($staTotal === 0) {
unset($result['issues']['stability']);
} else {
if ($staWar === 0) {
unset($result['issues']['stability']['warning']);
$result['issues']['stability']['critical']['total'] = $staCri;
} elseif ($staCri === 0) {
unset($result['issues']['stability']['critical']);
$result['issues']['stability']['warning']['total'] = $staWar;
} else {
$result['issues']['stability']['warning']['total'] = $staWar;
$result['issues']['stability']['critical']['total'] = $staCri;
}
$result['issues']['stability']['total'] = $staTotal;
}
$datTotal = $datWar + $datCri;
if ($datTotal === 0) {
unset($result['issues']['database']);
} else {
if ($datWar === 0) {
unset($result['issues']['database']['warning']);
$result['issues']['database']['critical']['total'] = $datCri;
} elseif ($datCri === 0) {
unset($result['issues']['database']['critical']);
$result['issues']['database']['warning']['total'] = $datWar;
} else {
$result['issues']['database']['warning']['total'] = $datWar;
$result['issues']['database']['critical']['total'] = $datCri;
}
$result['issues']['database']['total'] = $datTotal;
}
$latTotal = $latWar + $latCri;
if ($latTotal === 0) {
unset($result['issues']['latency']);
} else {
if ($latWar === 0) {
unset($result['issues']['latency']['warning']);
$result['issues']['latency']['critical']['total'] = $latCri;
} elseif ($latCri === 0) {
unset($result['issues']['latency']['critical']);
$result['issues']['latency']['warning']['total'] = $latWar;
} else {
$result['issues']['latency']['warning']['total'] = $latWar;
$result['issues']['latency']['critical']['total'] = $latCri;
}
$result['issues']['latency']['total'] = $latTotal;
}
return $result;
}
/**
* Get the hosts status
*
* Method GET
*
* @throws RestInternalServerErrorException
* @throws RestUnauthorizedException
* @return array|mixed
*/
public function getHosts_status()
{
if (! $this->hasAccessToTopCounter) {
throw new RestUnauthorizedException("You're not authorized to access resource data");
}
if (
isset($_SESSION['topCounterHostStatus'])
&& (time() - $this->refreshTime) < $_SESSION['topCounterHostStatus']['time']
) {
return $_SESSION['topCounterHostStatus'];
}
$query = 'SELECT 1 AS REALTIME,
COALESCE(SUM(CASE WHEN h.state = 0 THEN 1 ELSE 0 END), 0) AS up_total,
COALESCE(SUM(CASE WHEN h.state = 1 THEN 1 ELSE 0 END), 0) AS down_total,
COALESCE(SUM(CASE WHEN h.state = 2 THEN 1 ELSE 0 END), 0) AS unreachable_total,
COALESCE(SUM(CASE WHEN h.state = 4 THEN 1 ELSE 0 END), 0) AS pending_total,
COALESCE(SUM(CASE WHEN h.state = 1 AND (h.acknowledged = 0 AND h.scheduled_downtime_depth = 0)
THEN 1 ELSE 0 END), 0) AS down_unhandled,
COALESCE(SUM(CASE WHEN h.state = 2 AND (h.acknowledged = 0 AND h.scheduled_downtime_depth = 0)
THEN 1 ELSE 0 END), 0) AS unreachable_unhandled
FROM hosts h, instances i';
$query .= ' WHERE i.deleted = 0
AND h.instance_id = i.instance_id
AND h.enabled = 1
AND h.name NOT LIKE "\_Module\_%"';
if (! $this->centreon->user->admin) {
$query .= ' AND EXISTS (
SELECT a.host_id FROM centreon_acl a
WHERE a.host_id = h.host_id
AND a.group_id IN (' . $this->centreon->user->access->getAccessGroupsString() . '))';
}
try {
$res = $this->pearDBMonitoring->query($query);
} catch (Exception $e) {
throw new RestInternalServerErrorException($e);
}
$row = $res->fetch();
$result = ['down' => ['total' => $row['down_total'], 'unhandled' => $row['down_unhandled']], 'unreachable' => ['total' => $row['unreachable_total'], 'unhandled' => $row['unreachable_unhandled']], 'ok' => $row['up_total'], 'pending' => $row['pending_total'], 'total' => $row['up_total'] + $row['pending_total'] + $row['down_total'] + $row['unreachable_total'], 'refreshTime' => $this->refreshTime, 'time' => time()];
CentreonSession::writeSessionClose('topCounterHostStatus', $result);
return $result;
}
/**
* Get the services status
*
* Method GET
*
* @throws RestInternalServerErrorException
* @throws RestUnauthorizedException
* @return array|mixed
*/
public function getServicesStatus()
{
if (! $this->hasAccessToTopCounter) {
throw new RestUnauthorizedException("You're not authorized to access resource data");
}
if (
isset($_SESSION['topCounterServiceStatus'])
&& (time() - $this->refreshTime) < $_SESSION['topCounterServiceStatus']['time']
) {
return $_SESSION['topCounterServiceStatus'];
}
$query = 'SELECT 1 AS REALTIME,
COALESCE(SUM(CASE WHEN s.state = 0 THEN 1 ELSE 0 END), 0) AS ok_total,
COALESCE(SUM(CASE WHEN s.state = 1 THEN 1 ELSE 0 END), 0) AS warning_total,
COALESCE(SUM(CASE WHEN s.state = 2 THEN 1 ELSE 0 END), 0) AS critical_total,
COALESCE(SUM(CASE WHEN s.state = 3 THEN 1 ELSE 0 END), 0) AS unknown_total,
COALESCE(SUM(CASE WHEN s.state = 4 THEN 1 ELSE 0 END), 0) AS pending_total,
COALESCE(SUM(CASE WHEN s.state = 1 AND (h.acknowledged = 0 AND h.scheduled_downtime_depth = 0
AND s.state_type = 1 AND s.acknowledged = 0 AND s.scheduled_downtime_depth = 0)
THEN 1 ELSE 0 END), 0) AS warning_unhandled,
COALESCE(SUM(CASE WHEN s.state = 2 AND (h.acknowledged = 0 AND h.scheduled_downtime_depth = 0
AND s.state_type = 1 AND s.acknowledged = 0 AND s.scheduled_downtime_depth = 0)
THEN 1 ELSE 0 END), 0) AS critical_unhandled,
COALESCE(SUM(CASE WHEN s.state = 3 AND (h.acknowledged = 0 AND h.scheduled_downtime_depth = 0
AND s.state_type = 1 AND s.acknowledged = 0 AND s.scheduled_downtime_depth = 0)
THEN 1 ELSE 0 END), 0) AS unknown_unhandled
FROM hosts h, services s, instances i';
$query .= ' WHERE i.deleted = 0
AND h.instance_id = i.instance_id
AND h.enabled = 1
AND (h.name NOT LIKE "\_Module\_%" OR h.name LIKE "\_Module\_Meta%")
AND s.enabled = 1
AND h.host_id = s.host_id';
if (! $this->centreon->user->admin) {
$query .= ' AND EXISTS (
SELECT a.service_id FROM centreon_acl a
WHERE a.host_id = h.host_id
AND a.service_id = s.service_id
AND a.group_id IN (' . $this->centreon->user->access->getAccessGroupsString() . ')
)';
}
try {
$res = $this->pearDBMonitoring->query($query);
} catch (Exception $e) {
throw new RestInternalServerErrorException($e);
}
$row = $res->fetch();
$result = ['critical' => ['total' => $row['critical_total'], 'unhandled' => $row['critical_unhandled']], 'warning' => ['total' => $row['warning_total'], 'unhandled' => $row['warning_unhandled']], 'unknown' => ['total' => $row['unknown_total'], 'unhandled' => $row['unknown_unhandled']], 'ok' => $row['ok_total'], 'pending' => $row['pending_total'], 'total' => $row['ok_total'] + $row['pending_total'] + $row['critical_total'] + $row['unknown_total']
+ $row['warning_total'], 'refreshTime' => $this->refreshTime, 'time' => time()];
CentreonSession::writeSessionClose('topCounterServiceStatus', $result);
return $result;
}
/**
* Get intervals for refreshing header data
* Method: GET
*
* @throws RestInternalServerErrorException
* @return array
*/
public function getRefreshIntervals()
{
$query = "SELECT * FROM `options` WHERE `key` IN ('AjaxTimeReloadMonitoring','AjaxTimeReloadStatistic')";
try {
$res = $this->pearDB->query($query);
} catch (Exception $e) {
throw new RestInternalServerErrorException($e);
}
$row = $res->fetchAll();
$result = [];
foreach ($row as $item) {
$result[$item['key']] = (intval($item['value']) > 10) ? $item['value'] : 10;
}
return $result;
}
/**
* Authorize to access to the action
*
* @param string $action The action name
* @param CentreonUser $user The current user
* @param bool $isInternal If the api is call in internal
* @return bool If the has access to the action
*/
public function authorize($action, $user, $isInternal = false)
{
return (bool) (
parent::authorize($action, $user, $isInternal)
|| ($user && $user->hasAccessRestApiRealtime())
);
}
/**
* Get the configured pollers
*
* @throws RestInternalServerErrorException
* @return array
*/
protected function pollersList()
{
// Get the list of configured pollers
$listPoller = [];
$query = 'SELECT id, name, last_restart, updated FROM nagios_server WHERE ns_activate = "1"';
// Add ACL
$aclPoller = $this->centreon->user->access->getPollerString('id');
if (! $this->centreon->user->admin) {
if ($aclPoller === '') {
return [];
}
$query .= ' AND id IN (' . $aclPoller . ')';
}
try {
$res = $this->pearDB->query($query);
} catch (Exception $e) {
throw new RestInternalServerErrorException($e);
}
if ($res->rowCount() === 0) {
return [];
}
while ($row = $res->fetch()) {
$listPoller[$row['id']] = ['id' => $row['id'], 'name' => $row['name'], 'lastRestart' => $row['last_restart'], 'updated' => $row['updated']];
}
return $listPoller;
}
/**
* Get information for pollers
*
* @throws RestInternalServerErrorException
* @return array
*/
protected function pollersStatusList()
{
$listPoller = [];
$listConfPoller = $this->pollersList();
foreach ($listConfPoller as $poller) {
$listPoller[$poller['id']] = ['id' => $poller['id'], 'name' => $poller['name'], 'stability' => 0, 'database' => ['state' => 0, 'time' => null], 'latency' => ['state' => 0, 'time' => null]];
}
// Get status of pollers
$query = 'SELECT 1 AS REALTIME, instance_id, last_alive, running FROM instances
WHERE deleted = 0 AND instance_id IN (' . implode(', ', array_keys($listPoller)) . ')';
try {
$res = $this->pearDBMonitoring->query($query);
} catch (Exception $e) {
throw new RestInternalServerErrorException($e);
}
while ($row = $res->fetch()) {
// Test if poller running and activity
if (time() - $row['last_alive'] >= $this->timeUnit * 10) {
$listPoller[$row['instance_id']]['stability'] = 2;
$listPoller[$row['instance_id']]['database']['state'] = 2;
$listPoller[$row['instance_id']]['database']['time'] = time() - $row['last_alive'];
} elseif (time() - $row['last_alive'] >= $this->timeUnit * 5) {
$listPoller[$row['instance_id']]['stability'] = 1;
$listPoller[$row['instance_id']]['database']['state'] = 1;
$listPoller[$row['instance_id']]['database']['time'] = time() - $row['last_alive'];
}
if ($row['running'] == 0) {
$listPoller[$row['instance_id']]['stability'] = 2;
}
}
// Get latency
$query = 'SELECT 1 AS REALTIME, n.stat_value, i.instance_id
FROM nagios_stats n, instances i
WHERE n.stat_label = "Service Check Latency"
AND n.stat_key = "Average"
AND n.instance_id = i.instance_id
AND i.deleted = 0
AND i.instance_id IN (' . implode(', ', array_keys($listPoller)) . ')';
try {
$res = $this->pearDBMonitoring->query($query);
} catch (Exception $e) {
throw new RestInternalServerErrorException($e);
}
while ($row = $res->fetch()) {
if ($row['stat_value'] >= 120) {
$listPoller[$row['instance_id']]['latency']['state'] = 2;
$listPoller[$row['instance_id']]['latency']['time'] = $row['stat_value'];
} elseif ($row['stat_value'] >= 60) {
$listPoller[$row['instance_id']]['latency']['state'] = 1;
$listPoller[$row['instance_id']]['latency']['time'] = $row['stat_value'];
}
}
return $listPoller;
}
/**
* Get refresh interval of top counter
*
* @throws PDOException
* @return void
*/
private function initRefreshInterval(): void
{
$refreshInterval = 60;
$query = 'SELECT `value` FROM options WHERE `key` = "AjaxTimeReloadStatistic"';
$res = $this->pearDB->query($query);
if ($row = $res->fetch()) {
$refreshInterval = (int) $row['value'];
}
$this->refreshTime = $refreshInterval;
}
/**
* @return void
*/
private function checkAccess(): void
{
if ($this->centreon->user->access->admin == 0) {
$tabActionACL = $this->centreon->user->access->getActions();
session_start();
$_SESSION['centreon'] = $this->centreon;
session_write_close();
if (isset($tabActionACL['top_counter'])) {
$this->hasAccessToTopCounter = true;
}
if (isset($tabActionACL['poller_stats'])) {
$this->hasAccessToPollers = true;
}
} else {
$this->hasAccessToTopCounter = true;
$this->hasAccessToPollers = true;
}
if (
isset($this->centreon->user->access->topology[50104])
&& $this->centreon->user->access->topology[50104] === 1
) {
$this->hasAccessToProfile = true;
}
}
/**
* Get password remaining time
* null : never expired
* int : number of seconds before expiration
*
* @throws PDOException
* @return int|null
*/
private function getPasswordRemainingTime(): ?int
{
if ($this->centreon->user->authType === CentreonAuth::AUTH_TYPE_LDAP) {
return null;
}
$passwordRemainingTime = null;
$contact = new CentreonContact($this->pearDB);
$passwordCreationDate = $contact->findLastPasswordCreationDate((int) $this->centreon->user->user_id);
if ($passwordCreationDate !== null) {
$passwordPolicy = $contact->getPasswordSecurityPolicy();
$expirationDelay = $passwordPolicy['password_expiration']['expiration_delay'];
$excludedUsers = $passwordPolicy['password_expiration']['excluded_users'];
if ($expirationDelay !== null && ! in_array($this->centreon->user->alias, $excludedUsers)) {
$passwordRemainingTime = $passwordCreationDate->getTimestamp() + $expirationDelay - time();
if ($passwordRemainingTime < 0) {
$passwordRemainingTime = 0;
}
}
}
return $passwordRemainingTime;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/api/class/centreon_keepalive.class.php | centreon/www/api/class/centreon_keepalive.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/centreonSession.class.php';
require_once __DIR__ . '/webService.class.php';
/**
* Class
*
* @class CentreonKeepalive
*/
class CentreonKeepalive extends CentreonWebService
{
/**
* CentreonKeepalive constructor
*/
public function __construct()
{
parent::__construct();
}
/**
* Keep alive
* @throws PDOException
* @throws RestUnauthorizedException
*/
public function getKeepAlive(): void
{
$session = new CentreonSession();
if (! $session->updateSession($this->pearDB)) {
// return 401 if session is not updated (session expired)
throw new RestUnauthorizedException(_('Session is expired'));
}
}
/**
* Authorize to access to the action
*
* @param string $action The action name
* @param array $user The current user
* @param bool $isInternal If the api is call in internal
* @return bool If the user has access to the action
*/
public function authorize($action, $user, $isInternal = false)
{
return $isInternal;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/api/class/centreon_configuration_hosttemplate.class.php | centreon/www/api/class/centreon_configuration_hosttemplate.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 __DIR__ . '/centreon_configuration_objects.class.php';
/**
* Class
*
* @class CentreonConfigurationHosttemplate
*/
class CentreonConfigurationHosttemplate extends CentreonConfigurationObjects
{
/** @var CentreonDB */
protected $pearDBMonitoring;
/**
* CentreonConfigurationHosttemplate constructor
*/
public function __construct()
{
parent::__construct();
$this->pearDBMonitoring = new CentreonDB('centstorage');
}
/**
* @throws PDOException
* @throws RestBadRequestException
* @return array
*/
public function getList()
{
$queryValues = [];
// Check for select2 'q' argument
$queryValues['hostName'] = isset($this->arguments['q']) ? '%' . (string) $this->arguments['q'] . '%' : '%%';
$query = 'SELECT SQL_CALC_FOUND_ROWS DISTINCT h.host_name, h.host_id FROM host h '
. 'WHERE h.host_register = "0" '
. 'AND h.host_name LIKE :hostName '
. 'ORDER BY h.host_name ';
if (isset($this->arguments['page_limit'], $this->arguments['page'])) {
if (
! is_numeric($this->arguments['page'])
|| ! is_numeric($this->arguments['page_limit'])
|| $this->arguments['page_limit'] < 1
) {
throw new RestBadRequestException('Error, limit must be an integer greater than zero');
}
$offset = ($this->arguments['page'] - 1) * $this->arguments['page_limit'];
$query .= 'LIMIT :offset, :limit';
$queryValues['offset'] = (int) $offset;
$queryValues['limit'] = (int) $this->arguments['page_limit'];
}
$stmt = $this->pearDB->prepare($query);
$stmt->bindParam(':hostName', $queryValues['hostName'], PDO::PARAM_STR);
if (isset($queryValues['offset'])) {
$stmt->bindParam(':offset', $queryValues['offset'], PDO::PARAM_INT);
$stmt->bindParam(':limit', $queryValues['limit'], PDO::PARAM_INT);
}
$stmt->execute();
$hostList = [];
while ($data = $stmt->fetch()) {
$hostList[] = ['id' => htmlentities($data['host_id']), 'text' => $data['host_name']];
}
return ['items' => $hostList, 'total' => (int) $this->pearDB->numberRows()];
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/api/class/centreon_results_acceptor.class.php | centreon/www/api/class/centreon_results_acceptor.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 __DIR__ . '/centreon_configuration_objects.class.php';
require_once _CENTREON_PATH_ . '/www/class/centreonHost.class.php';
/**
* Class
*
* @class CentreonResultsAcceptor
*/
class CentreonResultsAcceptor extends CentreonConfigurationObjects
{
/** @var CentreonDB */
protected $pearDBMonitoring;
/** @var string */
protected $centcore_file;
/** @var */
protected $pollers;
/** @var int */
protected $pipeOpened;
/** @var resource */
protected $fh;
/** @var CentreonDB */
protected $pearDBC;
/** @var array */
protected $pollerHosts;
/** @var array */
protected $hostServices;
/**
* CentreonResultsAcceptor constructor
*/
public function __construct()
{
parent::__construct();
if (is_dir(_CENTREON_VARLIB_ . '/centcore')) {
$this->centcore_file = _CENTREON_VARLIB_ . '/centcore/' . microtime(true) . '-externalcommand.cmd';
} else {
$this->centcore_file = _CENTREON_VARLIB_ . '/centcore.cmd';
}
$this->pearDBC = new CentreonDB('centstorage');
$this->getPollers();
$this->pipeOpened = 0;
}
/**
* @throws PDOException
* @throws RestBadRequestException
* @throws RestException
* @return array
*/
public function postSubmit()
{
// print_r($this->arguments);
$this->getHostServiceInfo();
if (isset($this->arguments['results']) && is_array($this->arguments['results'])) {
if ($this->arguments['results'] !== []) {
if ($this->pipeOpened == 0) {
$this->openPipe();
}
foreach ($this->arguments['results'] as $data) {
if (! isset($this->hostServices[$data['host']])
|| ! isset($this->hostServices[$data['host']][$data['service']])
) {
if (! isset($this->pollerHosts['name'][$data['host']])) {
$host = new CentreonHost($this->pearDB);
$ret = ['host_name' => $data['host'], 'host_alias' => 'Passif host - ' . $data['host'], 'host_address' => $data['host'], 'host_active_checks_enabled' => ['host_active_checks_enabled', 0], 'host_passive_checks_enabled' => ['host_passive_checks_enabled' => 1], 'host_retry_check_interval' => 1, 'host_max_check_attempts' => 3, 'host_register' => 1, 'host_activate' => ['host_activate' => 1], 'host_comment' => 'Host imported by rest API at ' . date('Y/m/d') . ''];
$host_id = $host->insert($ret);
$host->insertExtendedInfos(['host_id' => $host_id]);
$host->setPollerInstance($host_id, 1);
// update reference table
$this->hostServices[$data['host']] = [];
}
if (! isset($this->hostServices[$data['host']][$data['service']])) {
if (! isset($host)) {
$host = new CentreonHost($this->pearDB);
}
$service = new CentreonService($this->pearDB);
$ret = ['service_description' => $data['service'], 'service_max_check_attempts' => 3, 'service_template_model_stm_id' => 1, 'service_normal_check_interval' => $data['interval'], 'service_retry_check_interval' => $data['interval'], 'service_active_checks_enabled' => ['service_active_checks_enabled' => 0], 'service_passive_checks_enabled' => ['service_passive_checks_enabled' => 1], 'service_register' => 1, 'service_activate' => ['service_activate' => 1], 'service_comment' => 'Service imported by Rest API at ' . date('Y/m/d') . ''];
$service_id = $service->insert($ret);
if (! isset($host_id)) {
$host_id = $host->getHostId($data['host']);
}
$service->insertExtendInfo(['service_service_id' => $service_id]);
$host->insertRelHostService($host_id, $service_id);
}
}
if (isset($this->pollerHosts['name'][$data['host']])) {
$this->sendResults($data);
} else {
throw new RestException(
"Can't find the pushed resource (" . $data['host'] . ' / ' . $data['service']
. ')... Try again later'
);
}
}
$this->closePipe();
}
return ['success' => true];
}
throw new RestBadRequestException('Bad arguments - Cannot find command list');
}
/**
* Authorize to access to the action
*
* @param string $action The action name
* @param CentreonUser $user The current user
* @param bool $isInternal If the api is call in internal
* @return bool If the user has access to the action
*/
public function authorize($action, $user, $isInternal = false)
{
return (bool) (
parent::authorize($action, $user, $isInternal)
|| ($user && $user->hasAccessRestApiConfiguration())
);
}
/**
* Get poller Listing
*
* @throws PDOException
* @return void
*/
private function getPollers(): void
{
if (! isset($this->hostServices)) {
$query = 'SELECT h.host_id, h.host_name, ns.nagios_server_id AS poller_id '
. 'FROM host h, ns_host_relation ns '
. 'WHERE host_host_id = host_id '
. 'AND h.host_activate = "1" '
. 'AND h.host_register = "1"';
$dbResult = $this->pearDB->query($query);
$this->pollerHosts = ['name' => [], 'id' => []];
while ($row = $dbResult->fetch()) {
$this->pollerHosts['id'][$row['host_id']] = $row['poller_id'];
$this->pollerHosts['name'][$row['host_name']] = $row['poller_id'];
}
$dbResult->closeCursor();
}
}
/**
* @throws PDOException
* @return void
*/
private function getHostServiceInfo(): void
{
if (! isset($this->hostServices)) {
$query = 'SELECT host_name, service_description '
. 'FROM host h, service s, host_service_relation hs '
. 'WHERE h.host_id = hs.host_host_id '
. 'AND s.service_id = hs.service_service_id '
. 'AND s.service_activate = "1" '
. 'AND s.service_activate = "1" '
. 'AND h.host_activate = "1" '
. 'AND h.host_register = "1" ';
$dbResult = $this->pearDB->query($query);
$this->hostServices = [];
while ($row = $dbResult->fetch()) {
if (! isset($this->hostServices[$row['host_name']])) {
$this->hostServices[$row['host_name']] = [];
}
$this->hostServices[$row['host_name']][$row['service_description']] = 1;
}
$dbResult->closeCursor();
}
}
/**
* @throws RestBadRequestException
* @return void
*/
private function openPipe(): void
{
if ($this->fh = @fopen($this->centcore_file, 'a+')) {
$this->pipeOpened = 1;
} else {
throw new RestBadRequestException("Can't open centcore pipe");
}
}
/**
* @return void
*/
private function closePipe(): void
{
fclose($this->fh);
$this->pipeOpened = 0;
}
/**
* @param $string
*
* @throws RestBadRequestException
* @return void
*/
private function writeInPipe($string): void
{
if ($this->pipeOpened == 0) {
throw new RestBadRequestException("Can't write results because pipe is closed");
}
if ($string != '') {
fwrite($this->fh, $string . "\n");
}
}
/**
* @param $data
*
* @throws RestBadRequestException
* @return void
*/
private function sendResults($data): void
{
if (! isset($this->pollerHosts['name'][$data['host']])) {
throw new RestBadRequestException("Can't find poller_id for host: " . $data['host']);
}
if (isset($data['service']) && $data['service'] == '') {
// Services update
$command = $data['host'] . ';' . $data['service'] . ';' . $data['status'] . ';'
. $data['output'] . '|' . $data['perfdata'];
$this->writeInPipe('EXTERNALCMD:' . $this->pollerHosts['name'][$data['host']]
. ':[' . $data['updatetime'] . '] PROCESS_HOST_CHECK_RESULT;' . $command);
} else {
// Host Update
$command = $data['host'] . ';' . $data['status'] . ';' . $data['output'] . '|' . $data['perfdata'];
$this->writeInPipe('EXTERNALCMD:' . $this->pollerHosts['name'][$data['host']]
. ':[' . $data['updatetime'] . '] PROCESS_SERVICE_CHECK_RESULT;' . $command);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/api/class/centreon_featuretesting.class.php | centreon/www/api/class/centreon_featuretesting.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__ . '/webService.class.php';
require_once _CENTREON_PATH_ . '/www/class/centreonFeature.class.php';
/**
* Class
*
* @class CentreonFeaturetesting
*/
class CentreonFeaturetesting extends CentreonWebService
{
/** @var CentreonFeature */
protected $obj;
/**
* CentreonFeaturetesting constructor
*/
public function __construct()
{
parent::__construct();
$this->obj = new CentreonFeature($this->pearDB);
}
/**
* Enabled or disabled a feature flipping for an user
*
* METHOD POST
*
* @throws PDOException
* @throws RestBadRequestException
* @throws RestUnauthorizedException
* @return void
*/
public function postEnabled(): void
{
if (! isset($this->arguments['name'])
|| ! isset($this->arguments['version'])
|| ! isset($this->arguments['enabled'])) {
throw new RestBadRequestException('Missing arguments');
}
if (! isset($_SESSION['centreon'])) {
throw new RestUnauthorizedException('Session does not exists.');
}
$userId = $_SESSION['centreon']->user->user_id;
$features = [];
$features[$this->arguments['name']] = [];
$features[$this->arguments['name']][$this->arguments['version']] = $this->arguments['enabled'] ? 1 : 0;
$this->obj->saveUserFeaturesValue(
$userId,
$features
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/api/class/centreon_configuration_graphtemplate.class.php | centreon/www/api/class/centreon_configuration_graphtemplate.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 __DIR__ . '/centreon_configuration_objects.class.php';
/**
* Class
*
* @class CentreonConfigurationGraphtemplate
*/
class CentreonConfigurationGraphtemplate extends CentreonConfigurationObjects
{
/**
* CentreonConfigurationGraphtemplate constructor
*/
public function __construct()
{
parent::__construct();
}
/**
* @throws PDOException
* @throws RestBadRequestException
* @return array
*/
public function getList()
{
$queryValues = [];
// Check for select2 'q' argument
$queryValues['name'] = isset($this->arguments['q']) === false ? '%%' : '%' . (string) $this->arguments['q'] . '%';
$query = 'SELECT SQL_CALC_FOUND_ROWS DISTINCT graph_id, name '
. 'FROM giv_graphs_template '
. 'WHERE name LIKE :name '
. 'ORDER BY name ';
if (isset($this->arguments['page_limit'], $this->arguments['page'])) {
if (
! is_numeric($this->arguments['page'])
|| ! is_numeric($this->arguments['page_limit'])
|| $this->arguments['page_limit'] < 1
) {
throw new RestBadRequestException('Error, limit must be an integer greater than zero');
}
$offset = ($this->arguments['page'] - 1) * $this->arguments['page_limit'];
$query .= 'LIMIT :offset, :limit ';
$queryValues['offset'] = (int) $offset;
$queryValues['limit'] = (int) $this->arguments['page_limit'];
}
$stmt = $this->pearDB->prepare($query);
$stmt->bindParam(':name', $queryValues['name'], PDO::PARAM_STR);
if (isset($queryValues['offset'])) {
$stmt->bindParam(':offset', $queryValues['offset'], PDO::PARAM_INT);
$stmt->bindParam(':limit', $queryValues['limit'], PDO::PARAM_INT);
}
$stmt->execute();
$serviceList = [];
while ($data = $stmt->fetch()) {
$serviceList[] = ['id' => $data['graph_id'], 'text' => $data['name']];
}
return ['items' => $serviceList, 'total' => (int) $this->pearDB->numberRows()];
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/api/class/centreon_realtime_services.class.php | centreon/www/api/class/centreon_realtime_services.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 __DIR__ . '/centreon_configuration_objects.class.php';
require_once __DIR__ . '/centreon_realtime_base.class.php';
/**
* Class
*
* @class CentreonRealtimeServices
*/
class CentreonRealtimeServices extends CentreonRealtimeBase
{
/** @var int|string|null */
public $servicegroup;
/** @var string|null */
public $searchOutput;
/** @var CentreonACL */
protected $aclObj;
/** @var int */
protected $admin;
// parameters
/** @var int|null */
protected $limit;
/** @var int|null */
protected $number;
/** @var string|null */
protected $status;
/** @var string|null */
protected $hostgroup;
/** @var string|null */
protected $search;
/** @var string|null */
protected $searchHost;
/** @var string|null */
protected $viewType;
/** @var string|null */
protected $sortType;
/** @var string|null */
protected $order;
/** @var int|null */
protected $instance;
/** @var string|null */
protected $criticality;
/** @var string|null */
protected $fieldList;
/** @var array|null */
protected $criticalityList;
/**
* CentreonConfigurationService constructor
*/
public function __construct()
{
global $centreon;
parent::__construct();
// Init ACL
if (! $centreon->user->admin) {
$this->admin = 0;
$this->aclObj = new CentreonACL($centreon->user->user_id, $centreon->user->admin);
} else {
$this->admin = 1;
}
// Init Values
$this->getCriticality();
}
/**
* @throws PDOException
* @throws RestBadRequestException
* @return array
*/
public function getList()
{
$this->setServiceFilters();
$this->setServiceFieldList();
return $this->getServiceState();
}
/**
* @throws PDOException
* @throws RestBadRequestException
* @return array
*/
public function getServiceState()
{
$queryValues = [];
/** * *************************************************
* Get Service status
*/
$query = 'SELECT SQL_CALC_FOUND_ROWS DISTINCT ' . $this->fieldList . ' ';
$query .= ' FROM hosts h, instances i ';
if (isset($this->hostgroup) && $this->hostgroup != 0) {
$query .= ', hosts_hostgroups hg, hostgroups hg2';
}
if (isset($this->servicegroup) && $this->servicegroup != 0) {
$query .= ', services_servicegroups ssg, servicegroups sg';
}
if ($this->criticality) {
$query .= ', customvariables cvs ';
}
if (! $this->admin) {
$query .= ', centreon_acl ';
}
$query .= ', services s LEFT JOIN customvariables cv ON (s.service_id = cv.service_id '
. "AND cv.host_id = s.host_id AND cv.name = 'CRITICALITY_LEVEL') ";
$query .= ' WHERE h.host_id = s.host_id '
. 'AND s.enabled = 1 '
. 'AND h.enabled = 1 '
. 'AND h.instance_id = i.instance_id ';
if ($this->criticality) {
$query .= ' AND s.service_id = cvs. service_id '
. 'AND cvs.host_id = h.host_id '
. "AND cvs.name = 'CRITICALITY_LEVEL' "
. 'AND cvs.value = :criticality';
$queryValues['criticality'] = (string) $this->criticality;
}
$query .= " AND h.name NOT LIKE '\_Module\_BAM%' ";
// Search string to a host name, alias or address
if ($this->searchHost) {
$query .= ' AND (h.name LIKE :searchName ';
$queryValues['searchName'] = (string) '%' . $this->searchHost . '%';
$query .= ' OR h.alias LIKE :searchAlias ';
$queryValues['searchAlias'] = (string) '%' . $this->searchHost . '%';
$query .= ' OR h.address LIKE :searchAddress ) ';
$queryValues['searchAddress'] = (string) '%' . $this->searchHost . '%';
}
// Search string to a service
if ($this->search) {
$query .= ' AND (s.description LIKE :serviceName ';
$queryValues['serviceName'] = (string) '%' . $this->search . '%';
$query .= ' OR s.display_name LIKE :serviceDisplay )';
$queryValues['serviceDisplay'] = (string) '%' . $this->search . '%';
}
if ($this->searchOutput) {
$query .= ' AND s.output LIKE :output ';
$queryValues['output'] = (string) '%' . $this->searchOutput . '%';
}
if ($this->instance != -1 && ! empty($this->instance)) {
$query .= ' AND h.instance_id = :instanceId ';
$queryValues['instanceId'] = (int) $this->instance;
}
$q = 'ASC';
if (isset($this->order) && strtoupper($this->order) === 'DESC') {
$q = 'DESC';
}
$tabOrder = [];
$tabOrder['criticality_id'] = " ORDER BY criticality {$q}, h.name, s.description ";
$tabOrder['service_id'] = " ORDER BY s.service_id {$q} ";
$tabOrder['host_name'] = " ORDER BY h.name {$q}, s.description ";
$tabOrder['service_description'] = " ORDER BY s.description {$q}, h.name";
$tabOrder['current_state'] = " ORDER BY s.state {$q}, h.name, s.description";
$tabOrder['last_state_change'] = " ORDER BY s.last_state_change {$q}, h.name, s.description";
$tabOrder['last_hard_state_change'] = " ORDER by s.last_hard_state_change {$q}, h.name, s.description";
$tabOrder['last_check'] = " ORDER BY s.last_check {$q}, h.name, s.description";
$tabOrder['current_attempt'] = " ORDER BY s.check_attempt {$q}, h.name, s.description";
$tabOrder['output'] = " ORDER BY s.output {$q}, h.name, s.description";
$tabOrder['default'] = " ORDER BY s.description {$q}, h.name";
if ($this->viewType !== null && preg_match('/^unhandled/', $this->viewType)) {
if (preg_match('/^unhandled_(warning|critical|unknown)$/', $this->viewType, $matches)) {
if (isset($matches[1]) && $matches[1] == 'warning') {
$query .= ' AND s.state = 1 ';
} elseif (isset($matches[1]) && $matches[1] == 'critical') {
$query .= ' AND s.state = 2 ';
} elseif (isset($matches[1]) && $matches[1] == 'unknown') {
$query .= ' AND s.state = 3 ';
} elseif (isset($matches[1]) && $matches[1] == 'pending') {
$query .= ' AND s.state = 4 ';
} else {
$query .= ' AND s.state <> 0 ';
}
} else {
$query .= ' AND (s.state <> 0 AND s.state <> 4) ';
}
$query .= ' AND s.state_type = 1';
$query .= ' AND s.acknowledged = 0';
$query .= ' AND s.scheduled_downtime_depth = 0';
$query .= ' AND h.acknowledged = 0 AND h.scheduled_downtime_depth = 0 ';
} elseif ($this->viewType == 'problems') {
$query .= ' AND s.state <> 0 AND s.state <> 4 ';
}
if ($this->status == 'ok') {
$query .= ' AND s.state = 0';
} elseif ($this->status == 'warning') {
$query .= ' AND s.state = 1';
} elseif ($this->status == 'critical') {
$query .= ' AND s.state = 2';
} elseif ($this->status == 'unknown') {
$query .= ' AND s.state = 3';
} elseif ($this->status == 'pending') {
$query .= ' AND s.state = 4';
}
/**
* HostGroup Filter
*/
if (isset($this->hostgroup) && $this->hostgroup != 0) {
$explodedValues = '';
foreach (explode(',', $this->hostgroup) as $hgId => $hgValue) {
if (! is_numeric($hgValue)) {
throw new RestBadRequestException('Error, host group id must be numerical');
}
$explodedValues .= ':hostgroup' . $hgId . ',';
$queryValues['hostgroup'][$hgId] = (int) $hgValue;
}
$explodedValues = rtrim($explodedValues, ',');
$query .= ' AND hg.hostgroup_id = hg2.hostgroup_id '
. 'AND hg.host_id = h.host_id AND hg.hostgroup_id IN (' . $explodedValues . ') ';
}
/**
* ServiceGroup Filter
*/
if (isset($this->servicegroup) && $this->servicegroup != 0) {
$explodedValues = '';
foreach (explode(',', $this->servicegroup) as $sgId => $sgValue) {
if (! is_numeric($sgValue)) {
throw new RestBadRequestException('Error, service group id must be numerical');
}
$explodedValues .= ':servicegroup' . $sgId . ',';
$queryValues['servicegroup'][$sgId] = (int) $sgValue;
}
$explodedValues = rtrim($explodedValues, ',');
$query .= ' AND ssg.servicegroup_id = sg.servicegroup_id '
. 'AND ssg.service_id = s.service_id AND ssg.servicegroup_id IN (' . $explodedValues . ') ';
}
/**
* ACL activation
*/
if (! $this->admin) {
$query .= ' AND h.host_id = centreon_acl.host_id '
. 'AND s.service_id = centreon_acl.service_id '
. 'AND group_id IN (' . $this->aclObj->getAccessGroupsString() . ') ';
}
(isset($tabOrder[$this->sortType])) ? $query .= $tabOrder[$this->sortType] : $query .= $tabOrder['default'];
$query .= ' LIMIT :offset,:limit';
$queryValues['offset'] = (int) ($this->number * $this->limit);
$queryValues['limit'] = (int) $this->limit;
$stmt = $this->realTimeDb->prepare($query);
if (isset($queryValues['criticality'])) {
$stmt->bindParam(':criticality', $queryValues['criticality'], PDO::PARAM_INT);
}
if (isset($queryValues['searchName'])) {
$stmt->bindParam(':searchName', $queryValues['searchName'], PDO::PARAM_STR);
$stmt->bindParam(':searchAlias', $queryValues['searchAlias'], PDO::PARAM_STR);
$stmt->bindParam(':searchAddress', $queryValues['searchAddress'], PDO::PARAM_STR);
}
if (isset($queryValues['serviceName'])) {
$stmt->bindParam(':serviceName', $queryValues['serviceName'], PDO::PARAM_STR);
$stmt->bindParam(':serviceDisplay', $queryValues['serviceDisplay'], PDO::PARAM_STR);
}
if (isset($queryValues['output'])) {
$stmt->bindParam(':output', $queryValues['output'], PDO::PARAM_STR);
}
if (isset($queryValues['instanceId'])) {
$stmt->bindParam(':instanceId', $queryValues['instanceId'], PDO::PARAM_INT);
}
if (isset($queryValues['hostgroup'])) {
foreach ($queryValues['hostgroup'] as $hgId => $hgValue) {
$stmt->bindValue(':hostgroup' . $hgId, $hgValue, PDO::PARAM_INT);
}
}
if (isset($queryValues['servicegroup'])) {
foreach ($queryValues['servicegroup'] as $hgId => $hgValue) {
$stmt->bindValue(':servicegroup' . $hgId, $hgValue, PDO::PARAM_INT);
}
}
$stmt->bindParam(':offset', $queryValues['offset'], PDO::PARAM_INT);
$stmt->bindParam(':limit', $queryValues['limit'], PDO::PARAM_INT);
$stmt->execute();
$dataList = [];
while ($data = $stmt->fetch()) {
if (isset($data['criticality'], $this->criticalityList[$data['criticality']])) {
$data['criticality'] = $this->criticalityList[$data['criticality']];
}
$dataList[] = $data;
}
return $dataList;
}
/**
* @return array
*/
protected function getFieldContent()
{
$tab = explode(',', $this->arguments['fields']);
$fieldList = [];
foreach ($tab as $key) {
$fieldList[$key] = 1;
}
return $fieldList;
}
/**
* @throws RestBadRequestException
* @return void
*/
protected function setServiceFilters()
{
// Pagination Elements
$this->limit = $this->arguments['limit'] ?? 30;
$this->number = $this->arguments['number'] ?? 0;
if (! is_numeric($this->number) || ! is_numeric($this->limit)) {
throw new RestBadRequestException('Error, limit must be numerical');
}
// Filters
if (isset($this->arguments['status'])) {
$statusList = ['ok', 'warning', 'critical', 'unknown', 'pending', 'all'];
if (in_array(strtolower($this->arguments['status']), $statusList)) {
$this->status = $this->arguments['status'];
} else {
throw new RestBadRequestException('Error, bad status parameter');
}
} else {
$this->status = null;
}
$this->hostgroup = $this->arguments['hostgroup'] ?? null;
$this->servicegroup = $this->arguments['servicegroup'] ?? null;
$this->search = $this->arguments['search'] ?? null;
$this->searchHost = $this->arguments['searchHost'] ?? null;
$this->searchOutput = $this->arguments['searchOutput'] ?? null;
$this->instance = $this->arguments['instance'] ?? null;
// set criticality
$this->criticality = $this->arguments['criticality'] ?? null;
// view properties
$this->viewType = $this->arguments['viewType'] ?? null;
$this->sortType = $this->arguments['sortType'] ?? null;
$this->order = $this->arguments['order'] ?? null;
}
/**
* @return void
*/
protected function setServiceFieldList()
{
$fields = [];
if (! isset($this->arguments['fields'])) {
$fields['h.host_id'] = 'host_id';
$fields['h.name'] = 'name';
$fields['s.description'] = 'description';
$fields['s.service_id'] = 'service_id';
$fields['s.state'] = 'state';
$fields['s.state_type'] = 'state_type';
$fields['s.output'] = 'output';
$fields['s.perfdata'] = 'perfdata';
$fields['s.max_check_attempts'] = 'max_check_attempts';
$fields['s.check_attempt'] = 'check_attempt';
$fields['s.last_check'] = 'last_check';
$fields['s.last_state_change'] = 'last_state_change';
$fields['s.last_hard_state_change'] = 'last_hard_state_change';
$fields['s.acknowledged'] = 'acknowledged';
$fields['cv.value as criticality'] = 'criticality';
} else {
$tab = explode(',', $this->arguments['fields']);
$fieldList = [];
foreach ($tab as $key) {
$fieldList[trim($key)] = 1;
}
// hosts informations
if (isset($fieldList['host_id'])) {
$fields['h.host_id'] = 'host_id';
}
if (isset($fieldList['host_name'])) {
$fields['h.name as host_name'] = 'host_name';
}
if (isset($fieldList['host_alias'])) {
$fields['h.alias as host_alias'] = 'host_alias';
}
if (isset($fieldList['host_address'])) {
$fields['h.address as host_address'] = 'host_address';
}
if (isset($fieldList['host_state'])) {
$fields['h.state as host_state'] = 'host_state';
}
if (isset($fieldList['host_state_type'])) {
$fields['h.state_type as host_state_type'] = 'host_state_type';
}
if (isset($fieldList['host_output'])) {
$fields['h.output as host_output'] = 'host_output';
}
if (isset($fieldList['host_last_check'])) {
$fields['h.last_check as host_last_check'] = 'host_last_check';
}
if (isset($fieldList['host_next_check'])) {
$fields['h.next_check as host_next_check'] = 'host_next_check';
}
if (isset($fieldList['host_acknowledged'])) {
$fields['h.acknowledged as host_acknowledged'] = 'host_acknowledged';
}
if (isset($fieldList['instance'])) {
$fields['i.name as instance_name'] = 'instance';
}
if (isset($fieldList['instance_id'])) {
$fields['i.instance_id as instance_id'] = 'instance_id';
}
if (isset($fieldList['host_action_url'])) {
$fields['h.action_url as host_action_url'] = 'host_action_url';
}
if (isset($fieldList['host_notes_url'])) {
$fields['h.notes_url as host_notes_url'] = 'host_notes_url';
}
if (isset($fieldList['host_notes'])) {
$fields['h.notes as host_notes'] = 'host_notes';
}
if (isset($fieldList['host_icon_image'])) {
$fields['h.icon_image as host_icon_image'] = 'host_icon_image';
}
// services informations
if (isset($fieldList['description'])) {
$fields['s.description'] = 'description';
}
if (isset($fieldList['state'])) {
$fields['s.state'] = 'state';
}
if (isset($fieldList['state_type'])) {
$fields['s.state_type'] = 'state_type';
}
if (isset($fieldList['service_id'])) {
$fields['s.service_id'] = 'service_id';
}
if (isset($fieldList['output'])) {
$fields['s.output'] = 'output';
}
if (isset($fieldList['perfdata'])) {
$fields['s.perfdata'] = 'perfdata';
}
if (isset($fieldList['current_attempt'])) {
$fields['s.check_attempt as current_attempt'] = 'current_attempt';
}
if (isset($fieldList['last_update'])) {
$fields['s.last_update'] = 'last_update';
}
if (isset($fieldList['last_state_change'])) {
$fields['s.last_state_change'] = 'last_state_change';
}
if (isset($fieldList['last_hard_state_change'])) {
$fields['s.last_hard_state_change'] = 'last_hard_state_change';
}
if (isset($fieldList['last_state_change'])) {
$fields['s.last_state_change'] = 'last_state_change';
}
if (isset($fieldList['last_check'])) {
$fields['s.last_check'] = 'last_check';
}
if (isset($fieldList['next_check'])) {
$fields['s.next_check'] = 'next_check';
}
if (isset($fieldList['max_check_attempts'])) {
$fields['s.max_check_attempts'] = 'max_check_attempts';
}
if (isset($fieldList['notes'])) {
$fields['s.notes'] = 'notes';
}
if (isset($fieldList['notes_url'])) {
$fields['s.notes_url'] = 'notes_url';
}
if (isset($fieldList['action_url'])) {
$fields['s.action_url'] = 'action_url';
}
if (isset($fieldList['icon_image'])) {
$fields['s.icon_image'] = 'icon_image';
}
if (isset($fieldList['display_name'])) {
$fields['s.display_name'] = 'display_name';
}
if (isset($fieldList['notify'])) {
$fields['s.notify'] = 'notify';
}
if (isset($fieldList['acknowledged'])) {
$fields['s.acknowledged'] = 'acknowledged';
}
if (isset($fieldList['passive_checks'])) {
$fields['s.passive_checks'] = 'passive_checks';
}
if (isset($fieldList['active_checks'])) {
$fields['s.active_checks'] = 'active_checks';
}
if (isset($fieldList['event_handler_enabled'])) {
$fields['s.event_handler_enabled'] = 'event_handler_enabled';
}
if (isset($fieldList['flapping'])) {
$fields['s.flapping'] = 'flapping';
}
if (isset($fieldList['scheduled_downtime_depth'])) {
$fields['s.scheduled_downtime_depth'] = 'scheduled_downtime_depth';
}
if (isset($fieldList['flap_detection'])) {
$fields['s.flap_detection'] = 'flap_detection';
}
if (isset($fieldList['criticality'])) {
$fields['cv.value as criticality'] = 'criticality';
}
}
$sortColumns = [
'criticality_id' => ['criticality', 'h.name', 's.description'],
'service_id' => ['s.service_id'],
'host_name' => ['h.name', 's.description'],
'service_description' => ['s.description', 'h.name'],
'current_state' => ['s.state', 'h.name', 's.description'],
'last_state_change' => ['s.last_state_change', 'h.name', 's.description'],
'last_hard_state_change' => ['s.last_hard_state_change', 'h.name', 's.description'],
'last_check' => ['s.last_check', 'h.name', 's.description'],
'current_attempt' => ['s.check_attempt', 'h.name', 's.description'],
'output' => ['s.output', 'h.name', 's.description'],
'default' => ['s.description', 'h.name'],
];
$sortType = $this->sortType ?? 'default';
$columnsToAdd = $sortColumns[$sortType] ?? $sortColumns['default'];
foreach ($columnsToAdd as $col) {
// If column isn't already in the SELECT, add it
$alreadyPresent = false;
foreach ($fields as $key => $alias) {
if (str_contains($key, $col)) {
$alreadyPresent = true;
break;
}
}
if (! $alreadyPresent) {
$fields[$col] = $col;
}
}
// Build Field List
$this->fieldList = '';
foreach ($fields as $key => $value) {
if ($this->fieldList != '') {
$this->fieldList .= ', ';
}
$this->fieldList .= $key;
}
}
/**
* @throws PDOException
* @return void
*/
protected function getCriticality()
{
$this->criticalityList = [];
$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->pearDB->query($sql);
while ($row = $res->fetch()) {
$this->criticalityList[$row['sc_name']] = $row;
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/api/class/centreon_configuration_downtime.class.php | centreon/www/api/class/centreon_configuration_downtime.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/centreonDowntime.class.php';
require_once __DIR__ . '/centreon_configuration_objects.class.php';
/**
* Class
*
* @class CentreonConfigurationDowntime
*/
class CentreonConfigurationDowntime extends CentreonConfigurationObjects
{
/** @var CentreonDB */
protected $pearDBMonitoring;
/**
* CentreonConfigurationDowntime constructor
*/
public function __construct()
{
global $pearDBO;
parent::__construct();
$this->pearDBMonitoring = new CentreonDB('centstorage');
$pearDBO = $this->pearDBMonitoring;
}
/**
* @throws Exception
* @return array
*/
public function getList()
{
$queryValues = [];
// Check for select2 'q' argument
$queryValues['dtName'] = isset($this->arguments['q']) === false ? '%%' : '%' . (string) $this->arguments['q'] . '%';
$queryDowntime = 'SELECT SQL_CALC_FOUND_ROWS DISTINCT dt.dt_name, dt.dt_id '
. 'FROM downtime dt '
. 'WHERE dt.dt_name LIKE :dtName '
. 'ORDER BY dt.dt_name';
$stmt = $this->pearDB->prepare($queryDowntime);
$stmt->bindParam(':dtName', $queryValues['dtName'], PDO::PARAM_STR);
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception('An error occured');
}
$downtimeList = [];
while ($data = $stmt->fetch()) {
$downtimeList[] = ['id' => htmlentities($data['dt_id']), 'text' => $data['dt_name']];
}
return ['items' => $downtimeList, 'total' => (int) $this->pearDB->numberRows()];
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/api/class/centreon_configuration_graphvirtualmetric.class.php | centreon/www/api/class/centreon_configuration_graphvirtualmetric.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 __DIR__ . '/centreon_configuration_objects.class.php';
/**
* Class
*
* @class CentreonConfigurationGraphvirtualmetric
*/
class CentreonConfigurationGraphvirtualmetric extends CentreonConfigurationObjects
{
/**
* CentreonConfigurationGraphvirtualmetric constructor
*/
public function __construct()
{
parent::__construct();
}
/**
* @param $currentObject
* @param int $id
* @param string $field
* @throws Exception
* @return array
*/
protected function retrieveSimpleValues($currentObject, $id, $field)
{
$tmpValues = [];
// Getting Current Values
$query = 'SELECT id.host_id, id.service_id '
. 'FROM ' . dbcstg . '.index_data id, virtual_metrics vm '
. 'WHERE id.id = vm.index_id '
. 'AND vm.vmetric_id = :metricId ';
$stmt = $this->pearDB->prepare($query);
$stmt->bindParam(':metricId', $id, PDO::PARAM_INT);
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception('An error occured');
}
while ($row = $stmt->fetch()) {
$tmpValues[] = $row['host_id'] . '-' . $row['service_id'];
}
return $tmpValues;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/api/class/centreon_configuration_timeperiod.class.php | centreon/www/api/class/centreon_configuration_timeperiod.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 __DIR__ . '/centreon_configuration_objects.class.php';
/**
* Class
*
* @class CentreonConfigurationTimeperiod
*/
class CentreonConfigurationTimeperiod extends CentreonConfigurationObjects
{
/**
* CentreonConfigurationTimeperiod constructor
*/
public function __construct()
{
parent::__construct();
}
/**
* Get a list of time periods as a source of data for the select2 widget
*
* @throws PDOException
* @throws RestBadRequestException If some parameter is missing will throw this exception
* @return array
*/
public function getList()
{
$queryWhere = [];
$queryValues = [];
// Check for select2 'q' argument
if (isset($this->arguments['q'])) {
$queryWhere[] = 'tp_name LIKE :name';
$queryValues['name'] = [
PDO::PARAM_STR => "%{$this->arguments['q']}%",
];
}
// exclude some values from the result
if (isset($this->arguments['exclude'])) {
$queryWhere[] = 'tp_id <> :exclude';
$queryValues['exclude'] = [
PDO::PARAM_INT => (int) $this->arguments['exclude'],
];
}
$queryTimePeriod = 'SELECT SQL_CALC_FOUND_ROWS DISTINCT tp_id, tp_name FROM timeperiod '
. ($queryWhere ? 'WHERE ' . join(' AND ', $queryWhere) : '')
. ' ORDER BY tp_name ';
if (isset($this->arguments['page_limit'], $this->arguments['page'])) {
if (
! is_numeric($this->arguments['page'])
|| ! is_numeric($this->arguments['page_limit'])
|| $this->arguments['page_limit'] < 1
) {
throw new RestBadRequestException('Error, limit must be an integer greater than zero');
}
$offset = ($this->arguments['page'] - 1) * $this->arguments['page_limit'];
$queryTimePeriod .= 'LIMIT :offset, :limit';
$queryValues['offset'] = [
PDO::PARAM_INT => (int) $offset,
];
$queryValues['limit'] = [
PDO::PARAM_INT => (int) $this->arguments['page_limit'],
];
}
$stmt = $this->pearDB->prepare($queryTimePeriod);
foreach ($queryValues as $bindId => $bindData) {
foreach ($bindData as $bindType => $bindValue) {
$stmt->bindValue($bindId, $bindValue, $bindType);
break;
}
}
$stmt->execute();
$timePeriodList = [];
while ($data = $stmt->fetch()) {
$timePeriodList[] = [
'id' => $data['tp_id'],
'text' => html_entity_decode($data['tp_name']),
];
}
return [
'items' => $timePeriodList,
'total' => (int) $this->pearDB->numberRows(),
];
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/api/class/centreon_configuration_servicetemplate.class.php | centreon/www/api/class/centreon_configuration_servicetemplate.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 __DIR__ . '/centreon_configuration_service.class.php';
/**
* Class
*
* @class CentreonConfigurationServicetemplate
*/
class CentreonConfigurationServicetemplate extends CentreonConfigurationService
{
/**
* CentreonConfigurationServicetemplate constructor
*/
public function __construct()
{
parent::__construct();
}
/**
* @throws RestBadRequestException
* @return array
*/
public function getList()
{
$range = [];
// Check for select2 'q' argument
$q = isset($this->arguments['q']) ? (string) $this->arguments['q'] : '';
if (isset($this->arguments['l'])) {
$templateType = ['0', '1'];
if (in_array($this->arguments['l'], $templateType)) {
$l = $this->arguments['l'];
} else {
throw new RestBadRequestException('Error, bad list parameter');
}
} else {
$l = '0';
}
if (isset($this->arguments['page_limit'], $this->arguments['page'])) {
if (
! is_numeric($this->arguments['page'])
|| ! is_numeric($this->arguments['page_limit'])
|| $this->arguments['page_limit'] < 1
) {
throw new RestBadRequestException('Error, limit must be an integer greater than zero');
}
$offset = ($this->arguments['page'] - 1) * $this->arguments['page_limit'];
$range[] = (int) $offset;
$range[] = (int) $this->arguments['page_limit'];
}
return $l == '1' ? $this->listWithHostTemplate($q, $range) : $this->listClassic($q, $range);
}
/**
* @param $q
* @param array $range
*
* @throws PDOException
* @return array
*/
private function listClassic($q, $range = [])
{
$serviceList = [];
$queryValues = [];
$queryContact = 'SELECT SQL_CALC_FOUND_ROWS DISTINCT service_id, service_description '
. 'FROM service '
. 'WHERE service_description LIKE :description '
. 'AND service_register = "0" '
. 'ORDER BY service_description ';
if (isset($range) && ! empty($range)) {
$queryContact .= 'LIMIT :offset, :limit';
$queryValues['offset'] = (int) $range[0];
$queryValues['limit'] = (int) $range[1];
}
$queryValues['description'] = '%' . (string) $q . '%';
$stmt = $this->pearDB->prepare($queryContact);
$stmt->bindParam(':description', $queryValues['description'], PDO::PARAM_STR);
if (isset($queryValues['offset'])) {
$stmt->bindParam(':offset', $queryValues['offset'], PDO::PARAM_INT);
$stmt->bindParam(':limit', $queryValues['limit'], PDO::PARAM_INT);
}
$stmt->execute();
while ($data = $stmt->fetch()) {
$serviceList[] = ['id' => $data['service_id'], 'text' => $data['service_description']];
}
return ['items' => $serviceList, 'total' => (int) $this->pearDB->numberRows()];
}
/**
* @param string $q
* @param array $range
*
* @throws PDOException
* @return array
*/
private function listWithHostTemplate($q = '', $range = [])
{
$queryValues = [];
$queryValues['description'] = '%' . (string) $q . '%';
$queryService = 'SELECT SQL_CALC_FOUND_ROWS DISTINCT s.service_description, s.service_id, '
. 'h.host_name, h.host_id '
. 'FROM host h, service s, host_service_relation hsr '
. 'WHERE hsr.host_host_id = h.host_id '
. 'AND hsr.service_service_id = s.service_id '
. 'AND h.host_register = "0" '
. 'AND s.service_register = "0" '
. 'AND CONCAT(h.host_name, " - ", s.service_description) LIKE :description '
. 'ORDER BY h.host_name ';
if (isset($range) && ! empty($range)) {
$queryService .= 'LIMIT :offset, :limit';
$queryValues['offset'] = (int) $range[0];
$queryValues['limit'] = (int) $range[1];
}
$stmt = $this->pearDB->prepare($queryService);
$stmt->bindParam(':description', $queryValues['description'], PDO::PARAM_STR);
if (isset($queryValues['offset'])) {
$stmt->bindParam(':offset', $queryValues['offset'], PDO::PARAM_INT);
$stmt->bindParam(':limit', $queryValues['limit'], PDO::PARAM_INT);
}
$stmt->execute();
$serviceList = [];
while ($data = $stmt->fetch()) {
$serviceCompleteName = $data['host_name'] . ' - ' . $data['service_description'];
$serviceCompleteId = $data['host_id'] . '-' . $data['service_id'];
$serviceList[] = ['id' => htmlentities($serviceCompleteId), 'text' => $serviceCompleteName];
}
return ['items' => $serviceList, 'total' => (int) $this->pearDB->numberRows()];
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/api/class/centreon_configuration_host.class.php | centreon/www/api/class/centreon_configuration_host.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/centreonHost.class.php';
require_once _CENTREON_PATH_ . '/www/class/centreonHook.class.php';
require_once __DIR__ . '/centreon_configuration_objects.class.php';
/**
* Class
*
* @class CentreonConfigurationHost
*/
class CentreonConfigurationHost extends CentreonConfigurationObjects
{
/** @var CentreonDB */
protected $pearDBMonitoring;
/**
* CentreonConfigurationHost constructor
*/
public function __construct()
{
global $pearDBO;
parent::__construct();
$this->pearDBMonitoring = new CentreonDB('centstorage');
$pearDBO = $this->pearDBMonitoring;
}
/**
* @throws PDOException
* @throws RestBadRequestException
* @return array
*/
public function getList()
{
global $centreon;
$userId = $centreon->user->user_id;
$isAdmin = $centreon->user->admin;
$aclHosts = '';
$additionalTables = '';
$additionalCondition = '';
$explodedValues = '';
$queryValues = [];
$query = '';
// Check for select2 'q' argument
$queryValues['hostName'] = isset($this->arguments['q']) === false ? '%%' : '%' . (string) $this->arguments['q'] . '%';
$query .= 'SELECT SQL_CALC_FOUND_ROWS DISTINCT host_name, host_id, host_activate '
. 'FROM ( '
. '( SELECT DISTINCT h.host_name, h.host_id, h.host_activate '
. 'FROM host h ';
if (isset($this->arguments['hostgroup'])) {
$additionalTables .= ',hostgroup_relation hg ';
$additionalCondition .= 'AND hg.host_host_id = h.host_id AND hg.hostgroup_hg_id IN (';
$hostgroups = is_array($this->arguments['hostgroup']) ? $this->arguments['hostgroup'] : explode(',', $this->arguments['hostgroup']);
foreach ($hostgroups as $hgId => $hgValue) {
if (! is_numeric($hgValue)) {
throw new RestBadRequestException('Error, host group id must be numerical');
}
$explodedValues .= ':hostgroup' . $hgId . ',';
$queryValues['hostgroup'][$hgId] = (int) $hgValue;
}
$explodedValues = rtrim($explodedValues, ',');
$additionalCondition .= $explodedValues . ') ';
}
$query .= $additionalTables . 'WHERE h.host_register = "1" ';
// Get ACL if user is not admin
if (! $isAdmin) {
$acl = new CentreonACL($userId, $isAdmin);
$aclHosts .= 'AND h.host_id IN (' . $acl->getHostsString('ID', $this->pearDBMonitoring) . ') ';
}
$query .= $aclHosts;
$query .= $additionalCondition . ') ';
// Check for virtual hosts
$virtualHostCondition = '';
if (! isset($this->arguments['hostgroup']) && isset($this->arguments['h']) && $this->arguments['h'] == 'all') {
$allVirtualHosts = CentreonHook::execute('Host', 'getVirtualHosts');
foreach ($allVirtualHosts as $virtualHosts) {
foreach ($virtualHosts as $vHostId => $vHostName) {
$virtualHostCondition .= 'UNION ALL '
. "(SELECT :hostNameTable{$vHostId} as host_name, "
. ":virtualHostId{$vHostId} as host_id, "
. "'1' AS host_activate ) ";
$queryValues['virtualHost'][$vHostId] = (string) $vHostName;
}
}
}
$query .= $virtualHostCondition
. ') t_union '
. 'WHERE host_name LIKE :hostName '
. 'ORDER BY host_name ';
if (isset($this->arguments['page_limit'], $this->arguments['page'])) {
if (
! is_numeric($this->arguments['page'])
|| ! is_numeric($this->arguments['page_limit'])
|| $this->arguments['page_limit'] < 1
) {
throw new RestBadRequestException('Error, limit must be an integer greater than zero');
}
$offset = ($this->arguments['page'] - 1) * $this->arguments['page_limit'];
$query .= 'LIMIT :offset, :limit';
$queryValues['offset'] = (int) $offset;
$queryValues['limit'] = (int) $this->arguments['page_limit'];
}
$stmt = $this->pearDB->prepare($query);
$stmt->bindParam(':hostName', $queryValues['hostName'], PDO::PARAM_STR);
if (isset($queryValues['hostgroup'])) {
foreach ($queryValues['hostgroup'] as $hgId => $hgValue) {
$stmt->bindValue(':hostgroup' . $hgId, $hgValue, PDO::PARAM_INT);
}
}
if (isset($queryValues['virtualHost'])) {
foreach ($queryValues['virtualHost'] as $vhId => $vhValue) {
$stmt->bindValue(':hostNameTable' . $vhId, $vhValue, PDO::PARAM_STR);
$stmt->bindValue(':virtualHostId' . $vhId, $vhId, PDO::PARAM_INT);
}
}
if (isset($queryValues['offset'])) {
$stmt->bindParam(':offset', $queryValues['offset'], PDO::PARAM_INT);
$stmt->bindParam(':limit', $queryValues['limit'], PDO::PARAM_INT);
}
$stmt->execute();
$hostList = [];
while ($data = $stmt->fetch()) {
$hostList[] = ['id' => htmlentities($data['host_id']), 'text' => $data['host_name'], 'status' => (bool) $data['host_activate']];
}
return ['items' => $hostList, 'total' => (int) $this->pearDB->numberRows()];
}
/**
* @throws PDOException
* @throws RestBadRequestException
* @return array
*/
public function getServices()
{
// Check for id
if (isset($this->arguments['id']) === false) {
throw new RestBadRequestException('Missing host id');
}
$id = $this->arguments['id'];
$allServices = false;
if (isset($this->arguments['all'])) {
$allServices = true;
}
$hostObj = new CentreonHost($this->pearDB);
$serviceList = [];
$serviceListRaw = $hostObj->getServices($id, false, $allServices);
foreach ($serviceListRaw as $service_id => $service_description) {
if ($allServices || service_has_graph($id, $service_id)) {
$serviceList[$service_id] = $service_description;
}
}
return $serviceList;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/api/class/centreon_ws.class.php | centreon/www/api/class/centreon_ws.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__ . '/webService.class.php';
/**
* Class
*
* @class CentreonWs
*/
class CentreonWs extends CentreonWebService
{
/**
* CentreonWs constructor
*/
public function __construct()
{
parent::__construct();
}
/**
* Keep alive function
*
* @return void
*/
public function getKeepAlive(): void
{
self::sendResult(true);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/api/class/centreon_configuration_service.class.php | centreon/www/api/class/centreon_configuration_service.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 __DIR__ . '/centreon_configuration_objects.class.php';
/**
* Class
*
* @class CentreonConfigurationService
*/
class CentreonConfigurationService extends CentreonConfigurationObjects
{
/** @var CentreonDB */
public $db;
/** @var CentreonDB */
protected $pearDBMonitoring;
/**
* CentreonConfigurationService constructor
*/
public function __construct()
{
global $pearDBO;
parent::__construct();
$this->pearDBMonitoring = new CentreonDB('centstorage');
$pearDBO = $this->pearDBMonitoring;
}
/**
* @throws RestBadRequestException
* @return array
*/
public function getList()
{
global $centreon;
$userId = $centreon->user->user_id;
$isAdmin = $centreon->user->admin;
$aclServices = '';
$aclMetaServices = '';
$range = [];
// Get ACL if user is not admin
if (! $isAdmin) {
$acl = new CentreonACL($userId, $isAdmin);
$aclServices .= 'AND s.service_id IN (' . $acl->getServicesString('ID', $this->pearDBMonitoring) . ') ';
$aclMetaServices .= 'AND ms.service_id IN ('
. $acl->getMetaServiceString() . ') ';
}
// Check for select2 'q' argument
$q = isset($this->arguments['q']) ? (string) $this->arguments['q'] : '';
// Check for service enable
if (isset($this->arguments['e'])) {
$enableList = ['enable', 'disable'];
if (in_array(strtolower($this->arguments['e']), $enableList)) {
$e = $this->arguments['e'];
} else {
throw new RestBadRequestException('Error, bad enable status');
}
} else {
$e = '';
}
// Check for service type
if (isset($this->arguments['t'])) {
$typeList = ['hostgroup', 'host'];
if (in_array(strtolower($this->arguments['t']), $typeList)) {
$t = $this->arguments['t'];
} else {
throw new RestBadRequestException('Error, bad service type');
}
} else {
$t = 'host';
}
// Check for service with graph
$g = false;
if (isset($this->arguments['g'])) {
$g = $this->arguments['g'];
if ($g == '1') {
$g = true;
}
}
// Check for service type
if (isset($this->arguments['s'])) {
$sTypeList = ['s', 'm', 'all'];
if (in_array(strtolower($this->arguments['s']), $sTypeList)) {
$s = $this->arguments['s'];
} else {
throw new RestBadRequestException('Error, bad service type');
}
} else {
$s = 'all';
}
if (isset($this->arguments['page_limit'], $this->arguments['page'])) {
if (
! is_numeric($this->arguments['page'])
|| ! is_numeric($this->arguments['page_limit'])
|| $this->arguments['page_limit'] < 1
) {
throw new RestBadRequestException('Error, limit must be an integer greater than zero');
}
$offset = ($this->arguments['page'] - 1) * $this->arguments['page_limit'];
$range[] = (int) $offset;
$range[] = (int) $this->arguments['page_limit'];
}
switch ($t) {
default:
case 'host':
$serviceList = $this->getServicesByHost($q, $aclServices, $range, $g, $aclMetaServices, $s, $e);
break;
case 'hostgroup':
$serviceList = $this->getServicesByHostgroup($q, $aclServices, $range);
break;
}
return $serviceList;
}
/**
* @param $q
* @param $aclServices
* @param array $range
* @param bool $hasGraph
* @param $aclMetaServices
* @param $s
* @param $e
* @throws Exception
* @return array
*/
private function getServicesByHost(
$q,
$aclServices,
$range = [],
$hasGraph = false,
$aclMetaServices = '',
$s = 'all',
$e = 'enable',
) {
$queryValues = [];
if ($e == 'enable') {
$enableQuery = 'AND s.service_activate = \'1\' AND h.host_activate = \'1\' ';
$enableQueryMeta = 'AND ms.service_activate = \'1\' AND mh.host_activate = \'1\' ';
} elseif ($e == 'disable') {
$enableQuery = 'AND ( s.service_activate = \'0\' OR h.host_activate = \'0\' ) ';
$enableQueryMeta = 'AND ( ms.service_activate = \'0\' OR mh.host_activate = \'0\') ';
} else {
$enableQuery = '';
$enableQueryMeta = '';
}
switch ($s) {
case 'all':
$queryService = 'SELECT SQL_CALC_FOUND_ROWS DISTINCT fullname, service_id, host_id, service_activate '
. 'FROM ( '
. '( SELECT DISTINCT CONCAT(h.host_name, " - ", s.service_description) '
. 'as fullname, s.service_id, h.host_id, s.service_activate '
. 'FROM host h, service s, host_service_relation hsr '
. 'WHERE hsr.host_host_id = h.host_id '
. 'AND hsr.service_service_id = s.service_id '
. 'AND h.host_register = "1" '
. 'AND (s.service_register = "1" OR s.service_register = "3") '
. 'AND CONCAT(h.host_name, " - ", s.service_description) LIKE :description '
. $enableQuery . $aclServices . ') '
. 'UNION ALL ( '
. 'SELECT DISTINCT CONCAT("Meta - ", ms.display_name) as fullname, ms.service_id, mh.host_id, ms.service_activate '
. 'FROM host mh, service ms '
. 'WHERE mh.host_name = "_Module_Meta" '
. 'AND mh.host_register = "2" '
. 'AND ms.service_register = "2" '
. 'AND CONCAT("Meta - ", ms.display_name) LIKE :description '
. $enableQueryMeta . $aclMetaServices . ') '
. ') as t_union '
. 'ORDER BY fullname ';
if (! empty($range)) {
$queryService .= 'LIMIT :offset, :limit';
$queryValues['offset'] = $range[0];
$queryValues['limit'] = $range[1];
}
$queryValues['description'] = '%' . $q . '%';
$stmt = $this->pearDB->prepare($queryService);
$stmt->bindValue(':description', $queryValues['description'], PDO::PARAM_STR);
if (isset($queryValues['offset'])) {
$stmt->bindValue(':offset', $queryValues['offset'], PDO::PARAM_INT);
$stmt->bindValue(':limit', $queryValues['limit'], PDO::PARAM_INT);
}
$dbResult = $stmt->execute();
break;
case 's':
$queryService = 'SELECT SQL_CALC_FOUND_ROWS DISTINCT CONCAT(h.host_name, " - ", '
. 's.service_description) as fullname, s.service_id, h.host_id, s.service_activate '
. 'FROM host h, service s, host_service_relation hsr '
. 'WHERE hsr.host_host_id = h.host_id '
. 'AND hsr.service_service_id = s.service_id '
. 'AND h.host_register = "1" '
. 'AND (s.service_register = "1" OR s.service_register = "3") '
. 'AND CONCAT(h.host_name, " - ", s.service_description) LIKE :description '
. $enableQuery . $aclServices
. 'ORDER BY fullname ';
if (! empty($range)) {
$queryService .= 'LIMIT :offset, :limit';
$queryValues['offset'] = $range[0];
$queryValues['limit'] = $range[1];
}
$queryValues['description'] = '%' . $q . '%';
$stmt = $this->pearDB->prepare($queryService);
$stmt->bindValue(':description', $queryValues['description'], PDO::PARAM_STR);
if (isset($queryValues['offset'])) {
$stmt->bindValue(':offset', $queryValues['offset'], PDO::PARAM_INT);
$stmt->bindValue(':limit', $queryValues['limit'], PDO::PARAM_INT);
}
$dbResult = $stmt->execute();
break;
case 'm':
$queryService = 'SELECT SQL_CALC_FOUND_ROWS DISTINCT CONCAT("Meta - ", ms.display_name) '
. 'as fullname, ms.service_id, mh.host_id, ms.service_activate '
. 'FROM host mh, service ms '
. 'WHERE mh.host_name = "_Module_Meta" '
. 'AND mh.host_register = "2" '
. 'AND ms.service_register = "2" '
. 'AND CONCAT("Meta - ", ms.display_name) LIKE :description '
. $enableQueryMeta . $aclMetaServices
. 'ORDER BY fullname ';
if (! empty($range)) {
$queryService .= 'LIMIT :offset, :limit';
$queryValues['offset'] = $range[0];
$queryValues['limit'] = $range[1];
}
$queryValues['description'] = '%' . $q . '%';
$stmt = $this->pearDB->prepare($queryService);
$stmt->bindValue(':description', $queryValues['description'], PDO::PARAM_STR);
if (isset($queryValues['offset'])) {
$stmt->bindValue(':offset', $queryValues['offset'], PDO::PARAM_INT);
$stmt->bindValue(':limit', $queryValues['limit'], PDO::PARAM_INT);
}
$dbResult = $stmt->execute();
break;
}
if (! $dbResult) {
throw new Exception('An error occured');
}
$serviceList = [];
while ($data = $stmt->fetch()) {
if ($hasGraph) {
if (service_has_graph($data['host_id'], $data['service_id'], $this->pearDBMonitoring)) {
$serviceCompleteName = $data['fullname'];
$serviceCompleteId = $data['host_id'] . '-' . $data['service_id'];
$serviceList[] = [
'id' => htmlentities($serviceCompleteId),
'text' => $serviceCompleteName,
'status' => (bool) $data['service_activate'],
];
}
} else {
$serviceCompleteName = $data['fullname'];
$serviceCompleteId = $data['host_id'] . '-' . $data['service_id'];
$serviceList[] = [
'id' => htmlentities($serviceCompleteId),
'text' => $serviceCompleteName,
'status' => (bool) $data['service_activate'],
];
}
}
return ['items' => $serviceList, 'total' => (int) $this->pearDB->numberRows()];
}
/**
* @param $q
* @param $aclServices
* @param array $range
* @throws Exception
* @return array
*/
private function getServicesByHostgroup($q, $aclServices, $range = [])
{
$queryValues = [];
$queryService = 'SELECT SQL_CALC_FOUND_ROWS DISTINCT CONCAT(hg.hg_name, " - ", s.service_description) '
. 'as fullname, s.service_id, hg.hg_id '
. 'FROM hostgroup hg, service s, host_service_relation hsr '
. 'WHERE hsr.hostgroup_hg_id = hg.hg_id '
. 'AND hsr.service_service_id = s.service_id '
. 'AND s.service_register = "1" '
. 'AND CONCAT(hg.hg_name, " - ", s.service_description) LIKE :description '
. $aclServices . 'ORDER BY fullname ';
if (! empty($range)) {
$queryService .= 'LIMIT :offset,:limit';
$queryValues['offset'] = $range[0];
$queryValues['limit'] = $range[1];
}
$queryValues['description'] = '%' . $q . '%';
$stmt = $this->pearDB->prepare($queryService);
$stmt->bindValue(':description', $queryValues['description'], PDO::PARAM_STR);
if (isset($queryValues['offset'])) {
$stmt->bindValue(':offset', $queryValues['offset'], PDO::PARAM_INT);
$stmt->bindValue(':limit', $queryValues['limit'], PDO::PARAM_INT);
}
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception('An error occured');
}
$serviceList = [];
while ($data = $stmt->fetch()) {
$serviceCompleteName = $data['fullname'];
$serviceCompleteId = $data['hg_id'] . '-' . $data['service_id'];
$serviceList[] = ['id' => htmlentities($serviceCompleteId), 'text' => $serviceCompleteName];
}
return ['items' => $serviceList, 'total' => (int) $this->pearDB->numberRows()];
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/api/class/centreon_monitoring_metric.class.php | centreon/www/api/class/centreon_monitoring_metric.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/centreonGraphService.class.php';
require_once __DIR__ . '/centreon_configuration_objects.class.php';
/**
* Class
*
* @class CentreonMonitoringMetric
*/
class CentreonMonitoringMetric extends CentreonConfigurationObjects
{
/** @var CentreonDB */
protected $pearDBMonitoring;
/**
* CentreonMonitoringMetric constructor
*/
public function __construct()
{
$this->pearDBMonitoring = new CentreonDB('centstorage');
parent::__construct();
}
/**
* @throws Exception
* @return array{items: array{id: string, text: string}, total: int}
*/
public function getList(): array
{
global $centreon;
$configurationDbName = db;
$aclSubQuery = '';
$whereClause = '';
$limitClause = '';
$queryValues = [];
if (! $centreon->user->admin) {
$aclSubQuery = <<<SQL
INNER JOIN `index_data` i
ON i.`id` = m.`index_id`
INNER JOIN `centreon_acl` acl
ON acl.`host_id` = i.`host_id`
AND acl.`service_id` = i.`service_id`
INNER JOIN {$configurationDbName}.`acl_groups` ag
ON ag.`acl_group_id` = acl.`group_id`
AND ag.acl_group_activate = '1'
AND (`acl_group_id` IN (SELECT `acl_group_id`
FROM {$configurationDbName}.`acl_group_contacts_relations`
WHERE `contact_contact_id` = :contact_id)
OR `acl_group_id` IN (SELECT `acl_group_id`
FROM {$configurationDbName}.`acl_group_contactgroups_relations` acgr
INNER JOIN {$configurationDbName}.`contactgroup_contact_relation` cgcr
ON cgcr.`contactgroup_cg_id` = acgr.cg_cg_id
WHERE cgcr.`contact_contact_id` = :contact_id
)
)
SQL;
$queryValues[':contact_id'] = [$centreon->user->user_id, PDO::PARAM_INT];
}
if (isset($this->arguments['q'])) {
$whereClause = <<<'SQL'
WHERE `metric_name` LIKE :name
SQL;
$queryValues[':name'] = ['%' . (string) $this->arguments['q'] . '%', PDO::PARAM_STR];
}
if (isset($this->arguments['page_limit'], $this->arguments['page'])) {
if (
filter_var(($limit = $this->arguments['page_limit']), FILTER_VALIDATE_INT) === false
|| filter_var(($page = $this->arguments['page']), FILTER_VALIDATE_INT) === false
) {
throw new InvalidArgumentException('Pagination parameters must be integers');
}
if ($page < 1) {
throw new InvalidArgumentException('Page number must be greater than zero');
}
$offset = ($page - 1) * $limit;
$limitClause = 'LIMIT :offset, :limit';
$queryValues[':offset'] = [$offset, PDO::PARAM_INT];
$queryValues[':limit'] = [$limit, PDO::PARAM_INT];
}
$query = <<<SQL
SELECT SQL_CALC_FOUND_ROWS DISTINCT `metric_name`
FROM `metrics` m
{$aclSubQuery}
{$whereClause}
ORDER BY `metric_name`
{$limitClause}
SQL;
$stmt = $this->pearDBMonitoring->prepare($query);
foreach ($queryValues as $name => $parameters) {
[$value, $type] = $parameters;
$stmt->bindValue($name, $value, $type);
}
$stmt->execute();
$metrics = [];
while ($row = $stmt->fetch()) {
$metrics[] = [
'id' => (string) $row['metric_name'],
'text' => (string) $row['metric_name'],
];
}
return [
'items' => $metrics,
'total' => (int) $this->pearDBMonitoring->numberRows(),
];
}
/**
* @throws Exception
* @throws RestBadRequestException
* @throws RestForbiddenException
* @throws RestNotFoundException
* @return array
*/
public function getMetricsDataByService()
{
global $centreon;
$userId = $centreon->user->user_id;
$isAdmin = $centreon->user->admin;
// Get ACL if user is not admin
if (! $isAdmin) {
$acl = new CentreonACL($userId, $isAdmin);
$aclGroups = $acl->getAccessGroupsString();
}
// Validate options
if (isset($this->arguments['start']) === false
|| is_numeric($this->arguments['start']) === false
|| isset($this->arguments['end']) === false
|| is_numeric($this->arguments['end']) === false
) {
throw new RestBadRequestException('Bad parameters');
}
$start = $this->arguments['start'];
$end = $this->arguments['end'];
// Get the numbers of points
$rows = 200;
if (isset($this->arguments['rows'])) {
if (is_numeric($this->arguments['rows']) === false) {
throw new RestBadRequestException('Bad parameters');
}
$rows = $this->arguments['rows'];
}
if ($rows < 10) {
throw new RestBadRequestException('The rows must be greater as 10');
}
if (isset($this->arguments['ids']) === false) {
self::sendResult([]);
}
// Get the list of service ID
$ids = explode(',', $this->arguments['ids']);
$result = [];
foreach ($ids as $id) {
[$hostId, $serviceId] = explode('_', $id);
if (is_numeric($hostId) === false || is_numeric($serviceId) === false) {
throw new RestBadRequestException('Bad parameters');
}
// Check ACL is not admin
if (! $isAdmin) {
$query = 'SELECT service_id '
. 'FROM centreon_acl '
. 'WHERE host_id = :hostId '
. 'AND service_id = :serviceId '
. 'AND group_id IN (' . $aclGroups . ')';
$stmt = $this->pearDBMonitoring->prepare($query);
$stmt->bindParam(':hostId', $hostId, PDO::PARAM_INT);
$stmt->bindParam(':serviceId', $serviceId, PDO::PARAM_INT);
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception('An error occured');
}
if ($stmt->rowCount() == 0) {
throw new RestForbiddenException('Access denied');
}
}
// Prepare graph
try {
// Get index data
$indexData = CentreonGraphService::getIndexId($hostId, $serviceId, $this->pearDBMonitoring);
$graph = new CentreonGraphService($indexData, $userId);
} catch (Exception $e) {
throw new RestNotFoundException('Graph not found');
}
$graph->setRRDOption('start', $start);
$graph->setRRDOption('end', $end);
$graph->initCurveList();
$graph->createLegend();
$serviceData = $graph->getData($rows);
// Replace NaN
$counter = count($serviceData);
for ($i = 0; $i < $counter; $i++) {
if (isset($serviceData[$i]['data'])) {
$times = array_keys($serviceData[$i]['data']);
$values = array_map(
[$this, 'convertNaN'],
array_values($serviceData[$i]['data'])
);
}
$serviceData[$i]['data'] = $values;
$serviceData[$i]['label'] = $serviceData[$i]['legend'];
unset($serviceData[$i]['legend']);
$serviceData[$i]['type'] = $serviceData[$i]['graph_type'];
unset($serviceData[$i]['graph_type']);
}
$result[] = ['service_id' => $id, 'data' => $serviceData, 'times' => $times, 'size' => $rows];
}
return $result;
}
/**
* Function for test is a value is NaN
*
* @param mixed $element The element to test
* @return mixed|null null if NaN else the element
*/
protected function convertNaN($element)
{
if (strtoupper($element) == 'NAN') {
return null;
}
return $element;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/api/class/centreon_configuration_trap.class.php | centreon/www/api/class/centreon_configuration_trap.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 __DIR__ . '/centreon_configuration_objects.class.php';
/**
* Class
*
* @class CentreonConfigurationTrap
*/
class CentreonConfigurationTrap extends CentreonConfigurationObjects
{
/** @var CentreonDB */
protected $pearDBMonitoring;
/**
* CentreonConfigurationTrap constructor
*/
public function __construct()
{
parent::__construct();
$this->pearDBMonitoring = new CentreonDB('centstorage');
}
/**
* @throws PDOException
* @throws RestBadRequestException
* @return array
*/
public function getList()
{
$queryValues = [];
// Check for select2 'q' argument
$queryValues['name'] = isset($this->arguments['q']) ? '%' . (string) $this->arguments['q'] . '%' : '%%';
$queryTraps = 'SELECT SQL_CALC_FOUND_ROWS DISTINCT t.traps_name, t.traps_id, m.name '
. 'FROM traps t, traps_vendor m '
. 'WHERE t.manufacturer_id = m.id '
. 'AND CONCAT(m.name, " - ", t.traps_name) LIKE :name '
. 'ORDER BY m.name, t.traps_name ';
if (isset($this->arguments['page_limit'], $this->arguments['page'])) {
if (
! is_numeric($this->arguments['page'])
|| ! is_numeric($this->arguments['page_limit'])
|| $this->arguments['page_limit'] < 1
) {
throw new RestBadRequestException('Error, limit must be an integer greater than zero');
}
$offset = ($this->arguments['page'] - 1) * $this->arguments['page_limit'];
$queryTraps .= 'LIMIT :offset,:limit';
$queryValues['offset'] = (int) $offset;
$queryValues['limit'] = (int) $this->arguments['page_limit'];
}
$stmt = $this->pearDB->prepare($queryTraps);
$stmt->bindParam(':name', $queryValues['name'], PDO::PARAM_STR);
if (isset($queryValues['offset'])) {
$stmt->bindParam(':offset', $queryValues['offset'], PDO::PARAM_INT);
$stmt->bindParam(':limit', $queryValues['limit'], PDO::PARAM_INT);
}
$stmt->execute();
$trapList = [];
while ($data = $stmt->fetch()) {
$trapCompleteName = $data['name'] . ' - ' . $data['traps_name'];
$trapCompleteId = $data['traps_id'];
$trapList[] = ['id' => htmlentities($trapCompleteId), 'text' => $trapCompleteName];
}
return ['items' => $trapList, 'total' => (int) $this->pearDB->numberRows()];
}
/**
* @throws PDOException
* @throws RestBadRequestException
* @return array
*/
public function getDefaultValues()
{
$finalDatas = parent::getDefaultValues();
foreach ($finalDatas as &$trap) {
$queryTraps = 'SELECT m.name '
. 'FROM traps t, traps_vendor m '
. 'WHERE t.manufacturer_id = m.id '
. 'AND traps_id = :id';
$stmt = $this->pearDB->prepare($queryTraps);
$stmt->bindParam(':id', $trap['id'], PDO::PARAM_INT);
$stmt->execute();
$vendor = $stmt->fetch();
$trap['text'] = $vendor['name'] . ' - ' . $trap['text'];
}
return $finalDatas;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/api/class/centreon_configuration_command.class.php | centreon/www/api/class/centreon_configuration_command.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 __DIR__ . '/centreon_configuration_objects.class.php';
/**
* Class
*
* @class CentreonConfigurationCommand
*/
class CentreonConfigurationCommand extends CentreonConfigurationObjects
{
/**
* CentreonConfigurationCommand constructor
*/
public function __construct()
{
parent::__construct();
}
/**
* @throws Exception
* @throws RestBadRequestException
* @return array
*/
public function getList()
{
$queryValues = [];
// Check for select2 'q' argument
if (isset($this->arguments['q']) === false) {
$queryValues['commandName'] = '%%';
} else {
$queryValues['commandName'] = '%' . (string) $this->arguments['q'] . '%';
}
if (isset($this->arguments['t'])) {
if (! is_numeric($this->arguments['t'])) {
throw new RestBadRequestException('Error, command type must be numerical');
}
$queryCommandType = 'AND command_type = :commandType ';
$queryValues['commandType'] = (int) $this->arguments['t'];
} else {
$queryCommandType = '';
}
$queryCommand = 'SELECT SQL_CALC_FOUND_ROWS command_id, command_name '
. 'FROM command '
. 'WHERE command_name LIKE :commandName AND command_activate = "1" '
. $queryCommandType
. 'ORDER BY command_name ';
if (isset($this->arguments['page_limit'], $this->arguments['page'])) {
if (
! is_numeric($this->arguments['page'])
|| ! is_numeric($this->arguments['page_limit'])
|| $this->arguments['page_limit'] < 1
) {
throw new RestBadRequestException('Error, limit must be an integer greater than zero');
}
$offset = ($this->arguments['page'] - 1) * $this->arguments['page_limit'];
$queryCommand .= 'LIMIT :offset, :limit';
$queryValues['offset'] = (int) $offset;
$queryValues['limit'] = (int) $this->arguments['page_limit'];
}
$stmt = $this->pearDB->prepare($queryCommand);
$stmt->bindParam(':commandName', $queryValues['commandName'], PDO::PARAM_STR);
if (isset($queryValues['commandType'])) {
$stmt->bindParam(':commandType', $queryValues['commandType'], PDO::PARAM_INT);
}
if (isset($queryValues['offset'])) {
$stmt->bindParam(':offset', $queryValues['offset'], PDO::PARAM_INT);
$stmt->bindParam(':limit', $queryValues['limit'], PDO::PARAM_INT);
}
$stmt->execute();
$commandList = [];
while ($data = $stmt->fetch()) {
$commandList[] = ['id' => $data['command_id'], 'text' => $data['command_name']];
}
return ['items' => $commandList, 'total' => (int) $this->pearDB->numberRows()];
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/widgets/require.php | centreon/www/widgets/require.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__ . '/../../vendor/autoload.php');
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/widgets/widget-error-handling.php | centreon/www/widgets/widget-error-handling.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
*
*/
/**
* @param string $message
* @param string $theme
*/
function showError(string $message, string $theme)
{
$escapedMessage = htmlspecialchars($message, ENT_QUOTES, 'UTF-8');
$escapedTheme = htmlspecialchars($theme, ENT_QUOTES, 'UTF-8');
echo <<<HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Error</title>
<link href="../../Themes/Generic-theme/style.css" rel="stylesheet" type="text/css"/>
<link href="../../Themes/Generic-theme/color.css" rel="stylesheet" type="text/css"/>
<link href="../../Themes/{$escapedTheme}/variables.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div class="update" style="text-align: center; width: 350px; margin: 0 auto;">
{$escapedMessage}
</div>
</body>
</html>
HTML;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/widgets/httploader/index.php | centreon/www/widgets/httploader/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 . '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 . 'bootstrap.php';
session_start();
if (! isset($_SESSION['centreon']) || ! isset($_REQUEST['widgetId'])) {
exit;
}
$centreon = $_SESSION['centreon'];
$widgetId = filter_var($_REQUEST['widgetId'], FILTER_VALIDATE_INT);
$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;
try {
if ($widgetId === false) {
throw new InvalidArgumentException('Widget ID must be an integer');
}
$db = $dependencyInjector['configuration_db'];
$widgetObj = new CentreonWidget($centreon, $db);
$preferences = $widgetObj->getWidgetPreferences($widgetId);
$autoRefresh = filter_var($preferences['refresh_interval'], FILTER_VALIDATE_INT);
$frameheight = filter_var($preferences['frameheight'], FILTER_VALIDATE_INT);
$website = filter_var($preferences['website'], FILTER_VALIDATE_URL);
if ($autoRefresh === false || $autoRefresh < 5) {
$autoRefresh = 30;
}
if ($frameheight === false) {
$frameheight = 900;
}
if ($website === false) {
throw new Exception(_('The URL provided for the website does not use a valid URL pattern.'));
}
} catch (Exception $exception) {
CentreonLog::create()->error(
logTypeId: CentreonLog::TYPE_BUSINESS_LOG,
message: 'Error while using httploader widget: ' . $exception->getMessage(),
customContext: [
'widget_id' => $widgetId,
],
exception: $exception
);
showError($exception->getMessage(), $theme ?? 'Generic-theme/Variables-css');
exit;
}
?>
<html>
<style type="text/css">
body{ margin:0; padding:0;}
div#actionBar { position:absolute; top:0; left:0; width:100%; height:25px; background-color: #FFFFFF; }
@media screen { body>div#actionBar { position: fixed; } }
* html body { overflow:hidden; }
* html div#hgMonitoringTable { height:100%; overflow:auto; }
</style>
<head>
<title>Graph Monitoring</title>
<link href="../../Themes/Generic-theme/style.css" rel="stylesheet" type="text/css"/>
<link href="../../Themes/Generic-theme/jquery-ui/jquery-ui.css" rel="stylesheet" type="text/css"/>
<link href="../../Themes/Generic-theme/jquery-ui/jquery-ui-centreon.css" rel="stylesheet" type="text/css"/>
<link href="./Themes/<?php echo $variablesThemeCSS === 'Generic-theme' ? $variablesThemeCSS . '/Variables-css/'
: $variablesThemeCSS . '/'; ?>variables.css" rel="stylesheet" type="text/css"
/>
<script type="text/javascript" src="../../include/common/javascript/jquery/jquery.min.js"></script>
<script type="text/javascript" src="../../include/common/javascript/jquery/jquery-ui.js"></script>
<script type="text/javascript" src="../../include/common/javascript/widgetUtils.js"></script>
</head>
<body>
<iframe id="webContainer" width="100%" height="900px"></iframe>
</body>
<script type="text/javascript">
var widgetId = <?php echo $widgetId; ?>;
var website = '<?php echo $preferences['website']; ?>';
var frameheight = <?php echo $frameheight; ?>;
var autoRefresh = <?php echo $autoRefresh; ?>;
var timeout;
function loadPage() {
jQuery("#webContainer").attr('src', website);
parent.iResize(window.name, frameheight);
if (autoRefresh) {
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(loadPage, (autoRefresh * 1000));
}
}
jQuery(function() {
loadPage();
});
</script>
</html>
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/widgets/tactical-overview/index.php | centreon/www/widgets/tactical-overview/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 . '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';
const OBJECT_TYPE_HOST = 'hosts';
const OBJECT_TYPE_SERVICE = 'services';
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 {
$configurationDatabase = $dependencyInjector['configuration_db'];
$widgetObj = new CentreonWidget($centreon, $configurationDatabase);
$preferences = $widgetObj->getWidgetPreferences($widgetId);
$objectType = ! empty($preferences['object_type']) ? $preferences['object_type'] : OBJECT_TYPE_HOST;
if (! in_array($objectType, [OBJECT_TYPE_HOST, OBJECT_TYPE_SERVICE])) {
throw new InvalidArgumentException('Invalid object type provided in tactical-overview. Accepted: hosts or services');
}
$autoRefresh = (isset($preferences['refresh_interval']) && (int) $preferences['refresh_interval'] > 0)
? (int) $preferences['refresh_interval']
: 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 tactical-overview 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/tactical-overview/src/';
$template = SmartyBC::createSmartyTemplate($path, './');
$template->assign(
'theme',
$variablesThemeCSS === 'Generic-theme'
? $variablesThemeCSS . '/Variables-css'
: $variablesThemeCSS
);
$kernel = App\Kernel::createForWeb();
$resourceController = $kernel->getContainer()->get(
Centreon\Application\Controller\MonitoringResourceController::class
);
$buildParameter = function (string $id, string $name) {
return [
'id' => $id,
'name' => $name,
];
};
$objectType === OBJECT_TYPE_HOST ? require_once 'src/hosts_status.php' : require_once 'src/services_status.php';
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/widgets/tactical-overview/src/hosts_status.php | centreon/www/widgets/tactical-overview/src/hosts_status.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;
$hostsDownStatus = [];
$hostsUnknownStatus = [];
$hostsUpStatus = [];
$hostsPendingStatus = [];
$dataList = [];
$realtimeConnection = new CentreonDB('centstorage');
/**
* true: URIs will correspond to deprecated pages
* false: URIs will correspond to new page (Resource Status)
*/
$useDeprecatedPages = $centreon->user->doesShowDeprecatedPages();
$autoRefresh = (isset($preferences['refresh_interval']) && (int) $preferences['refresh_interval'] > 0)
? (int) $preferences['refresh_interval']
: 30;
$buildHostUri = function (array $states, array $statuses) use ($resourceController, $buildParameter) {
return $resourceController->buildListingUri(
[
'filter' => json_encode(
[
'criterias' => [
'resourceTypes' => [$buildParameter('host', 'Host')],
'states' => $states,
'statuses' => $statuses,
],
]
),
]
);
};
$pendingStatus = $buildParameter('PENDING', 'Pending');
$upStatus = $buildParameter('UP', 'Up');
$downStatus = $buildParameter('DOWN', 'Down');
$unreachableStatus = $buildParameter('UNREACHABLE', 'Unreachable');
$unhandledState = $buildParameter('unhandled_problems', 'Unhandled');
$acknowledgedState = $buildParameter('acknowledged', 'Acknowledged');
$inDowntimeState = $buildParameter('in_downtime', 'In downtime');
$deprecatedHostListingUri = '../../main.php?p=20202&search=&o=h_';
$queryParameters = [];
$aclSubQuery = '';
if (! $centreon->user->admin) {
$acls = new CentreonAclLazy($centreon->user->user_id);
// Make request return nothing
if ($acls->getAccessGroups()->isEmpty()) {
$aclSubQuery = ' WHERE 1 = 0';
} else {
['parameters' => $queryParameters, 'placeholderList' => $bindQuery] = createMultipleBindParameters(
$acls->getAccessGroups()->getIds(),
'access_group',
QueryParameterTypeEnum::INTEGER
);
$aclSubQuery = <<<SQL
INNER JOIN centreon_acl acl
ON acl.host_id = h.host_id
AND acl.service_id IS NULL
WHERE acl.group_id IN ({$bindQuery})
SQL;
}
}
$downStatusQuery = <<<SQL
SELECT 1 AS REALTIME,
SUM(
CASE WHEN h.state = 1
AND h.enabled = 1
AND h.name NOT LIKE '%Module%'
THEN 1 ELSE 0 END
) as status,
SUM(
CASE WHEN h.acknowledged = 1
AND h.state = 1
AND h.enabled = 1
AND h.name NOT LIKE '%Module%'
THEN 1 ELSE 0 END
) as ack,
SUM(
CASE WHEN h.scheduled_downtime_depth = 1
AND h.state = 1
AND h.enabled = 1
AND h.name NOT LIKE '%Module%'
THEN 1 ELSE 0 END
) as down
FROM hosts AS h
{$aclSubQuery}
SQL;
foreach ($realtimeConnection->iterateAssociative($downStatusQuery, QueryParameters::create($queryParameters)) as $record) {
$record['un'] = $record['status'] - ($record['ack'] + $record['down']);
$deprecatedDownHostListingUri = $deprecatedHostListingUri . 'down';
$record['listing_uri'] = $useDeprecatedPages
? $deprecatedDownHostListingUri
: $buildHostUri([], [$downStatus]);
$record['listing_ack_uri'] = $useDeprecatedPages
? $deprecatedDownHostListingUri
: $buildHostUri([$acknowledgedState], [$downStatus]);
$record['listing_downtime_uri'] = $useDeprecatedPages
? $deprecatedDownHostListingUri
: $buildHostUri([$inDowntimeState], [$downStatus]);
$record['listing_unhandled_uri'] = $useDeprecatedPages
? $deprecatedDownHostListingUri
: $buildHostUri([$unhandledState], [$downStatus]);
$hostsDownStatus[] = $record;
}
$query = <<<SQL
SELECT 1 AS REALTIME,
SUM(
CASE WHEN h.state = 2
AND h.enabled = 1
AND h.name NOT LIKE '%Module%'
THEN 1 ELSE 0 END
) as status,
SUM(
CASE WHEN h.acknowledged = 1
AND h.state = 2
AND h.enabled = 1
AND h.name NOT LIKE '%Module%'
THEN 1 ELSE 0 END
) as ack,
SUM(
CASE WHEN h.state = 2
AND h.enabled = 1
AND h.name NOT LIKE '%Module%'
AND h.scheduled_downtime_depth = 1
THEN 1 ELSE 0 END
) as down
FROM hosts AS h
{$aclSubQuery}
SQL;
foreach ($realtimeConnection->iterateAssociative($query, QueryParameters::create($queryParameters)) as $record) {
$record['un'] = $record['status'] - ($record['ack'] + $record['down']);
$deprecatedUnreachableHostListingUri = $deprecatedHostListingUri . 'unreachable';
$record['listing_uri'] = $useDeprecatedPages
? $deprecatedUnreachableHostListingUri
: $buildHostUri([], [$unreachableStatus]);
$record['listing_ack_uri'] = $useDeprecatedPages
? $deprecatedUnreachableHostListingUri
: $buildHostUri([$acknowledgedState], [$unreachableStatus]);
$record['listing_downtime_uri'] = $useDeprecatedPages
? $deprecatedUnreachableHostListingUri
: $buildHostUri([$inDowntimeState], [$unreachableStatus]);
$record['listing_unhandled_uri'] = $useDeprecatedPages
? $deprecatedUnreachableHostListingUri
: $buildHostUri([$unhandledState], [$unreachableStatus]);
$hostsUnknownStatus[] = $record;
}
$query = <<<SQL
SELECT 1 AS REALTIME,
SUM(
CASE WHEN h.state = 0
AND h.enabled = 1
AND h.name NOT LIKE '%Module%'
THEN 1 ELSE 0 END
) as status
FROM hosts AS h
{$aclSubQuery}
SQL;
foreach ($realtimeConnection->iterateAssociative($query, QueryParameters::create($queryParameters)) as $record) {
$record['listing_uri'] = $useDeprecatedPages
? $deprecatedHostListingUri . 'up'
: $buildHostUri([], [$upStatus]);
$hostsUpStatus[] = $record;
}
$query = <<<SQL
SELECT 1 AS REALTIME,
SUM(
CASE WHEN h.state = 4
AND h.enabled = 1
AND h.name NOT LIKE '%Module%'
THEN 1 ELSE 0 END
) as status
FROM hosts AS h
{$aclSubQuery}
SQL;
foreach ($realtimeConnection->iterateAssociative($query, QueryParameters::create($queryParameters)) as $record) {
$record['listing_uri'] = $useDeprecatedPages
? $deprecatedHostListingUri . 'pending'
: $buildHostUri([], [$pendingStatus]);
$hostsPendingStatus[] = $record;
}
$template->assign('preferences', $preferences);
$template->assign('widgetId', $widgetId);
$template->assign('autoRefresh', $autoRefresh);
$template->assign('dataPEND', $hostsPendingStatus);
$template->assign('dataUP', $hostsUpStatus);
$template->assign('dataUN', $hostsUnknownStatus);
$template->assign('dataDO', $hostsDownStatus);
$template->display('hosts_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/tactical-overview/src/services_status.php | centreon/www/widgets/tactical-overview/src/services_status.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;
require_once $centreon_path . 'www/include/common/sqlCommonFunction.php';
$serviceCriticalStatus = [];
$serviceWarningStatus = [];
$serviceOkStatus = [];
$serviceUnknownStatus = [];
$servicePendingStatus = [];
$db = new CentreonDB('centstorage');
/**
* true: URIs will correspond to deprecated pages
* false: URIs will correspond to new page (Resource Status)
*/
$useDeprecatedPages = $centreon->user->doesShowDeprecatedPages();
$autoRefresh = (isset($preferences['refresh_interval']) && (int) $preferences['refresh_interval'] > 0)
? (int) $preferences['refresh_interval']
: 30;
$buildServiceUri = function (array $states, array $statuses) use ($resourceController, $buildParameter) {
return $resourceController->buildListingUri(
[
'filter' => json_encode(
[
'criterias' => [
'resourceTypes' => [$buildParameter('service', 'Service')],
'states' => $states,
'statuses' => $statuses,
],
]
),
]
);
};
$pendingStatus = $buildParameter('PENDING', 'Pending');
$okStatus = $buildParameter('OK', 'Ok');
$warningStatus = $buildParameter('WARNING', 'Warning');
$criticalStatus = $buildParameter('CRITICAL', 'Critical');
$unknownStatus = $buildParameter('UNKNOWN', 'Unknown');
$unhandledState = $buildParameter('unhandled_problems', 'Unhandled');
$acknowledgedState = $buildParameter('acknowledged', 'Acknowledged');
$inDowntimeState = $buildParameter('in_downtime', 'In downtime');
$deprecatedServiceListingUri = '../../main.php?p=20201&search=';
$queryParameters = [];
$aclSubQuery = '';
if (! $centreon->user->admin) {
$acls = new CentreonAclLazy($centreon->user->user_id);
['parameters' => $queryParameters, 'placeholderList' => $bindQuery] = createMultipleBindParameters(
$acls->getAccessGroups()->getIds(),
'access_group',
QueryParameterTypeEnum::INTEGER
);
$aclSubQuery = <<<SQL
INNER JOIN centreon_acl acl
ON acl.host_id = h.host_id
AND acl.service_id = s.service_id
WHERE acl.group_id IN ({$bindQuery})
SQL;
}
$query = <<<SQL
SELECT 1 AS REALTIME,
SUM(
CASE WHEN s.state = 2
AND s.enabled = 1
AND h.enabled = 1
AND h.name NOT LIKE '%Module%'
THEN 1 ELSE 0 END
) AS status,
SUM(
CASE WHEN s.acknowledged = 1
AND s.state = 2
AND s.enabled = 1
AND h.enabled = 1
AND h.name NOT LIKE '%Module%'
THEN 1 ELSE 0 END
) AS ack,
SUM(
CASE WHEN s.scheduled_downtime_depth = 1
AND s.state = 2
AND s.enabled = 1
AND h.enabled = 1
AND h.name NOT LIKE '%Module%'
THEN 1 ELSE 0 END
) AS down,
SUM(
CASE WHEN s.state = 2
AND (h.state = 1 OR h.state = 4 OR h.state = 2)
AND s.enabled = 1
AND h.enabled = 1
AND h.name NOT LIKE '%Module%'
THEN 1 ELSE 0 END
) AS pb,
SUM(
CASE WHEN s.state = 2
AND s.enabled = 1
AND h.enabled = 1
AND h.name NOT LIKE '%Module%'
AND s.acknowledged = 0
AND s.scheduled_downtime_depth = 0
AND h.state = 0
THEN 1 ELSE 0 END
) AS un
FROM services AS s
LEFT JOIN hosts AS h
ON h.host_id = s.host_id
{$aclSubQuery}
SQL;
foreach ($db->iterateAssociative($query, QueryParameters::create($queryParameters)) as $record) {
$record['listing_uri'] = $useDeprecatedPages
? $deprecatedServiceListingUri . '&statusFilter=critical&o=svc'
: $buildServiceUri([], [$criticalStatus]);
$record['listing_ack_uri'] = $useDeprecatedPages
? $deprecatedServiceListingUri . '&statusFilter=critical&statusService=svcpb'
: $buildServiceUri([$acknowledgedState], [$criticalStatus]);
$record['listing_downtime_uri'] = $useDeprecatedPages
? $deprecatedServiceListingUri . '&statusFilter=critical&statusService=svcpb'
: $buildServiceUri([$inDowntimeState], [$criticalStatus]);
$record['listing_unhandled_uri'] = $useDeprecatedPages
? $deprecatedServiceListingUri . '&statusFilter=critical&statusService=svc_unhandled'
: $buildServiceUri([$unhandledState], [$criticalStatus]);
$serviceCriticalStatus[] = $record;
}
$query = <<<SQL
SELECT 1 AS REALTIME,
SUM(
CASE WHEN s.state = 1
AND s.enabled = 1
AND h.enabled = 1
AND h.name NOT LIKE '%Module%'
THEN 1 ELSE 0 END
) AS status,
SUM(
CASE WHEN s.acknowledged = 1
AND s.state = 1
AND s.enabled = 1
AND h.enabled = 1
AND h.name NOT LIKE '%Module%'
THEN 1 ELSE 0 END
) AS ack,
SUM(
CASE WHEN s.scheduled_downtime_depth > 0
AND s.state = 1
AND s.enabled = 1
AND h.enabled = 1
AND h.name NOT LIKE '%Module%'
THEN 1 ELSE 0 END
) AS down,
SUM(
CASE WHEN s.state = 1
AND (h.state = 1 OR h.state = 4 OR h.state = 2)
AND s.enabled = 1
AND h.enabled = 1
AND h.name NOT LIKE '%Module%'
THEN 1 ELSE 0 END
) AS pb,
SUM(
CASE WHEN s.state = 1
AND s.enabled = 1
AND h.enabled = 1
AND h.name NOT LIKE '%Module%'
AND s.acknowledged = 0
AND s.scheduled_downtime_depth = 0
AND h.state = 0
THEN 1 ELSE 0 END
) AS un
FROM services AS s
LEFT JOIN hosts AS h
ON h.host_id = s.host_id
{$aclSubQuery}
SQL;
foreach ($db->iterateAssociative($query, QueryParameters::create($queryParameters)) as $record) {
$record['listing_uri'] = $useDeprecatedPages
? $deprecatedServiceListingUri . '&statusFilter=warning&o=svc'
: $buildServiceUri([], [$warningStatus]);
$record['listing_ack_uri'] = $useDeprecatedPages
? $deprecatedServiceListingUri . '&statusFilter=warning&statusService=svcpb'
: $buildServiceUri([$acknowledgedState], [$warningStatus]);
$record['listing_downtime_uri'] = $useDeprecatedPages
? $deprecatedServiceListingUri . '&statusFilter=warning&statusService=svcpb'
: $buildServiceUri([$inDowntimeState], [$warningStatus]);
$record['listing_unhandled_uri'] = $useDeprecatedPages
? $deprecatedServiceListingUri . '&statusFilter=critical&statusService=svc_unhandled'
: $buildServiceUri([$unhandledState], [$warningStatus]);
$serviceWarningStatus[] = $record;
}
$query = <<<SQL
SELECT 1 AS REALTIME,
SUM(
CASE WHEN s.state = 0
AND s.enabled = 1
AND h.enabled = 1
AND h.name NOT LIKE '%Module%'
THEN 1 ELSE 0 END
) AS status
FROM services AS s
LEFT JOIN hosts AS h
ON h.host_id = s.host_id
{$aclSubQuery}
SQL;
foreach ($db->iterateAssociative($query, QueryParameters::create($queryParameters)) as $record) {
$record['listing_uri'] = $useDeprecatedPages
? $deprecatedServiceListingUri . '&statusFilter=ok&o=svc'
: $buildServiceUri([], [$okStatus]);
$serviceOkStatus[] = $record;
}
$query = <<<SQL
SELECT 1 AS REALTIME,
SUM(
CASE WHEN s.state = 4
AND s.enabled = 1
AND h.enabled = 1
AND h.name NOT LIKE '%Module%'
THEN 1 ELSE 0 END
) AS status
FROM services AS s
LEFT JOIN hosts AS h
ON h.host_id = s.host_id
{$aclSubQuery}
SQL;
foreach ($db->iterateAssociative($query, QueryParameters::create($queryParameters)) as $record) {
$record['listing_uri'] = $useDeprecatedPages
? $deprecatedServiceListingUri . '&statusFilter=pending&o=svc'
: $buildServiceUri([], [$pendingStatus]);
$servicePendingStatus[] = $record;
}
$query = <<<SQL
SELECT 1 AS REALTIME,
SUM(
CASE WHEN s.state = 3
AND s.enabled = 1
AND h.enabled = 1
AND h.name NOT LIKE '%Module%'
THEN 1 ELSE 0 END
) AS status,
SUM(
CASE WHEN s.acknowledged = 1
AND s.state = 3
AND s.enabled = 1
AND h.enabled = 1
AND h.name NOT LIKE '%Module%'
THEN 1 ELSE 0 END
) AS ack,
SUM(
CASE WHEN s.scheduled_downtime_depth > 0
AND s.state = 3
AND s.enabled = 1
AND h.enabled = 1
AND h.name NOT LIKE '%Module%'
THEN 1 ELSE 0 END
) AS down,
SUM(
CASE WHEN s.state = 3
AND (h.state = 1 OR h.state = 4 OR h.state = 2)
AND s.enabled = 1
AND h.enabled = 1
AND h.name NOT LIKE '%Module%'
THEN 1 ELSE 0 END
) AS pb,
SUM(
CASE WHEN s.state = 3
AND s.enabled = 1
AND h.enabled = 1
AND h.name NOT LIKE '%Module%'
AND s.acknowledged = 0
AND s.scheduled_downtime_depth = 0
AND h.state = 0
THEN 1 ELSE 0 END
) AS un
FROM services AS s
LEFT JOIN hosts AS h
ON h.host_id = s.host_id
{$aclSubQuery}
SQL;
foreach ($db->iterateAssociative($query, QueryParameters::create($queryParameters)) as $record) {
$record['listing_uri'] = $useDeprecatedPages
? $deprecatedServiceListingUri . '&statusFilter=unknown&o=svc'
: $buildServiceUri([], [$unknownStatus]);
$record['listing_ack_uri'] = $useDeprecatedPages
? $deprecatedServiceListingUri . '&statusFilter=unknown&statusService=svcpb'
: $buildServiceUri([$acknowledgedState], [$unknownStatus]);
$record['listing_downtime_uri'] = $useDeprecatedPages
? $deprecatedServiceListingUri . '&statusFilter=unknown&statusService=svcpb'
: $buildServiceUri([$inDowntimeState], [$unknownStatus]);
$record['listing_unhandled_uri'] = $useDeprecatedPages
? $deprecatedServiceListingUri . '&statusFilter=unknown&statusService=svc_unhandled'
: $buildServiceUri([$unhandledState], [$unknownStatus]);
$serviceUnknownStatus[] = $record;
}
$template->assign('widgetId', $widgetId);
$template->assign('autoRefresh', $autoRefresh);
$template->assign('dataPEND', $servicePendingStatus);
$template->assign('dataOK', $serviceOkStatus);
$template->assign('dataWA', $serviceWarningStatus);
$template->assign('dataCRI', $serviceCriticalStatus);
$template->assign('dataUNK', $serviceUnknownStatus);
$template->display('services_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/global-health/index.php | centreon/www/widgets/global-health/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 $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');
}
$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;
}
$broker = 'broker';
$res = $db->query("SELECT `value` FROM `options` WHERE `key` = 'broker'");
if ($res->rowCount()) {
$row = $res->fetchRow();
$broker = strtolower($row['value']);
} else {
throw new Exception('Unknown broker module');
}
$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;
}
?>
<HTML>
<HEAD>
<TITLE></TITLE>
<link href="../../Themes/Generic-theme/style.css" rel="stylesheet" type="text/css"/>
<link href="../../Themes/Generic-theme/jquery-ui/jquery-ui.css" rel="stylesheet" type="text/css"/>
<link href="../../Themes/Generic-theme/jquery-ui/jquery-ui-centreon.css" rel="stylesheet" type="text/css"/>
<link
href="../../Themes/<?php
echo $variablesThemeCSS === 'Generic-theme' ? $variablesThemeCSS . '/Variables-css/'
: $variablesThemeCSS . '/'; ?>variables.css"
rel="stylesheet"
type="text/css"
/>
<script type="text/javascript" src="../../include/common/javascript/jquery/jquery.min.js"></script>
<script type="text/javascript" src="../../include/common/javascript/jquery/jquery-ui.js"></script>
<script type="text/javascript"
src="../../include/common/javascript/jquery/plugins/pagination/jquery.pagination.js"></script>
<script type="text/javascript" src="../../include/common/javascript/widgetUtils.js"></script>
<script type="text/javascript"
src="../../include/common/javascript/jquery/plugins/treeTable/jquery.treeTable.min.js"></script>
<script src="./lib/apexcharts.min.js" language="javascript"></script>
</HEAD>
<BODY>
<DIV id='global_health'></DIV>
</BODY>
<script type="text/javascript">
let widgetId = <?= $widgetId; ?>;
let autoRefresh = <?= $autoRefresh; ?>;
let timeout;
let pageNumber = 0;
let broker = '<?= $broker; ?>';
jQuery(function () {
loadPage();
});
function loadPage() {
let indexPage = "global_health";
jQuery.ajax("./src/" + indexPage + ".php?widgetId=" + widgetId, {
success: function (htmlData) {
jQuery("#global_health").html("");
jQuery("#global_health").html(htmlData);
let h = jQuery("#global_health").prop("scrollHeight") + 36;
parent.iResize(window.name, h);
jQuery("#global_health").find("img, style, script, link").on('load', function () {
let h = jQuery("#global_health").prop("scrollHeight") + 36;
parent.iResize(window.name, h);
});
}
});
if (autoRefresh) {
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(loadPage, (autoRefresh * 1000));
}
}
</script>
</HTML>
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/widgets/global-health/src/global_health.php | centreon/www/widgets/global-health/src/global_health.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';
require_once $centreon_path . 'www/class/centreonHost.class.php';
require_once $centreon_path . 'www/class/centreonLang.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'])) {
exit;
}
$db = $dependencyInjector['configuration_db'];
if (CentreonSession::checkSession(session_id(), $db) == 0) {
exit;
}
$dbb = $dependencyInjector['realtime_db'];
// Init Objects
$criticality = new CentreonCriticality($db);
$media = new CentreonMedia($db);
// Smarty template initialization
$path = $centreon_path . 'www/widgets/global-health/src/';
$template = SmartyBC::createSmartyTemplate($path, './');
$template->assign('session', session_id());
$template->assign('host_label', _('Hosts'));
$template->assign('svc_label', _('Services'));
$centreon = $_SESSION['centreon'];
$widgetId = filter_var($_REQUEST['widgetId'], FILTER_VALIDATE_INT);
if ($widgetId === false) {
throw new InvalidArgumentException('Widget ID must be an integer');
}
$widgetObj = new CentreonWidget($centreon, $db);
$preferences = $widgetObj->getWidgetPreferences($widgetId);
$template->assign('preferences', $preferences);
$oreon = $_SESSION['centreon'];
/**
* Initiate Language class
*/
$centreonLang = new CentreonLang($centreon_path, $oreon);
$centreonLang->bindLang();
/**
* Tab status
*/
$tabStatusHost = [0 => 'UP', 1 => 'DOWN', 2 => 'UNREACHABLE', 4 => 'PENDING'];
$tabStatusService = [0 => 'OK', 1 => 'WARNING', 2 => 'CRITICAL', 3 => 'UNKNOWN', 4 => 'PENDING'];
$serviceArray = [];
$hostArray = [];
foreach ($tabStatusService as $key => $statusService) {
$serviceArray[$tabStatusService[$key]]['value'] = 0;
$serviceArray[$tabStatusService[$key]]['acknowledged'] = 0;
$serviceArray[$tabStatusService[$key]]['downtime'] = 0;
$serviceArray[$tabStatusService[$key]]['percent'] = 0;
}
foreach ($tabStatusHost as $key => $statusHost) {
$hostArray[$tabStatusHost[$key]]['value'] = 0;
$hostArray[$tabStatusHost[$key]]['acknowledged'] = 0;
$hostArray[$tabStatusHost[$key]]['downtime'] = 0;
$hostArray[$tabStatusHost[$key]]['percent'] = 0;
}
$hgName = false;
// get hostgroup name if defined in preferences
if (! empty($preferences['hostgroup'])) {
$sql = 'select hg.hg_name from hostgroup hg where hg.hg_id = :hostgroup_id';
$stmt = $db->prepare($sql);
$stmt->bindValue(':hostgroup_id', $preferences['hostgroup'], PDO::PARAM_INT);
$stmt->execute();
if ($row = $stmt->fetch()) {
$hgName = $row['hg_name'];
}
}
if (isset($preferences['hosts_services']) && $preferences['hosts_services'] == 'hosts') {
$innerJoinGroup = '';
if ($hgName) {
$innerJoinGroup = ' INNER JOIN hosts_hostgroups hhg ON h.host_id = hhg.host_id '
. ' INNER JOIN hostgroups hg ON hhg.hostgroup_id = hg.hostgroup_id and hg.name = \'' . $hgName . '\' ';
}
$rq1 = ' SELECT 1 AS REALTIME, count(DISTINCT h.name) cnt, h.state, SUM(h.acknowledged) as acknowledged, '
. 'SUM(CASE WHEN h.scheduled_downtime_depth >= 1 THEN 1 ELSE 0 END) AS downtime '
. 'FROM `hosts` h '
. $innerJoinGroup
. 'WHERE h.enabled = 1 '
. $oreon->user->access->queryBuilder('AND', 'h.name', $oreon->user->access->getHostsString('NAME', $dbb))
. ' AND h.name NOT LIKE \'_Module_%\' '
. ' GROUP BY h.state '
. ' ORDER BY h.state';
$dbResult = $dbb->query($rq1);
$data = [];
$color = [];
$legend = [];
$counter = 0;
while ($ndo = $dbResult->fetchRow()) {
$data[$ndo['state']]['count'] = $ndo['cnt'];
$data[$ndo['state']]['acknowledged'] = $ndo['acknowledged'];
$data[$ndo['state']]['downtime'] = $ndo['downtime'];
$counter += $ndo['cnt'];
}
$dbResult->closeCursor();
foreach ($data as $key => $value) {
$hostArray[$tabStatusHost[$key]]['value'] = $value['count'];
$valuePercent = round($value['count'] / $counter * 100, 2);
$valuePercent = str_replace(',', '.', $valuePercent);
$hostArray[$tabStatusHost[$key]]['percent'] = $valuePercent;
$hostArray[$tabStatusHost[$key]]['acknowledged'] = $value['acknowledged'];
$hostArray[$tabStatusHost[$key]]['downtime'] = $value['downtime'];
}
$template->assign('hosts', $hostArray);
$template->display('global_health_host.ihtml');
} elseif (isset($preferences['hosts_services']) && $preferences['hosts_services'] == 'services') {
$sgName = false;
if (! empty($preferences['servicegroup'])) {
$sql = 'select sg.sg_name from servicegroup sg where sg.sg_id = ' . $dbb->escape($preferences['servicegroup']);
$dbResult = $db->query($sql);
$row = $dbResult->fetchRow();
$sgName = $row['sg_name'];
}
$innerJoinGroup = '';
if ($sgName) {
$innerJoinGroup = ' INNER JOIN services_servicegroups ssg ON ssg.service_id = s.service_id '
. 'and ssg.host_id = s.host_id INNER JOIN servicegroups sg ON ssg.servicegroup_id = sg.servicegroup_id '
. 'and sg.name = \'' . $sgName . '\' ';
}
if ($hgName) {
$innerJoinGroup .= ' INNER JOIN hosts_hostgroups hhg ON h.host_id = hhg.host_id '
. ' INNER JOIN hostgroups hg ON hhg.hostgroup_id = hg.hostgroup_id and hg.name = \'' . $hgName . '\' ';
}
global $is_admin;
$is_admin = $oreon->user->admin;
$grouplistStr = $oreon->user->access->getAccessGroupsString();
/**
* Get DB informations for creating Flash
*/
if (! $is_admin) {
$rq2 = ' SELECT 1 AS REALTIME, count(DISTINCT s.state, s.host_id, s.service_id) count, s.state state, '
. ' SUM(s.acknowledged) as acknowledged, '
. ' SUM(CASE WHEN s.scheduled_downtime_depth >= 1 THEN 1 ELSE 0 END) AS downtime '
. ' FROM services s '
. ' INNER JOIN centreon_acl acl ON s.host_id = acl.host_id AND s.service_id = acl.service_id '
. ' INNER JOIN hosts h ON s.host_id = h.host_id '
. $innerJoinGroup
. ' WHERE h.name NOT LIKE \'_Module_%\' '
. ' AND h.enabled = 1 '
. ' AND s.enabled = 1 '
. ' AND acl.group_id IN (' . $grouplistStr . ') '
. ' GROUP BY s.state ORDER by s.state';
} else {
$rq2 = ' SELECT 1 AS REALTIME, count(DISTINCT s.state, s.host_id, s.service_id) count, s.state state, '
. ' SUM(s.acknowledged) as acknowledged, '
. ' SUM(CASE WHEN s.scheduled_downtime_depth >= 1 THEN 1 ELSE 0 END) AS downtime '
. ' FROM services s'
. ' INNER JOIN hosts h ON s.host_id = h.host_id '
. $innerJoinGroup
. ' WHERE h.name NOT LIKE \'_Module_%\' '
. ' AND h.enabled = 1 '
. ' AND s.enabled = 1 '
. ' GROUP BY s.state ORDER by s.state';
}
$dbResult = $dbb->query($rq2);
$svc_stat = [0 => 0, 1 => 0, 2 => 0, 3 => 0, 4 => 0];
$info = [];
$color = [];
$legend = [];
$counter = 0;
while ($data = $dbResult->fetchRow()) {
$info[$data['state']]['count'] = $data['count'];
$info[$data['state']]['acknowledged'] = $data['acknowledged'];
$info[$data['state']]['downtime'] = $data['downtime'];
$counter += $data['count'];
$legend[] = $tabStatusService[$data['state']];
}
$dbResult->closeCursor();
/**
* create the dataset
*/
foreach ($info as $key => $value) {
$serviceArray[$tabStatusService[$key]]['value'] = $value['count'];
$valuePercent = round($value['count'] / $counter * 100, 2);
$valuePercent = str_replace(',', '.', $valuePercent);
$serviceArray[$tabStatusService[$key]]['percent'] = $valuePercent;
$serviceArray[$tabStatusService[$key]]['acknowledged'] = $value['acknowledged'];
$serviceArray[$tabStatusService[$key]]['downtime'] = $value['downtime'];
}
$template->assign('services', $serviceArray);
/**
* Display Templates
*/
$template->display('global_health_service.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/hostgroup-monitoring/index.php | centreon/www/widgets/hostgroup-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 . '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';
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');
}
$db = new CentreonDB();
$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 hostgroup-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/hostgroup-monitoring/src/';
$template = SmartyBC::createSmartyTemplate($path, './');
$template->assign('widgetId', $widgetId);
$template->assign('preferences', $preferences);
$template->assign('autoRefresh', $autoRefresh);
$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/hostgroup-monitoring/src/export.php | centreon/www/widgets/hostgroup-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\ValueObject\QueryParameter;
use Core\Security\AccessGroup\Domain\Collection\AccessGroupCollection;
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename="hostgroups-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/include/common/sqlCommonFunction.php';
require_once $centreon_path . 'www/widgets/hostgroup-monitoring/src/class/HostgroupMonitoring.class.php';
session_start();
if (! isset($_SESSION['centreon']) || ! isset($_REQUEST['widgetId'])) {
exit;
}
/**
* @var CentreonDB $configurationDatabase
*/
$configurationDatabase = new CentreonDB();
if (CentreonSession::checkSession(session_id(), $configurationDatabase) == 0) {
exit;
}
// Smarty template initialization
$path = $centreon_path . 'www/widgets/hostgroup-monitoring/src/';
$template = SmartyBC::createSmartyTemplate($path, './');
$centreon = $_SESSION['centreon'];
$widgetId = filter_var($_REQUEST['widgetId'], FILTER_VALIDATE_INT);
if ($widgetId === false) {
throw new InvalidArgumentException('Widget ID must be an integer');
}
/**
* @var CentreonDB $realtimeDatabase
*/
$realtimeDatabase = $dependencyInjector['realtime_db'];
$widgetObj = new CentreonWidget($centreon, $configurationDatabase);
$hostGroupService = new HostgroupMonitoring($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',
];
const ORDER_DIRECTION_ASC = 'ASC';
const ORDER_DIRECTION_DESC = 'DESC';
$accessGroups = new AccessGroupCollection();
if (! $centreon->user->admin) {
$acls = new CentreonAclLazy($centreon->user->user_id);
$accessGroups->mergeWith($acls->getAccessGroups());
}
try {
$columns = 'SELECT DISTINCT 1 AS REALTIME, name ';
$baseQuery = ' FROM hostgroups';
$queryParameters = [];
if (! $centreon->user->admin) {
$accessGroupsList = implode(',', $accessGroups->getIds());
$configurationDatabaseName = $configurationDatabase->getConnectionConfig()->getDatabaseNameConfiguration();
$baseQuery .= <<<SQL
INNER JOIN {$configurationDatabaseName}.acl_resources_hg_relations arhr
ON hostgroups.hostgroup_id = arhr.hg_hg_id
INNER JOIN {$configurationDatabaseName}.acl_resources res
ON arhr.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
AND ag.acl_group_id IN ({$accessGroupsList})
SQL;
}
if (isset($preferences['hg_name_search']) && trim($preferences['hg_name_search']) !== '') {
$tab = explode(' ', $preferences['hg_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 ' . ORDER_DIRECTION_ASC;
$allowedOrderColumns = ['name'];
$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;
}
}
// Query to count total rows
$countQuery = 'SELECT COUNT(*) ' . $baseQuery;
// Main SELECT query
$query = $columns . $baseQuery;
$query .= " ORDER BY {$orderby}";
$nbRows = (int) $realtimeDatabase->fetchOne($countQuery, QueryParameters::create($queryParameters));
$detailMode = false;
if (isset($preferences['enable_detailed_mode']) && $preferences['enable_detailed_mode']) {
$detailMode = true;
}
$data = [];
foreach ($realtimeDatabase->iterateAssociative($query, QueryParameters::create($queryParameters)) as $record) {
$name = HtmlSanitizer::createFromString($record['name'])->sanitize()->getString();
$data[$name]['name'] = $name;
}
} catch (CentreonDbException $e) {
CentreonLog::create()->error(
logTypeId: CentreonLog::TYPE_BUSINESS_LOG,
message: 'Error fetching hostgroup monitoring usage data for export: ' . $e->getMessage(),
exception: $e
);
throw new Exception('Error fetching hostgroup monitoring usage data for export: ' . $e->getMessage());
}
$hostGroupService->getHostStates(
$data,
$centreon->user->admin === '1',
$accessGroups,
$detailMode,
);
$hostGroupService->getServiceStates(
$data,
$centreon->user->admin === '1',
$accessGroups,
$detailMode,
);
$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/hostgroup-monitoring/src/index.php | centreon/www/widgets/hostgroup-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\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 . '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/hostgroup-monitoring/src/class/HostgroupMonitoring.class.php';
require_once $centreon_path . 'www/include/common/sqlCommonFunction.php';
require_once $centreon_path . 'www/class/centreonAclLazy.class.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/hostgroup-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);
try {
if ($widgetId === false) {
throw new InvalidArgumentException('Widget ID must be an integer');
}
if ($page === false) {
throw new InvalidArgumentException('Page must be an integer');
}
$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 hostgroup-monitoring widget: ' . $exception->getMessage(),
customContext: [
'widget_id' => $widgetId,
],
exception: $exception
);
showError($exception->getMessage(), $theme ?? 'Generic-theme/Variables-css');
exit;
}
/**
* @var CentreonDB $realtimeDatabase
*/
$realtimeDatabase = $dependencyInjector['realtime_db'];
$widgetObj = new CentreonWidget($centreon, $configurationDatabase);
$hostGroupMonitoringService = new HostgroupMonitoring($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',
];
const ORDER_DIRECTION_ASC = 'ASC';
const ORDER_DIRECTION_DESC = 'DESC';
const DEFAULT_ENTRIES_PER_PAGE = 10;
$accessGroups = new AccessGroupCollection();
if (! $centreon->user->admin) {
$acls = new CentreonAclLazy($centreon->user->user_id);
$accessGroups->mergeWith($acls->getAccessGroups());
}
try {
$columns = 'SELECT DISTINCT 1 AS REALTIME, name, hostgroup_id ';
$baseQuery = ' FROM hostgroups';
$queryParameters = [];
if (! $centreon->user->admin) {
// Shortcut the request and make it return nothing if user has no accessgroups.
if ($accessGroups->isEmpty()) {
$baseQuery .= ' WHERE 1 = 0';
} else {
$accessGroupsList = implode(',', $accessGroups->getIds());
$configurationDatabaseName = $configurationDatabase->getConnectionConfig()->getDatabaseNameConfiguration();
$baseQuery .= <<<SQL
INNER JOIN {$configurationDatabaseName}.acl_resources_hg_relations arhr
ON hostgroups.hostgroup_id = arhr.hg_hg_id
INNER JOIN {$configurationDatabaseName}.acl_resources res
ON arhr.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
AND ag.acl_group_id IN ({$accessGroupsList})
SQL;
}
}
if (isset($preferences['hg_name_search']) && trim($preferences['hg_name_search']) !== '') {
$tab = explode(' ', $preferences['hg_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 ' . ORDER_DIRECTION_ASC;
$allowedOrderColumns = ['name'];
$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;
}
}
// 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;
// Query to count total rows
$countQuery = 'SELECT COUNT(DISTINCT hostgroups.hostgroup_id) ' . $baseQuery;
$nbRows = (int) $realtimeDatabase->fetchOne($countQuery, QueryParameters::create($queryParameters));
// Main SELECT query with LIMIT
$query = $columns . $baseQuery;
$query .= " ORDER BY {$orderby}";
$query .= ' LIMIT :offset, :entriesPerPage';
$queryParameters[] = QueryParameter::int('offset', $offset);
$queryParameters[] = QueryParameter::int('entriesPerPage', $entriesPerPage);
$data = [];
$detailMode = false;
if (isset($preferences['enable_detailed_mode']) && $preferences['enable_detailed_mode']) {
$detailMode = true;
}
$kernel = App\Kernel::createForWeb();
$resourceController = $kernel->getContainer()->get(
Centreon\Application\Controller\MonitoringResourceController::class
);
$buildHostgroupUri = function (array $hostgroup, array $types, array $statuses) use ($resourceController) {
$filter = [
'criterias' => [
[
'name' => 'host_groups',
'value' => $hostgroup,
],
[
'name' => 'resource_types',
'value' => $types,
],
[
'name' => 'statuses',
'value' => $statuses,
],
],
];
try {
$encodedFilter = json_encode($filter, JSON_THROW_ON_ERROR);
return $resourceController->buildListingUri(
[
'filter' => $encodedFilter,
]
);
} catch (JsonException $e) {
CentreonLog::create()->error(
logTypeId: CentreonLog::TYPE_BUSINESS_LOG,
message: 'Error while handling hostgroup monitoring data: ' . $e->getMessage(),
exception: $e
);
throw new Exception('Error while handling hostgroup monitoring data: ' . $e->getMessage());
}
};
$buildParameter = function (string $id, string $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');
$upStatus = $buildParameter('UP', 'Up');
$downStatus = $buildParameter('DOWN', 'Down');
$unreachableStatus = $buildParameter('UNREACHABLE', 'Unreachable');
foreach ($realtimeDatabase->fetchAllAssociative($query, QueryParameters::create($queryParameters)) as $row) {
$hostgroup = [
'id' => (int) $row['hostgroup_id'],
'name' => HtmlSanitizer::createFromString($row['name'])->sanitize()->getString(),
];
$hostgroupServicesUri = $useDeprecatedPages
? '../../main.php?p=20201&search=&o=svc&hg=' . $hostgroup['id']
: $buildHostgroupUri([$hostgroup], [$serviceType], []);
$hostgroupOkServicesUri = $useDeprecatedPages
? $hostgroupServicesUri . '&statusFilter=ok'
: $buildHostgroupUri([$hostgroup], [$serviceType], [$okStatus]);
$hostgroupWarningServicesUri = $useDeprecatedPages
? $hostgroupServicesUri . '&statusFilter=warning'
: $buildHostgroupUri([$hostgroup], [$serviceType], [$warningStatus]);
$hostgroupCriticalServicesUri = $useDeprecatedPages
? $hostgroupServicesUri . '&statusFilter=critical'
: $buildHostgroupUri([$hostgroup], [$serviceType], [$criticalStatus]);
$hostgroupUnknownServicesUri = $useDeprecatedPages
? $hostgroupServicesUri . '&statusFilter=unknown'
: $buildHostgroupUri([$hostgroup], [$serviceType], [$unknownStatus]);
$hostgroupPendingServicesUri = $useDeprecatedPages
? $hostgroupServicesUri . '&statusFilter=pending'
: $buildHostgroupUri([$hostgroup], [$serviceType], [$pendingStatus]);
$hostgroupHostsUri = $useDeprecatedPages
? '../../main.php?p=20202&search=&hostgroups=' . $hostgroup['id'] . '&o=h_'
: $buildHostgroupUri([$hostgroup], [$hostType], []);
$hostgroupUpHostsUri = $useDeprecatedPages
? $hostgroupHostsUri . 'up'
: $buildHostgroupUri([$hostgroup], [$hostType], [$upStatus]);
$hostgroupDownHostsUri = $useDeprecatedPages
? $hostgroupHostsUri . 'down'
: $buildHostgroupUri([$hostgroup], [$hostType], [$downStatus]);
$hostgroupUnreachableHostsUri = $useDeprecatedPages
? $hostgroupHostsUri . 'unreachable'
: $buildHostgroupUri([$hostgroup], [$hostType], [$unreachableStatus]);
$hostgroupPendingHostsUri = $useDeprecatedPages
? $hostgroupHostsUri . 'pending'
: $buildHostgroupUri([$hostgroup], [$hostType], [$pendingStatus]);
$data[$row['name']] = [
'name' => $row['name'],
'hg_id' => $row['hostgroup_id'],
'hg_uri' => $hostgroupServicesUri,
'hg_service_uri' => $hostgroupServicesUri,
'hg_service_ok_uri' => $hostgroupOkServicesUri,
'hg_service_warning_uri' => $hostgroupWarningServicesUri,
'hg_service_critical_uri' => $hostgroupCriticalServicesUri,
'hg_service_unknown_uri' => $hostgroupUnknownServicesUri,
'hg_service_pending_uri' => $hostgroupPendingServicesUri,
'hg_host_uri' => $hostgroupHostsUri,
'hg_host_up_uri' => $hostgroupUpHostsUri,
'hg_host_down_uri' => $hostgroupDownHostsUri,
'hg_host_unreachable_uri' => $hostgroupUnreachableHostsUri,
'hg_host_pending_uri' => $hostgroupPendingHostsUri,
'host_state' => [],
'service_state' => [],
];
}
} catch (ConnectionException $e) {
CentreonLog::create()->error(
logTypeId: CentreonLog::TYPE_BUSINESS_LOG,
message: 'Error while fetching hostgroup monitoring data: ' . $e->getMessage(),
exception: $e
);
throw new Exception('Error while fetching hostgroup monitoring data: ' . $e->getMessage());
}
$hostGroupMonitoringService->getHostStates($data, (int) $centreon->user->admin === 1, $accessGroups, $detailMode);
$hostGroupMonitoringService->getServiceStates($data, (int) $centreon->user->admin === 1, $accessGroups, $detailMode);
if ($detailMode === true) {
foreach ($data as $hostgroupName => &$properties) {
foreach ($properties['host_state'] as $hostName => &$hostProperties) {
$hostProperties['details_uri'] = $useDeprecatedPages
? '../../main.php?p=20202&o=hd&host_name=' . $hostProperties['name']
: $resourceController->buildHostDetailsUri($hostProperties['host_id']);
}
foreach ($properties['service_state'] as $hostId => &$services) {
foreach ($services as &$serviceProperties) {
$serviceProperties['details_uri'] = $useDeprecatedPages
? '../../main.php?o=svcd&p=20201'
. '&host_name=' . $serviceProperties['name']
. '&service_description=' . $serviceProperties['description']
: $resourceController->buildServiceDetailsUri($hostId, $serviceProperties['service_id']);
}
}
}
}
$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('data', $data);
$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/hostgroup-monitoring/src/class/HostgroupMonitoring.class.php | centreon/www/widgets/hostgroup-monitoring/src/class/HostgroupMonitoring.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\Enum\QueryParameterTypeEnum;
use Core\Security\AccessGroup\Domain\Collection\AccessGroupCollection;
class HostgroupMonitoring
{
protected $dbb;
/**
* Constructor
*
* @param CentreonDB $dbb
* @return void
*/
public function __construct($dbb)
{
$this->dbb = $dbb;
}
/**
* Get Host States
*
* @param $data | array('name' => '', 'host_state' => array(), 'service_state' => array())
* @param bool $isUserAdmin
* @param AccessGroupCollection $accessGroups
* @param bool $detailFlag
*/
public function getHostStates(
array &$data,
bool $isUserAdmin,
AccessGroupCollection $accessGroups,
bool $detailFlag = false,
) {
if (
$data === []
|| (! $isUserAdmin && $accessGroups->isEmpty())
) {
return [];
}
['parameters' => $queryParameters, 'placeholderList' => $hostGroupNameList] = createMultipleBindParameters(
array_keys($data),
'hg_name',
QueryParameterTypeEnum::STRING,
);
$query = <<<SQL
SELECT
1 AS REALTIME,
h.host_id,
h.state,
h.name,
h.alias,
hhg.hostgroup_id,
hg.name AS hgname
FROM hosts h
INNER JOIN hosts_hostgroups hhg
ON h.host_id = hhg.host_id
INNER JOIN hostgroups hg
ON hhg.hostgroup_id = hg.hostgroup_id
AND hg.name IN ({$hostGroupNameList})
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 .= ' WHERE h.enabled = 1 ORDER BY h.name';
foreach ($this->dbb->iterateAssociative($query, QueryParameters::create($queryParameters)) as $row) {
$k = $row['hgname'];
if ($detailFlag === true) {
if (! isset($data[$k]['host_state'][$row['name']])) {
$data[$k]['host_state'][$row['name']] = [];
}
foreach ($row as $key => $val) {
$data[$k]['host_state'][$row['name']][$key] = $val;
}
} else {
if (! isset($data[$k]['host_state'][$row['state']])) {
$data[$k]['host_state'][$row['state']] = 0;
}
$data[$k]['host_state'][$row['state']]++;
}
}
}
/**
* Get Service States
*
* @param array $data
* @param bool $isUserAdmin
* @param AccessGroupCollection $accessGroups
* @param bool $detailFlag
*/
public function getServiceStates(
array &$data,
bool $isUserAdmin,
AccessGroupCollection $accessGroups,
bool $detailFlag = false,
) {
if (
$data === []
|| (! $isUserAdmin && $accessGroups->isEmpty())
) {
return [];
}
['parameters' => $queryParameters, 'placeholderList' => $hostGroupNameList] = createMultipleBindParameters(
array_keys($data),
'hg_name',
QueryParameterTypeEnum::STRING,
);
$query = <<<SQL
SELECT
1 AS REALTIME,
h.host_id,
h.name,
s.service_id,
s.description,
s.state,
hhg.hostgroup_id,
hg.name as hgname,
CASE s.state
WHEN 0 THEN 3
WHEN 2 THEN 0
WHEN 3 THEN 2
ELSE s.state
END AS tri
FROM hosts h
INNER JOIN hosts_hostgroups hhg
ON h.host_id = hhg.host_id
INNER JOIN services s
ON s.host_id = h.host_id
INNER JOIN hostgroups hg
ON hg.hostgroup_id = hhg.hostgroup_id
AND hg.name IN ({$hostGroupNameList})
SQL;
if (! $isUserAdmin) {
$accessGroupsList = implode(', ', $accessGroups->getIds());
$query .= <<<SQL
INNER JOIN centreon_acl
ON centreon_acl.host_id = h.host_id
AND centreon_acl.service_id = s.service_id
AND centreon_acl.group_id IN ({$accessGroupsList})
SQL;
}
$query .= <<<'SQL'
WHERE s.enabled = 1 AND h.enabled = 1 ORDER BY tri, s.description ASC
SQL;
foreach ($this->dbb->iterateAssociative($query, QueryParameters::create($queryParameters)) as $row) {
$k = $row['hgname'];
if ($detailFlag === true) {
if (! isset($data[$k]['service_state'][$row['host_id']])) {
$data[$k]['service_state'][$row['host_id']] = [];
}
if (
isset($data[$k]['service_state'][$row['host_id']])
&& ! isset($data[$k]['service_state'][$row['host_id']][$row['service_id']])
) {
$data[$k]['service_state'][$row['host_id']][$row['service_id']] = [];
}
foreach ($row as $key => $val) {
$data[$k]['service_state'][$row['host_id']][$row['service_id']][$key] = $val;
}
} else {
if (! isset($data[$k]['service_state'][$row['state']])) {
$data[$k]['service_state'][$row['state']] = 0;
}
$data[$k]['service_state'][$row['state']]++;
}
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/widgets/graph-monitoring/index.php | centreon/www/widgets/graph-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
*
*/
use Adaptation\Database\Connection\Collection\QueryParameters;
use Adaptation\Database\Connection\Enum\QueryParameterTypeEnum;
use Adaptation\Database\Connection\ValueObject\QueryParameter;
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';
require_once $centreon_path . 'www/class/centreonUser.class.php';
require_once $centreon_path . 'www/class/centreonAclLazy.class.php';
require_once $centreon_path . 'www/include/common/sqlCommonFunction.php';
/** @var CentreonDB $configurationDatabase */
$configurationDatabase = $dependencyInjector['configuration_db'];
CentreonSession::start(1);
if (! CentreonSession::checkSession(session_id(), $configurationDatabase)) {
echo 'Bad Session';
exit();
}
if (! isset($_REQUEST['widgetId'])) {
exit;
}
$centreon = $_SESSION['centreon'];
$widgetId = filter_var(
$_REQUEST['widgetId'],
FILTER_VALIDATE_INT,
);
try {
$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;
if ($widgetId === false) {
throw new InvalidArgumentException('Widget ID must be an integer');
}
/** @var CentreonDB $realTimeDatabase */
$realTimeDatabase = $dependencyInjector['realtime_db'];
$widgetObj = new CentreonWidget($centreon, $configurationDatabase);
/**
* @var array{
* service: string,
* graph_period: string,
* refresh_interval: string,
* } $preferences
*/
$preferences = $widgetObj->getWidgetPreferences($widgetId);
if (! preg_match('/^(\d+)-(\d+)$/', $preferences['service'], $matches)) {
throw new InvalidArgumentException(_('Please select a resource first'));
}
[, $hostId, $serviceId] = $matches;
if (empty($preferences['graph_period'])) {
throw new InvalidArgumentException(_('Please select a graph period'));
}
$autoRefresh = filter_var(
$preferences['refresh_interval'],
FILTER_VALIDATE_INT,
);
if ($autoRefresh === false || $autoRefresh < 5) {
$autoRefresh = 30;
}
if (! $centreon->user->admin) {
$acls = new CentreonAclLazy($centreon->user->user_id);
$accessGroups = $acls->getAccessGroups();
if ($accessGroups->isEmpty()) {
throw new Exception(sprintf('You are not allowed to see graphs for service identified by ID %d', $serviceId));
}
$queryParameters = [
QueryParameter::int('serviceId', (int) $serviceId),
QueryParameter::int('hostId', (int) $hostId),
];
['parameters' => $aclParameters, 'placeholderList' => $bindQuery] = createMultipleBindParameters(
$accessGroups->getIds(),
'access_group_id',
QueryParameterTypeEnum::INTEGER,
);
$request = <<<SQL
SELECT
1 AS REALTIME,
host_id
FROM
centreon_acl
WHERE
host_id = :hostId
AND service_id = :serviceId
AND group_id IN ({$bindQuery})
SQL;
if ($realTimeDatabase->fetchAllAssociative($request, QueryParameters::create([...$queryParameters, ...$aclParameters])) === []) {
throw new Exception(sprintf('You are not allowed to see graphs for service identified by ID %d', $serviceId));
}
}
} catch (Exception $exception) {
CentreonLog::create()->error(
logTypeId: CentreonLog::TYPE_BUSINESS_LOG,
message: 'Error fetching data for graph-monitoring widget: ' . $exception->getMessage(),
exception: $exception
);
showError($exception->getMessage(), $theme ?? 'Generic-theme/Variables-css');
exit;
}
// Smarty template initialization
$path = $centreon_path . 'www/widgets/graph-monitoring/src/';
$template = SmartyBC::createSmartyTemplate($path, '/');
$template->assign('theme', $theme);
$template->assign('widgetId', $widgetId);
$template->assign('preferences', $preferences);
$template->assign('interval', $preferences['graph_period']);
$template->assign('autoRefresh', $autoRefresh);
$template->assign('graphId', sprintf('%d_%d', (int) $hostId, (int) $serviceId));
$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/graph-monitoring/src/generateGraph.php | centreon/www/widgets/graph-monitoring/src/generateGraph.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/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';
require_once $centreon_path . 'www/class/centreonGraph.class.php';
CentreonSession::start(1);
if (! isset($_GET['service'])) {
exit;
}
[$hostId, $serviceId] = explode('-', $_GET['service']);
$db = $dependencyInjector['realtime_db'];
$query = <<<'SQL'
SELECT
1 AS REALTIME,
`id`
FROM index_data
WHERE host_id = :hostId
AND service_id = :serviceId
LIMIT 1
SQL;
$stmt = $db->prepare($query);
$stmt->bindValue(':hostId', $hostId, PDO::PARAM_INT);
$stmt->bindValue(':serviceId', $serviceId, PDO::PARAM_INT);
$stmt->execute();
if ($stmt->rowCount()) {
$row = $stmt->fetch();
$index = $row['id'];
} else {
$index = 0;
}
/**
* Create XML Request Objects
*/
$iIdUser = (int) $_GET['user'];
$obj = new CentreonGraph($iIdUser, $index, 0, 1);
require_once $centreon_path . 'www/include/common/common-Func.php';
/**
* Set arguments from GET
*/
(int) $graphPeriod = $_GET['tp'] ?? (60 * 60 * 48);
$obj->setRRDOption('start', (time() - $graphPeriod));
$obj->setRRDOption('end', time());
$obj->GMT->getMyGMTFromSession(session_id());
/**
* Template Management
*/
$obj->setTemplate();
$obj->init();
// Set colors
$obj->setColor('CANVAS', '#FFFFFF');
$obj->setColor('BACK', '#FFFFFF');
$obj->setColor('SHADEA', '#FFFFFF');
$obj->setColor('SHADEB', '#FFFFFF');
if (isset($_GET['width']) && $_GET['width']) {
$obj->setRRDOption('width', (int) ($_GET['width'] - 110));
}
/**
* Init Curve list
*/
$obj->initCurveList();
/**
* Comment time
*/
$obj->setOption('comment_time');
/**
* Create Legend
*/
$obj->createLegend();
/**
* Display Images Binary Data
*/
$obj->displayImageFlow();
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/widgets/grid-map/index.php | centreon/www/widgets/grid-map/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 '../../../config/centreon.config.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/centreonUtils.class.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');
}
$widgetObj = new CentreonWidget($centreon, $dependencyInjector['configuration_db']);
/**
* @var array{
* host_group: string,
* service: string,
* refresh_interval: string
* } $preferences
*/
$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 grid-map widget: ' . $exception->getMessage(),
customContext: [
'widget_id' => $widgetId,
],
exception: $exception
);
showError($exception->getMessage(), $theme ?? 'Generic-theme/Variables-css');
exit;
}
// Smarty template initialization
$template = SmartyBC::createSmartyTemplate(getcwd() . '/', './');
$template->assign('autoRefresh', $autoRefresh);
$template->assign('widgetId', $widgetId);
$template->assign('theme', $theme);
$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/grid-map/src/table.php | centreon/www/widgets/grid-map/src/table.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 '../../../../config/centreon.config.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 . 'bootstrap.php';
require_once $centreon_path . 'www/include/common/sqlCommonFunction.php';
require_once $centreon_path . 'www/class/centreonAclLazy.class.php';
CentreonSession::start(1);
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);
// INIT
$colors = [0 => 'service_ok', 1 => 'service_warning', 2 => 'service_critical', 3 => 'unknown', 4 => 'pending'];
$accessGroups = [];
$arrayKeysAccessGroups = [];
try {
if ($widgetId === false) {
throw new InvalidArgumentException('Widget ID must be an integer');
}
$configurationDatabase = $dependencyInjector['configuration_db'];
$realTimeDatabase = $dependencyInjector['realtime_db'];
if ($centreon->user->admin == 0) {
$access = new CentreonAclLazy($centreon->user->user_id);
$accessGroups = $access->getAccessGroups();
}
$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),
};
} catch (Exception $exception) {
echo $exception->getMessage() . '<br/>';
exit;
}
$kernel = App\Kernel::createForWeb();
$resourceController = $kernel->getContainer()->get(
Centreon\Application\Controller\MonitoringResourceController::class
);
// Smarty template initialization
$template = SmartyBC::createSmartyTemplate(getcwd() . '/', './');
$data = [];
$data_service = [];
// Only process if a host group has been selected in the preferences
if (! empty($preferences['host_group'])) {
$aclJoin = '';
$aclSubRequest = '';
$bindParams1 = [];
$bindValuesAcl = [];
/* ---------------------------
* Query 1: Host Listing
* ---------------------------
* Uses the built conditions and filter access groups if needed.
*/
if ($accessGroups !== []) {
$aclJoin = $centreon->user->admin == 0 ? ' INNER JOIN centreon_acl acl ON T1.host_id = acl.host_id' : '';
[$bindValuesAcl, $bindQueryAcl] = createMultipleBindQuery(
list: $accessGroups->getIds(),
prefix: ':access_group_id_host_',
bindType: PDO::PARAM_INT
);
$aclSubRequest = ' AND acl.group_id IN (' . $bindQueryAcl . ')';
}
$query1 = <<<SQL
SELECT DISTINCT 1 AS REALTIME, T1.name, T2.host_id
FROM hosts T1
INNER JOIN hosts_hostgroups T2 ON T1.host_id = T2.host_id
{$aclJoin}
WHERE T1.enabled = 1
AND T2.hostgroup_id = :hostgroup_id
{$aclSubRequest}
ORDER BY T1.name
SQL;
$bindParams1[':hostgroup_id'] = [$preferences['host_group'], PDO::PARAM_INT];
$bindParams1 = array_merge($bindParams1, $bindValuesAcl);
try {
$stmt1 = $realTimeDatabase->prepareQuery($query1);
$realTimeDatabase->executePreparedQuery($stmt1, $bindParams1, true);
while ($row = $realTimeDatabase->fetch($stmt1)) {
$row['details_uri'] = $useDeprecatedPages
? '../../main.php?p=20202&o=hd&host_name=' . $row['name']
: $resourceController->buildHostDetailsUri($row['host_id']);
$data[] = $row;
}
} catch (CentreonDbException $exception) {
CentreonLog::create()->error(
CentreonLog::TYPE_SQL,
'Error while fetching host listing for widget',
[
'query' => $query1,
'bindParams' => $bindParams1,
'exception' => [
'message' => $exception->getMessage(),
'trace' => $exception->getTrace(),
],
]
);
}
/* ---------------------------
* Prepare service filter conditions
* ---------------------------
* The preferences['service'] is a comma-separated list. We build an array of conditions
* with proper bound parameters.
*/
$serviceList = array_map('trim', explode(',', $preferences['service']));
// For Query 2 (service listing)
$bindParams2 = [];
[$bindValues, $bindQuery] = createMultipleBindQuery(
list: $serviceList,
prefix: ':service_description_',
bindType: PDO::PARAM_STR
);
$whereService2 = 'T1.description IN (' . $bindQuery . ')';
/* ---------------------------
* Query 2: Service Listing
* ---------------------------
* Uses the built conditions and binds each service filter.
*/
if ($accessGroups !== []) {
$aclJoin = $centreon->user->admin == 0 ? ' INNER JOIN centreon_acl acl ON T1.service_id = acl.service_id' : '';
}
$query2 = <<<SQL
SELECT DISTINCT 1 AS REALTIME, T1.description
FROM services T1
{$aclJoin}
WHERE T1.enabled = 1
{$aclSubRequest}
AND {$whereService2}
SQL;
$bindParams2 = array_merge($bindValues, $bindValuesAcl);
try {
$stmt2 = $realTimeDatabase->prepareQuery($query2);
$realTimeDatabase->executePreparedQuery($stmt2, $bindParams2, true);
while ($row = $realTimeDatabase->fetch($stmt2)) {
$data_service[$row['description']] = [
'description' => $row['description'],
'hosts' => [],
'hostsStatus' => [],
'details_uri' => [],
];
}
} catch (CentreonDbException $exception) {
CentreonLog::create()->error(
CentreonLog::TYPE_SQL,
'Error while fetching service listing for widget',
[
'query' => $query2,
'bindParams' => $bindParams2,
'exception' => [
'message' => $exception->getMessage(),
'trace' => $exception->getTrace(),
],
]
);
}
/* ---------------------------
* Query 3: Host Service Statuses
* ---------------------------
* Almost the same filter as Query 2 but with additional conditions on description.
*/
$whereService3 = $whereService2;
$query3 = <<<SQL
SELECT DISTINCT 1 AS REALTIME, T1.service_id, T1.description, T1.state, T1.host_id, T2.name
FROM services T1
INNER JOIN hosts T2 ON T1.host_id = T2.host_id
{$aclJoin}
WHERE T1.enabled = 1
AND T1.description NOT LIKE 'ba\_%'
AND T1.description NOT LIKE 'meta\_%'
{$aclSubRequest}
AND {$whereService3}
SQL;
$bindParams3 = $bindParams2;
try {
$stmt3 = $realTimeDatabase->prepareQuery($query3);
$realTimeDatabase->executePreparedQuery($stmt3, $bindParams3, true);
while ($row = $realTimeDatabase->fetch($stmt3)) {
if (isset($data_service[$row['description']])) {
$data_service[$row['description']]['hosts'][] = $row['host_id'];
$data_service[$row['description']]['hostsStatus'][$row['host_id']] = $colors[$row['state']];
$data_service[$row['description']]['details_uri'][$row['host_id']] = $useDeprecatedPages
? '../../main.php?p=20201&o=svcd&host_name=' . $row['name'] . '&service_description=' . $row['description']
: $resourceController->buildServiceDetailsUri($row['host_id'], $row['service_id']);
}
}
} catch (CentreonDbException $exception) {
CentreonLog::create()->error(
CentreonLog::TYPE_SQL,
'Error while fetching host service statuses for widget',
[
'query' => $query3,
'bindParams' => $bindParams3,
'exception' => [
'message' => $exception->getMessage(),
'trace' => $exception->getTrace(),
],
]
);
}
}
$template->assign('theme', $variablesThemeCSS);
$template->assign('autoRefresh', $autoRefresh);
$template->assign('preferences', $preferences);
$template->assign('widgetId', $widgetId);
$template->assign('data', $data);
$template->assign('data_service', $data_service);
// Display
$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/live-top10-cpu-usage/index.php | centreon/www/widgets/live-top10-cpu-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';
CentreonSession::start(1);
if (! isset($_SESSION['centreon']) || ! isset($_REQUEST['widgetId'])) {
exit;
}
$centreon = $_SESSION['centreon'];
$widgetId = filter_var($_REQUEST['widgetId'], FILTER_VALIDATE_INT);
/**
* true: URIs will correspond to deprecated pages
* false: URIs will correspond to new page (Resource Status)
*/
$useDeprecatedPages = $centreon->user->doesShowDeprecatedPages();
try {
if ($widgetId === false) {
throw new InvalidArgumentException('Widget ID must be an integer');
}
$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-cpu-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-cpu-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,
AVG(m.current_value) AS current_value,
s.state AS status
FROM index_data i
INNER JOIN metrics m
ON i.id = m.index_id
INNER 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 m.current_value <= 100
AND h.enabled = 1
GROUP BY
i.host_id,
i.service_id,
i.host_name,
i.service_description,
s.state
ORDER BY current_value 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;
foreach ($realtimeDatabase->iterateAssociative($query, QueryParameters::create($queryParameters)) as $record) {
$record['numLin'] = $numLine;
$record['current_value'] = ceil($record['current_value']);
$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 cpu usage data: ' . $exception->getMessage(),
exception: $exception
);
throw $exception;
}
$template->assign('preferences', $preferences);
$template->assign('widgetId', $widgetId);
$template->assign('autoRefresh', $autoRefresh);
$template->assign('data', $data);
$template->assign('theme', $variablesThemeCSS);
$template->display('table_top10cpu.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/single-metric/functions.php | centreon/www/widgets/single-metric/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
*
*/
/**
* Convert a size to be human readable.
*
* @param float|int $value Value to convert
* @param string $unit Unit of value
* @param int $base Conversion base (ex: 1024)
* @return array{0: float, 1: string}
*/
function convertSizeToHumanReadable(float|int $value, string $unit, int $base): array
{
$accuracy = 2;
$prefix = ['a', 'f', 'p', 'n', 'u', 'm', '', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'];
$power = min(max(floor(log(abs($value), $base)), -6), 6);
return [round((float) $value / pow($base, $power), $accuracy), $prefix[$power + 6] . $unit];
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/widgets/single-metric/index.php | centreon/www/widgets/single-metric/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 'functions.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';
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');
}
$centreonDb = $dependencyInjector['configuration_db'];
$centreonRtDb = $dependencyInjector['realtime_db'];
$centreonWidget = new CentreonWidget($centreon, $centreonDb);
$preferences = $centreonWidget->getWidgetPreferences($widgetId);
$autoRefresh = filter_var($preferences['refresh_interval'], FILTER_VALIDATE_INT);
$preferences['metric_name'] = filter_var($preferences['metric_name'], FILTER_SANITIZE_STRING);
$preferences['font_size'] = filter_var($preferences['font_size'] ?? 80, FILTER_VALIDATE_INT);
$preferences['display_number'] = filter_var($preferences['display_number'] ?? 1000, FILTER_VALIDATE_INT);
$preferences['coloring'] = filter_var($preferences['coloring'] ?? 'black', FILTER_SANITIZE_STRING);
$preferences['display_path'] = filter_var($preferences['display_path'] ?? false, FILTER_VALIDATE_BOOLEAN);
$preferences['display_threshold'] = filter_var($preferences['display_threshold'] ?? false, FILTER_VALIDATE_BOOLEAN);
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 single-metric widget: ' . $exception->getMessage(),
customContext: [
'widget_id' => $widgetId,
],
exception: $exception
);
showError($exception->getMessage(), $theme);
exit;
}
$kernel = App\Kernel::createForWeb();
/**
* @var Centreon\Application\Controller\MonitoringResourceController $resourceController
*/
$resourceController = $kernel->getContainer()->get(
Centreon\Application\Controller\MonitoringResourceController::class
);
// configure smarty
$isAdmin = $centreon->user->admin === '1';
$accessGroups = [];
if (! $isAdmin) {
$acls = new CentreonAclLazy($centreon->user->user_id);
$accessGroups = $acls->getAccessGroups()->getIds();
}
// Smarty template initialization
$path = $centreon_path . 'www/widgets/single-metric/src/';
$template = SmartyBC::createSmartyTemplate($path, './');
$template->assign('theme', $variablesThemeCSS);
$template->assign(
'webTheme',
$variablesThemeCSS === 'Generic-theme'
? $variablesThemeCSS . '/Variables-css'
: $variablesThemeCSS
);
$data = [];
if (! isset($preferences['service']) || $preferences['service'] === '') {
$template->display('metric.ihtml');
} else {
[$hostId, $serviceId] = explode('-', $preferences['service']);
$numLine = 0;
if ($isAdmin || $accessGroups !== []) {
$query
= "SELECT
1 AS REALTIME,
i.host_name AS host_name,
i.service_description AS service_description,
i.service_id AS service_id,
i.host_id AS host_id,
REPLACE(m.current_value, '.', ',') AS current_value,
m.current_value AS current_float_value,
m.metric_name AS metric_name,
m.unit_name AS unit_name,
m.warn AS warning,
m.crit AS critical,
s.state AS status
FROM
metrics m,
hosts h "
. (! $isAdmin ? ', centreon_acl acl ' : '')
. ' , index_data i
LEFT JOIN services s ON s.service_id = i.service_id AND s.enabled = 1
WHERE i.service_id = :serviceId
AND i.id = m.index_id
AND m.metric_name = :metricName
AND i.host_id = h.host_id
AND i.host_id = :hostId ';
if (! $isAdmin) {
$query .= 'AND i.host_id = acl.host_id
AND i.service_id = acl.service_id
AND acl.group_id IN (' . implode(',', array_keys($accessGroups)) . ')';
}
$query .= 'AND s.enabled = 1
AND h.enabled = 1;';
$stmt = $centreonRtDb->prepare($query);
$stmt->bindParam(':hostId', $hostId, PDO::PARAM_INT);
$stmt->bindParam(':metricName', $preferences['metric_name'], PDO::PARAM_STR);
$stmt->bindParam(':serviceId', $serviceId, PDO::PARAM_INT);
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$row['details_uri'] = $resourceController->buildServiceDetailsUri($row['host_id'], $row['service_id']);
$row['host_uri'] = $resourceController->buildHostDetailsUri($row['host_id']);
$row['graph_uri'] = $resourceController->buildServiceUri($row['host_id'], $row['service_id'], 'graph');
$data[] = $row;
$numLine++;
}
}
// Calculate Threshold font size
$preferences['threshold_font_size'] = round($preferences['font_size'] / 8, 0);
if ($preferences['threshold_font_size'] < 9) {
$preferences['threshold_font_size'] = 9;
}
if ($numLine > 0) {
// Human readable
if ($preferences['display_number'] === 1000 || $preferences['display_number'] === 1024) {
[$size, $data[0]['unit_displayed']] = convertSizeToHumanReadable(
$data[0]['current_float_value'],
$data[0]['unit_name'],
$preferences['display_number']
);
$data[0]['value_displayed'] = str_replace('.', ',', (string) $size);
if (is_numeric($data[0]['warning'])) {
$newWarning = convertSizeToHumanReadable(
$data[0]['warning'],
$data[0]['unit_name'],
$preferences['display_number']
);
$data[0]['warning_displayed'] = str_replace('.', ',', (string) $newWarning[0]);
}
if (is_numeric($data[0]['critical'])) {
$newCritical = convertSizeToHumanReadable(
$data[0]['critical'],
$data[0]['unit_name'],
$preferences['display_number']
);
$data[0]['critical_displayed'] = str_replace('.', ',', (string) $newCritical[0]);
}
} else {
$data[0]['value_displayed'] = $data[0]['current_value'];
$data[0]['unit_displayed'] = $data[0]['unit_name'];
$data[0]['warning_displayed'] = $data[0]['warning'];
$data[0]['critical_displayed'] = $data[0]['critical'];
}
}
$template->assign('preferences', $preferences);
$template->assign('widgetId', $widgetId);
$template->assign('autoRefresh', $autoRefresh);
$template->assign('data', $data);
$template->display('metric.ihtml');
}
| 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.