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/class/centreon-partition/config.class.php | centreon/www/class/centreon-partition/config.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 Config
* @category Database
* @package Centreon
* @author qgarnier <qgarnier@centreon.com>
* @license GPLv2 http://www.gnu.org/licenses
* @see http://www.centreon.com
*/
class Config
{
/** @var string */
public $XMLFile;
/** @var array */
public $tables = [];
/** @var CentreonDB */
public $centstorageDb;
/** @var array */
private $defaultConfiguration;
/** @var CentreonDB */
private $centreonDb;
/**
* Config constructor
*
* @param CentreonDB $centstorageDb the centstorage database
* @param string $file the xml file name
* @param CentreonDB $centreonDb the centreon database
*
* @throws Exception
*/
public function __construct($centstorageDb, $file, $centreonDb)
{
$this->XMLFile = $file;
$this->centstorageDb = $centstorageDb;
$this->centreonDb = $centreonDb;
$this->loadCentreonDefaultConfiguration();
$this->parseXML($this->XMLFile);
}
/**
* @throws PDOException
* @return void
*/
public function loadCentreonDefaultConfiguration(): void
{
$queryOptions = 'SELECT `opt`.`key`, `opt`.`value` '
. 'FROM `options` opt '
. 'WHERE `opt`.`key` IN ('
. "'partitioning_backup_directory', 'partitioning_backup_format', "
. "'partitioning_retention', 'partitioning_retention_forward'"
. ')';
$res = $this->centreonDb->query($queryOptions);
while ($row = $res->fetchRow()) {
$this->defaultConfiguration[$row['key']] = $row['value'];
}
}
/**
* Parse XML configuration file to get properties of table to process
*
* @param string $xmlfile the xml file name
*
* @throws Exception
* @return null
*/
public function parseXML($xmlfile): void
{
if (! file_exists($xmlfile)) {
throw new Exception("Config file '" . $xmlfile . "' does not exist\n");
}
$node = new SimpleXMLElement(file_get_contents($xmlfile));
foreach ($node->table as $table_config) {
$table = new MysqlTable(
$this->centstorageDb,
(string) $table_config['name'],
(string) dbcstg
);
if (! is_null($table->getName()) && ! is_null($table->getSchema())) {
$table->setActivate((string) $table_config->activate);
$table->setColumn((string) $table_config->column);
$table->setType((string) $table_config->type);
$table->setDuration('daily');
$table->setTimezone((string) $table_config->timezone);
if (isset($this->defaultConfiguration['partitioning_retention'])) {
$table->setRetention((string) $this->defaultConfiguration['partitioning_retention']);
} else {
$table->setRetention('365');
}
if (isset($this->defaultConfiguration['partitioning_retention_forward'])) {
$table->setRetentionForward((string) $this->defaultConfiguration['partitioning_retention_forward']);
} else {
$table->setRetentionForward('10');
}
if (isset($this->defaultConfiguration['partitioning_backup_directory'])) {
$table->setBackupFolder((string) $this->defaultConfiguration['partitioning_backup_directory']);
} else {
$table->setBackupFolder('/var/backups/');
}
$table->setBackupFormat('%Y-%m-%d');
$table->setCreateStmt((string) $table_config->createstmt);
$this->tables[$table->getName()] = $table;
}
}
}
/**
* Return all tables partitioning properties
*
* @return array
*/
public function getTables()
{
return $this->tables;
}
/**
* Return partitioning properties for a specific table
*
* @param string $name the table name
*
* @return string
*/
public function getTable($name)
{
foreach ($this->tables as $key => $instance) {
if ($key == $name) {
return $instance;
}
}
return null;
}
/**
* Check if each table property is set
*
* @return bool
*/
public function isValid()
{
foreach ($this->tables as $key => $inst) {
if (! $inst->isValid()) {
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/class/centreon-partition/partEngine.class.php | centreon/www/class/centreon-partition/partEngine.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 PartEngine
* @description Class that handles MySQL table partitions
*/
class PartEngine
{
/**
* Create a new table with partitions
*
* @param MysqlTable $table The table to partition
* @param CentreonDB $db The database connection
* @param bool $createPastPartitions If the past partitions need to be created
*
* @throws Exception
*/
public function createParts($table, $db, $createPastPartitions): void
{
$tableName = '`' . $table->getSchema() . '`.' . $table->getName();
if ($table->exists()) {
throw new Exception('Warning: Table ' . $tableName . " already exists\n");
}
$partition_part = null;
if ($table->getType() == 'date' && $table->getDuration() == 'daily') {
$partition_part = $this->createDailyPartitions($table, $createPastPartitions);
}
if (is_null($partition_part)) {
throw new Exception(
"SQL Error: Cannot build partition part \n"
);
}
try {
$dbResult = $db->query('use `' . $table->getSchema() . '`');
} catch (PDOException $e) {
throw new Exception(
'SQL Error: Cannot use database '
. $table->getSchema() . ',' . $e->getMessage() . "\n"
);
}
try {
$dbResult = $db->query($table->getCreateStmt() . $partition_part);
} catch (PDOException $e) {
throw new Exception(
'Error : Cannot create table ' . $tableName . ' with partitions, '
. $e->getMessage() . "\n"
);
}
if ($table->getType() == 'date') {
$this->createMaxvaluePartition($db, $tableName, $table);
}
}
/**
* Drop partitions that are older than the retention duration
*
* @param MysqlTable $table
* @param $db
*
* @throws Exception
* @return true|void
*/
public function purgeParts($table, $db)
{
if ($table->getType() != 'date') {
echo '[' . date(DATE_RFC822) . "][purge] No need to purge\n";
return true;
}
if ($table->getType() == 'date' && $table->getDuration() == 'daily') {
$condition = $this->purgeDailyPartitionCondition($table);
}
$tableName = '`' . $table->getSchema() . '`.' . $table->getName();
if (! $table->exists()) {
throw new Exception('Error: Table ' . $tableName . " does not exists\n");
}
$request = "SELECT PARTITION_NAME FROM INFORMATION_SCHEMA.PARTITIONS
WHERE TABLE_NAME='" . $table->getName() . "'
AND TABLE_SCHEMA='" . $table->getSchema() . "'
AND CONVERT(PARTITION_DESCRIPTION, SIGNED INTEGER) IS NOT NULL ";
$request .= $condition;
try {
$dbResult = $db->query($request);
} catch (PDOException $e) {
throw new Exception('Error : Cannot get partitions to purge for table '
. $tableName . ', ' . $e->getMessage() . "\n");
}
while ($row = $dbResult->fetch()) {
$request = 'ALTER TABLE ' . $tableName . ' DROP PARTITION `' . $row['PARTITION_NAME'] . '`;';
try {
$dbResult2 = & $db->query($request);
} catch (PDOException $e) {
throw new Exception('Error : Cannot drop partition ' . $row['PARTITION_NAME'] . ' of table '
. $tableName . ', ' . $e->getMessage() . "\n");
}
}
}
/**
* Enable partitions for an existing table
* Must dump data from initial table
* Rename existing table
* Create new table with partitions and initial name
* Load data into new table
* Delete old table
*
* @param $table
* @param $db
*
* @throws Exception
* @return void
*/
public function migrate($table, $db): void
{
$tableName = '`' . $table->getSchema() . '`.' . $table->getName();
$db->query('SET bulk_insert_buffer_size= 1024 * 1024 * 256');
if (! $table->exists() || ! $table->columnExists()) {
throw new Exception('Error: Table ' . $table->getSchema() . '.' . $table->getName() . " does not exists\n");
}
// Renaming existing table with the suffix '_old'
echo '[' . date(DATE_RFC822) . '][migrate] Renaming table ' . $tableName . ' TO ' . $tableName . "_old\n";
try {
$dbResult = $db->query('RENAME TABLE ' . $tableName . ' TO ' . $tableName . '_old');
} catch (PDOException $e) {
throw new Exception(
'Error: Cannot rename table ' . $tableName
. ' to ' . $tableName . '_old, '
. $e->getMessage() . "\n"
);
}
// creating new table with the initial name
echo '[' . date(DATE_RFC822) . '][migrate] Creating parts for new table ' . $tableName . "\n";
// create partitions for past and future
$this->createParts($table, $db, true);
// dumping data from existing table
echo '[' . date(DATE_RFC822) . '][migrate] Insert data from ' . $tableName . "_old to new table\n";
$request = 'INSERT INTO ' . $tableName . ' SELECT * FROM ' . $tableName . '_old';
try {
$dbResult = $db->query($request);
} catch (PDOException $e) {
throw new Exception(
'Error: Cannot copy ' . $tableName . '_old data to new table '
. $e->getMessage() . "\n"
);
}
}
/**
* Update a partitionned table to add new partitions
*
* @param $table
* @param $db
*
* @throws Exception
* @return void
*/
public function updateParts($table, $db): void
{
$tableName = '`' . $table->getSchema() . '`.' . $table->getName();
// verifying if table is partitioned
if ($this->isPartitioned($table, $db) === false) {
throw new Exception('Error: cannot update non partitioned table ' . $tableName . "\n");
}
// Get Last
$lastTime = $this->getLastPartRange($table, $db);
if ($table->getType() == 'date' && $table->getDuration() == 'daily') {
$this->updateDailyPartitions($db, $tableName, $table, $lastTime);
}
}
/**
* list all partitions for a table
*
* @param MysqlTable $table
* @param $db
* @param bool $throwException
*
* @throws Exception
* @return array
*/
public function listParts($table, $db, $throwException = true)
{
$tableName = '`' . $table->getSchema() . '`.' . $table->getName();
if (! $table->exists()) {
throw new Exception('Parts list error: Table ' . $tableName . " does not exists\n");
}
$request = '';
if ($table->getType() == '') {
$request = 'SELECT FROM_UNIXTIME(PARTITION_DESCRIPTION) as PART_RANGE, ';
} else {
$request = 'SELECT PARTITION_DESCRIPTION as PART_RANGE, ';
}
$request .= 'PARTITION_NAME, PARTITION_ORDINAL_POSITION, '
. 'INDEX_LENGTH, DATA_LENGTH, CREATE_TIME, TABLE_ROWS ';
$request .= 'FROM information_schema.`PARTITIONS` ';
$request .= "WHERE `TABLE_NAME`='" . $table->getName() . "' ";
$request .= "AND TABLE_SCHEMA='" . $table->getSchema() . "' ";
$request .= 'ORDER BY PARTITION_NAME DESC ';
try {
$dbResult = $db->query($request);
} catch (PDOException $e) {
throw new Exception(
'Error : Cannot get table schema information for '
. $tableName . ', ' . $e->getMessage() . "\n"
);
}
$partitions = [];
while ($row = $dbResult->fetch()) {
if (! is_null($row['PARTITION_NAME'])) {
$row['INDEX_LENGTH'] = round($row['INDEX_LENGTH'] / (1024 * 1024), 2);
$row['DATA_LENGTH'] = round($row['DATA_LENGTH'] / (1024 * 1024), 2);
$row['TOTAL_LENGTH'] = $row['INDEX_LENGTH'] + $row['DATA_LENGTH'];
$partitions[] = $row;
}
}
if ($partitions === [] && $throwException) {
throw new Exception('No partition found for table ' . $tableName . "\n");
}
return $partitions;
$dbResult->closeCursor();
}
/**
* Backup Partition
*
* @param MysqlTable $table
* @param $db
*
* @throws Exception
*/
public function backupParts($table, $db): void
{
$tableName = '`' . $table->getSchema() . '`.' . $table->getName();
if (! $table->exists()) {
throw new Exception('Error: Table ' . $tableName . " does not exists\n");
}
$format = 'PARTITION_DESCRIPTION';
if (! is_null($table->getBackupFormat()) && $table->getType() == 'date' && $table->getDuration() == 'daily') {
$format = "date_format(FROM_UNIXTIME(PARTITION_DESCRIPTION), '" . $table->getBackupFormat() . "')";
}
$request = 'SELECT PARTITION_NAME, PARTITION_DESCRIPTION, '
. $format . ' as filename FROM information_schema.`PARTITIONS` ';
$request .= "WHERE `TABLE_NAME`='" . $table->getName() . "' ";
$request .= "AND TABLE_SCHEMA='" . $table->getSchema() . "' ";
$request .= 'ORDER BY PARTITION_ORDINAL_POSITION desc ';
$request .= 'LIMIT 2';
try {
$dbResult = $db->query($request);
} catch (PDOException $e) {
throw new Exception(
'Error : Cannot get table schema information for '
. $tableName . ', ' . $e->getMessage() . "\n"
);
}
$count = 0;
$filename = $table->getBackupFolder() . '/' . $tableName;
$start = '';
$end = '';
while ($row = $dbResult->fetch()) {
if (! $count) {
$filename .= '_' . $row['PARTITION_NAME'] . '_' . $row['filename'];
$end = $row['PARTITION_DESCRIPTION'];
$count++;
} else {
$start = $row['PARTITION_DESCRIPTION'];
}
}
if ($start == '' || $end == '') {
throw new Exception('FATAL : Cannot get last partition ranges of table ' . $tableName . "\n");
}
$filename .= '_' . date('Ymd-hi') . '.dump';
$dbResult->closeCursor();
$request = 'SELECT * FROM ' . $tableName;
$request .= ' WHERE ' . $table->getColumn() . ' >= ' . $start;
$request .= ' AND ' . $table->getColumn() . ' < ' . $end;
$request .= " INTO OUTFILE '" . $filename . "'";
try {
$dbResult = $db->query($request);
} catch (PDOException $e) {
throw new Exception(
'FATAL : Cannot dump table ' . $tableName
. ' into file ' . $filename . ', '
. $e->getMessage() . "\n"
);
}
}
/**
* Check if MySQL/MariaDB version is compatible with partitionning.
*
* @param CentreonDB $db The Db singleton
*
* @throws PDOException
* @return bool
*/
public function isCompatible($db)
{
$dbResult = $db->query("SELECT plugin_status FROM INFORMATION_SCHEMA.PLUGINS WHERE plugin_name = 'partition'");
$config = $dbResult->fetch();
$dbResult->closeCursor();
if ($config === false || empty($config['plugin_status'])) {
// as the plugin "partition" was deprecated in mysql 5.7
// and as it was removed from mysql 8 and replaced by the native partitioning one,
// we need to check the current version and db before failing this step
$dbResult = $db->query(
"SHOW VARIABLES WHERE Variable_name LIKE 'version%'"
);
$versionName = null;
$versionNumber = null;
while ($row = $dbResult->fetch()) {
switch ($row['Variable_name']) {
case 'version_comment':
$versionName = $row['Value'];
break;
case 'version':
$versionNumber = $row['Value'];
break;
}
}
$dbResult->closeCursor();
$dbType = match ($versionName) {
'MariaDB' => 'mariadb',
'MySQL','Source distribution','Percona Server' => 'mysql',
default => (($versionNumber === null || version_compare($versionNumber, '10.5.0', '>=')) ? 'mariadb' : 'mysql'),
};
if ($dbType === 'mysql') {
return true;
}
}
return (bool) ($config['plugin_status'] === 'ACTIVE');
}
/**
* Check if a table is partitioned.
*
* @param $table
* @param $db
*
* @throws Exception
* @return bool
*/
public function isPartitioned($table, $db): bool
{
try {
$dbResult = $db->query(
'SHOW CREATE TABLE `' . $table->getSchema() . '`.`' . $table->getName() . '`'
);
} catch (PDOException $e) {
throw new Exception('Cannot get partition information');
}
if ($row = $dbResult->fetch()) {
if (preg_match('/PARTITION BY/', $row['Create Table']) === 1) {
return true;
}
}
return false;
}
/**
* @param $db
* @param $tableName
* @param $table
*
* @throws Exception
* @return void
*/
private function createMaxvaluePartition($db, $tableName, $table): void
{
if ($this->hasMaxValuePartition($db, $table) === false) {
try {
$dbResult = $db->query(
'ALTER TABLE ' . $tableName . ' ADD PARTITION (PARTITION `pmax` VALUES LESS THAN MAXVALUE)'
);
} catch (PDOException $e) {
throw new Exception(
'Error: cannot add a maxvalue partition for table '
. $tableName . ', ' . $e->getMessage() . "\n"
);
}
}
}
/**
* @param $table
*
* @return string
*/
private function purgeDailyPartitionCondition($table)
{
date_default_timezone_set($table->getTimezone());
$ltime = localtime();
$current_time = mktime(0, 0, 0, $ltime[4] + 1, $ltime[3] - $table->getRetention(), $ltime[5] + 1900);
return 'AND CONVERT(PARTITION_DESCRIPTION, SIGNED INTEGER) < ' . $current_time . ' '
. "AND PARTITION_DESCRIPTION != 'MAXVALUE' ";
}
/**
* @param $db
* @param $tableName
* @param $month
* @param $day
* @param $year
* @param $hasMaxValuePartition
*
* @throws Exception
* @return false|int
*/
private function updateAddDailyPartitions($db, $tableName, $month, $day, $year, $hasMaxValuePartition = false)
{
$current_time = mktime(0, 0, 0, $month, $day, $year);
$ntime = localtime($current_time);
$month = $ntime[4] + 1;
$day = $ntime[3];
if ($month < 10) {
$month = '0' . $month;
}
if ($day < 10) {
$day = '0' . $day;
}
$partitionQuery = 'PARTITION `p' . ($ntime[5] + 1900) . $month . $day
. '` VALUES LESS THAN(' . $current_time . ')';
$request = 'ALTER TABLE ' . $tableName . ' ';
if ($hasMaxValuePartition) {
$request .= 'REORGANIZE PARTITION `pmax` INTO ('
. $partitionQuery
. ', PARTITION `pmax` VALUES LESS THAN MAXVALUE)';
} else {
$request .= 'ADD PARTITION ('
. $partitionQuery
. ')';
}
try {
$dbResult = $db->query($request);
} catch (PDOException $e) {
throw new Exception("Error: cannot add a new partition 'p" . ($ntime[5] + 1900) . $month . $day
. "' for table " . $tableName . ', ' . $e->getMessage() . "\n");
}
return $current_time;
}
/**
* @param $db
* @param $tableName
* @param $table
* @param $lastTime
*
* @throws Exception
* @return void
*/
private function updateDailyPartitions($db, $tableName, $table, $lastTime): void
{
$hasMaxValuePartition = $this->hasMaxValuePartition($db, $table);
date_default_timezone_set($table->getTimezone());
$how_much_forward = 0;
$ltime = localtime();
$currentTime = mktime(0, 0, 0, $ltime[4] + 1, $ltime[3], $ltime[5] + 1900);
// Avoid to add since 1970 if we have only pmax partition
if ($lastTime == 0) {
$lastTime = $currentTime;
}
// Gap when you have a cron not updated
while ($lastTime < $currentTime) {
$ntime = localtime($lastTime);
$lastTime = $this->updateAddDailyPartitions(
$db,
$tableName,
$ntime[4] + 1,
$ntime[3] + 1,
$ntime[5] + 1900,
$hasMaxValuePartition
);
}
while ($currentTime < $lastTime) {
$how_much_forward++;
$currentTime = mktime(0, 0, 0, $ltime[4] + 1, $ltime[3] + $how_much_forward, $ltime[5] + 1900);
}
$num_days_forward = $table->getRetentionForward();
while ($how_much_forward < $num_days_forward) {
$this->updateAddDailyPartitions(
$db,
$tableName,
$ltime[4] + 1,
$ltime[3] + $how_much_forward + 1,
$ltime[5] + 1900,
$hasMaxValuePartition
);
$how_much_forward++;
}
if (! $hasMaxValuePartition) {
$this->createMaxvaluePartition($db, $tableName, $table);
}
}
/**
* Generate query part to build partitions
*
* @param MysqlTable $table The table to partition
* @param bool $createPastPartitions If the past partitions need to be created
*
* @return string The built partitions query
*/
private function createDailyPartitions($table, $createPastPartitions): string
{
date_default_timezone_set($table->getTimezone());
$ltime = localtime();
$createPart = ' PARTITION BY RANGE(' . $table->getColumn() . ') (';
// Create past partitions if needed (not needed in fresh install)
$num_days = ($createPastPartitions === true) ? $table->getRetention() : 0;
$append = '';
while ($num_days >= 0) {
$current_time = mktime(0, 0, 0, $ltime[4] + 1, $ltime[3] - $num_days, $ltime[5] + 1900);
$ntime = localtime($current_time);
$month = $ntime[4] + 1;
$day = $ntime[3];
if ($month < 10) {
$month = '0' . $month;
}
if ($day < 10) {
$day = '0' . $day;
}
$createPart .= $append . 'PARTITION p' . ($ntime[5] + 1900)
. $month . $day . ' VALUES LESS THAN (' . $current_time . ')';
$num_days--;
$append = ',';
}
// Create future partitions
$num_days_forward = $table->getRetentionForward();
$count = 1;
while ($count <= $num_days_forward) {
$current_time = mktime(0, 0, 0, $ltime[4] + 1, $ltime[3] + $count, $ltime[5] + 1900);
$ntime = localtime($current_time);
$month = $ntime[4] + 1;
$day = $ntime[3];
if ($month < 10) {
$month = '0' . $month;
}
if ($day < 10) {
$day = '0' . $day;
}
$createPart .= $append . 'PARTITION p' . ($ntime[5] + 1900)
. $month . $day . ' VALUES LESS THAN (' . $current_time . ')';
$append = ',';
$count++;
}
$createPart .= ');';
return $createPart;
}
/**
* Get last part range max value
*
* @param $table
* @param $db
*
* @throws Exception
* @return int|string
*/
private function getLastPartRange($table, $db)
{
$error = false;
try {
$dbResult = $db->query(
'SHOW CREATE TABLE `' . $table->getSchema() . '`.`' . $table->getName() . '`'
);
} catch (PDOException $e) {
$error = true;
}
if ($error || ! $dbResult->rowCount()) {
throw new Exception(
'Error: cannot get table ' . $table->getSchema() . '.' . $table->getName()
. " last partition range \n"
);
}
$row = $dbResult->fetch();
$lastPart = 0;
// dont care of MAXVALUE
if (preg_match_all('/PARTITION (.*?) VALUES LESS THAN \(([0-9]+?)\)/', $row['Create Table'], $matches)) {
for ($i = 0; isset($matches[2][$i]); $i++) {
if ($matches[2][$i] > $lastPart) {
$lastPart = $matches[2][$i];
}
}
}
return $lastPart;
}
/**
* Check if a table has max value partition.
*
* @param $db
* @param $table
*
* @throws Exception
* @return bool
*/
private function hasMaxValuePartition($db, $table): bool
{
// Check if we need to create it
try {
$dbResult = $db->query('SHOW CREATE TABLE `' . $table->getSchema() . '`.`' . $table->getName() . '`');
} catch (PDOException $e) {
throw new Exception(
'Error : Cannot get partition maxvalue information for table '
. $table->getName() . ', ' . $e->getMessage() . "\n"
);
}
if ($row = $dbResult->fetch()) {
if (preg_match('/PARTITION.*?pmax/', $row['Create Table']) === 1) {
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/class/centreon-partition/mysqlTable.class.php | centreon/www/class/centreon-partition/mysqlTable.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 MysqlTable
* @descrfiption Class that handles properties to create partitions for a table
* @category Database
* @package Centreon
* @author qgarnier <qgarnier@centreon.com>
* @license GPL http://www.gnu.org/licenses
* @see http://www.centreon.com
*/
class MysqlTable
{
/** @var string|null */
public $type = null;
/** @var CentreonDB */
private $db;
/** @var string|null */
private $name = null;
/** @var string|null */
private $schema = null;
/** @var int */
private $activate = 1;
/** @var string|null */
private $column = null;
/** @var string|null */
private $duration = null;
/** @var string|null */
private $timezone = null;
/** @var int|null */
private $retention = null;
/** @var int|null */
private $retentionforward = null;
/** @var string|null */
private $createstmt = null;
/** @var string|null */
private $backupFolder = null;
/** @var string|null */
private $backupFormat = null;
/**
* Class constructor
*
* @param CentreonDB $DBobj the centreon database
* @param string $tableName the database table name
* @param string $schema the schema
*/
public function __construct($DBobj, $tableName, $schema)
{
$this->db = $DBobj;
$this->setName($tableName);
$this->setSchema($schema);
}
/**
* Get table name
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Get table schema
*
* @return string
*/
public function getSchema()
{
return $this->schema;
}
/**
* Set partitioning activation flag
*
* @param int $activate the activate integer
*
* @return null
*/
public function setActivate($activate): void
{
if (isset($activate) && is_numeric($activate)) {
$this->activate = $activate;
}
}
/**
* Get activate value
*
* @return int
*/
public function getActivate()
{
return $this->activate;
}
/**
* Set partitioning column name
*
* @param string $column the column name
*
* @return null
*/
public function setColumn($column): void
{
if (isset($column) && $column != '') {
$this->column = $column;
}
}
/**
* Get column value
*
* @return string|null
*/
public function getColumn()
{
return $this->column;
}
/**
* Set partitioning timezone
*
* @param string $timezone the timezone
*
* @return null
*/
public function setTimezone($timezone): void
{
$this->timezone = isset($timezone) && $timezone != '' ? $timezone : date_default_timezone_get();
}
/**
* Get timezone value
*
* @return string|null
*/
public function getTimezone()
{
return $this->timezone;
}
/**
* Set partitioning column type
*
* @param string $type the type
*
* @throws Exception
* @return void
*/
public function setType($type): void
{
if (isset($type) && ($type == 'date')) {
$this->type = $type;
} else {
throw new Exception(
'Config Error: Wrong type format for table '
. $this->schema . '.' . $this->name . "\n"
);
}
}
/**
* Get partitioning column type
*
* @return string|null
*/
public function getType()
{
return $this->type;
}
/**
* Set partition range
*
* @param string $duration the duration
*
* @throws Exception
* @return null
*/
public function setDuration($duration): void
{
if (isset($duration) && ($duration != 'daily')) {
throw new Exception(
'Config Error: Wrong duration format for table '
. $this->schema . '.' . $this->name . "\n"
);
}
$this->duration = $duration;
}
/**
* Get partition range
*
* @return string|null
*/
public function getDuration()
{
return $this->duration;
}
/**
* Set partitioning create table
*
* @param string $createstmt the statement
*
* @return null
*/
public function setCreateStmt($createstmt): void
{
if (isset($createstmt) && $createstmt != '') {
$this->createstmt = str_replace(';', '', $createstmt);
}
}
/**
* Get create table value
*
* @return string|null
*/
public function getCreateStmt()
{
return $this->createstmt;
}
/**
* Set partition backup folder
*
* @param string $backupFolder the backup folder
*
* @return null
*/
public function setBackupFolder($backupFolder): void
{
if (isset($backupFolder) || $backupFolder != '') {
$this->backupFolder = $backupFolder;
}
}
/**
* Get partition backup folder
*
* @return string|null
*/
public function getBackupFolder()
{
return $this->backupFolder;
}
/**
* Set partition backup file name format
*
* @param string $backupFormat the backup format
*
* @return null
*/
public function setBackupFormat($backupFormat): void
{
if (isset($backupFormat) || $backupFormat != '') {
$this->backupFormat = $backupFormat;
}
}
/**
* Get partition backup file name format
*
* @return string|null
*/
public function getBackupFormat()
{
return $this->backupFormat;
}
/**
* Set partitions retention value
*
* @param int $retention the retention
*
* @throws Exception
* @return null
*/
public function setRetention($retention): void
{
if (isset($retention) && is_numeric($retention)) {
$this->retention = $retention;
} else {
throw new Exception(
'Config Error: Wrong format of retention value for table '
. $this->schema . '.' . $this->name . "\n"
);
}
}
/**
* Get retention value
*
* @return int|null
*/
public function getRetention()
{
return $this->retention;
}
/**
* Set partitions retention forward value
*
* @param int $retentionforward the retention forward
*
* @throws Exception
* @return void
*/
public function setRetentionForward($retentionforward): void
{
if (isset($retentionforward) && is_numeric($retentionforward)) {
$this->retentionforward = $retentionforward;
} else {
throw new Exception(
'Config Error: Wrong format of retention forward value for table '
. $this->schema . '.' . $this->name . "\n"
);
}
}
/**
* Get retention forward value
*
* @return int|null
*/
public function getRetentionForward()
{
return $this->retentionforward;
}
/**
* Check if table properties are all set
*
* @return bool
*/
public function isValid()
{
// Condition to mod with new version
return ! (
is_null($this->name) || is_null($this->column)
|| is_null($this->activate) || is_null($this->duration)
|| is_null($this->schema) || is_null($this->retention)
|| is_null($this->type) || is_null($this->createstmt)
);
}
/**
* Check if table exists in database
*
* @throws Exception
* @return bool
*/
public function exists()
{
try {
$DBRESULT = $this->db->query('use `' . $this->schema . '`');
} catch (PDOException $e) {
throw new Exception(
'SQL Error: Cannot use database '
. $this->schema . ',' . $e->getMessage() . "\n"
);
return false;
}
try {
$DBRESULT = $this->db->query("show tables like '" . $this->name . "'");
} catch (PDOException $e) {
throw new Exception(
'SQL Error: Cannot execute query,'
. $e->getMessage() . "\n"
);
return false;
}
return ! (! $DBRESULT->rowCount());
}
/**
* Check of column exists in table
*
* @throws Exception
* @return bool
*/
public function columnExists()
{
try {
$DBRESULT = $this->db->query(
'describe ' . $this->schema . '.' . $this->name
);
} catch (PDOException $e) {
throw new Exception(
'SQL query error : ' . $e->getMessage() . "\n"
);
}
$found = false;
while ($row = $DBRESULT->fetchRow()) {
if ($row['Field'] == $this->column) {
$found = true;
break;
}
}
return ! (! $found);
}
/**
* Set table name
*
* @param string $name the name
*
* @return null
*/
private function setName($name): void
{
$this->name = isset($name) && $name != '' ? $name : null;
}
/**
* Set table schema
*
* @param string $schema the schema
*
* @return null
*/
private function setSchema($schema): void
{
$this->schema = isset($schema) && $schema != '' ? $schema : null;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/utils/HtmlSanitizer.php | centreon/www/class/utils/HtmlSanitizer.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
/**
* Class
*
* @class HtmlSanitizer
*/
final class HtmlSanitizer
{
/**
* HtmlSanitizer constructor
*
* @param string $string
*/
private function __construct(private string $string)
{
}
/**
* @param string $string
*
* @return HtmlSanitizer
*/
public static function createFromString(string $string): self
{
return new self($string);
}
/**
* @return HtmlSanitizer
*/
public function sanitize(): self
{
$this->string = htmlspecialchars($this->string, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
return $this;
}
/**
* @param array|null $allowedTags
*
* @return HtmlSanitizer
*/
public function removeTags(?array $allowedTags = null): self
{
$this->string = strip_tags($this->string, $allowedTags);
return $this;
}
/**
* @return string
*/
public function getString(): string
{
return $this->string;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate-remote/Curves.php | centreon/www/class/config-generate-remote/Curves.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace ConfigGenerateRemote;
use ConfigGenerateRemote\Abstracts\AbstractObject;
use PDO;
/**
* Class
*
* @class Curves
* @package ConfigGenerateRemote
*/
class Curves extends AbstractObject
{
/** @var string */
protected $table = 'giv_components_template';
/** @var string */
protected $generateFilename = 'giv_components_template.infile';
/** @var string */
protected $attributesSelect = '
compo_id,
host_id,
service_id,
name,
ds_order,
ds_hidecurve,
ds_name,
ds_color_line,
ds_color_line_mode,
ds_color_area,
ds_color_area_warn,
ds_color_area_crit,
ds_filled,
ds_max,
ds_min,
ds_minmax_int,
ds_average,
ds_last,
ds_total,
ds_tickness,
ds_transparency,
ds_invert,
ds_legend,
ds_jumpline,
ds_stack,
default_tpl1,
comment
';
/** @var string[] */
protected $attributesWrite = [
'compo_id',
'host_id',
'service_id',
'name',
'ds_order',
'ds_hidecurve',
'ds_name',
'ds_color_line',
'ds_color_line_mode',
'ds_color_area',
'ds_color_area_warn',
'ds_color_area_crit',
'ds_filled',
'ds_max',
'ds_min',
'ds_minmax_int',
'ds_average',
'ds_last',
'ds_total',
'ds_tickness',
'ds_transparency',
'ds_invert',
'ds_legend',
'ds_jumpline',
'ds_stack',
'default_tpl1',
'comment',
];
/** @var array|null */
private $curves = null;
/**
* Generate curves
*
* @throws \Exception
* @return void
*/
public function generateObjects(): void
{
if (is_null($this->curves)) {
$this->getCurves();
}
$instanceService = Service::getInstance($this->dependencyInjector);
foreach ($this->curves as $id => $value) {
if ($this->checkGenerate($id)) {
continue;
}
if (is_null($value['service_id'])
|| $instanceService->checkGenerate($value['host_id'] . '.' . $value['service_id'])) {
$value['compo_id'] = $id;
$this->generateObjectInFile($value, $id);
}
}
}
/**
* Get curves
*
* @return void
*/
private function getCurves(): void
{
$stmt = $this->backendInstance->db->prepare(
"SELECT {$this->attributesSelect}
FROM giv_components_template"
);
$stmt->execute();
$this->curves = $stmt->fetchAll(PDO::FETCH_GROUP | PDO::FETCH_UNIQUE | PDO::FETCH_ASSOC);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate-remote/Command.php | centreon/www/class/config-generate-remote/Command.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace ConfigGenerateRemote;
use ConfigGenerateRemote\Abstracts\AbstractObject;
use PDO;
/**
* Class
*
* @class Command
* @package ConfigGenerateRemote
*/
class Command extends AbstractObject
{
/** @var string */
protected $table = 'command';
/** @var string */
protected $generateFilename = 'commands.infile';
/** @var string */
protected $attributesSelect = '
command_id,
command_name,
command_line,
command_type,
enable_shell,
graph_id
';
/** @var string[] */
protected $attributesWrite = [
'command_id',
'command_name',
'command_line',
'command_type',
'enable_shell',
'graph_id',
];
/** @var array|null */
private $commands = null;
/**
* Generate command and get command name
*
* @param null|int $commandId
*
* @throws \Exception
* @return string|null
*/
public function generateFromCommandId(?int $commandId): ?string
{
if (is_null($this->commands)) {
$this->getCommands();
}
if (! isset($this->commands[$commandId])) {
return null;
}
if ($this->checkGenerate($commandId)) {
return $this->commands[$commandId]['command_name'];
}
Graph::getInstance($this->dependencyInjector)->getGraphFromId($this->commands[$commandId]['graph_id']);
$this->commands[$commandId]['command_id'] = $commandId;
$this->generateObjectInFile(
$this->commands[$commandId],
$commandId
);
return $this->commands[$commandId]['command_name'];
}
/**
* Get commands
*
* @return void
*/
private function getCommands(): void
{
$query = "SELECT {$this->attributesSelect} FROM command";
$stmt = $this->backendInstance->db->prepare($query);
$stmt->execute();
$this->commands = $stmt->fetchAll(PDO::FETCH_GROUP | PDO::FETCH_UNIQUE | PDO::FETCH_ASSOC);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate-remote/TimePeriod.php | centreon/www/class/config-generate-remote/TimePeriod.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace ConfigGenerateRemote;
use ConfigGenerateRemote\Abstracts\AbstractObject;
use Exception;
use PDO;
/**
* Class
*
* @class TimePeriod
* @package ConfigGenerateRemote
*/
class TimePeriod extends AbstractObject
{
/** @var string */
protected $table = 'timeperiod';
/** @var string */
protected $generateFilename = 'timeperiods.infile';
/** @var string */
protected $attributesSelect = '
tp_id,
tp_name,
tp_alias,
tp_sunday,
tp_monday,
tp_tuesday,
tp_wednesday,
tp_thursday,
tp_friday,
tp_saturday
';
/** @var string[] */
protected $attributesWrite = [
'tp_id',
'tp_name',
'tp_alias',
'tp_sunday',
'tp_monday',
'tp_tuesday',
'tp_wednesday',
'tp_thursday',
'tp_friday',
'tp_saturday',
];
/** @var null[] */
protected $stmtExtend = [
'include' => null,
'exclude' => null,
];
/** @var null */
private $timeperiods = null;
/**
* Build cache of timeperiods
*
* @return void
*/
public function getTimeperiods(): void
{
$query = "SELECT {$this->attributesSelect} FROM timeperiod";
$stmt = $this->backendInstance->db->prepare($query);
$stmt->execute();
$this->timeperiods = $stmt->fetchAll(PDO::FETCH_GROUP | PDO::FETCH_UNIQUE | PDO::FETCH_ASSOC);
}
/**
* Generate timeperiod from id
*
* @param null|int $timeperiodId
*
* @throws Exception
* @return null|string
*/
public function generateFromTimeperiodId(?int $timeperiodId)
{
if (is_null($timeperiodId)) {
return null;
}
if (is_null($this->timeperiods)) {
$this->getTimeperiods();
}
if (! isset($this->timeperiods[$timeperiodId])) {
return null;
}
if ($this->checkGenerate($timeperiodId)) {
return $this->timeperiods[$timeperiodId]['tp_name'];
}
$this->getTimeperiodExceptionFromId($timeperiodId);
$this->timeperiods[$timeperiodId]['tp_id'] = $timeperiodId;
$this->generateObjectInFile($this->timeperiods[$timeperiodId], $timeperiodId);
return $this->timeperiods[$timeperiodId]['tp_name'];
}
/**
* Get timeperiod exceptions from id
*
* @param int $timeperiodId
* @return void|int
*/
protected function getTimeperiodExceptionFromId(int $timeperiodId)
{
if (isset($this->timeperiods[$timeperiodId]['exceptions'])) {
return 1;
}
$query = 'SELECT days, timerange FROM timeperiod_exceptions WHERE timeperiod_id = :timeperiodId';
$stmt = $this->backendInstance->db->prepare($query);
$stmt->bindParam(':timeperiodId', $timeperiodId, PDO::PARAM_INT);
$stmt->execute();
$exceptions = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($exceptions as $exception) {
$exception['timeperiod_id'] = $timeperiodId;
Relations\TimePeriodExceptions::getInstance($this->dependencyInjector)->add($exception, $timeperiodId);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate-remote/Graph.php | centreon/www/class/config-generate-remote/Graph.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace ConfigGenerateRemote;
use ConfigGenerateRemote\Abstracts\AbstractObject;
use PDO;
/**
* Class
*
* @class Graph
* @package ConfigGenerateRemote
*/
class Graph extends AbstractObject
{
/** @var string */
protected $table = 'giv_graphs_template';
/** @var string */
protected $generateFilename = 'graph.infile';
/** @var string */
protected $attributesSelect = '
graph_id,
name,
vertical_label,
width,
height,
base,
lower_limit,
upper_limit,
size_to_max,
default_tpl1,
stacked,
split_component,
scaled,
comment
';
/** @var string[] */
protected $attributesWrite = [
'graph_id',
'name',
'vertical_label',
'width',
'height',
'base',
'lower_limit',
'upper_limit',
'size_to_max',
'default_tpl1',
'stacked',
'split_component',
'scaled',
'comment',
];
/** @var array|null */
private $graphs = null;
/**
* Generate and get graph from id
*
* @param null|int $graphId
*
* @throws \Exception
* @return string|null
*/
public function getGraphFromId(?int $graphId)
{
if (is_null($this->graphs)) {
$this->getGraph();
}
$result = null;
if (! is_null($graphId) && isset($this->graphs[$graphId])) {
$result = $this->graphs[$graphId]['name'];
if ($this->checkGenerate($graphId)) {
return $result;
}
$this->generateObjectInFile($this->graphs[$graphId], $graphId);
}
return $result;
}
/**
* Get graph
*
* @return void
*/
private function getGraph(): void
{
$stmt = $this->backendInstance->db->prepare(
"SELECT {$this->attributesSelect}
FROM giv_graphs_template"
);
$stmt->execute();
$this->graphs = $stmt->fetchAll(PDO::FETCH_GROUP | PDO::FETCH_UNIQUE | PDO::FETCH_ASSOC);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate-remote/PlatformTopology.php | centreon/www/class/config-generate-remote/PlatformTopology.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace ConfigGenerateRemote;
use Centreon\Domain\PlatformTopology\Model\PlatformRegistered;
use ConfigGenerateRemote\Abstracts\AbstractObject;
use Exception;
use PDO;
use PDOStatement;
/**
* Class
*
* @class PlatformTopology
* @package ConfigGenerateRemote
*/
class PlatformTopology extends AbstractObject
{
/** @var string */
protected $table = 'platform_topology';
/** @var string */
protected $generateFilename = 'platform_topology.infile';
/** @var string */
protected $attributesSelect = '
id,
address,
hostname,
name,
type,
parent_id,
server_id
';
/** @var string[] */
protected $attributesWrite = [
'id',
'address',
'hostname',
'name',
'type',
'parent_id',
'server_id',
];
/** @var PDOStatement */
protected $stmtPlatformTopology = null;
/**
* Generate topology configuration from remote server id
*
* @param int $remoteServerId
*
* @throws Exception
* @return void
*/
public function generateFromRemoteServerId(int $remoteServerId): void
{
$this->generate($remoteServerId);
}
/**
* Generate topology configuration from remote server id
*
* @param int $remoteServerId
*
* @throws Exception
* @return void
*/
private function generate(int $remoteServerId): void
{
if (is_null($this->stmtPlatformTopology)) {
$this->stmtPlatformTopology = $this->backendInstance->db->prepare(
"SELECT {$this->attributesSelect} FROM platform_topology
WHERE server_id = :poller_id
OR parent_id = (SELECT id FROM platform_topology WHERE server_id = :poller_id )"
);
}
$this->stmtPlatformTopology->bindParam(':poller_id', $remoteServerId, PDO::PARAM_INT);
$this->stmtPlatformTopology->execute();
$result = $this->stmtPlatformTopology->fetchAll(PDO::FETCH_ASSOC);
foreach ($result as $entry) {
if ($entry['type'] === PlatformRegistered::TYPE_REMOTE) {
$entry['parent_id'] = null;
}
$this->generateObjectInFile($entry);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate-remote/Trap.php | centreon/www/class/config-generate-remote/Trap.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace ConfigGenerateRemote;
use ConfigGenerateRemote\Abstracts\AbstractObject;
use Exception;
use PDO;
use Pimple\Container;
/**
* Class
*
* @class Trap
* @package ConfigGenerateRemote
*/
class Trap extends AbstractObject
{
/** @var string */
protected $table = 'traps';
/** @var string */
protected $generateFilename = 'traps.infile';
/** @var null */
protected $stmtService = null;
/** @var string[] */
protected $attributesWrite = [
'traps_id',
'traps_name',
'traps_oid',
'traps_args',
'traps_status',
'severity_id',
'manufacturer_id',
'traps_reschedule_svc_enable',
'traps_execution_command',
'traps_execution_command_enable',
'traps_submit_result_enable',
'traps_advanced_treatment',
'traps_advanced_treatment_default',
'traps_timeout',
'traps_exec_interval',
'traps_exec_interval_type',
'traps_log',
'traps_routing_mode',
'traps_routing_value',
'traps_routing_filter_services',
'traps_exec_method',
'traps_downtime',
'traps_output_transform',
'traps_customcode',
'traps_comments',
];
/** @var int */
private $useCache = 1;
/** @var int */
private $doneCache = 0;
/** @var array */
private $trapCache = [];
/** @var array */
private $serviceLinkedCache = [];
/**
* Trap constructor
*
* @param Container $dependencyInjector
*/
public function __construct(Container $dependencyInjector)
{
parent::__construct($dependencyInjector);
$this->buildCache();
}
/**
* Generate trap and relations
*
* @param int $serviceId
* @param array $serviceLinkedCache
* @param array $object
*
* @throws Exception
* @return void
*/
public function generateObject(int $serviceId, array $serviceLinkedCache, array &$object): void
{
foreach ($serviceLinkedCache as $trapId) {
Relations\TrapsServiceRelation::getInstance($this->dependencyInjector)->addRelation($trapId, $serviceId);
if ($this->checkGenerate($trapId)) {
continue;
}
$this->generateObjectInFile($object[$trapId], $trapId);
Relations\TrapsVendor::getInstance($this->dependencyInjector)->add(
$object[$trapId]['id'],
$object[$trapId]['name'],
$object[$trapId]['alias'],
$object[$trapId]['description']
);
Relations\TrapsGroup::getInstance($this->dependencyInjector)->getTrapGroupsByTrapId($trapId);
Relations\TrapsMatching::getInstance($this->dependencyInjector)->getTrapMatchingByTrapId($trapId);
Relations\TrapsPreexec::getInstance($this->dependencyInjector)->getTrapPreexecByTrapId($trapId);
ServiceCategory::getInstance($this->dependencyInjector)->generateObject($object[$trapId]['severity_id']);
}
}
/**
* Get service linked traps
*
* @param int $serviceId
*
* @throws Exception
* @return null|array
*/
public function getTrapsByServiceId(int $serviceId)
{
// Get from the cache
if (isset($this->serviceLinkedCache[$serviceId])) {
$this->generateObject($serviceId, $this->serviceLinkedCache[$serviceId], $this->trapCache);
return $this->serviceLinkedCache[$serviceId];
}
if ($this->useCache == 1) {
return null;
}
// We get unitary
if (is_null($this->stmtService)) {
$this->stmtService = $this->backendInstance->db->prepare(
'SELECT traps.*, traps_service_relation.service_id
FROM traps_service_relation, traps
LEFT JOIN traps_vendor ON traps_vendor.id = traps.manufacturer_id
WHERE traps_service_relation.service_id = :service_id
AND traps_service_relation.traps_id = traps.traps_id'
);
}
$this->stmtService->bindParam(':service_id', $serviceId, PDO::PARAM_INT);
$this->stmtService->execute();
$serviceLinkedCache = [];
$trapCache = [];
foreach ($this->stmtService->fetchAll(PDO::FETCH_ASSOC) as &$value) {
$serviceLinkedCache[] = $value['traps_id'];
$trapCache[$value['traps_id']] = $value;
}
$this->generateObject($serviceId, $serviceLinkedCache, $trapCache);
return $serviceLinkedCache;
}
/**
* Build cache of traps
*
* @return void
*/
private function cacheTrap(): void
{
$stmt = $this->backendInstance->db->prepare(
'SELECT * FROM traps
LEFT JOIN traps_vendor ON traps_vendor.id = traps.manufacturer_id'
);
$stmt->execute();
$values = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($values as &$value) {
$this->trapCache[$value['traps_id']] = &$value;
}
}
/**
* Build cache of relations between service and trap
*
* @return void
*/
private function cacheTrapLinked(): void
{
$stmt = $this->backendInstance->db->prepare(
'SELECT traps_id, service_id
FROM traps_service_relation'
);
$stmt->execute();
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $value) {
if (! isset($this->serviceLinkedCache[$value['service_id']])) {
$this->serviceLinkedCache[$value['service_id']] = [];
}
$this->serviceLinkedCache[$value['service_id']][] = $value['traps_id'];
}
}
/**
* Build cache
*
* @return void|int
*/
private function buildCache()
{
if ($this->doneCache == 1) {
return 0;
}
$this->cacheTrap();
$this->cacheTrapLinked();
$this->doneCache = 1;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate-remote/Broker.php | centreon/www/class/config-generate-remote/Broker.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace ConfigGenerateRemote;
use ConfigGenerateRemote\Abstracts\AbstractObject;
use Exception;
use PDO;
use PDOStatement;
/**
* Class
*
* @class Broker
* @package ConfigGenerateRemote
*/
class Broker extends AbstractObject
{
/** @var PDOStatement|null */
public $stmtEngine;
/** @var string */
protected $table = 'cfg_centreonbroker';
/** @var string */
protected $generateFilename = 'cfg_centreonbroker.infile';
/** @var string */
protected $attributesSelect = '
config_id,
config_name,
config_filename,
config_write_timestamp,
config_write_thread_id,
config_activate,
ns_nagios_server,
event_queue_max_size,
event_queues_total_size,
command_file,
cache_directory,
stats_activate,
daemon,
pool_size
';
/** @var string[] */
protected $attributesWrite = [
'config_id',
'config_name',
'config_filename',
'config_write_timestamp',
'config_write_thread_id',
'config_activate',
'ns_nagios_server',
'event_queue_max_size',
'event_queues_total_size',
'command_file',
'cache_directory',
'stats_activate',
'daemon',
'pool_size',
];
/** @var PDOStatement|null */
protected $stmtBroker = null;
/**
* Generate engine configuration from poller
*
* @param array $poller
*
* @throws Exception
* @return void
*/
public function generateFromPoller(array $poller): void
{
Resource::getInstance($this->dependencyInjector)->generateFromPollerId($poller['id']);
$this->generate($poller['id']);
}
/**
* Generate broker configuration from poller id
*
* @param int $pollerId
*
* @throws Exception
* @return void
*/
private function generate(int $pollerId): void
{
if (is_null($this->stmtEngine)) {
$this->stmtBroker = $this->backendInstance->db->prepare(
"SELECT {$this->attributesSelect} FROM cfg_centreonbroker "
. "WHERE ns_nagios_server = :poller_id AND config_activate = '1'"
);
}
$this->stmtBroker->bindParam(':poller_id', $pollerId, PDO::PARAM_INT);
$this->stmtBroker->execute();
$results = $this->stmtBroker->fetchAll(PDO::FETCH_ASSOC);
foreach ($results as $row) {
Relations\BrokerInfo::getInstance($this->dependencyInjector)->getBrokerInfoByConfigId($row['config_id']);
$this->generateObjectInFile(
$row,
$row['config_id']
);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate-remote/ContactGroup.php | centreon/www/class/config-generate-remote/ContactGroup.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace ConfigGenerateRemote;
use ConfigGenerateRemote\Abstracts\AbstractObject;
use PDO;
use PDOStatement;
/**
* Class
*
* @class ContactGroup
* @package ConfigGenerateRemote
*/
class ContactGroup extends AbstractObject
{
/** @var int */
protected $useCache = 1;
/** @var array */
protected $cgCache = [];
/** @var array|null */
protected $cg = null;
/** @var string */
protected $table = 'contactgroup';
/** @var string */
protected $generateFilename = 'contactgroups.infile';
/** @var string */
protected $attributesSelect = '
cg_id,
cg_name,
cg_alias,
cg_comment
';
/** @var string[] */
protected $attributesWrite = [
'cg_id',
'cg_name',
'cg_alias',
'cg_comment',
];
/** @var PDOStatement|null */
protected $stmtCg = null;
/** @var PDOStatement|null */
protected $stmtContact = null;
/** @var PDOStatement|null */
protected $stmtCgService = null;
/** @var int */
private $doneCache = 0;
/** @var array */
private $cgServiceLinkedCache = [];
/**
* Get service linked contact groups
*
* @param int $serviceId
* @return array
*/
public function getCgForService(int $serviceId): array
{
$this->buildCache();
// Get from the cache
if (isset($this->cgServiceLinkedCache[$serviceId])) {
return $this->cgServiceLinkedCache[$serviceId];
}
if ($this->doneCache == 1) {
return [];
}
if (is_null($this->stmtCgService)) {
$this->stmtCgService = $this->backendInstance->db->prepare('SELECT
contactgroup_cg_id
FROM contactgroup_service_relation
WHERE service_service_id = :service_id
');
}
$this->stmtCgService->bindParam(':service_id', $serviceId, PDO::PARAM_INT);
$this->stmtCgService->execute();
$this->cgServiceLinkedCache[$serviceId] = $this->stmtCgService->fetchAll(PDO::FETCH_COLUMN);
return $this->cgServiceLinkedCache[$serviceId];
}
/**
* Get contact group information
*
* @param int $cgId
* @return void
*/
public function getCgFromId(int $cgId)
{
if (is_null($this->stmtCg)) {
$this->stmtCg = $this->backendInstance->db->prepare(
"SELECT {$this->attributesSelect}
FROM contactgroup
WHERE cg_id = :cg_id AND cg_activate = '1'"
);
}
$this->stmtCg->bindParam(':cg_id', $cgId, PDO::PARAM_INT);
$this->stmtCg->execute();
$results = $this->stmtCg->fetchAll(PDO::FETCH_ASSOC);
$this->cg[$cgId] = array_pop($results);
return $this->cg[$cgId];
}
/**
* Get contact group linked contacts
*
* @param int $cgId
* @return void
*/
public function getContactFromCgId(int $cgId): void
{
if (! isset($this->cg[$cgId]['members_cache'])) {
if (is_null($this->stmtContact)) {
$this->stmtContact = $this->backendInstance->db->prepare(
'SELECT contact_contact_id
FROM contactgroup_contact_relation
WHERE contactgroup_cg_id = :cg_id'
);
}
$this->stmtContact->bindParam(':cg_id', $cgId, PDO::PARAM_INT);
$this->stmtContact->execute();
$this->cg[$cgId]['members_cache'] = $this->stmtContact->fetchAll(PDO::FETCH_COLUMN);
}
$contact = Contact::getInstance($this->dependencyInjector);
foreach ($this->cg[$cgId]['members_cache'] as $contactId) {
$contact->generateFromContactId($contactId);
}
}
/**
* Generate contact group and get contact group name
*
* @param null|int $cgId
*
* @throws \Exception
* @return void|string
*/
public function generateFromCgId(?int $cgId)
{
if (is_null($cgId)) {
return null;
}
$this->buildCache();
if ($this->useCache == 1) {
if (! isset($this->cgCache[$cgId])) {
return null;
}
$this->cg[$cgId] = &$this->cgCache[$cgId];
} elseif (! isset($this->cg[$cgId])) {
$this->getCgFromId($cgId);
}
if (is_null($this->cg[$cgId])) {
return null;
}
if ($this->checkGenerate($cgId)) {
return $this->cg[$cgId]['cg_name'];
}
$this->getContactFromCgId($cgId);
$this->cg[$cgId]['cg_id'] = $cgId;
$this->generateObjectInFile($this->cg[$cgId], $cgId);
return $this->cg[$cgId]['cg_name'];
}
/**
* Generate contact group cache
*
* @return void
*/
protected function getCgCache(): void
{
$stmt = $this->backendInstance->db->prepare(
"SELECT {$this->attributesSelect}
FROM contactgroup
WHERE cg_activate = '1'"
);
$stmt->execute();
$this->cgCache = $stmt->fetchAll(PDO::FETCH_GROUP | PDO::FETCH_UNIQUE | PDO::FETCH_ASSOC);
}
/**
* Build cache
*
* @return void|int
*/
protected function buildCache()
{
if ($this->doneCache == 1) {
return 0;
}
$this->getCgCache();
$this->getCgForServiceCache();
$this->doneCache = 1;
}
/**
* Get contact groups linked to services
*
* @return void
*/
private function getCgForServiceCache(): void
{
$stmt = $this->backendInstance->db->prepare(
'SELECT contactgroup_cg_id, service_service_id
FROM contactgroup_service_relation'
);
$stmt->execute();
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $value) {
if (isset($this->cgServiceLinkedCache[$value['service_service_id']])) {
$this->cgServiceLinkedCache[$value['service_service_id']][] = $value['contactgroup_cg_id'];
} else {
$this->cgServiceLinkedCache[$value['service_service_id']] = [$value['contactgroup_cg_id']];
}
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate-remote/ServiceTemplate.php | centreon/www/class/config-generate-remote/ServiceTemplate.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace ConfigGenerateRemote;
use ConfigGenerateRemote\Abstracts\AbstractService;
use Exception;
use PDO;
/**
* Class
*
* @class ServiceTemplate
* @package ConfigGenerateRemote
*/
class ServiceTemplate extends AbstractService
{
/** @var */
public $loop_stpl;
/** @var array */
public $serviceCache = [];
/** @var int|null */
public $currentHostId = null;
/** @var string|null */
public $currentHostName = null;
/** @var string|null */
public $currentServiceDescription = null;
/** @var int|null */
public $currentServiceId = null;
/** @var array|null */
protected $hosts = null;
/** @var string */
protected $table = 'service';
/** @var string */
protected $generateFilename = 'serviceTemplates.infile';
/** @var array */
protected $loopTpl = [];
/** @var string */
protected $attributesSelect = '
service_id,
service_template_model_stm_id,
command_command_id,
command_command_id_arg,
timeperiod_tp_id,
timeperiod_tp_id2,
command_command_id2,
command_command_id_arg2,
service_description,
service_alias,
display_name,
service_is_volatile,
service_max_check_attempts,
service_normal_check_interval,
service_retry_check_interval,
service_active_checks_enabled,
service_passive_checks_enabled,
service_event_handler_enabled,
service_notification_interval,
service_notification_options,
service_notifications_enabled,
service_register,
esi_notes,
esi_notes_url,
esi_action_url,
esi_icon_image,
esi_icon_image_alt,
service_acknowledgement_timeout,
graph_id
';
/** @var string[] */
protected $attributesWrite = [
'service_id',
'service_template_model_stm_id',
'command_command_id',
'command_command_id_arg',
'timeperiod_tp_id',
'timeperiod_tp_id2',
'command_command_id2',
'command_command_id_arg2',
'service_description',
'service_alias',
'display_name',
'service_is_volatile',
'service_max_check_attempts',
'service_normal_check_interval',
'service_retry_check_interval',
'service_active_checks_enabled',
'service_passive_checks_enabled',
'service_event_handler_enabled',
'service_notification_interval',
'service_notification_options',
'service_notifications_enabled',
'service_register',
'service_acknowledgement_timeout',
];
/**
* Generate service template
*
* @param null|int $serviceId
*
* @throws Exception
* @return void
*/
public function generateFromServiceId(?int $serviceId)
{
if (is_null($serviceId)) {
return null;
}
if (! isset($this->serviceCache[$serviceId])) {
$this->getServiceFromId($serviceId);
}
if (is_null($this->serviceCache[$serviceId])) {
return null;
}
if ($this->checkGenerate($serviceId)) {
if (! isset($this->loopTpl[$serviceId])) {
$this->loopTpl[$serviceId] = 1;
// Need to go in only to check servicegroup <-> stpl link
$this->getServiceTemplates($this->serviceCache[$serviceId]);
$this->getServiceGroups($serviceId);
}
return $this->serviceCache[$serviceId]['service_alias'];
}
// avoid loop. we return nothing
if (isset($this->loopTpl[$serviceId])) {
return null;
}
$this->loopTpl[$serviceId] = 1;
$this->getImages($this->serviceCache[$serviceId]);
$this->getMacros($this->serviceCache[$serviceId]);
$this->getServiceTemplates($this->serviceCache[$serviceId]);
$this->getServiceCommands($this->serviceCache[$serviceId]);
$this->getServicePeriods($this->serviceCache[$serviceId]);
$this->getTraps($this->serviceCache[$serviceId]);
if ($this->backendInstance->isExportContact()) {
$this->getContactGroups($this->serviceCache[$serviceId]);
$this->getContacts($this->serviceCache[$serviceId]);
}
$this->getServiceGroups($serviceId);
$this->getSeverity($serviceId);
$extendedInformation = $this->getExtendedInformation($this->serviceCache[$serviceId]);
Relations\ExtendedServiceInformation::getInstance($this->dependencyInjector)
->add($extendedInformation, $serviceId);
Graph::getInstance($this->dependencyInjector)->getGraphFromId($extendedInformation['graph_id']);
$this->serviceCache[$serviceId]['service_id'] = $serviceId;
$this->generateObjectInFile($this->serviceCache[$serviceId], $serviceId);
return $this->serviceCache[$serviceId]['service_alias'];
}
/**
* Reset loop
*
* @return void
*/
public function resetLoop(): void
{
$this->loopTpl = [];
}
/**
* Reset object
*
* @param bool $createfile
*
* @throws Exception
* @return void
*/
public function reset($createfile = false): void
{
$this->currentHostId = null;
$this->currentHostName = null;
$this->currentServiceDescription = null;
$this->currentServiceId = null;
$this->loop_stpl = [];
parent::reset($createfile);
}
/**
* Get linked service groups and generate relations
*
* @param int $serviceId
* @return void
*/
private function getServiceGroups(int $serviceId): void
{
$host = Host::getInstance($this->dependencyInjector);
$servicegroup = ServiceGroup::getInstance($this->dependencyInjector);
$this->serviceCache[$serviceId]['sg'] = $servicegroup->getServiceGroupsForStpl($serviceId);
foreach ($this->serviceCache[$serviceId]['sg'] as &$sg) {
if ($host->isHostTemplate($this->currentHostId, $sg['host_host_id'])) {
$servicegroup->addServiceInSg(
$sg['servicegroup_sg_id'],
$this->currentServiceId,
$this->currentServiceDescription,
$this->currentHostId,
$this->currentHostName
);
Relations\ServiceGroupRelation::getInstance($this->dependencyInjector)->addRelationHostService(
$sg['servicegroup_sg_id'],
$sg['host_host_id'],
$serviceId
);
}
}
}
/**
* Get service template from id
*
* @param int $serviceId
* @return void
*/
private function getServiceFromId(int $serviceId): void
{
if (is_null($this->stmtService)) {
$this->stmtService = $this->backendInstance->db->prepare(
"SELECT {$this->attributesSelect}
FROM service
LEFT JOIN extended_service_information
ON extended_service_information.service_service_id = service.service_id
WHERE service_id = :service_id AND service_activate = '1'"
);
}
$this->stmtService->bindParam(':service_id', $serviceId, PDO::PARAM_INT);
$this->stmtService->execute();
$results = $this->stmtService->fetchAll(PDO::FETCH_ASSOC);
$this->serviceCache[$serviceId] = array_pop($results);
}
/**
* Get severity from service id
*
* @param int $serviceId
* @return void|int
*/
private function getSeverity(int $serviceId)
{
if (isset($this->serviceCache[$serviceId]['severity_id'])) {
return 0;
}
$this->serviceCache[$serviceId]['severity_id']
= ServiceCategory::getInstance($this->dependencyInjector)->getServiceSeverityByServiceId($serviceId);
if (! is_null($this->serviceCache[$serviceId]['severity_id'])) {
Relations\ServiceCategoriesRelation::getInstance($this->dependencyInjector)
->addRelation($this->serviceCache[$serviceId]['severity_id'], $serviceId);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate-remote/HostGroup.php | centreon/www/class/config-generate-remote/HostGroup.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace ConfigGenerateRemote;
use ConfigGenerateRemote\Abstracts\AbstractObject;
use PDO;
/**
* Class
*
* @class HostGroup
* @package ConfigGenerateRemote
*/
class HostGroup extends AbstractObject
{
/** @var string */
protected $table = 'hostgroup';
/** @var string */
protected $generateFilename = 'hostgroups.infile';
/** @var string */
protected $attributesSelect = '
hg_id,
hg_name,
hg_alias,
hg_icon_image,
geo_coords,
';
/** @var string[] */
protected $attributesWrite = [
'hg_id',
'hg_name',
'hg_alias',
'hg_icon_image',
'geo_coords',
];
/** @var null */
protected $stmtHg = null;
/** @var array */
private $hg = [];
/**
* Add host in host group
*
* @param int $hgId
* @param int $hostId
* @param string $hostName
*
* @throws \Exception
* @return int
*/
public function addHostInHg(int $hgId, int $hostId, string $hostName)
{
if (! isset($this->hg[$hgId])) {
$this->getHostgroupFromId($hgId);
$this->generateObjectInFile($this->hg[$hgId], $hgId);
Media::getInstance($this->dependencyInjector)->getMediaPathFromId($this->hg[$hgId]['hg_icon_image']);
}
if (is_null($this->hg[$hgId]) || isset($this->hg[$hgId]['members'][$hostId])) {
return 1;
}
$this->hg[$hgId]['members'][$hostId] = $hostName;
return 0;
}
/**
* Generate objects
*
* @throws \Exception
* @return void
*/
public function generateObjects(): void
{
foreach ($this->hg as $id => &$value) {
if (count($value['members']) == 0) {
continue;
}
$value['hostgroup_id'] = $value['hg_id'];
$this->generateObjectInFile($value, $id);
}
}
/**
* Get host groups
*
* @return array
*/
public function getHostgroups()
{
$result = [];
foreach ($this->hg as $id => &$value) {
if (is_null($value) || count($value['members']) == 0) {
continue;
}
$result[$id] = &$value;
}
return $result;
}
/**
* Reset object
*
* @param bool $createfile
*
* @throws \Exception
* @return void
*/
public function reset($createfile = false): void
{
$this->hg = [];
parent::reset($createfile);
}
/**
* Get host group attribute
*
* @param int $hgId
* @param string $attr
* @return string|null
*/
public function getString(int $hgId, string $attr)
{
return $this->hg[$hgId][$attr] ?? null;
}
/**
* Get host group from id
*
* @param int $hgId
* @return void
*/
private function getHostgroupFromId(int $hgId)
{
if (is_null($this->stmtHg)) {
$this->stmtHg = $this->backendInstance->db->prepare(
"SELECT {$this->attributesSelect}
FROM hostgroup
WHERE hg_id = :hg_id AND hg_activate = '1'"
);
}
$this->stmtHg->bindParam(':hg_id', $hgId, PDO::PARAM_INT);
$this->stmtHg->execute();
$results = $this->stmtHg->fetchAll(PDO::FETCH_ASSOC);
$this->hg[$hgId] = array_pop($results);
if (is_null($this->hg[$hgId])) {
return null;
}
$this->hg[$hgId]['members'] = [];
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate-remote/Generate.php | centreon/www/class/config-generate-remote/Generate.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace ConfigGenerateRemote;
use Exception;
use PDO;
use Pimple\Container;
// file centreon.config.php may not exist in test environment
$configFile = realpath(__DIR__ . '/../../../config/centreon.config.php');
if ($configFile !== false) {
require_once $configFile;
}
require_once __DIR__ . '/Backend.php';
require_once __DIR__ . '/Abstracts/AbstractObject.php';
require_once __DIR__ . '/HostTemplate.php';
require_once __DIR__ . '/Command.php';
require_once __DIR__ . '/TimePeriod.php';
require_once __DIR__ . '/HostGroup.php';
require_once __DIR__ . '/ServiceGroup.php';
require_once __DIR__ . '/Contact.php';
require_once __DIR__ . '/ContactGroup.php';
require_once __DIR__ . '/ServiceTemplate.php';
require_once __DIR__ . '/Service.php';
require_once __DIR__ . '/Media.php';
require_once __DIR__ . '/MacroService.php';
require_once __DIR__ . '/Host.php';
require_once __DIR__ . '/ServiceCategory.php';
require_once __DIR__ . '/Resource.php';
require_once __DIR__ . '/Engine.php';
require_once __DIR__ . '/Broker.php';
require_once __DIR__ . '/Graph.php';
require_once __DIR__ . '/Manifest.php';
require_once __DIR__ . '/HostCategory.php';
require_once __DIR__ . '/Curves.php';
require_once __DIR__ . '/Trap.php';
require_once __DIR__ . '/PlatformTopology.php';
require_once __DIR__ . '/Relations/BrokerInfo.php';
require_once __DIR__ . '/Relations/ViewImgDirRelation.php';
require_once __DIR__ . '/Relations/ViewImageDir.php';
require_once __DIR__ . '/Relations/ExtendedServiceInformation.php';
require_once __DIR__ . '/Relations/ExtendedHostInformation.php';
require_once __DIR__ . '/Relations/HostServiceRelation.php';
require_once __DIR__ . '/Relations/HostTemplateRelation.php';
require_once __DIR__ . '/Relations/MacroHost.php';
require_once __DIR__ . '/Relations/TimePeriodExceptions.php';
require_once __DIR__ . '/Relations/ContactGroupHostRelation.php';
require_once __DIR__ . '/Relations/ContactGroupServiceRelation.php';
require_once __DIR__ . '/Relations/ContactHostRelation.php';
require_once __DIR__ . '/Relations/ContactServiceRelation.php';
require_once __DIR__ . '/Relations/ContactHostCommandsRelation.php';
require_once __DIR__ . '/Relations/ContactServiceCommandsRelation.php';
require_once __DIR__ . '/Relations/HostCategoriesRelation.php';
require_once __DIR__ . '/Relations/ServiceCategoriesRelation.php';
require_once __DIR__ . '/Relations/HostGroupRelation.php';
require_once __DIR__ . '/Relations/ServiceGroupRelation.php';
require_once __DIR__ . '/Relations/TrapsServiceRelation.php';
require_once __DIR__ . '/Relations/TrapsVendor.php';
require_once __DIR__ . '/Relations/TrapsGroupRelation.php';
require_once __DIR__ . '/Relations/TrapsGroup.php';
require_once __DIR__ . '/Relations/TrapsMatching.php';
require_once __DIR__ . '/Relations/TrapsPreexec.php';
require_once __DIR__ . '/Relations/NagiosServer.php';
require_once __DIR__ . '/Relations/CfgResourceInstanceRelation.php';
/**
* Class
*
* @class Generate
* @package ConfigGenerateRemote
*/
class Generate
{
/** @var Container|null */
protected $dependencyInjector = null;
/** @var array */
private $pollerCache = [];
/** @var Backend|null */
private $backendInstance = null;
/** @var array|null */
private $currentPoller = null;
/** @var array|null */
private $installedModules = null;
/** @var array|null */
private $moduleObjects = null;
/**
* Constructor
*
* @param Container $dependencyInjector
*/
public function __construct(Container $dependencyInjector)
{
$this->dependencyInjector = $dependencyInjector;
$this->backendInstance = Backend::getInstance($this->dependencyInjector);
}
/**
* Reset linked objects
*
* @return void
*/
public function resetObjectsEngine(): void
{
Host::getInstance($this->dependencyInjector)->reset();
Service::getInstance($this->dependencyInjector)->reset();
}
/**
* Generate remote server configuration
*
* @param int $remoteServerId
* @param string $username
*
* @throws Exception
* @return void
*/
public function configRemoteServerFromId(int $remoteServerId, $username = 'unknown'): void
{
try {
$this->backendInstance->setUserName($username);
$this->backendInstance->initPath($remoteServerId);
$this->backendInstance->setPollerId($remoteServerId);
Manifest::getInstance($this->dependencyInjector)->clean();
$this->createFiles();
Manifest::getInstance($this->dependencyInjector)->addRemoteServer($remoteServerId);
$this->getPollerFromId($remoteServerId);
$this->currentPoller['localhost'] = 1;
$this->currentPoller['remote_id'] = 'NULL';
$this->currentPoller['remote_server_use_as_proxy'] = 0;
$this->configPoller($username);
Relations\NagiosServer::getInstance($this->dependencyInjector)->add($this->currentPoller, $remoteServerId);
PlatformTopology::getInstance($this->dependencyInjector)->generateFromRemoteServerId($remoteServerId);
$pollers = $this->getPollersFromRemote($remoteServerId);
foreach ($pollers as $poller) {
$poller['localhost'] = 0;
$poller['remote_id'] = 'NULL';
$poller['remote_server_use_as_proxy'] = 0;
$this->currentPoller = $poller;
$this->configPoller($username);
Relations\NagiosServer::getInstance($this->dependencyInjector)->add($poller, $poller['id']);
Manifest::getInstance($this->dependencyInjector)->addPoller($poller['id']);
}
$this->generateModuleObjects($remoteServerId);
$this->backendInstance->movePath($remoteServerId);
$this->resetObjects();
} catch (Exception $e) {
$this->resetObjects();
$this->backendInstance->cleanPath();
throw new Exception(
'Exception received : ' . $e->getMessage() . ' [file: ' . $e->getFile()
. '] [line: ' . $e->getLine() . "]\n"
);
}
}
/**
* Get installed modules
*
* @return void
*/
public function getInstalledModules()
{
if (! is_null($this->installedModules)) {
return $this->installedModules;
}
$this->installedModules = [];
$stmt = $this->backendInstance->db->prepare('SELECT name FROM modules_informations');
$stmt->execute();
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $value) {
$this->installedModules[] = $value['name'];
}
}
/**
* Get module generate objects
*
* @return void
*/
public function getModuleObjects(): void
{
$this->moduleObjects = [];
$this->getInstalledModules();
foreach ($this->installedModules as $module) {
$generateFile = __DIR__ . '/../../modules/' . $module . '/GenerateFilesRemote/Generate.php';
if (file_exists($generateFile)) {
require_once $generateFile;
$module = $this->ucFirst(['-', '_', ' '], $module);
$class = sprintf('\\%s\%s', $module, Generate::class);
if (class_exists($class)) {
$this->moduleObjects[] = $class;
}
}
}
}
/**
* Generate objects from modules
*
* @param int $remoteServerId
* @return void
*/
public function generateModuleObjects(int $remoteServerId): void
{
if (is_null($this->moduleObjects)) {
$this->getModuleObjects();
}
foreach ($this->moduleObjects as $moduleObject) {
$module = new $moduleObject($this->dependencyInjector);
$module->configRemoteServerFromId($remoteServerId);
}
}
/**
* Reset objects from modules
*
* @return void
*/
public function resetModuleObjects(): void
{
if (is_null($this->moduleObjects)) {
$this->getModuleObjects();
}
if (is_array($this->moduleObjects)) {
foreach ($this->moduleObjects as $module_object) {
$module_object::getInstance($this->dependencyInjector)->reset();
}
}
}
/**
* Reset the cache and the instance
*/
public function reset(): void
{
$this->pollerCache = [];
$this->currentPoller = null;
$this->installedModules = null;
$this->moduleObjects = null;
}
/**
* Remove delimiters and add ucfirst on following string
*
* @param array $delimiters
* @param string $string
* @return string
*/
private function ucFirst(array $delimiters, string $string): string
{
$string = str_replace($delimiters, $delimiters[0], $string);
$result = '';
foreach (explode($delimiters[0], $string) as $value) {
$result .= ucfirst($value);
}
return $result;
}
/**
* Get poller information
*
* @param int $pollerId
*
* @throws Exception
* @return void
*/
private function getPollerFromId(int $pollerId): void
{
$stmt = $this->backendInstance->db->prepare(
'SELECT * FROM nagios_server
WHERE id = :poller_id'
);
$stmt->bindParam(':poller_id', $pollerId, PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$this->currentPoller = array_pop($result);
if (is_null($this->currentPoller)) {
throw new Exception("Cannot find poller id '" . $pollerId . "'");
}
}
/**
* Get pollers information
*
* @param int $remoteId
* @return void
*/
private function getPollersFromRemote(int $remoteId)
{
$stmt = $this->backendInstance->db->prepare(
'SELECT ns1.*
FROM nagios_server AS ns1
WHERE ns1.remote_id = :remote_id
GROUP BY ns1.id
UNION
SELECT ns2.*
FROM nagios_server AS ns2
INNER JOIN rs_poller_relation AS rspr ON rspr.poller_server_id = ns2.id
AND rspr.remote_server_id = :remote_id
GROUP BY ns2.id'
);
$stmt->bindParam(':remote_id', $remoteId, PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (is_null($result)) {
$result = [];
}
return $result;
}
/**
* Generate host and engine objects
*
* @param string $username
* @return void
*/
private function configPoller($username = 'unknown'): void
{
$this->resetObjectsEngine();
Host::getInstance($this->dependencyInjector)->generateFromPollerId(
$this->currentPoller['id'],
$this->currentPoller['localhost']
);
Engine::getInstance($this->dependencyInjector)->generateFromPoller($this->currentPoller);
Broker::getInstance($this->dependencyInjector)->generateFromPoller($this->currentPoller);
}
/**
* Force to create a manifest and empty file
*
* @return void
*/
private function createFiles(): void
{
Host::getInstance($this->dependencyInjector)->reset(true, true);
Service::getInstance($this->dependencyInjector)->reset(true, true);
HostTemplate::getInstance($this->dependencyInjector)->reset(true);
ServiceGroup::getInstance($this->dependencyInjector)->reset(true);
HostTemplate::getInstance($this->dependencyInjector)->reset(true);
if ($this->backendInstance->isExportContact()) {
Contact::getInstance($this->dependencyInjector)->reset(true);
}
Command::getInstance($this->dependencyInjector)->reset(true);
Curves::getInstance($this->dependencyInjector)->reset(true);
Engine::getInstance($this->dependencyInjector)->reset(true);
Broker::getInstance($this->dependencyInjector)->reset(true);
Graph::getInstance($this->dependencyInjector)->reset(true);
HostCategory::getInstance($this->dependencyInjector)->reset(true);
HostGroup::getInstance($this->dependencyInjector)->reset(true);
MacroService::getInstance($this->dependencyInjector)->reset(true);
Media::getInstance($this->dependencyInjector)->reset(true);
Resource::getInstance($this->dependencyInjector)->reset(true);
ServiceCategory::getInstance($this->dependencyInjector)->reset(true);
ServiceTemplate::getInstance($this->dependencyInjector)->reset(true);
TimePeriod::getInstance($this->dependencyInjector)->reset(true);
Trap::getInstance($this->dependencyInjector)->reset(true);
PlatformTopology::getInstance($this->dependencyInjector)->reset(true);
Relations\BrokerInfo::getInstance($this->dependencyInjector)->reset(true);
Relations\CfgResourceInstanceRelation::getInstance($this->dependencyInjector)->reset(true);
Relations\ContactGroupHostRelation::getInstance($this->dependencyInjector)->reset(true);
Relations\ContactGroupServiceRelation::getInstance($this->dependencyInjector)->reset(true);
Relations\ContactHostcommandsRelation::getInstance($this->dependencyInjector)->reset(true);
Relations\ContactHostRelation::getInstance($this->dependencyInjector)->reset(true);
Relations\ContactServicecommandsRelation::getInstance($this->dependencyInjector)->reset(true);
Relations\ContactServiceRelation::getInstance($this->dependencyInjector)->reset(true);
Relations\ExtendedHostInformation::getInstance($this->dependencyInjector)->reset(true);
Relations\ExtendedServiceInformation::getInstance($this->dependencyInjector)->reset(true);
Relations\HostCategoriesRelation::getInstance($this->dependencyInjector)->reset(true);
Relations\HostGroupRelation::getInstance($this->dependencyInjector)->reset(true);
Relations\HostServiceRelation::getInstance($this->dependencyInjector)->reset(true);
Relations\HostTemplateRelation::getInstance($this->dependencyInjector)->reset(true);
Relations\HostPollerRelation::getInstance($this->dependencyInjector)->reset(true);
Relations\MacroHost::getInstance($this->dependencyInjector)->reset(true);
Relations\NagiosServer::getInstance($this->dependencyInjector)->reset(true);
Relations\ServiceCategoriesRelation::getInstance($this->dependencyInjector)->reset(true);
Relations\ServiceGroupRelation::getInstance($this->dependencyInjector)->reset(true);
Relations\TimePeriodExceptions::getInstance($this->dependencyInjector)->reset(true);
Relations\TrapsGroup::getInstance($this->dependencyInjector)->reset(true);
Relations\TrapsGroupRelation::getInstance($this->dependencyInjector)->reset(true);
Relations\TrapsMatching::getInstance($this->dependencyInjector)->reset(true);
Relations\TrapsPreexec::getInstance($this->dependencyInjector)->reset(true);
Relations\TrapsServiceRelation::getInstance($this->dependencyInjector)->reset(true);
Relations\TrapsVendor::getInstance($this->dependencyInjector)->reset(true);
Relations\ViewImageDir::getInstance($this->dependencyInjector)->reset(true);
Relations\ViewImgDirRelation::getInstance($this->dependencyInjector)->reset(true);
}
/**
* Reset objects
*
* @return void
*/
private function resetObjects(): void
{
Host::getInstance($this->dependencyInjector)->reset(true);
Service::getInstance($this->dependencyInjector)->reset(true);
HostTemplate::getInstance($this->dependencyInjector)->reset();
ServiceGroup::getInstance($this->dependencyInjector)->reset();
HostTemplate::getInstance($this->dependencyInjector)->reset();
Command::getInstance($this->dependencyInjector)->reset();
Contact::getInstance($this->dependencyInjector)->reset();
ContactGroup::getInstance($this->dependencyInjector)->reset();
Curves::getInstance($this->dependencyInjector)->reset();
Engine::getInstance($this->dependencyInjector)->reset();
Broker::getInstance($this->dependencyInjector)->reset();
Graph::getInstance($this->dependencyInjector)->reset();
HostCategory::getInstance($this->dependencyInjector)->reset();
HostGroup::getInstance($this->dependencyInjector)->reset();
MacroService::getInstance($this->dependencyInjector)->reset();
Media::getInstance($this->dependencyInjector)->reset();
Resource::getInstance($this->dependencyInjector)->reset();
ServiceCategory::getInstance($this->dependencyInjector)->reset();
ServiceTemplate::getInstance($this->dependencyInjector)->reset();
TimePeriod::getInstance($this->dependencyInjector)->reset();
Trap::getInstance($this->dependencyInjector)->reset();
PlatformTopology::getInstance($this->dependencyInjector)->reset();
Relations\BrokerInfo::getInstance($this->dependencyInjector)->reset();
Relations\CfgResourceInstanceRelation::getInstance($this->dependencyInjector)->reset();
Relations\ContactGroupHostRelation::getInstance($this->dependencyInjector)->reset();
Relations\ContactGroupServiceRelation::getInstance($this->dependencyInjector)->reset();
Relations\ContactHostcommandsRelation::getInstance($this->dependencyInjector)->reset();
Relations\ContactHostRelation::getInstance($this->dependencyInjector)->reset();
Relations\ContactServicecommandsRelation::getInstance($this->dependencyInjector)->reset();
Relations\ContactServiceRelation::getInstance($this->dependencyInjector)->reset();
Relations\ExtendedHostInformation::getInstance($this->dependencyInjector)->reset();
Relations\ExtendedServiceInformation::getInstance($this->dependencyInjector)->reset();
Relations\HostCategoriesRelation::getInstance($this->dependencyInjector)->reset();
Relations\HostGroupRelation::getInstance($this->dependencyInjector)->reset();
Relations\HostServiceRelation::getInstance($this->dependencyInjector)->reset();
Relations\HostTemplateRelation::getInstance($this->dependencyInjector)->reset();
Relations\HostPollerRelation::getInstance($this->dependencyInjector)->reset();
Relations\MacroHost::getInstance($this->dependencyInjector)->reset();
Relations\NagiosServer::getInstance($this->dependencyInjector)->reset();
Relations\ServiceCategoriesRelation::getInstance($this->dependencyInjector)->reset();
Relations\ServiceGroupRelation::getInstance($this->dependencyInjector)->reset();
Relations\TimePeriodExceptions::getInstance($this->dependencyInjector)->reset();
Relations\TrapsGroup::getInstance($this->dependencyInjector)->reset();
Relations\TrapsGroupRelation::getInstance($this->dependencyInjector)->reset();
Relations\TrapsMatching::getInstance($this->dependencyInjector)->reset();
Relations\TrapsPreexec::getInstance($this->dependencyInjector)->reset();
Relations\TrapsServiceRelation::getInstance($this->dependencyInjector)->reset();
Relations\TrapsVendor::getInstance($this->dependencyInjector)->reset();
Relations\ViewImageDir::getInstance($this->dependencyInjector)->reset();
Relations\ViewImgDirRelation::getInstance($this->dependencyInjector)->reset();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate-remote/Service.php | centreon/www/class/config-generate-remote/Service.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace ConfigGenerateRemote;
use ConfigGenerateRemote\Abstracts\AbstractService;
use PDO;
/**
* Class
*
* @class Service
* @package ConfigGenerateRemote
*/
class Service extends AbstractService
{
/** @var int|null */
public $pollerId = null; // for by poller cache
/** @var array|null */
protected $serviceCache = null;
/** @var string */
protected $table = 'service';
/** @var string */
protected $generateFilename = 'services.infile';
/** @var int */
private $useCache = 0;
/** @var int */
private $useCachePoller = 1;
/** @var int */
private $doneCache = 0;
/**
* Set useCache to 1
*
* @return void
*/
public function useCache(): void
{
$this->useCache = 1;
}
/**
* Add service in cache
*
* @param int $serviceId
* @param array $attr
* @return void
*/
public function addServiceCache(int $serviceId, array $attr = []): void
{
$this->serviceCache[$serviceId] = $attr;
}
/**
* Generate service object from service id
*
* @param int $hostId
* @param string $hostName
* @param null|int $serviceId
* @param int $by_hg
* @return void
*/
public function generateFromServiceId(int $hostId, string $hostName, ?int $serviceId, $by_hg = 0)
{
if (is_null($serviceId)) {
return null;
}
$this->buildCache();
// No need to do it again for service by hostgroup
if ($by_hg == 1 && isset($this->serviceCache[$serviceId])) {
return $this->serviceCache[$serviceId]['service_description'];
}
if (($this->useCache == 0 || $by_hg == 1) && ! isset($this->serviceCache[$serviceId])) {
$this->getServiceFromId($serviceId);
}
if (! isset($this->serviceCache[$serviceId]) || is_null($this->serviceCache[$serviceId])) {
return null;
}
if ($this->checkGenerate($hostId . '.' . $serviceId)) {
return $this->serviceCache[$serviceId]['service_description'];
}
$this->getImages($this->serviceCache[$serviceId]);
$this->getMacros($this->serviceCache[$serviceId]);
$this->getTraps($this->serviceCache[$serviceId]);
// useful for servicegroup on servicetemplate
$serviceTemplate = ServiceTemplate::getInstance($this->dependencyInjector);
$serviceTemplate->resetLoop();
$serviceTemplate->currentHostId = $hostId;
$serviceTemplate->currentHostName = $hostName;
$serviceTemplate->currentServiceId = $serviceId;
$serviceTemplate->currentServiceDescription = $this->serviceCache[$serviceId]['service_description'];
$this->getServiceTemplates($this->serviceCache[$serviceId]);
$this->getServiceCommands($this->serviceCache[$serviceId]);
$this->getServicePeriods($this->serviceCache[$serviceId]);
if ($this->backendInstance->isExportContact()) {
$this->getContactGroups($this->serviceCache[$serviceId]);
$this->getContacts($this->serviceCache[$serviceId]);
}
$this->getSeverity($hostId, $serviceId);
$this->getServiceGroups($serviceId, $hostId, $hostName);
$extendedInformation = $this->getExtendedInformation($this->serviceCache[$serviceId]);
Relations\ExtendedServiceInformation::getInstance($this->dependencyInjector)
->add($extendedInformation, $serviceId);
Graph::getInstance($this->dependencyInjector)->getGraphFromId($extendedInformation['graph_id']);
$this->serviceCache[$serviceId]['service_id'] = $serviceId;
$this->generateObjectInFile(
$this->serviceCache[$serviceId],
$hostId . '.' . $serviceId
);
$this->clean($this->serviceCache[$serviceId]);
return $this->serviceCache[$serviceId]['service_description'];
}
/**
* Set poller
*
* @param int $pollerId
* @return void
*/
public function setPoller(int $pollerId): void
{
$this->pollerId = $pollerId;
}
/**
* Reset object
*
* @param bool $resetParent
* @param bool $createfile
* @return void
*/
public function reset($resetParent = false, $createfile = false): void
{
// We reset it by poller (dont need all. We save memory)
if ($this->useCachePoller == 1) {
$this->serviceCache = [];
$this->doneCache = 0;
}
if ($resetParent == true) {
parent::reset($createfile);
}
}
/**
* Get severity from service id
*
* @param int $hostId
* @param int $serviceId
* @return void
*/
protected function getSeverity($hostId, int $serviceId)
{
$severityId
= ServiceCategory::getInstance($this->dependencyInjector)->getServiceSeverityByServiceId($serviceId);
if (! is_null($severityId)) {
Relations\ServiceCategoriesRelation::getInstance($this->dependencyInjector)
->addRelation($severityId, $serviceId);
}
return null;
}
/**
* Get servicegroups
*
* @param int $serviceId
* @param int $hostId
* @param string $hostName
* @return void
*/
private function getServiceGroups(int $serviceId, int $hostId, string $hostName): void
{
$servicegroup = ServiceGroup::getInstance($this->dependencyInjector);
$this->serviceCache[$serviceId]['sg'] = $servicegroup->getServiceGroupsForService($hostId, $serviceId);
foreach ($this->serviceCache[$serviceId]['sg'] as &$value) {
if (is_null($value['host_host_id']) || $hostId == $value['host_host_id']) {
$servicegroup->addServiceInSg(
$value['servicegroup_sg_id'],
$serviceId,
$this->serviceCache[$serviceId]['service_description'],
$hostId,
$hostName
);
Relations\ServiceGroupRelation::getInstance($this->dependencyInjector)->addRelationHostService(
$value['servicegroup_sg_id'],
$hostId,
$serviceId
);
}
}
}
/**
* Build cache of services by poller
*
* @return void
*/
private function getServiceByPollerCache(): void
{
$query = "SELECT {$this->attributesSelect} FROM ns_host_relation, host_service_relation, service "
. 'LEFT JOIN extended_service_information ON extended_service_information.service_service_id = '
. 'service.service_id WHERE ns_host_relation.nagios_server_id = :server_id '
. 'AND ns_host_relation.host_host_id = host_service_relation.host_host_id '
. "AND host_service_relation.service_service_id = service.service_id AND service_activate = '1'";
$stmt = $this->backendInstance->db->prepare($query);
$stmt->bindParam(':server_id', $this->pollerId, PDO::PARAM_INT);
$stmt->execute();
while (($value = $stmt->fetch(PDO::FETCH_ASSOC))) {
$this->serviceCache[$value['service_id']] = $value;
}
}
/**
* Build cache of services
*/
private function getServiceCache(): void
{
$query = "SELECT {$this->attributesSelect} FROM service "
. 'LEFT JOIN extended_service_information ON extended_service_information.service_service_id = '
. "service.service_id WHERE service_register = '1' AND service_activate = '1'";
$stmt = $this->backendInstance->db->prepare($query);
$stmt->execute();
$this->serviceCache = $stmt->fetchAll(PDO::FETCH_GROUP | PDO::FETCH_UNIQUE | PDO::FETCH_ASSOC);
}
/**
* Get service from service id
*
* @param int $serviceId
* @return void
*/
private function getServiceFromId(int $serviceId): void
{
if (is_null($this->stmtService)) {
$query = "SELECT {$this->attributesSelect} FROM service "
. 'LEFT JOIN extended_service_information ON extended_service_information.service_service_id = '
. "service.service_id WHERE service_id = :service_id AND service_activate = '1'";
$this->stmtService = $this->backendInstance->db->prepare($query);
}
$this->stmtService->bindParam(':service_id', $serviceId, PDO::PARAM_INT);
$this->stmtService->execute();
$results = $this->stmtService->fetchAll(PDO::FETCH_ASSOC);
$this->serviceCache[$serviceId] = array_pop($results);
}
/**
* Clean (nothing)
*
* @param array $service
* @return void
*/
private function clean(array &$service)
{
}
/**
* Build cache
*
* @return void|int
*/
private function buildCache()
{
if ($this->doneCache == 1
|| ($this->useCache == 0 && $this->useCachePoller == 0)
) {
return 0;
}
if ($this->useCachePoller == 1) {
$this->getServiceByPollerCache();
} else {
$this->getServiceCache();
}
$this->doneCache = 1;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate-remote/Resource.php | centreon/www/class/config-generate-remote/Resource.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace ConfigGenerateRemote;
use ConfigGenerateRemote\Abstracts\AbstractObject;
use Exception;
use PDO;
use PDOStatement;
/**
* Class
*
* @class Resource
* @package ConfigGenerateRemote
*/
class Resource extends AbstractObject
{
/** @var string */
protected $table = 'cfg_resource';
/** @var string */
protected $generateFilename = 'resource.infile';
/** @var string|null */
protected $objectName = null;
/** @var PDOStatement */
protected $stmt = null;
/** @var string[] */
protected $attributesWrite = [
'resource_id',
'resource_name',
'resource_line',
'resource_comment',
'resource_activate',
];
/**
* Generate resource objects
*
* @param null|int $pollerId
*
* @throws Exception
* @return void
*/
public function generateFromPollerId(?int $pollerId)
{
if (is_null($pollerId)) {
return 0;
}
if (is_null($this->stmt)) {
$query
= "SELECT cfg_resource.resource_id, resource_name, resource_line, resource_comment, resource_activate
FROM cfg_resource_instance_relations, cfg_resource
WHERE instance_id = :poller_id
AND cfg_resource_instance_relations.resource_id = cfg_resource.resource_id
AND cfg_resource.resource_activate = '1'";
$this->stmt = $this->backendInstance->db->prepare($query);
}
$this->stmt->bindParam(':poller_id', $pollerId, PDO::PARAM_INT);
$this->stmt->execute();
foreach ($this->stmt->fetchAll(PDO::FETCH_ASSOC) as $value) {
Relations\CfgResourceInstanceRelation::getInstance($this->dependencyInjector)
->addRelation($value['resource_id'], $pollerId);
if ($this->checkGenerate($value['resource_id'])) {
continue;
}
$this->generateObjectInFile($value, $value['resource_id']);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate-remote/MacroService.php | centreon/www/class/config-generate-remote/MacroService.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace ConfigGenerateRemote;
use ConfigGenerateRemote\Abstracts\AbstractObject;
use Exception;
use PDO;
use PDOStatement;
use Pimple\Container;
/**
* Class
*
* @class MacroService
* @package ConfigGenerateRemote
*/
class MacroService extends AbstractObject
{
/** @var PDOStatement|null */
protected $stmtService = null;
/** @var string */
protected $table = 'on_demand_macro_service';
/** @var string */
protected $generateFilename = 'on_demand_macro_service.infile';
/** @var string[] */
protected $attributesWrite = [
'svc_svc_id',
'svc_macro_name',
'svc_macro_value',
'is_password',
'description',
];
/** @var int */
private $useCache = 1;
/** @var int */
private $doneCache = 0;
/** @var array */
private $macroServiceCache = [];
/**
* MacroService constructor
*
* @param Container $dependencyInjector
*/
public function __construct(Container $dependencyInjector)
{
parent::__construct($dependencyInjector);
$this->buildCache();
}
/**
* Get service macro from service id
*
* @param int $serviceId
*
* @throws Exception
* @return null|array
*/
public function getServiceMacroByServiceId(int $serviceId)
{
// Get from the cache
if (isset($this->macroServiceCache[$serviceId])) {
$this->writeMacrosService($serviceId);
return $this->macroServiceCache[$serviceId];
}
if ($this->doneCache == 1) {
return null;
}
// We get unitary
if (is_null($this->stmtService)) {
$this->stmtService = $this->backendInstance->db->prepare(
'SELECT svc_macro_id, svc_macro_name, svc_macro_value, is_password, description
FROM on_demand_macro_service
WHERE svc_svc_id = :service_id'
);
}
$this->stmtService->bindParam(':service_id', $serviceId, PDO::PARAM_INT);
$this->stmtService->execute();
$this->macroServiceCache[$serviceId] = [];
while ($macro = $this->stmtService->fetch(PDO::FETCH_ASSOC)) {
$this->macroServiceCache[$serviceId][$macro['svc_macro_id']] = [
'svc_svc_id' => $macro['svc_svc_id'],
'svc_macro_name' => $macro['svc_macro_name'],
'svc_macro_value' => $macro['svc_macro_value'],
'is_password' => $macro['is_password'],
'description' => $macro['description'],
];
}
$this->writeMacrosService($serviceId);
return $this->macroServiceCache[$serviceId];
}
/**
* Build cache of service macros
*
* @return void
*/
private function cacheMacroService(): void
{
$stmt = $this->backendInstance->db->prepare(
'SELECT svc_macro_id, svc_svc_id, svc_macro_name, svc_macro_value, is_password, description
FROM on_demand_macro_service'
);
$stmt->execute();
while (($macro = $stmt->fetch(PDO::FETCH_ASSOC))) {
if (! isset($this->macroServiceCache[$macro['svc_svc_id']])) {
$this->macroServiceCache[$macro['svc_svc_id']] = [];
}
$this->macroServiceCache[$macro['svc_svc_id']][$macro['svc_macro_id']] = [
'svc_svc_id' => $macro['svc_svc_id'],
'svc_macro_name' => $macro['svc_macro_name'],
'svc_macro_value' => $macro['svc_macro_value'],
'is_password' => $macro['is_password'],
'description' => $macro['description'],
];
}
}
/**
* Generate service macros
*
* @param int $serviceId
*
* @throws Exception
* @return null|void
*/
private function writeMacrosService(int $serviceId)
{
if ($this->checkGenerate($serviceId)) {
return null;
}
foreach ($this->macroServiceCache[$serviceId] as $value) {
$this->generateObjectInFile($value, $serviceId);
}
}
/**
* Build cache
*
* @return void
*/
private function buildCache()
{
if ($this->doneCache == 1) {
return 0;
}
$this->cacheMacroService();
$this->doneCache = 1;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate-remote/Engine.php | centreon/www/class/config-generate-remote/Engine.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace ConfigGenerateRemote;
use ConfigGenerateRemote\Abstracts\AbstractObject;
use Exception;
use PDO;
use PDOStatement;
/**
* Class
*
* @class Engine
* @package ConfigGenerateRemote
*/
class Engine extends AbstractObject
{
/** @var array|null */
protected $engine = null;
/** @var string */
protected $table = 'cfg_nagios';
/** @var string */
protected $generateFilename = 'cfg_nagios.infile';
/** @var string */
protected $attributesSelect = '
nagios_server_id,
nagios_id,
nagios_name,
use_timezone,
cfg_dir,
cfg_file,
log_file,
status_file,
status_update_interval,
external_command_buffer_slots,
command_check_interval,
command_file,
state_retention_file,
retention_update_interval,
sleep_time,
service_inter_check_delay_method,
host_inter_check_delay_method,
service_interleave_factor,
max_concurrent_checks,
max_service_check_spread,
max_host_check_spread,
check_result_reaper_frequency,
auto_rescheduling_interval,
auto_rescheduling_window,
enable_flap_detection,
low_service_flap_threshold,
high_service_flap_threshold,
low_host_flap_threshold,
high_host_flap_threshold,
service_check_timeout,
host_check_timeout,
event_handler_timeout,
notification_timeout,
service_freshness_check_interval,
host_freshness_check_interval,
date_format,
illegal_object_name_chars,
illegal_macro_output_chars,
admin_email,
admin_pager,
event_broker_options,
cached_host_check_horizon,
cached_service_check_horizon,
additional_freshness_latency,
debug_file,
debug_level,
debug_level_opt,
debug_verbosity,
max_debug_file_size,
log_pid,
enable_notifications,
execute_service_checks,
accept_passive_service_checks,
execute_host_checks,
accept_passive_host_checks,
enable_event_handlers,
check_external_commands,
use_retained_program_state,
use_retained_scheduling_info,
use_syslog,
log_notifications,
log_service_retries,
log_host_retries,
log_event_handlers,
log_external_commands,
log_passive_checks,
auto_reschedule_checks,
soft_state_dependencies,
check_for_orphaned_services,
check_for_orphaned_hosts,
check_service_freshness,
check_host_freshness,
use_regexp_matching,
use_true_regexp_matching,
enable_predictive_host_dependency_checks,
enable_predictive_service_dependency_checks,
host_down_disable_service_checks,
enable_environment_macros,
enable_macros_filter,
macros_filter,
nagios_activate
';
/** @var string[] */
protected $attributesWrite = [
'nagios_server_id',
'nagios_id',
'nagios_name',
'use_timezone',
'log_file',
'status_file',
'status_update_interval',
'external_command_buffer_slots',
'command_check_interval',
'command_file',
'state_retention_file',
'retention_update_interval',
'sleep_time',
'service_inter_check_delay_method',
'host_inter_check_delay_method',
'service_interleave_factor',
'max_concurrent_checks',
'max_service_check_spread',
'max_host_check_spread',
'check_result_reaper_frequency',
'auto_rescheduling_interval',
'auto_rescheduling_window',
'low_service_flap_threshold',
'high_service_flap_threshold',
'low_host_flap_threshold',
'high_host_flap_threshold',
'service_check_timeout',
'host_check_timeout',
'event_handler_timeout',
'notification_timeout',
'service_freshness_check_interval',
'host_freshness_check_interval',
'date_format',
'illegal_object_name_chars',
'illegal_macro_output_chars',
'admin_email',
'admin_pager',
'event_broker_options',
'cached_host_check_horizon',
'cached_service_check_horizon',
'additional_freshness_latency',
'debug_file',
'debug_level',
'debug_verbosity',
'max_debug_file_size',
'log_pid', // centengine
'macros_filter',
'enable_macros_filter',
'nagios_activate',
'cfg_dir',
'cfg_file',
];
/** @var PDOStatement|null */
protected $stmtEngine = null;
/**
* Generate engine configuration from poller
*
* @param array $poller
*
* @throws Exception
* @return void
*/
public function generateFromPoller(array $poller): void
{
Resource::getInstance($this->dependencyInjector)->generateFromPollerId($poller['id']);
$this->generate($poller['id']);
}
/**
* Generate engine configuration from poller id
*
* @param int $pollerId
*
* @throws Exception
* @return void
*/
private function generate(int $pollerId): void
{
if (is_null($this->stmtEngine)) {
$this->stmtEngine = $this->backendInstance->db->prepare(
"SELECT {$this->attributesSelect} FROM cfg_nagios "
. "WHERE nagios_server_id = :poller_id AND nagios_activate = '1'"
);
}
$this->stmtEngine->bindParam(':poller_id', $pollerId, PDO::PARAM_INT);
$this->stmtEngine->execute();
$result = $this->stmtEngine->fetchAll(PDO::FETCH_ASSOC);
$this->engine = array_pop($result);
if (is_null($this->engine)) {
throw new Exception(
"Cannot get engine configuration for poller id (maybe not activate) '" . $pollerId . "'"
);
}
$this->generateObjectInFile(
$this->engine,
$pollerId
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate-remote/HostTemplate.php | centreon/www/class/config-generate-remote/HostTemplate.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace ConfigGenerateRemote;
use ConfigGenerateRemote\Abstracts\AbstractHost;
use PDO;
/**
* Class
*
* @class HostTemplate
* @package ConfigGenerateRemote
*/
class HostTemplate extends AbstractHost
{
/** @var array|null */
public $hosts = null;
/** @var string */
protected $generateFilename = 'hostTemplates.infile';
/** @var string */
protected $table = 'host';
/** @var string */
protected $attributesSelect = '
host_id,
command_command_id,
command_command_id_arg1,
timeperiod_tp_id,
timeperiod_tp_id2,
command_command_id2,
command_command_id_arg2,
host_name,
host_alias,
host_location,
display_name,
host_max_check_attempts,
host_check_interval,
host_retry_check_interval,
host_active_checks_enabled,
host_passive_checks_enabled,
initial_state,
host_obsess_over_host,
host_check_freshness,
host_freshness_threshold,
host_event_handler_enabled,
host_low_flap_threshold,
host_high_flap_threshold,
host_flap_detection_enabled,
flap_detection_options,
host_process_perf_data,
host_retain_status_information,
host_retain_nonstatus_information,
host_notification_interval,
host_notification_options,
host_notifications_enabled,
contact_additive_inheritance,
cg_additive_inheritance,
host_first_notification_delay,
host_recovery_notification_delay,
host_stalking_options,
host_snmp_community,
host_snmp_version,
host_register,
ehi_notes,
ehi_notes_url,
ehi_action_url,
ehi_icon_image,
ehi_icon_image_alt,
ehi_statusmap_image,
ehi_2d_coords,
ehi_3d_coords,
host_acknowledgement_timeout
';
/** @var string[] */
protected $attributesWrite = [
'host_id',
'command_command_id',
'command_command_id_arg1',
'timeperiod_tp_id',
'timeperiod_tp_id2',
'command_command_id2',
'command_command_id_arg2',
'host_name',
'host_alias',
'host_address',
'display_name',
'host_max_check_attempts',
'host_check_interval',
'host_retry_check_interval',
'host_active_checks_enabled',
'host_passive_checks_enabled',
'host_event_handler_enabled',
'host_notification_interval',
'host_notification_options',
'host_notifications_enabled',
'host_snmp_community',
'host_snmp_version',
'host_register',
'host_location',
'host_acknowledgement_timeout',
];
/**
* Generate from host id and get host name
*
* @param int $hostId
* @return null|string
*/
public function generateFromHostId(int $hostId)
{
if (is_null($this->hosts)) {
$this->getHosts();
}
if (! isset($this->hosts[$hostId])) {
return null;
}
if ($this->checkGenerate($hostId)) {
return $this->hosts[$hostId]['host_name'];
}
// Avoid infinite loop!
if (isset($this->loopHtpl[$hostId])) {
return $this->hosts[$hostId]['host_name'];
}
$this->loopHtpl[$hostId] = 1;
$this->hosts[$hostId]['host_id'] = $hostId;
$this->getImages($this->hosts[$hostId]);
$this->getMacros($this->hosts[$hostId]);
$this->getHostTimezone($this->hosts[$hostId]);
$this->getHostTemplates($this->hosts[$hostId]);
$this->getHostCommands($this->hosts[$hostId]);
$this->getHostPeriods($this->hosts[$hostId]);
if ($this->backendInstance->isExportContact()) {
$this->getContactGroups($this->hosts[$hostId]);
$this->getContacts($this->hosts[$hostId]);
}
$this->getSeverity($hostId);
$extendedInformation = $this->getExtendedInformation($this->hosts[$hostId]);
Relations\ExtendedHostInformation::getInstance($this->dependencyInjector)->add($extendedInformation, $hostId);
$this->generateObjectInFile($this->hosts[$hostId], $hostId);
return $this->hosts[$hostId]['host_name'];
}
/**
* Reset object
*
* @param bool $createfile
* @return void
*/
public function reset($createfile = false): void
{
$this->loopHtpl = [];
parent::reset($createfile);
}
/**
* Get hosts
*
* @return void
*/
private function getHosts(): void
{
$stmt = $this->backendInstance->db->prepare(
"SELECT {$this->attributesSelect}
FROM host
LEFT JOIN extended_host_information ON extended_host_information.host_host_id = host.host_id
WHERE host.host_register = '0' AND host.host_activate = '1'"
);
$stmt->execute();
$this->hosts = $stmt->fetchAll(PDO::FETCH_GROUP | PDO::FETCH_UNIQUE | PDO::FETCH_ASSOC);
}
/**
* Get severity from host id
*
* @param int $hostId
* @return int|void
*/
private function getSeverity(int $hostId)
{
if (isset($this->hosts[$hostId]['severity_id'])) {
return 0;
}
$this->hosts[$hostId]['severity_id']
= HostCategory::getInstance($this->dependencyInjector)->getHostSeverityByHostId($hostId);
if (! is_null($this->hosts[$hostId]['severity_id'])) {
Relations\HostCategoriesRelation::getInstance($this->dependencyInjector)
->addRelation($this->hosts[$hostId]['severity_id'], $hostId);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate-remote/ServiceCategory.php | centreon/www/class/config-generate-remote/ServiceCategory.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace ConfigGenerateRemote;
use ConfigGenerateRemote\Abstracts\AbstractObject;
use Exception;
use PDO;
use PDOStatement;
use Pimple\Container;
/**
* Class
*
* @class ServiceCategory
* @package ConfigGenerateRemote
*/
class ServiceCategory extends AbstractObject
{
/** @var string */
protected $table = 'service_categories';
/** @var string */
protected $generateFilename = 'servicecategories.infile';
/** @var PDOStatement */
protected $stmtService = null;
/** @var PDOStatement */
protected $stmtHcName = null;
/** @var string[] */
protected $attributesWrite = [
'sc_id',
'sc_name',
'sc_description',
'level',
'icon_id',
];
/** @var int */
private $useCache = 1;
/** @var int */
private $doneCache = 0;
/** @var array */
private $serviceSeverityCache = [];
/** @var array */
private $serviceSeverityByNameCache = [];
/** @var array */
private $serviceLinkedCache = [];
/**
* ServiceCategory constructor
*
* @param Container $dependencyInjector
*/
public function __construct(Container $dependencyInjector)
{
parent::__construct($dependencyInjector);
$this->buildCache();
}
/**
* Generate object
*
* @param null|int $scId
*
* @throws Exception
* @return void
*/
public function generateObject(?int $scId)
{
if (is_null($scId) || $this->checkGenerate($scId)) {
return null;
}
if (! isset($this->serviceSeverityCache[$scId])) {
return null;
}
$this->generateObjectInFile($this->serviceSeverityCache[$scId], $scId);
Media::getInstance($this->dependencyInjector)
->getMediaPathFromId($this->serviceSeverityCache[$scId]['icon_id']);
}
/**
* Get severity by service id
*
* @param int $serviceId
*
* @throws Exception
* @return void
*/
public function getServiceSeverityByServiceId(int $serviceId)
{
// Get from the cache
if (isset($this->serviceLinkedCache[$serviceId])) {
if (! $this->checkGenerate($this->serviceLinkedCache[$serviceId])) {
$this->generateObjectInFile(
$this->serviceSeverityCache[$this->serviceLinkedCache[$serviceId]],
$this->serviceLinkedCache[$serviceId]
);
Media::getInstance($this->dependencyInjector)
->getMediaPathFromId($this->serviceSeverityCache[$this->serviceLinkedCache[$serviceId]]['icon_id']);
}
return $this->serviceLinkedCache[$serviceId];
}
if ($this->doneCache == 1) {
return null;
}
// We get unitary
if (is_null($this->stmtService)) {
$this->stmtService = $this->backendInstance->db->prepare(
"SELECT service_categories.sc_id, sc_name, level, icon_id
FROM service_categories_relation, service_categories
WHERE service_categories_relation.service_service_id = :service_id
AND service_categories_relation.sc_id = service_categories.sc_id
AND level IS NOT NULL AND sc_activate = '1'
ORDER BY level DESC
LIMIT 1"
);
}
$this->stmtService->bindParam(':service_id', $serviceId, PDO::PARAM_INT);
$this->stmtService->execute();
$severity = array_pop($this->stmtService->fetchAll(PDO::FETCH_ASSOC));
if (is_null($severity)) {
$this->serviceLinkedCache[$serviceId] = null;
return null;
}
$this->serviceLinkedCache[$serviceId] = $severity['sc_id'];
$this->serviceSeverityByNameCache[$severity['sc_name']] = &$severity;
$this->serviceSeverityCache[$severity['sc_id']] = &$severity;
$this->generateObjectInFile($severity, $severity['sc_id']);
Media::getInstance($this->dependencyInjector)
->getMediaPathFromId($this->serviceSeverityCache[$this->serviceLinkedCache[$serviceId]]['icon_id']);
return $severity['sc_id'];
}
/**
* Get severity by id
*
* @param null|int $scId
* @return void
*/
public function getServiceSeverityById(?int $scId)
{
if (is_null($scId)) {
return null;
}
if (! isset($this->serviceSeverityCache[$scId])) {
return null;
}
return $this->serviceSeverityCache[$scId];
}
/**
* Get mapping with host severity name
*
* @param string $hcName
* @return null|int
*/
public function getServiceSeverityMappingHostSeverityByName(string $hcName)
{
if (isset($this->serviceSeverityByNameCache[$hcName])) {
return $this->serviceSeverityByNameCache[$hcName];
}
if ($this->doneCache == 1) {
return null;
}
// We get unitary
if (is_null($this->stmtHcName)) {
$this->stmtHcName = $this->backendInstance->db->prepare(
"SELECT sc_name, sc_id, level
FROM service_categories
WHERE sc_name = :sc_name AND level IS NOT NULL AND sc_activate = '1'"
);
}
$this->stmtHcName->bindParam(':sc_name', $hcName, PDO::PARAM_STR);
$this->stmtHcName->execute();
$severity = array_pop($this->stmtHcName->fetchAll(PDO::FETCH_ASSOC));
if (is_null($severity)) {
$this->serviceSeverityByNameCache[$hcName] = null;
return null;
}
$this->serviceSeverityByNameCache[$hcName] = &$severity;
$this->serviceSeverityCache[$hcName] = &$severity;
return $severity['sc_id'];
}
/**
* Build cache of service severity
*
* @return void
*/
private function cacheServiceSeverity(): void
{
$stmt = $this->backendInstance->db->prepare(
"SELECT sc_name, sc_id, level, icon_id
FROM service_categories
WHERE level IS NOT NULL AND sc_activate = '1'"
);
$stmt->execute();
$values = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($values as &$value) {
$this->serviceSeverityByNameCache[$value['sc_name']] = &$value;
$this->serviceSeverityCache[$value['sc_id']] = &$value;
}
}
/**
* Build cache of relations between service and severity
*
* @return void
*/
private function cacheServiceSeverityLinked(): void
{
$stmt = $this->backendInstance->db->prepare(
'SELECT service_categories.sc_id, service_service_id '
. 'FROM service_categories, service_categories_relation '
. 'WHERE level IS NOT NULL '
. 'AND sc_activate = "1" '
. 'AND service_categories_relation.sc_id = service_categories.sc_id'
);
$stmt->execute();
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $value) {
if (isset($this->serviceLinkedCache[$value['service_service_id']])) {
if ($this->serviceSeverityCache[$value['sc_id']]['level']
< $this->serviceSeverityCache[$this->serviceLinkedCache[$value['service_service_id']]]
) {
$this->serviceLinkedCache[$value['service_service_id']] = $value['sc_id'];
}
} else {
$this->serviceLinkedCache[$value['service_service_id']] = $value['sc_id'];
}
}
}
/**
* Build cache
*/
private function buildCache()
{
if ($this->doneCache == 1) {
return 0;
}
$this->cacheServiceSeverity();
$this->cacheServiceSeverityLinked();
$this->doneCache = 1;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate-remote/ServiceGroup.php | centreon/www/class/config-generate-remote/ServiceGroup.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace ConfigGenerateRemote;
use ConfigGenerateRemote\Abstracts\AbstractObject;
use Exception;
use PDO;
use PDOStatement;
use Pimple\Container;
/**
* Class
*
* @class ServiceGroup
* @package ConfigGenerateRemote
*/
class ServiceGroup extends AbstractObject
{
/** @var string */
protected $table = 'servicegroup';
/** @var string */
protected $generateFilename = 'servicegroups.infile';
/** @var string */
protected $attributesSelect = '
sg_id,
sg_name,
sg_alias,
geo_coords
';
/** @var string[] */
protected $attributesWrite = [
'sg_id',
'sg_name',
'sg_alias',
'geo_coords',
];
/** @var PDOStatement */
protected $stmtSg = null;
/** @var PDOStatement */
protected $stmtServiceSg = null;
/** @var PDOStatement */
protected $stmtStplSg = null;
/** @var int */
private $useCache = 1;
/** @var int */
private $doneCache = 0;
/** @var array */
private $sg = [];
/** @var array */
private $sgRelationCache = [];
/**
* ServiceGroup constructor
*
* @param Container $dependencyInjector
*/
public function __construct(Container $dependencyInjector)
{
parent::__construct($dependencyInjector);
$this->buildCache();
}
/**
* Generate service group
*
* @param int $sgId
* @param int $serviceId
* @param string $serviceDescription
* @param int $hostId
* @param string $hostName
*
* @throws Exception
* @return int
*/
public function addServiceInSg(int $sgId, int $serviceId, string $serviceDescription, int $hostId, string $hostName)
{
if (! isset($this->sg[$sgId])) {
$this->getServicegroupFromId($sgId);
$this->generateObjectInFile($this->sg[$sgId], $sgId);
}
if (is_null($this->sg[$sgId]) || isset($this->sg[$sgId]['members_cache'][$hostId . '_' . $serviceId])) {
return 1;
}
$this->sg[$sgId]['members_cache'][$hostId . '_' . $serviceId] = [$hostName, $serviceDescription];
return 0;
}
/**
* Get service group from service template id
*
* @param int $serviceId
* @return void
*/
public function getServiceGroupsForStpl(int $serviceId)
{
// Get from the cache
if (isset($this->sgRelationCache[$serviceId])) {
return $this->sgRelationCache[$serviceId];
}
if ($this->doneCache == 1) {
return [];
}
if (is_null($this->stmtStplSg)) {
// Meaning, linked with the host or hostgroup (for the null expression)
$this->stmtStplSg = $this->backendInstance->db->prepare(
'SELECT servicegroup_sg_id, host_host_id, service_service_id
FROM servicegroup_relation
WHERE service_service_id = :service_id'
);
}
$this->stmtStplSg->bindParam(':service_id', $serviceId, PDO::PARAM_INT);
$this->stmtStplSg->execute();
$this->sgRelationCache[$serviceId] = array_merge(
$this->stmtStplSg->fetchAll(PDO::FETCH_ASSOC),
$this->sgRelationCache[$serviceId]
);
return $this->sgRelationCache[$serviceId];
}
/**
* Get service linked service groups
*
* @param int $hostId
* @param int $serviceId
* @return void
*/
public function getServiceGroupsForService(int $hostId, int $serviceId)
{
// Get from the cache
if (isset($this->sgRelationCache[$serviceId])) {
return $this->sgRelationCache[$serviceId];
}
if ($this->doneCache == 1) {
return [];
}
if (is_null($this->stmtServiceSg)) {
// Meaning, linked with the host or hostgroup (for the null expression)
$this->stmtServiceSg = $this->backendInstance->db->prepare(
'SELECT servicegroup_sg_id, host_host_id, service_service_id
FROM servicegroup_relation
WHERE service_service_id = :service_id
AND (host_host_id = :host_id OR host_host_id IS NULL)'
);
}
$this->stmtServiceSg->bindParam(':service_id', $serviceId, PDO::PARAM_INT);
$this->stmtServiceSg->bindParam(':host_id', $hostId, PDO::PARAM_INT);
$this->stmtServiceSg->execute();
$this->sgRelationCache[$serviceId] = array_merge(
$this->stmtServiceSg->fetchAll(PDO::FETCH_ASSOC),
$this->sgRelationCache[$serviceId]
);
return $this->sgRelationCache[$serviceId];
}
/**
* Generate object
*
* @param int $sgId
*
* @throws Exception
* @return void
*/
public function generateObject(int $sgId)
{
if ($this->checkGenerate($sgId)) {
return null;
}
$this->generateObjectInFile($this->sg[$sgId], $sgId);
}
/**
* Generate objects
*
* @throws Exception
* @return void
*/
public function generateObjects(): void
{
foreach ($this->sg as $id => &$value) {
if (count($value['members_cache']) == 0) {
continue;
}
$this->sg[$id]['sg_id'] = $id;
$this->generateObjectInFile($this->sg[$id], $id);
}
}
/**
* Get service groups
*
* @return array
*/
public function getServicegroups()
{
$result = [];
foreach ($this->sg as $id => &$value) {
if (is_null($value) || count($value['members_cache']) == 0) {
continue;
}
$result[$id] = &$value;
}
return $result;
}
/**
* Reset object
*
* @param bool $createfile
*
* @throws Exception
* @return void
*/
public function reset($createfile = false): void
{
$this->sg = [];
parent::reset($createfile);
}
/**
* Get servicegroup attribute
*
* @param int $sgId
* @param string $attr
* @return void
*/
public function getString(int $sgId, string $attr)
{
return $this->sg[$sgId][$attr] ?? null;
}
/**
* Get servicegroup frm id
*
* @param int $sgId
* @return void
*/
private function getServicegroupFromId(int $sgId)
{
if (is_null($this->stmtSg)) {
$this->stmtSg = $this->backendInstance->db->prepare(
"SELECT {$this->attributesSelect}
FROM servicegroup
WHERE sg_id = :sg_id AND sg_activate = '1'"
);
}
$this->stmtSg->bindParam(':sg_id', $sgId, PDO::PARAM_INT);
$this->stmtSg->execute();
$results = $this->stmtSg->fetchAll(PDO::FETCH_ASSOC);
$this->sg[$sgId] = array_pop($results);
if (is_null($this->sg[$sgId])) {
return 1;
}
$this->sg[$sgId]['members_cache'] = [];
}
/**
* Build cache
*
* @return void
*/
private function buildCache()
{
if ($this->doneCache == 1) {
return 0;
}
$stmt = $this->backendInstance->db->prepare('SELECT
service_service_id, servicegroup_sg_id, host_host_id
FROM servicegroup_relation
');
$stmt->execute();
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $value) {
if (isset($this->sgRelationCache[$value['service_service_id']])) {
$this->sgRelationCache[$value['service_service_id']][] = $value;
} else {
$this->sgRelationCache[$value['service_service_id']] = [$value];
}
}
$this->doneCache = 1;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate-remote/Backend.php | centreon/www/class/config-generate-remote/Backend.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace ConfigGenerateRemote;
use CentreonDB;
use Exception;
use PDOException;
use PDOStatement;
use Pimple\Container;
// file centreon.config.php may not exist in test environment
$configFile = realpath(__DIR__ . '/../../../config/centreon.config.php');
if ($configFile !== false) {
require_once $configFile;
}
/**
* Class
*
* @class Backend
* @package ConfigGenerateRemote
*/
class Backend
{
/** @var string */
public $generatePath;
/** @var string */
public $engine_sub;
/** @var PDOStatement */
public $stmtCentralPoller;
/** @var CentreonDB|null */
public $db = null;
/** @var CentreonDB|null */
public $dbCs = null;
/** @var Backend|null */
private static $instance = null;
/** @var string[] */
private $subdirs = ['configuration', 'media'];
/** @var string */
private $fieldSeparatorInfile = '~~~';
/** @var string */
private $lineSeparatorInfile = '######';
/** @var string */
private $tmpDirPrefix = 'tmpdir_';
/** @var string|null */
private $tmpFile = null;
/** @var string|null */
private $tmpDir = null;
/** @var string */
private $tmpDirSuffix = '.d';
/** @var string|null */
private $fullPath = null;
/** @var string */
private $whoaim = 'unknown';
/** @var bool */
private $exportContact = false;
/** @var int|null */
private $pollerId = null;
/** @var int|null */
private $centralPollerId = null;
/**
* Backend constructor
*
* @param Container $dependencyInjector
*/
private function __construct(Container $dependencyInjector)
{
$this->generatePath = _CENTREON_CACHEDIR_ . '/config/export';
$this->db = $dependencyInjector['configuration_db'];
$this->dbCs = $dependencyInjector['realtime_db'];
}
/**
* Get backend singleton
*
* @param Container $dependencyInjector
*
* @return Backend|null
*/
public static function getInstance(Container $dependencyInjector)
{
if (is_null(self::$instance)) {
self::$instance = new Backend($dependencyInjector);
}
return self::$instance;
}
/**
* Create multiple directories
*
* @param array $paths
*
* @throws Exception
* @return string created directory path
*/
public function createDirectories(array $paths): string
{
$dir = '';
$dirAppend = '';
foreach ($paths as $path) {
$dir .= $dirAppend . $path;
$dirAppend .= '/';
if (file_exists($dir)) {
if (! is_dir($dir)) {
throw new Exception("Generation path '" . $dir . "' is not a directory.");
}
if (posix_getuid() === fileowner($dir)) {
chmod($dir, 0770);
}
} elseif (! mkdir($dir, 0770, true)) {
throw new Exception("Cannot create directory '" . $dir . "'");
}
}
return $dir;
}
/**
* generatePath getter
*
* @return string
*/
public function getEngineGeneratePath(): string
{
return $this->generatePath . '/' . $this->engine_sub;
}
/**
* Create directories to generation configuration
*
* @param int $pollerId
*
* @throws Exception
* @return void
*/
public function initPath(int $pollerId): void
{
$this->createDirectories([$this->generatePath]);
$this->fullPath = $this->generatePath;
if (! is_writable($this->fullPath)) {
throw new Exception("Not writeable directory '" . $this->fullPath . "'");
}
if (is_dir($this->fullPath . '/' . $pollerId) && ! is_writable($this->fullPath . '/' . $pollerId)) {
throw new Exception("Not writeable directory '" . $this->fullPath . '/' . $pollerId . "'");
}
$this->tmpFile = basename(tempnam($this->fullPath, $this->tmpDirPrefix));
$this->tmpDir = $this->tmpFile . $this->tmpDirSuffix;
$this->fullPath .= '/' . $this->tmpDir;
$this->createDirectories([$this->fullPath]);
foreach ($this->subdirs as $subdir) {
$this->createDirectories([$this->fullPath . '/' . $subdir]);
}
}
/**
* fieldSeparatorInfile getter
*
* @return string
*/
public function getFieldSeparatorInfile()
{
return $this->fieldSeparatorInfile;
}
/**
* lineSeparatorInfile getter
*
* @return string
*/
public function getLineSeparatorInfile()
{
return $this->lineSeparatorInfile;
}
/**
* exportContact getter
*
* @return bool
*/
public function isExportContact()
{
return $this->exportContact;
}
/**
* fullPath getter
*
* @return string|null
*/
public function getPath()
{
return $this->fullPath;
}
/**
* Move poller directory
*
* @param int $pollerId
* @return void
*/
public function movePath(int $pollerId): void
{
$subdir = dirname($this->fullPath);
$this->deleteDir($subdir . '/' . $pollerId);
unlink($subdir . '/' . $this->tmpFile);
rename($this->fullPath, $subdir . '/' . $pollerId);
}
/**
* Clean directory and files
*
* @return void
*/
public function cleanPath(): void
{
$subdir = dirname($this->fullPath);
if (is_dir($this->fullPath)) {
$this->deleteDir($this->fullPath, true);
}
@unlink($subdir . '/' . $this->tmpFile);
}
/**
* username setter
*
* @param string $username
* @return void
*/
public function setUserName(string $username): void
{
$this->whoaim = $username;
}
/**
* username getter
*
* @return string
*/
public function getUserName(): string
{
return $this->whoaim;
}
/**
* poller id setter
*
* @param int $pollerId
* @return void
*/
public function setPollerId(int $pollerId): void
{
$this->pollerId = $pollerId;
}
/**
* poller id getter
*
* @return int
*/
public function getPollerId(): int
{
return $this->pollerId;
}
/**
* Get id of central server
*
* @throws PDOException
* @return int
*/
public function getCentralPollerId(): int
{
if (! is_null($this->centralPollerId)) {
return $this->centralPollerId;
}
$this->stmtCentralPoller = $this->db->prepare("SELECT id
FROM nagios_server
WHERE localhost = '1' AND ns_activate = '1'
");
$this->stmtCentralPoller->execute();
if ($this->stmtCentralPoller->rowCount()) {
$row = $this->stmtCentralPoller->fetch(PDO::FETCH_ASSOC);
$this->centralPollerId = $row['id'];
return $this->centralPollerId;
}
throw new Exception('Cannot get central poller id');
}
/**
* Delete directory recursively
*
* @param string $path
* @param bool $onlyContent if set to false, do not delete directory itself
* @return bool
*/
private function deleteDir(?string $path, bool $onlyContent = false): bool
{
if (is_dir($path)) {
$files = array_diff(scandir($path), ['.', '..']);
foreach ($files as $file) {
$this->deleteDir(realpath($path) . '/' . $file);
}
if (! $onlyContent) {
return rmdir($path);
}
return true;
}
if (is_file($path)) {
return unlink($path);
}
return false;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate-remote/Manifest.php | centreon/www/class/config-generate-remote/Manifest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace ConfigGenerateRemote;
use ConfigGenerateRemote\Abstracts\AbstractObject;
/**
* Class
*
* @class Manifest
* @package ConfigGenerateRemote
*/
class Manifest extends AbstractObject
{
/** @var string */
protected $generateFilename = 'manifest.json';
/** @var array */
protected $manifest = [];
/** @var string */
protected $type = 'manifest';
/** @var string */
protected $subdir = '';
/**
* Manifest constructor
*
* @param \Pimple\Container $dependencyInjector
*/
protected function __construct(\Pimple\Container $dependencyInjector)
{
parent::__construct($dependencyInjector);
$this->manifest['date'] = date('l jS \of F Y h:i:s A');
$this->manifest['pollers'] = [];
$this->manifest['import'] = [
'infile_clauses' => [
'fields_clause' => [
'terminated_by' => $this->fieldSeparatorInfile,
'enclosed_by' => '"',
'escaped_by' => '\\\\',
],
'lines_clause' => [
'terminated_by' => $this->lineSeparatorInfile,
'starting_by' => '',
],
],
'data' => [],
];
}
/**
* Destructor
*/
public function __destruct()
{
// fwrite($this->fp, json_encode($this->manifest));
// parent::__destruct();
}
/**
* Get manifest
*
* @return array
*/
public function getManifest()
{
return $this->manifest;
}
/**
* Add remote server
*
* @param int $remoteId
* @return void
*/
public function addRemoteServer(int $remoteId): void
{
$this->manifest['remote_server'] = $remoteId;
}
/**
* Add poller
*
* @param int $pollerId
* @return void
*/
public function addPoller(int $pollerId): void
{
$this->manifest['pollers'][] = $pollerId;
}
/**
* Add file
*
* @param string $filename
* @param string $type
* @param string $table
* @param array $columns
* @return void
*/
public function addFile(string $filename, string $type, string $table, array $columns): void
{
$this->manifest['import']['data'][$filename] = [
'filename' => $filename,
'type' => $type,
'table' => $table,
'columns' => $columns,
];
}
/**
* clean
*
* @return void
*/
public function clean(): void
{
$this->manifest['date'] = date('l jS \of F Y h:i:s A');
$this->manifest['import']['data'] = [];
$this->manifest['pollers'] = [];
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate-remote/HostCategory.php | centreon/www/class/config-generate-remote/HostCategory.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace ConfigGenerateRemote;
use ConfigGenerateRemote\Abstracts\AbstractObject;
use Exception;
use PDO;
use PDOStatement;
use Pimple\Container;
/**
* Class
*
* @class HostCategory
* @package ConfigGenerateRemote
*/
class HostCategory extends AbstractObject
{
/** @var string */
protected $table = 'hostcategories';
/** @var string */
protected $generateFilename = 'hostcategories.infile';
/** @var PDOStatement|null */
protected $stmtHost = null;
/** @var PDOStatement|null */
protected $stmtHcName = null;
/** @var string[] */
protected $attributesWrite = [
'hc_id',
'hc_name',
'hc_alias',
'level',
'icon_id',
];
/** @var int */
private $useCache = 1;
/** @var int */
private $doneCache = 0;
/** @var array */
private $hostSeverityCache = [];
/** @var array */
private $hostLinkedCache = [];
/**
* HostCategory constructor
*
* @param Container $dependencyInjector
*/
public function __construct(Container $dependencyInjector)
{
parent::__construct($dependencyInjector);
$this->buildCache();
}
/**
* Get host severity by host id
*
* @param int $hostId
*
* @throws Exception
* @return array|null
*/
public function getHostSeverityByHostId(int $hostId)
{
// Get from the cache
if (isset($this->hostLinkedCache[$hostId])) {
if (! $this->checkGenerate($this->hostLinkedCache[$hostId])) {
$this->generateObjectInFile(
$this->hostSeverityCache[$this->hostLinkedCache[$hostId]],
$this->hostLinkedCache[$hostId]
);
Media::getInstance($this->dependencyInjector)
->getMediaPathFromId($this->hostSeverityCache[$this->hostLinkedCache[$hostId]]['icon_id']);
}
return $this->hostLinkedCache[$hostId];
}
if ($this->doneCache == 1) {
return null;
}
// We get unitary
if (is_null($this->stmtHost)) {
$this->stmtHost = $this->backendInstance->db->prepare(
"SELECT hc_id, hc_name, hc_alias, level, icon_id
FROM hostcategories_relation, hostcategories
WHERE hostcategories_relation.host_host_id = :host_id
AND hostcategories_relation.hostcategories_hc_id = hostcategories.hc_id
AND level IS NOT NULL AND hc_activate = '1'
ORDER BY level DESC
LIMIT 1"
);
}
$this->stmtHost->bindParam(':host_id', $hostId, PDO::PARAM_INT);
$this->stmtHost->execute();
$severity = array_pop($this->stmtHost->fetchAll(PDO::FETCH_ASSOC));
if (is_null($severity)) {
$this->hostLinkedCache[$hostId] = null;
return null;
}
$this->hostLinkedCache[$hostId] = $severity['hc_id'];
$this->hostSeverityCache[$severity['hc_id']] = &$severity;
$this->generateObjectInFile($severity, $severity['hc_id']);
Media::getInstance($this->dependencyInjector)
->getMediaPathFromId($this->hostSeverityCache[$this->hostLinkedCache[$hostId]]['icon_id']);
return $severity['hc_id'];
}
/**
* Get host severity by id
*
* @param null|int $hcId
* @return array|null
*/
public function getHostSeverityById(?int $hcId)
{
if (is_null($hcId)) {
return null;
}
if (! isset($this->hostSeverityCache[$hcId])) {
return null;
}
return $this->hostSeverityCache[$hcId];
}
/**
* Build cache of host severity
*
* @return void
*/
private function cacheHostSeverity(): void
{
$stmt = $this->backendInstance->db->prepare(
"SELECT hc_name, hc_alias, hc_id, level, icon_id
FROM hostcategories
WHERE level IS NOT NULL AND hc_activate = '1'"
);
$stmt->execute();
$values = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($values as &$value) {
$this->hostSeverityCache[$value['hc_id']] = &$value;
}
}
/**
* Build cache of relations between host and severities
*
* @return void
*/
private function cacheHostSeverityLinked(): void
{
$stmt = $this->backendInstance->db->prepare(
'SELECT hc_id, host_host_id '
. 'FROM hostcategories, hostcategories_relation '
. 'WHERE level IS NOT NULL '
. 'AND hc_activate = "1" '
. 'AND hostcategories_relation.hostcategories_hc_id = hostcategories.hc_id'
);
$stmt->execute();
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $value) {
if (isset($this->hostLinkedCache[$value['host_host_id']])) {
if ($this->hostSeverityCache[$value['hc_id']]['level']
< $this->hostSeverityCache[$this->hostLinkedCache[$value['host_host_id']]]
) {
$this->hostLinkedCache[$value['host_host_id']] = $value['hc_id'];
}
} else {
$this->hostLinkedCache[$value['host_host_id']] = $value['hc_id'];
}
}
}
/**
* Build cache
*
* @return void
*/
private function buildCache()
{
if ($this->doneCache == 1) {
return 0;
}
$this->cacheHostSeverity();
$this->cacheHostSeverityLinked();
$this->doneCache = 1;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate-remote/Media.php | centreon/www/class/config-generate-remote/Media.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace ConfigGenerateRemote;
use ConfigGenerateRemote\Abstracts\AbstractObject;
use PDO;
/**
* Class
*
* @class Media
* @package ConfigGenerateRemote
*/
class Media extends AbstractObject
{
/** @var string */
protected $table = 'view_img';
/** @var string */
protected $generateFilename = 'view_img.infile';
/** @var string */
protected $attributesSelect = '
img_id,
img_name,
img_path,
img_comment,
dir_id,
dir_name,
dir_alias,
dir_comment
';
/** @var string[] */
protected $attributesWrite = [
'img_id',
'img_name',
'img_path',
'img_comment',
];
/** @var string|null */
protected $pathImg = null;
/** @var array|null */
private $medias = null;
/**
* Generate media object and get path
*
* @param int|null $mediaId
*
* @throws \Exception
* @return null|string
*/
public function getMediaPathFromId(?int $mediaId)
{
if (is_null($this->medias)) {
$this->getMedias();
}
$result = null;
if (! is_null($mediaId) && isset($this->medias[$mediaId])) {
$result = $this->medias[$mediaId]['dir_name'] . '/' . $this->medias[$mediaId]['img_path'];
if ($this->checkGenerate($mediaId)) {
return $result;
}
$media = [
'img_id' => $mediaId,
'img_name' => $this->medias[$mediaId]['img_name'],
'img_path' => $this->medias[$mediaId]['img_path'],
'img_comment' => $this->medias[$mediaId]['img_comment'],
];
$this->generateObjectInFile($media, $mediaId);
Relations\ViewImgDirRelation::getInstance($this->dependencyInjector)
->addRelation($mediaId, $this->medias[$mediaId]['dir_id']);
Relations\ViewImageDir::getInstance($this->dependencyInjector)
->add($this->medias[$mediaId], $this->medias[$mediaId]['dir_id']);
$this->copyMedia($this->medias[$mediaId]['dir_name'], $this->medias[$mediaId]['img_path']);
}
return $result;
}
/**
* Copy media
*
* @param string $dir
* @param string $file
*
* @throws \Exception
* @return void
*/
protected function copyMedia(string $dir, string $file)
{
$this->backendInstance->createDirectories([$this->backendInstance->getPath() . '/media/' . $dir]);
@copy(
$this->pathImg . '/' . $dir . '/' . $file,
$this->backendInstance->getPath() . '/media/' . $dir . '/' . $file
);
}
/**
* Get medias
*
* @return void
*/
private function getMedias(): void
{
$stmt = $this->backendInstance->db->prepare(
"SELECT {$this->attributesSelect}
FROM view_img, view_img_dir_relation, view_img_dir
WHERE view_img.img_id = view_img_dir_relation.img_img_id
AND view_img_dir_relation.dir_dir_parent_id = view_img_dir.dir_id"
);
$stmt->execute();
$this->medias = $stmt->fetchAll(PDO::FETCH_GROUP | PDO::FETCH_UNIQUE | PDO::FETCH_ASSOC);
$this->pathImg = \CentreonMedia::CENTREON_MEDIA_PATH;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate-remote/Host.php | centreon/www/class/config-generate-remote/Host.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace ConfigGenerateRemote;
use ConfigGenerateRemote\Abstracts\AbstractHost;
use Exception;
use PDO;
use PDOException;
use PDOStatement;
/**
* Class
*
* @class Host
* @package ConfigGenerateRemote
*/
class Host extends AbstractHost
{
/** @var array */
protected $hostsByName = [];
/** @var array|null */
protected $hosts = null;
/** @var string */
protected $table = 'host';
/** @var string */
protected $generateFilename = 'hosts.infile';
/** @var PDOStatement|null */
protected $stmtHg = null;
/** @var PDOStatement|null */
protected $stmtParent = null;
/** @var PDOStatement|null */
protected $stmtService = null;
/** @var PDOStatement|null */
protected $stmtServiceSg = null;
/** @var array */
protected $generatedParentship = [];
/** @var array */
protected $generatedHosts = [];
/**
* Add host in cache
*
* @param int $hostId
* @param array $attr
* @return void
*/
public function addHost(int $hostId, array $attr = []): void
{
$this->hosts[$hostId] = $attr;
}
/**
* Generate from host id
*
* @param array $host
* @return void
*/
public function generateFromHostId(array &$host): void
{
$this->getImages($host);
$this->getMacros($host);
$this->getHostTimezone($host);
$this->getHostTemplates($host);
$this->getHostPoller($host);
$this->getHostCommands($host);
$this->getHostPeriods($host);
if ($this->backendInstance->isExportContact()) {
$this->getContactGroups($host);
$this->getContacts($host);
}
$this->getHostGroups($host);
$this->getSeverity($host['host_id']);
$this->getServices($host);
$this->getServicesByHg($host);
$extendedInformation = $this->getExtendedInformation($host);
Relations\ExtendedHostInformation::getInstance($this->dependencyInjector)
->add($extendedInformation, $host['host_id']);
$this->generateObjectInFile($host, $host['host_id']);
$this->addGeneratedHost($host['host_id']);
}
/**
* Generate from poller id
*
* @param int $pollerId
* @param int $localhost
* @return void
*/
public function generateFromPollerId(int $pollerId, int $localhost = 0): void
{
if (is_null($this->hosts)) {
$this->getHosts($pollerId);
}
Service::getInstance($this->dependencyInjector)->setPoller($pollerId);
foreach ($this->hosts as $hostId => &$host) {
$this->hostsByName[$host['host_name']] = $hostId;
$host['host_id'] = $hostId;
$this->generateFromHostId($host);
}
// Forces the recreation of centreon-map images not linked to any resource,
// which are deleted by the export. Not the best fix, but an easy workaround.
foreach ($this->getMapImageIds() as $mapImageId) {
$media = Media::getInstance($this->dependencyInjector);
$media->getMediaPathFromId($mapImageId);
}
if ($localhost == 1) {
// MetaService::getInstance($this->dependencyInjector)->generateObjects();
}
Curves::getInstance($this->dependencyInjector)->generateObjects();
}
/**
* Get host id by host name
*
* @param string $hostName
* @return string|void
*/
public function getHostIdByHostName(string $hostName)
{
return $this->hostsByName[$hostName] ?? null;
}
/**
* Get generated parentship
*
* @return array
*/
public function getGeneratedParentship()
{
return $this->generatedParentship;
}
/**
* Add generated host
*
* @param int $hostId
* @return void
*/
public function addGeneratedHost(int $hostId): void
{
$this->generatedHosts[] = $hostId;
}
/**
* Get generated hosts
*
* @return array
*/
public function getGeneratedHosts()
{
return $this->generatedHosts;
}
/**
* Reset object
*
* @param bool $resetParent
* @param bool $createfile
*
* @throws Exception
* @return void
*/
public function reset($resetParent = false, $createfile = false): void
{
$this->hostsByName = [];
$this->hosts = null;
$this->generatedParentship = [];
$this->generatedHosts = [];
if ($resetParent == true) {
parent::reset($createfile);
}
}
/**
* Get linked severity
*
* @param int $hostIdArg
* @return void
*/
protected function getSeverity($hostIdArg)
{
$severityId = HostCategory::getInstance($this->dependencyInjector)->getHostSeverityByHostId($hostIdArg);
if (! is_null($severityId)) {
Relations\HostCategoriesRelation::getInstance($this->dependencyInjector)->addRelation($severityId, $hostIdArg);
}
}
/**
* Get linked host groups
*
* @param array $host
*
* @throws PDOException
* @return void
*/
private function getHostGroups(array &$host): void
{
if (! isset($host['hg'])) {
if (is_null($this->stmtHg)) {
$this->stmtHg = $this->backendInstance->db->prepare("SELECT
hostgroup_hg_id
FROM hostgroup_relation
INNER JOIN hostgroup ON hg_id = hostgroup_hg_id
AND hg_activate = '1'
WHERE host_host_id = :host_id
");
}
$this->stmtHg->bindParam(':host_id', $host['host_id'], PDO::PARAM_INT);
$this->stmtHg->execute();
$host['hg'] = $this->stmtHg->fetchAll(PDO::FETCH_COLUMN);
}
$hostgroup = HostGroup::getInstance($this->dependencyInjector);
foreach ($host['hg'] as $hgId) {
$hostgroup->addHostInHg($hgId, $host['host_id'], $host['host_name']);
Relations\HostGroupRelation::getInstance($this->dependencyInjector)->addRelation(
$hgId,
$host['host_id']
);
}
}
/**
* Get linked services
*
* @param array $host
*
* @throws PDOException
* @return void
*/
private function getServices(array &$host): void
{
if (is_null($this->stmtService)) {
$this->stmtService = $this->backendInstance->db->prepare('SELECT
service_service_id
FROM host_service_relation
WHERE host_host_id = :host_id AND service_service_id IS NOT NULL
');
}
$this->stmtService->bindParam(':host_id', $host['host_id'], PDO::PARAM_INT);
$this->stmtService->execute();
$host['services_cache'] = $this->stmtService->fetchAll(PDO::FETCH_COLUMN);
$service = Service::getInstance($this->dependencyInjector);
foreach ($host['services_cache'] as $serviceId) {
$service->generateFromServiceId($host['host_id'], $host['host_name'], $serviceId);
Relations\HostServiceRelation::getInstance($this->dependencyInjector)
->addRelationHostService($host['host_id'], $serviceId);
}
}
/**
* Get linked services by host group
*
* @param array $host
*
* @throws PDOException
* @return void
*/
private function getServicesByHg(array &$host)
{
if (count($host['hg']) == 0) {
return 1;
}
if (is_null($this->stmtServiceSg)) {
$query = 'SELECT host_service_relation.hostgroup_hg_id, service_service_id FROM host_service_relation '
. 'JOIN hostgroup_relation ON (hostgroup_relation.hostgroup_hg_id = '
. 'host_service_relation.hostgroup_hg_id) WHERE hostgroup_relation.host_host_id = :host_id';
$this->stmtServiceSg = $this->backendInstance->db->prepare($query);
}
$this->stmtServiceSg->bindParam(':host_id', $host['host_id'], PDO::PARAM_INT);
$this->stmtServiceSg->execute();
$host['services_hg_cache'] = $this->stmtServiceSg->fetchAll(PDO::FETCH_ASSOC);
$service = Service::getInstance($this->dependencyInjector);
foreach ($host['services_hg_cache'] as $value) {
$service->generateFromServiceId($host['host_id'], $host['host_name'], $value['service_service_id'], 1);
Relations\HostServiceRelation::getInstance($this->dependencyInjector)
->addRelationHgService($value['hostgroup_hg_id'], $value['service_service_id']);
}
}
/**
* Get linked hosts to poller id
*
* @param int $pollerId
* @return void
*/
private function getHosts(int $pollerId): void
{
// We use host_register = 1 because we don't want _Module_* hosts
$stmt = $this->backendInstance->db->prepare(
"SELECT {$this->attributesSelect}
FROM ns_host_relation, host
LEFT JOIN extended_host_information ON extended_host_information.host_host_id = host.host_id
WHERE ns_host_relation.nagios_server_id = :server_id
AND ns_host_relation.host_host_id = host.host_id
AND host.host_activate = '1'
AND host.host_register = '1'"
);
$stmt->bindParam(':server_id', $pollerId, PDO::PARAM_INT);
$stmt->execute();
$this->hosts = $stmt->fetchAll(PDO::FETCH_GROUP | PDO::FETCH_UNIQUE | PDO::FETCH_ASSOC);
}
/**
* @return array<int>
*/
private function getMapImageIds(): array
{
$stmt = $this->backendInstance->db->prepare(
<<<'SQL'
SELECT img_img_id
FROM view_img_dir_relation AS vidr
JOIN view_img_dir AS vid ON vidr.dir_dir_parent_id = vid.dir_id
WHERE vid.dir_name="centreon-map"
SQL
);
$stmt->execute();
return array_keys($stmt->fetchAll(PDO::FETCH_GROUP | PDO::FETCH_UNIQUE | PDO::FETCH_ASSOC) ?: []);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate-remote/Contact.php | centreon/www/class/config-generate-remote/Contact.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace ConfigGenerateRemote;
use ConfigGenerateRemote\Abstracts\AbstractObject;
use PDO;
use PDOStatement;
/**
* Class
*
* @class Contact
* @package ConfigGenerateRemote
*/
class Contact extends AbstractObject
{
/** @var int */
protected $useCache = 1;
/** @var array */
protected $contactsCache = [];
/** @var array */
protected $contacts = [];
/** @var string */
protected $table = 'contact';
/** @var string */
protected $generateFilename = 'contacts.infile';
/** @var string */
protected $objectName = 'contact';
/** @var string */
protected $attributesSelect = '
contact_id,
contact_template_id,
timeperiod_tp_id,
timeperiod_tp_id2,
contact_name,
contact_alias,
contact_host_notification_options,
contact_service_notification_options,
contact_email,
contact_enable_notifications,
contact_register,
contact_location,
reach_api,
reach_api_rt
';
/** @var string[] */
protected $attributesWrite = [
'contact_id',
'contact_template_id',
'timeperiod_tp_id',
'timeperiod_tp_id2',
'contact_name',
'contact_alias',
'contact_email',
'contact_register',
'contact_location',
'contact_enable_notifications',
'reach_api',
'reach_api_rt',
'contact_register',
];
/** @var PDOStatement|null */
protected $stmtContact = null;
/** @var <string,PDOStatement[]> */
protected $stmtCommands = ['host' => null, 'service' => null];
/** @var PDOStatement|null */
protected $stmtContactService = null;
/** @var int */
private $doneCache = 0;
/** @var array */
private $contactsServiceLinkedCache = [];
/**
* Get contact information linked to a service id
*
* @param int $serviceId
* @return array
*/
public function getContactForService(int $serviceId): array
{
$this->buildCache();
// Get from the cache
if (isset($this->contactsServiceLinkedCache[$serviceId])) {
return $this->contactsServiceLinkedCache[$serviceId];
}
if ($this->doneCache == 1) {
return [];
}
if (is_null($this->stmtContactService)) {
$this->stmtContactService = $this->backendInstance->db->prepare(
'SELECT contact_id
FROM contact_service_relation
WHERE service_service_id = :service_id'
);
}
$this->stmtContactService->bindParam(':service_id', $serviceId, PDO::PARAM_INT);
$this->stmtContactService->execute();
$this->contactsServiceLinkedCache[$serviceId] = $this->stmtContactService->fetchAll(PDO::FETCH_COLUMN);
return $this->contactsServiceLinkedCache[$serviceId];
}
/**
* Generation configuration from a contact id
*
* @param null|int $contactId
*
* @throws \Exception
* @return string|null the contact name or alias
*/
public function generateFromContactId(?int $contactId): ?string
{
if (is_null($contactId)) {
return null;
}
$this->buildCache();
if ($this->useCache == 1) {
if (! isset($this->contactsCache[$contactId])) {
return null;
}
$this->contacts[$contactId] = &$this->contactsCache[$contactId];
} elseif (! isset($this->contacts[$contactId])) {
$this->getContactFromId($contactId);
}
if (is_null($this->contacts[$contactId])) {
return null;
}
if ($this->checkGenerate($contactId)) {
return $this->contacts[$contactId]['contact_register'] == 1
? $this->contacts[$contactId]['contact_name']
: $this->contacts[$contactId]['contact_alias'];
}
$this->generateFromContactId($this->contacts[$contactId]['contact_template_id']);
$this->getContactNotificationCommands(
$contactId,
'host',
Relations\ContactHostCommandsRelation::getInstance($this->dependencyInjector)
);
$this->getContactNotificationCommands(
$contactId,
'service',
Relations\ContactServiceCommandsRelation::getInstance($this->dependencyInjector)
);
$period = Timeperiod::getInstance($this->dependencyInjector);
$period->generateFromTimeperiodId($this->contacts[$contactId]['timeperiod_tp_id']);
$period->generateFromTimeperiodId($this->contacts[$contactId]['timeperiod_tp_id2']);
$this->contacts[$contactId]['contact_id'] = $contactId;
$this->generateObjectInFile($this->contacts[$contactId], $contactId);
return $this->contacts[$contactId]['contact_register'] == 1
? $this->contacts[$contactId]['contact_name']
: $this->contacts[$contactId]['contact_alias'];
}
/**
* Store contact in contacts cache
*
* @param int $contactId
* @return void
*/
protected function getContactFromId(int $contactId)
{
if (is_null($this->stmtContact)) {
$this->stmtContact = $this->backendInstance->db->prepare(
"SELECT {$this->attributesSelect}
FROM contact
WHERE contact_id = :contact_id AND contact_activate = '1'"
);
}
$this->stmtContact->bindParam(':contact_id', $contactId, PDO::PARAM_INT);
$this->stmtContact->execute();
$results = $this->stmtContact->fetchAll(PDO::FETCH_ASSOC);
$this->contacts[$contactId] = array_pop($results);
if (is_null($this->contacts[$contactId])) {
return 1;
}
}
/**
* Generate notification commands linked to contact id
*
* @param int $contactId
* @param string $label
* @param object $instance
* @return void|null
*/
protected function getContactNotificationCommands(int $contactId, string $label, object $instance)
{
// avoid sql injection with label
if (in_array($label, ['host', 'service'])) {
return null;
}
if (! isset($this->contacts[$contactId][$label . '_commands_cache'])) {
if (is_null($this->stmtCommands[$label])) {
$this->stmtCommands[$label] = $this->backendInstance->db->prepare(
'SELECT command_command_id
FROM contact_' . $label . 'commands_relation
WHERE contact_contact_id = :contact_id'
);
}
$this->stmtCommands[$label]->bindParam(':contact_id', $contactId, PDO::PARAM_INT);
$this->stmtCommands[$label]->execute();
$this->contacts[$contactId][$label . '_commands_cache']
= $this->stmtCommands[$label]->fetchAll(PDO::FETCH_COLUMN);
}
$command = Command::getInstance($this->dependencyInjector);
foreach ($this->contacts[$contactId][$label . '_commands_cache'] as $commandId) {
$command->generateFromCommandId($commandId);
$instance->addRelation($contactId, $commandId);
}
}
/**
* Build contact cache
*/
protected function buildCache(): void
{
if ($this->doneCache == 1) {
return;
}
$this->getContactCache();
$this->getContactForServiceCache();
$this->doneCache = 1;
}
/**
* Store contacts in cache
*
* @return void
*/
private function getContactCache(): void
{
$stmt = $this->backendInstance->db->prepare(
"SELECT {$this->attributesSelect}
FROM contact
WHERE contact_activate = '1'"
);
$stmt->execute();
$this->contactsCache = $stmt->fetchAll(PDO::FETCH_GROUP | PDO::FETCH_UNIQUE | PDO::FETCH_ASSOC);
}
/**
* Store contacts linked to a service in cache
*
* @return void
*/
private function getContactForServiceCache(): void
{
$stmt = $this->backendInstance->db->prepare(
'SELECT contact_id, service_service_id
FROM contact_service_relation'
);
$stmt->execute();
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $value) {
if (isset($this->contactsServiceLinkedCache[$value['service_service_id']])) {
$this->contactsServiceLinkedCache[$value['service_service_id']][] = $value['contact_id'];
} else {
$this->contactsServiceLinkedCache[$value['service_service_id']] = [$value['contact_id']];
}
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate-remote/Abstracts/AbstractService.php | centreon/www/class/config-generate-remote/Abstracts/AbstractService.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace ConfigGenerateRemote\Abstracts;
use ConfigGenerateRemote\Command;
use ConfigGenerateRemote\Contact;
use ConfigGenerateRemote\ContactGroup;
use ConfigGenerateRemote\MacroService;
use ConfigGenerateRemote\Media;
use ConfigGenerateRemote\Relations\ContactGroupServiceRelation;
use ConfigGenerateRemote\Relations\ContactServiceRelation;
use ConfigGenerateRemote\ServiceTemplate;
use ConfigGenerateRemote\TimePeriod;
use ConfigGenerateRemote\Trap;
/**
* Class
*
* @class AbstractService
* @package ConfigGenerateRemote\Abstracts
*/
abstract class AbstractService extends AbstractObject
{
/** @var array */
protected $serviceCache;
/** @var string */
protected $attributesSelect = '
service_id,
service_template_model_stm_id,
command_command_id,
command_command_id_arg,
timeperiod_tp_id,
timeperiod_tp_id2,
command_command_id2,
command_command_id_arg2,
service_description,
service_alias,
display_name,
service_is_volatile,
service_max_check_attempts,
service_normal_check_interval,
service_retry_check_interval,
service_active_checks_enabled,
service_passive_checks_enabled,
service_event_handler_enabled,
service_notification_interval,
service_notification_options,
service_notifications_enabled,
service_register,
esi_notes,
esi_notes_url,
esi_action_url,
esi_icon_image,
esi_icon_image_alt,
graph_id,
service_acknowledgement_timeout
';
/** @var string[] */
protected $attributesWrite = ['service_id', 'service_template_model_stm_id', 'command_command_id', 'command_command_id_arg', 'timeperiod_tp_id', 'timeperiod_tp_id2', 'command_command_id2', 'command_command_id_arg2', 'service_description', 'service_alias', 'display_name', 'service_is_volatile', 'service_max_check_attempts', 'service_normal_check_interval', 'service_retry_check_interval', 'service_active_checks_enabled', 'service_passive_checks_enabled', 'service_event_handler_enabled', 'service_notification_interval', 'service_notification_options', 'service_notifications_enabled', 'service_register', 'service_acknowledgement_timeout'];
/** @var array */
protected $loopStpl = []; // To be reset
/** @var null */
protected $stmtMacro = null;
/** @var null */
protected $stmtStpl = null;
/** @var null */
protected $stmtContact = null;
/** @var null */
protected $stmtService = null;
/**
* Get service attribute
*
* @param int $serviceId
* @param string $attr
* @return string|null
*/
public function getString(int $serviceId, string $attr): ?string
{
return $this->serviceCache[$serviceId][$attr] ?? null;
}
/**
* Get service extended information
* extended information are unset on service object
*
* @param array $service the service to parse
* @return array the extended information
*/
protected function getExtendedInformation(array &$service): array
{
$extendedInformation = [
'service_service_id' => $service['service_id'],
'esi_notes' => $service['esi_notes'],
'esi_notes_url' => $service['esi_notes_url'],
'esi_action_url' => $service['esi_action_url'],
'esi_icon_image' => $service['esi_icon_image'],
'esi_icon_image_alt' => $service['esi_icon_image_alt'],
'graph_id' => $service['graph_id'],
];
unset($service['esi_notes'], $service['esi_notes_url'], $service['esi_action_url'], $service['esi_icon_image'], $service['esi_icon_image_alt'], $service['graph_id']);
return $extendedInformation;
}
/**
* Get service linked icons
*
* @param array $service
* @return void
*/
protected function getImages(array &$service): void
{
$media = Media::getInstance($this->dependencyInjector);
$media->getMediaPathFromId($service['esi_icon_image']);
}
/**
* Get service linked macros
*
* @param array $service
* @return int
*/
protected function getMacros(array &$service): int
{
if (isset($service['macros'])) {
return 1;
}
$service['macros'] = MacroService::getInstance($this->dependencyInjector)
->getServiceMacroByServiceId($service['service_id']);
return 0;
}
/**
* @param array $service
*
* @return void
*/
protected function getTraps(array &$service): void
{
Trap::getInstance($this->dependencyInjector)
->getTrapsByServiceId($service['service_id']);
}
/**
* Get service templates linked to the service
*
* @param array $service
* @return void
*/
protected function getServiceTemplates(array &$service): void
{
ServiceTemplate::getInstance($this->dependencyInjector)
->generateFromServiceId($service['service_template_model_stm_id']);
}
/**
* Get service linked contacts
*
* @param array $service
* @return void
*/
protected function getContacts(array &$service): void
{
$contact = Contact::getInstance($this->dependencyInjector);
$service['contacts_cache'] = $contact->getContactForService($service['service_id']);
foreach ($service['contacts_cache'] as $contactId) {
$contact->generateFromContactId($contactId);
ContactServiceRelation::getInstance($this->dependencyInjector)
->addRelation($service['service_id'], $contactId);
}
}
/**
* Get service linked contact groups
*
* @param array $service
* @return void
*/
protected function getContactGroups(array &$service): void
{
$cg = ContactGroup::getInstance($this->dependencyInjector);
$service['contact_groups_cache'] = $cg->getCgForService($service['service_id']);
foreach ($service['contact_groups_cache'] as $cgId) {
$cg->generateFromCgId($cgId);
ContactGroupServiceRelation::getInstance($this->dependencyInjector)
->addRelation($service['service_id'], $cgId);
}
}
/**
* Generate service linked command
*
* @param array $service
* @param string $commandIdLabel
* @return int
*/
protected function getServiceCommand(array &$service, string $commandIdLabel): int
{
Command::getInstance($this->dependencyInjector)
->generateFromCommandId($service[$commandIdLabel]);
return 0;
}
/**
* Get service linked commands
*
* @param array $service
* @return void
*/
protected function getServiceCommands(array &$service)
{
$this->getServiceCommand($service, 'command_command_id');
$this->getServiceCommand($service, 'command_command_id2');
}
/**
* Get service linked timeperiods
*
* @param array $service
* @return void
*/
protected function getServicePeriods(array &$service)
{
$period = TimePeriod::getInstance($this->dependencyInjector);
$period->generateFromTimeperiodId($service['timeperiod_tp_id']);
$period->generateFromTimeperiodId($service['timeperiod_tp_id2']);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate-remote/Abstracts/AbstractHost.php | centreon/www/class/config-generate-remote/Abstracts/AbstractHost.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace ConfigGenerateRemote\Abstracts;
use ConfigGenerateRemote\Command;
use ConfigGenerateRemote\Contact;
use ConfigGenerateRemote\ContactGroup;
use ConfigGenerateRemote\HostTemplate;
use ConfigGenerateRemote\Media;
use ConfigGenerateRemote\Relations\ContactGroupHostRelation;
use ConfigGenerateRemote\Relations\ContactHostRelation;
use ConfigGenerateRemote\Relations\HostPollerRelation;
use ConfigGenerateRemote\Relations\HostTemplateRelation;
use ConfigGenerateRemote\Relations\MacroHost;
use ConfigGenerateRemote\TimePeriod;
use PDO;
use PDOStatement;
/**
* Class
*
* @class AbstractHost
* @package ConfigGenerateRemote\Abstracts
*/
abstract class AbstractHost extends AbstractObject
{
/** @var PDOStatement */
protected $stmt_htpl;
/** @var array */
protected $hosts;
/** @var string */
protected $attributesSelect = '
host_id,
command_command_id,
command_command_id_arg1,
timeperiod_tp_id,
timeperiod_tp_id2,
command_command_id2,
command_command_id_arg2,
host_name,
host_alias,
host_address,
display_name,
host_max_check_attempts,
host_check_interval,
host_retry_check_interval,
host_active_checks_enabled,
host_passive_checks_enabled,
host_event_handler_enabled,
host_notification_interval,
host_notification_options,
host_notifications_enabled,
host_snmp_community,
host_snmp_version,
host_register,
ehi_notes,
ehi_notes_url,
ehi_action_url,
ehi_icon_image,
ehi_icon_image_alt,
ehi_statusmap_image,
ehi_2d_coords,
ehi_3d_coords,
host_location,
host_acknowledgement_timeout,
geo_coords
';
/** @var string[] */
protected $attributesWrite = [
'host_id',
'command_command_id',
'command_command_id_arg1',
'timeperiod_tp_id',
'timeperiod_tp_id2',
'command_command_id2',
'command_command_id_arg2',
'host_name',
'host_alias',
'host_address',
'display_name',
'host_max_check_attempts',
'host_check_interval',
'host_retry_check_interval',
'host_active_checks_enabled',
'host_passive_checks_enabled',
'host_event_handler_enabled',
'host_notification_interval',
'host_notification_options',
'host_notifications_enabled',
'host_snmp_community',
'host_snmp_version',
'host_register',
'host_location',
'host_acknowledgement_timeout',
'geo_coords',
];
/** @var array */
protected $loopHtpl = []; // To be reset
/** @var null */
protected $stmtMacro = null;
/** @var null */
protected $stmtHtpl = null;
/** @var null */
protected $stmtContact = null;
/** @var null */
protected $stmtCg = null;
/** @var null */
protected $stmtPoller = null;
/**
* Check if a host id is a host template
*
* @param int $hostId
* @param int $hostTplId
* @return bool
*/
public function isHostTemplate(int $hostId, int $hostTplId): bool
{
$loop = [];
$stack = [];
$hostsTpl = HostTemplate::getInstance($this->dependencyInjector)->hosts;
$stack = $this->hosts[$hostId]['htpl'];
while (($hostId = array_shift($stack))) {
if (isset($loop[$hostId])) {
continue;
}
$loop[$hostId] = 1;
if ($hostId == $hostTplId) {
return true;
}
$stack = array_merge($hostsTpl[$hostId]['htpl'], $stack);
}
return false;
}
/**
* Get host attribute
*
* @param int $hostId
* @param string $attr
* @return string|null
*/
public function getString(int $hostId, string $attr): ?string
{
return $this->hosts[$hostId][$attr] ?? null;
}
/**
* Get host extended information
* extended information are unset on host object
*
* @param array $host the host to parse
* @return array the extended information
*/
protected function getExtendedInformation(array &$host): array
{
$extendedInformation = [
'host_host_id' => $host['host_id'],
'ehi_notes' => $host['ehi_notes'],
'ehi_notes_url' => $host['ehi_notes_url'],
'ehi_action_url' => $host['ehi_action_url'],
'ehi_icon_image' => $host['ehi_icon_image'],
'ehi_icon_image_alt' => $host['ehi_icon_image_alt'],
'ehi_2d_coords' => $host['ehi_2d_coords'],
'ehi_3d_coords' => $host['ehi_3d_coords'],
];
unset($host['ehi_notes'], $host['ehi_notes_url'], $host['ehi_action_url'], $host['ehi_icon_image'], $host['ehi_icon_image_alt'], $host['ehi_2d_coords'], $host['ehi_3d_coords']);
return $extendedInformation;
}
/**
* Get host icons
*
* @param array $host
* @return void
*/
protected function getImages(array &$host): void
{
$media = Media::getInstance($this->dependencyInjector);
$media->getMediaPathFromId($host['ehi_icon_image']);
$media->getMediaPathFromId($host['ehi_statusmap_image']);
}
/**
* Get host macros
*
* @param array $host
* @return int
*/
protected function getMacros(array &$host): int
{
if (isset($host['macros'])) {
return 1;
}
$host['macros'] = MacroHost::getInstance($this->dependencyInjector)
->getHostMacroByHostId($host['host_id']);
return 0;
}
/**
* Get linked host templates
*
* @param array $host
* @return void
*/
protected function getHostTemplates(array &$host): void
{
if (! isset($host['htpl'])) {
if (is_null($this->stmt_htpl)) {
$this->stmt_htpl = $this->backendInstance->db->prepare(
'SELECT host_tpl_id
FROM host_template_relation
WHERE host_host_id = :host_id
ORDER BY `order` ASC'
);
}
$this->stmt_htpl->bindParam(':host_id', $host['host_id'], PDO::PARAM_INT);
$this->stmt_htpl->execute();
$host['htpl'] = $this->stmt_htpl->fetchAll(PDO::FETCH_COLUMN);
}
$host_template = HostTemplate::getInstance($this->dependencyInjector);
$order = 1;
foreach ($host['htpl'] as $templateId) {
$host_template->generateFromHostId($templateId);
HostTemplateRelation::getInstance($this->dependencyInjector)
->addRelation($host['host_id'], $templateId, $order);
$order++;
}
}
/**
* Get linked poller
*
* @param array $host
* @return void
*/
protected function getHostPoller(array $host): void
{
if (is_null($this->stmtPoller)) {
$this->stmtPoller = $this->backendInstance->db->prepare(
'SELECT nagios_server_id
FROM ns_host_relation
WHERE host_host_id = :host_id'
);
}
$this->stmtPoller->bindParam(':host_id', $host['host_id'], PDO::PARAM_INT);
$this->stmtPoller->execute();
$pollerId = $this->stmtPoller->fetchAll(PDO::FETCH_COLUMN);
HostPollerRelation::getInstance($this->dependencyInjector)
->addRelation($pollerId[0], $host['host_id']);
}
/**
* Get linked contacts
*
* @param array $host
* @return void
*/
protected function getContacts(array &$host): void
{
if (! isset($host['contacts_cache'])) {
if (is_null($this->stmtContact)) {
$this->stmtContact = $this->backendInstance->db->prepare(
'SELECT contact_id
FROM contact_host_relation
WHERE host_host_id = :host_id'
);
}
$this->stmtContact->bindParam(':host_id', $host['host_id'], PDO::PARAM_INT);
$this->stmtContact->execute();
$host['contacts_cache'] = $this->stmtContact->fetchAll(PDO::FETCH_COLUMN);
}
$contact = Contact::getInstance($this->dependencyInjector);
foreach ($host['contacts_cache'] as $contactId) {
$contact->generateFromContactId($contactId);
ContactHostRelation::getInstance($this->dependencyInjector)->addRelation($host['host_id'], $contactId);
}
}
/**
* Get linked contact groups
*
* @param array $host
* @return void
*/
protected function getContactGroups(array &$host): void
{
if (! isset($host['contact_groups_cache'])) {
if (is_null($this->stmtCg)) {
$this->stmtCg = $this->backendInstance->db->prepare(
'SELECT contactgroup_cg_id
FROM contactgroup_host_relation
WHERE host_host_id = :host_id'
);
}
$this->stmtCg->bindParam(':host_id', $host['host_id'], PDO::PARAM_INT);
$this->stmtCg->execute();
$host['contact_groups_cache'] = $this->stmtCg->fetchAll(PDO::FETCH_COLUMN);
}
$cg = ContactGroup::getInstance($this->dependencyInjector);
foreach ($host['contact_groups_cache'] as $cgId) {
$cg->generateFromCgId($cgId);
ContactGroupHostRelation::getInstance($this->dependencyInjector)->addRelation($host['host_id'], $cgId);
}
}
/**
* Get host timezone
*
* @param array $host
* @return void
*/
protected function getHostTimezone(array &$host): void
{
// not needed
}
/**
* Generate host command
*
* @param array $host
* @param string $commandIdLabel
* @return int
*/
protected function getHostCommand(array &$host, string $commandIdLabel): int
{
Command::getInstance($this->dependencyInjector)->generateFromCommandId($host[$commandIdLabel]);
return 0;
}
/**
* Get host linked commands
*
* @param array $host
* @return void
*/
protected function getHostCommands(array &$host): void
{
$this->getHostCommand($host, 'command_command_id');
$this->getHostCommand($host, 'command_command_id2');
}
/**
* Get host linked timeperiods
*
* @param array $host
* @return void
*/
protected function getHostPeriods(array &$host): void
{
$period = TimePeriod::getInstance($this->dependencyInjector);
$period->generateFromTimeperiodId($host['timeperiod_tp_id']);
$period->generateFromTimeperiodId($host['timeperiod_tp_id2']);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate-remote/Abstracts/AbstractObject.php | centreon/www/class/config-generate-remote/Abstracts/AbstractObject.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace ConfigGenerateRemote\Abstracts;
use ConfigGenerateRemote\Backend;
use ConfigGenerateRemote\Manifest;
use Exception;
use Pimple\Container;
/**
* Class
*
* @class AbstractObject
* @package ConfigGenerateRemote\Abstracts
*/
abstract class AbstractObject
{
/** @var array */
public $attributes_array;
/** @var array */
public $attributes_hash;
/** @var array */
public $attributes_default;
/** @var Backend|null */
protected $backendInstance = null;
/** @var string|null */
protected $generateFilename = null;
/** @var string|null */
protected $table = null;
/** @var array */
protected $exported = [];
/** @var resource|null */
protected $fp = null;
/** @var string */
protected $type = 'infile';
/** @var string */
protected $subdir = 'configuration';
/** @var array */
protected $attributesWrite = [];
/** @var array */
protected $attributesArray = [];
/** @var bool */
protected $engine = true;
/** @var bool */
protected $broker = false;
/** @var Container */
protected $dependencyInjector;
/** @var string|null */
protected $fieldSeparatorInfile = null;
/** @var string|null */
protected $lineSeparatorInfile = null;
/**
* Constructor
*
* @param Container $dependencyInjector
*/
protected function __construct(Container $dependencyInjector)
{
$this->dependencyInjector = $dependencyInjector;
$this->backendInstance = Backend::getInstance($this->dependencyInjector);
$this->fieldSeparatorInfile = $this->backendInstance->getFieldSeparatorInfile();
$this->lineSeparatorInfile = $this->backendInstance->getLineSeparatorInfile();
}
/**
* Destructor
*/
public function __destruct()
{
$this->closeFile();
}
/**
* Get instance singleton
*
* @param Container $dependencyInjector
* @return object
*/
public static function getInstance(Container $dependencyInjector)
{
static $instances = [];
$calledClass = static::class;
if (! isset($instances[$calledClass])) {
$instances[$calledClass] = new $calledClass($dependencyInjector);
}
return $instances[$calledClass];
}
/**
* Close file if open
*
* @return void
*/
public function closeFile(): void
{
if (! is_null($this->fp)) {
fclose($this->fp);
}
$this->fp = null;
}
/**
* Reset object
*
* @param bool $createfile
*
* @throws Exception
* @return void
*/
public function reset($createfile = false): void
{
$this->closeFile();
$this->exported = [];
if ($createfile == true) {
$this->createFile($this->backendInstance->getPath());
}
}
/**
* Check if an id has already been generated
*
* @param int $id
* @return bool
*/
public function checkGenerate($id): bool
{
return (bool) (isset($this->exported[$id]));
}
/**
* Get exported ids
*
* @return array
*/
public function getExported(): array
{
return $this->exported ?? [];
}
/**
* Check if current object is engine
*
* @return bool
*/
public function isEngineObject(): bool
{
return $this->engine;
}
/**
* Check if current object is broker
*
* @return bool
*/
public function isBrokerObject(): bool
{
return $this->broker;
}
/**
* Create generateFilename in given directory
*
* @param string $dir
*
* @throws Exception
* @return void
*/
protected function createFile(string $dir): void
{
$fullFile = $dir . '/' . $this->subdir . '/' . $this->generateFilename;
if (! ($this->fp = @fopen($fullFile, 'a+'))) {
throw new Exception("Cannot open file (writing permission) '" . $fullFile . "'");
}
if (posix_getuid() === fileowner($fullFile)) {
chmod($fullFile, 0660);
}
if ($this->type == 'infile') {
Manifest::getInstance($this->dependencyInjector)->addFile(
$this->generateFilename,
$this->type,
$this->table,
$this->attributesWrite
);
}
}
/**
* Write object in file
*
* @param array $object
* @return void
*/
protected function writeObject(array $object): void
{
$line = '';
$append = '';
$counter = count($this->attributesWrite);
for ($i = 0; $i < $counter; $i++) {
if (isset($object[$this->attributesWrite[$i]]) && strlen($object[$this->attributesWrite[$i]])) {
$line .= $append . '"' . str_replace('"', '""', $object[$this->attributesWrite[$i]]) . '"';
} else {
$line .= $append . '\N';
}
$append = $this->fieldSeparatorInfile;
}
fwrite($this->fp, $line . $this->lineSeparatorInfile);
}
/**
* Generate object in file
*
* @param array $object
* @param int|string|null $id
*
* @throws Exception
* @return void
*/
protected function generateObjectInFile(array $object, $id = null): void
{
if (is_null($this->fp)) {
$this->createFile($this->backendInstance->getPath());
}
$this->writeObject($object);
if (! is_null($id)) {
$this->exported[$id] = 1;
}
}
/**
* Generate file
*
* @param array $object
*
* @throws Exception
* @return void
*/
protected function generateFile(array $object): void
{
if (is_null($this->fp)) {
$this->createFile($this->backendInstance->getPath());
}
$this->writeNoObject($object);
}
/**
* Convert string in UTF-8
*
* @param string $str
* @return string
*/
private function toUTF8(string $str): string
{
$finalString = $str;
if (mb_detect_encoding($finalString, 'UTF-8', true) !== 'UTF-8') {
$finalString = mb_convert_encoding($finalString, 'UTF-8');
}
return $finalString;
}
/**
* Write string in file
*
* @param array $object
* @return void
*/
private function writeNoObject(array $object): void
{
foreach ($this->attributes_array as &$attr) {
if (isset($object[$attr]) && ! is_null($object[$attr]) && is_array($object[$attr])) {
foreach ($object[$attr] as $v) {
fwrite($this->fp, $this->toUTF8($attr . '=' . $v . "\n"));
}
}
}
foreach ($this->attributes_hash as &$attr) {
if (! isset($object[$attr])) {
continue;
}
foreach ($object[$attr] as $key => &$value) {
fwrite($this->fp, $this->toUTF8($key . '=' . $value . "\n"));
}
}
foreach ($this->attributesWrite as &$attr) {
if (isset($object[$attr]) && ! is_null($object[$attr]) && $object[$attr] != '') {
fwrite($this->fp, $this->toUTF8($attr . '=' . $object[$attr] . "\n"));
}
}
foreach ($this->attributes_default as &$attr) {
if (isset($object[$attr]) && ! is_null($object[$attr]) && $object[$attr] != 2) {
fwrite($this->fp, $this->toUTF8($attr . '=' . $object[$attr] . "\n"));
}
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate-remote/Relations/ServiceGroupRelation.php | centreon/www/class/config-generate-remote/Relations/ServiceGroupRelation.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace ConfigGenerateRemote\Relations;
use ConfigGenerateRemote\Abstracts\AbstractObject;
use Exception;
/**
* Class
*
* @class ServiceGroupRelation
* @package ConfigGenerateRemote\Relations
*/
class ServiceGroupRelation extends AbstractObject
{
protected $table = 'servicegroup_relation';
protected $generateFilename = 'servicegroup_relation.infile';
protected $attributesWrite = [
'host_host_id',
'service_service_id',
'servicegroup_sg_id',
];
/**
* Add relation
*
* @param int $sgId
* @param int $hostId
* @param int $serviceId
*
* @throws Exception
* @return void
*/
public function addRelationHostService(int $sgId, int $hostId, int $serviceId)
{
if ($this->checkGenerate($sgId . '.' . $hostId . '.' . $serviceId)) {
return null;
}
$relation = [
'servicegroup_sg_id' => $sgId,
'host_host_id' => $hostId,
'service_service_id' => $serviceId,
];
$this->generateObjectInFile($relation, $sgId . '.' . $hostId . '.' . $serviceId);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate-remote/Relations/TrapsGroup.php | centreon/www/class/config-generate-remote/Relations/TrapsGroup.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace ConfigGenerateRemote\Relations;
use ConfigGenerateRemote\Abstracts\AbstractObject;
use Exception;
use PDO;
use Pimple\Container;
/**
* Class
*
* @class TrapsGroup
* @package ConfigGenerateRemote\Relations
*/
class TrapsGroup extends AbstractObject
{
/** @var */
public $trapgroupCache;
/** @var */
public $serviceLinkedCache;
/** @var string */
protected $table = 'traps_group';
/** @var string */
protected $generateFilename = 'traps_group.infile';
/** @var null */
protected $stmtTrap = null;
/** @var string[] */
protected $attributesWrite = [
'traps_group_id',
'traps_group_name',
];
/** @var int */
private $useCache = 1;
/** @var int */
private $doneCache = 0;
/** @var array */
private $trapGroupCache = [];
/** @var array */
private $trapLinkedCache = [];
/**
* TrapsGroup constructor
*
* @param Container $dependencyInjector
*/
public function __construct(Container $dependencyInjector)
{
parent::__construct($dependencyInjector);
$this->buildCache();
}
/**
* Generate trap group
*
* @param int $trapId
* @param array $trapLinkedCache
* @param array $object
*
* @throws Exception
* @return void
*/
public function generateObject(int $trapId, array $trapLinkedCache, array &$object): void
{
foreach ($trapLinkedCache as $trapGroupId) {
trapsGroupRelation::getInstance($this->dependencyInjector)->addRelation($trapId, $trapGroupId);
if ($this->checkGenerate($trapGroupId)) {
continue;
}
$this->generateObjectInFile($object[$trapGroupId], $trapGroupId);
}
}
/**
* Get trap linked trap groups
*
* @param int $trapId
*
* @throws Exception
* @return void
*/
public function getTrapGroupsByTrapId(int $trapId)
{
// Get from the cache
if (isset($this->trapLinkedCache[$trapId])) {
$this->generateObject($trapId, $this->trapLinkedCache[$trapId], $this->trapgroupCache);
return $this->trapLinkedCache[$trapId];
}
if ($this->useCache == 1) {
return null;
}
// We get unitary
if (is_null($this->stmtTrap)) {
$this->stmtTrap = $this->backendInstance->db->prepare(
'SELECT traps_group.*
FROM traps_service_relation, traps_group
WHERE traps_group_relation.traps_id = :trap_id
AND traps_group_relation.traps_group_id = traps_group.traps_group_id'
);
}
$this->stmtTrap->bindParam(':trap_id', $trapId, PDO::PARAM_INT);
$this->stmtTrap->execute();
$trapLinkedCache = [];
$trapGroupCache = [];
foreach ($this->stmtTrap->fetchAll(PDO::FETCH_ASSOC) as &$value) {
$trapLinkedCache[] = $value['traps_group_id'];
$trapGroupCache[$value['traps_id']] = $value;
}
$this->generateObject($trapId, $trapLinkedCache, $trapGroupCache);
return $trapLinkedCache;
}
/**
* Build cache of trap groups
*
* @return void
*/
private function cacheTrapGroup(): void
{
$stmt = $this->backendInstance->db->prepare(
'SELECT *
FROM traps_group'
);
$stmt->execute();
$values = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($values as &$value) {
$this->trapgroupCache[$value['traps_group_id']] = &$value;
}
}
/**
* Build cache of relations between traps and trap groups
*
* @return void
*/
private function cacheTrapLinked(): void
{
$stmt = $this->backendInstance->db->prepare(
'SELECT traps_group_id, traps_id
FROM traps_group_relation'
);
$stmt->execute();
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $value) {
if (! isset($this->serviceLinkedCache[$value['traps_id']])) {
$this->trapLinkedCache[$value['traps_id']] = [];
}
$this->trapLinkedCache[$value['traps_id']][] = $value['traps_group_id'];
}
}
/**
* Build cache
*
* @return void
*/
private function buildCache()
{
if ($this->doneCache == 1) {
return 0;
}
$this->cacheTrapGroup();
$this->cacheTrapLinked();
$this->doneCache = 1;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate-remote/Relations/TrapsPreexec.php | centreon/www/class/config-generate-remote/Relations/TrapsPreexec.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace ConfigGenerateRemote\Relations;
use ConfigGenerateRemote\Abstracts\AbstractObject;
use Exception;
use PDO;
use Pimple\Container;
/**
* Class
*
* @class TrapsPreexec
* @package ConfigGenerateRemote\Relations
*/
class TrapsPreexec extends AbstractObject
{
/** @var string */
protected $table = 'traps_preexec';
/** @var string */
protected $generateFilename = 'traps_preexec.infile';
/** @var null */
protected $stmtTrap = null;
/** @var string[] */
protected $attributesWrite = [
'trap_id',
'tpe_order',
'tpe_string',
];
/** @var int */
private $useCache = 1;
/** @var int */
private $doneCache = 0;
/** @var array */
private $trapPreexecCache = [];
/**
* TrapsPreexec constructor
*
* @param Container $dependencyInjector
*/
public function __construct(Container $dependencyInjector)
{
parent::__construct($dependencyInjector);
$this->buildCache();
}
/**
* Generate object
*
* @param int $trapId
* @param array $trapPreexecCache
*
* @throws Exception
* @return void
*/
public function generateObject($trapId, $trapPreexecCache): void
{
foreach ($trapPreexecCache as $value) {
$this->generateObjectInFile($value);
}
}
/**
* Get trap preexec from trap id
*
* @param int $trapId
*
* @throws Exception
* @return void
*/
public function getTrapPreexecByTrapId(int $trapId)
{
// Get from the cache
if (isset($this->trapPreexecCache[$trapId])) {
$this->generateObject($trapId, $this->trapPreexecCache[$trapId]);
return $this->trapPreexecCache[$trapId];
}
if ($this->useCache == 1) {
return null;
}
// We get unitary
if (is_null($this->stmtTrap)) {
$this->stmtTrap = $this->backendInstance->db->prepare(
'SELECT *
FROM traps_preexec
WHERE trap_id = :trap_id'
);
}
$this->stmtTrap->bindParam(':trap_id', $trapId, PDO::PARAM_INT);
$this->stmtTrap->execute();
$trapPreexecCache = [];
foreach ($this->stmtTrap->fetchAll(PDO::FETCH_ASSOC) as &$value) {
$trapPreexecCache[$value['traps_id']] = $value;
}
$this->generateObject($trapId, $trapPreexecCache[$trapId]);
return $trapPreexecCache;
}
/**
* Build cache of trap preexec
*
* @return void
*/
private function cacheTrapPreexec(): void
{
$stmt = $this->backendInstance->db->prepare(
'SELECT *
FROM traps_preexec'
);
$stmt->execute();
$values = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($values as &$value) {
if (! isset($this->trapPreexecCache[$value['trap_id']])) {
$this->trapPreexecCache[$value['trap_id']] = [];
}
$this->trapPreexecCache[$value['trap_id']][] = &$value;
}
}
/**
* Build cache
*
* @return void
*/
private function buildCache()
{
if ($this->doneCache == 1) {
return 0;
}
$this->cacheTrapPreexec();
$this->doneCache = 1;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate-remote/Relations/ServiceCategoriesRelation.php | centreon/www/class/config-generate-remote/Relations/ServiceCategoriesRelation.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace ConfigGenerateRemote\Relations;
use ConfigGenerateRemote\Abstracts\AbstractObject;
use Exception;
/**
* Class
*
* @class ServiceCategoriesRelation
* @package ConfigGenerateRemote\Relations
*/
class ServiceCategoriesRelation extends AbstractObject
{
/** @var string */
protected $table = 'service_categories_relation';
/** @var string */
protected $generateFilename = 'service_categories_relation.infile';
/** @var string[] */
protected $attributesWrite = [
'sc_id',
'service_service_id',
];
/**
* Add relation
*
* @param int $scId
* @param int $serviceId
*
* @throws Exception
* @return void
*/
public function addRelation(int $scId, int $serviceId): void
{
$relation = [
'sc_id' => $scId,
'service_service_id' => $serviceId,
];
$this->generateObjectInFile($relation);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate-remote/Relations/HostServiceRelation.php | centreon/www/class/config-generate-remote/Relations/HostServiceRelation.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace ConfigGenerateRemote\Relations;
use ConfigGenerateRemote\Abstracts\AbstractObject;
use Exception;
/**
* Class
*
* @class HostServiceRelation
* @package ConfigGenerateRemote\Relations
*/
class HostServiceRelation extends AbstractObject
{
protected $table = 'host_service_relation';
protected $generateFilename = 'host_service_relation.infile';
protected $attributesWrite = [
'host_host_id',
'hostgroup_hg_id',
'service_service_id',
];
/**
* Add relation between host and service
*
* @param int $hostId
* @param int $serviceId
*
* @throws Exception
* @return void
*/
public function addRelationHostService(int $hostId, int $serviceId): void
{
$relation = [
'host_host_id' => $hostId,
'service_service_id' => $serviceId,
];
$this->generateObjectInFile($relation, 'h_s.' . $hostId . '.' . $serviceId);
}
/**
* Add relation between hostgroup and service
*
* @param int $hgId
* @param int $serviceId
* @return void
*/
public function addRelationHgService(int $hgId, int $serviceId)
{
if ($this->checkGenerate('hg_s.' . $hgId . '.' . $serviceId)) {
return null;
}
$relation = [
'hostgroup_hg_id' => $hgId,
'service_service_id' => $serviceId,
];
$this->generateObjectInFile($relation, 'hg_s.' . $hgId . '.' . $serviceId);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate-remote/Relations/ContactHostCommandsRelation.php | centreon/www/class/config-generate-remote/Relations/ContactHostCommandsRelation.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace ConfigGenerateRemote\Relations;
use ConfigGenerateRemote\Abstracts\AbstractObject;
use Exception;
/**
* Class
*
* @class ContactHostCommandsRelation
* @package ConfigGenerateRemote\Relations
*/
class ContactHostCommandsRelation extends AbstractObject
{
/** @var string */
protected $table = 'contact_hostcommands_relation';
/** @var string */
protected $generateFilename = 'contact_hostcommands_relation.infile';
/** @var string[] */
protected $attributesWrite = [
'contact_contact_id',
'command_command_id',
];
/**
* Add relaton
*
* @param int $contactId
* @param int $cmdId
*
* @throws Exception
* @return void
*/
public function addRelation(int $contactId, int $cmdId): void
{
$relation = [
'contact_contact_id' => $contactId,
'command_command_id' => $cmdId,
];
$this->generateObjectInFile($relation);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate-remote/Relations/TrapsVendor.php | centreon/www/class/config-generate-remote/Relations/TrapsVendor.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace ConfigGenerateRemote\Relations;
use ConfigGenerateRemote\Abstracts\AbstractObject;
use Exception;
/**
* Class
*
* @class TrapsVendor
* @package ConfigGenerateRemote\Relations
*/
class TrapsVendor extends AbstractObject
{
/** @var string */
protected $table = 'traps_vendor';
/** @var string */
protected $generateFilename = 'traps_vendor.infile';
/** @var string[] */
protected $attributesWrite = [
'id',
'name',
'alias',
'description',
];
/**
* Add relation
*
* @param int $id
* @param string $name
* @param string $alias
* @param string|null $description
*
* @throws Exception
* @return void
*/
public function add(int $id, string $name, string $alias, ?string $description = '')
{
if ($this->checkGenerate($id)) {
return null;
}
$relation = [
'id' => $id,
'name' => $name,
'alias' => $alias,
'description' => $description,
];
$this->generateObjectInFile($relation, $id);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate-remote/Relations/CfgResourceInstanceRelation.php | centreon/www/class/config-generate-remote/Relations/CfgResourceInstanceRelation.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace ConfigGenerateRemote\Relations;
use ConfigGenerateRemote\Abstracts\AbstractObject;
use Exception;
/**
* Class
*
* @class CfgResourceInstanceRelation
* @package ConfigGenerateRemote\Relations
*/
class CfgResourceInstanceRelation extends AbstractObject
{
/** @var string */
protected $table = 'cfg_resource_instance_relations';
/** @var string */
protected $generateFilename = 'cfg_resource_instance_relations.infile';
/** @var string[] */
protected $attributesWrite = [
'resource_id',
'instance_id',
];
/**
* Add relation
*
* @param int $resourceId
* @param int $instanceId
*
* @throws Exception
* @return void
*/
public function addRelation(int $resourceId, int $instanceId): void
{
$relation = [
'resource_id' => $resourceId,
'instance_id' => $instanceId,
];
$this->generateObjectInFile($relation);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate-remote/Relations/ContactGroupHostRelation.php | centreon/www/class/config-generate-remote/Relations/ContactGroupHostRelation.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace ConfigGenerateRemote\Relations;
use ConfigGenerateRemote\Abstracts\AbstractObject;
use Exception;
/**
* Class
*
* @class ContactGroupHostRelation
* @package ConfigGenerateRemote\Relations
*/
class ContactGroupHostRelation extends AbstractObject
{
protected $table = 'contactgroup_host_relation';
protected $generateFilename = 'contactgroup_host_relation.infile';
protected $attributesWrite = [
'host_host_id',
'contactgroup_cg_id',
];
/**
* Add relation
*
* @param int $hostId
* @param int $cgId
*
* @throws Exception
* @return void
*/
public function addRelation(int $hostId, int $cgId): void
{
$relation = [
'host_host_id' => $hostId,
'contactgroup_cg_id' => $cgId,
];
$this->generateObjectInFile($relation);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate-remote/Relations/ContactGroupServiceRelation.php | centreon/www/class/config-generate-remote/Relations/ContactGroupServiceRelation.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace ConfigGenerateRemote\Relations;
use ConfigGenerateRemote\Abstracts\AbstractObject;
use Exception;
/**
* Class
*
* @class ContactGroupServiceRelation
* @package ConfigGenerateRemote\Relations
*/
class ContactGroupServiceRelation extends AbstractObject
{
/** @var string */
protected $table = 'contactgroup_service_relation';
/** @var string */
protected $generateFilename = 'contactgroup_service_relation.infile';
/** @var string[] */
protected $attributesWrite = [
'service_service_id',
'contactgroup_cg_id',
];
/**
* Add relation
*
* @param int $serviceId
* @param int $cgId
*
* @throws Exception
* @return void
*/
public function addRelation(int $serviceId, int $cgId): void
{
$relation = [
'service_service_id' => $serviceId,
'contactgroup_cg_id' => $cgId,
];
$this->generateObjectInFile($relation);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate-remote/Relations/ExtendedHostInformation.php | centreon/www/class/config-generate-remote/Relations/ExtendedHostInformation.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace ConfigGenerateRemote\Relations;
use ConfigGenerateRemote\Abstracts\AbstractObject;
use Exception;
/**
* Class
*
* @class ExtendedHostInformation
* @package ConfigGenerateRemote\Relations
*/
class ExtendedHostInformation extends AbstractObject
{
/** @var string */
protected $table = 'extended_host_information';
/** @var string */
protected $generateFilename = 'extended_host_information.infile';
/** @var string[] */
protected $attributesWrite = [
'host_host_id',
'ehi_notes',
'ehi_notes_url',
'ehi_action_url',
'ehi_icon_image',
'ehi_icon_image_alt',
'ehi_2d_coords',
'ehi_3d_coords',
];
/**
* Add relation
*
* @param array $object
* @param int $hostId
*
* @throws Exception
* @return void
*/
public function add(array $object, int $hostId)
{
if ($this->checkGenerate($hostId)) {
return null;
}
$object['host_host_id'] = $hostId;
$this->generateObjectInFile($object, $hostId);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate-remote/Relations/ContactServiceCommandsRelation.php | centreon/www/class/config-generate-remote/Relations/ContactServiceCommandsRelation.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace ConfigGenerateRemote\Relations;
use ConfigGenerateRemote\Abstracts\AbstractObject;
use Exception;
/**
* Class
*
* @class ContactServiceCommandsRelation
* @package ConfigGenerateRemote\Relations
*/
class ContactServiceCommandsRelation extends AbstractObject
{
/** @var string */
protected $table = 'contact_servicecommands_relation';
/** @var string */
protected $generateFilename = 'contact_servicecommands_relation.infile';
/** @var string[] */
protected $attributesWrite = [
'contact_contact_id',
'command_command_id',
];
/**
* Add relation
*
* @param int $contactId
* @param int $cmdId
*
* @throws Exception
* @return void
*/
public function addRelation(int $contactId, int $cmdId): void
{
$relation = [
'contact_contact_id' => $contactId,
'command_command_id' => $cmdId,
];
$this->generateObjectInFile($relation);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate-remote/Relations/TrapsServiceRelation.php | centreon/www/class/config-generate-remote/Relations/TrapsServiceRelation.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace ConfigGenerateRemote\Relations;
use ConfigGenerateRemote\Abstracts\AbstractObject;
use Exception;
/**
* Class
*
* @class TrapsServiceRelation
* @package ConfigGenerateRemote\Relations
*/
class TrapsServiceRelation extends AbstractObject
{
/** @var string */
protected $table = 'traps_service_relation';
/** @var string */
protected $generateFilename = 'traps_service_relation.infile';
/** @var string[] */
protected $attributesWrite = [
'traps_id',
'service_id',
];
/**
* Add relation
*
* @param int $trapsId
* @param int $serviceId
*
* @throws Exception
* @return void
*/
public function addRelation(int $trapsId, int $serviceId): void
{
$relation = [
'traps_id' => $trapsId,
'service_id' => $serviceId,
];
$this->generateObjectInFile($relation);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate-remote/Relations/HostTemplateRelation.php | centreon/www/class/config-generate-remote/Relations/HostTemplateRelation.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace ConfigGenerateRemote\Relations;
use ConfigGenerateRemote\Abstracts\AbstractObject;
use Exception;
/**
* Class
*
* @class HostTemplateRelation
* @package ConfigGenerateRemote\Relations
*/
class HostTemplateRelation extends AbstractObject
{
/** @var string */
protected $table = 'host_template_relation';
/** @var string */
protected $generateFilename = 'host_template_relation.infile';
/** @var string[] */
protected $attributesWrite = [
'host_host_id',
'host_tpl_id',
'order',
];
/**
* Add relation
*
* @param int $hostId
* @param int $hostTplId
* @param int $order
*
* @throws Exception
* @return void
*/
public function addRelation(int $hostId, int $hostTplId, $order): void
{
$relation = [
'host_host_id' => $hostId,
'host_tpl_id' => $hostTplId,
'order' => $order,
];
$this->generateObjectInFile($relation, $hostId . '.' . $hostTplId . '.' . $order);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate-remote/Relations/TimePeriodExceptions.php | centreon/www/class/config-generate-remote/Relations/TimePeriodExceptions.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace ConfigGenerateRemote\Relations;
use ConfigGenerateRemote\Abstracts\AbstractObject;
use Exception;
/**
* Class
*
* @class TimePeriodExceptions
* @package ConfigGenerateRemote\Relations
*/
class TimePeriodExceptions extends AbstractObject
{
/** @var string */
protected $table = 'timeperiod_exceptions';
/** @var string */
protected $generateFilename = 'timeperiod_exceptions.infile';
/** @var string[] */
protected $attributesWrite = [
'timeperiod_id',
'days',
'timerange',
];
/**
* Add relation
*
* @param array $object
* @param int $tpId
*
* @throws Exception
* @return void
*/
public function add(array $object, int $tpId): void
{
$this->generateObjectInFile($object, $tpId);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate-remote/Relations/TrapsGroupRelation.php | centreon/www/class/config-generate-remote/Relations/TrapsGroupRelation.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace ConfigGenerateRemote\Relations;
use ConfigGenerateRemote\Abstracts\AbstractObject;
use Exception;
/**
* Class
*
* @class TrapsGroupRelation
* @package ConfigGenerateRemote\Relations
*/
class TrapsGroupRelation extends AbstractObject
{
/** @var string */
protected $table = 'traps_group_relation';
/** @var string */
protected $generateFilename = 'traps_group_relation.infile';
/** @var string[] */
protected $attributesWrite = [
'traps_group_id',
'traps_id',
];
/**
* Add relation
*
* @param int $trapsId
* @param int $trapsGroupId
*
* @throws Exception
* @return void
*/
public function addRelation(int $trapsId, int $trapsGroupId): void
{
$relation = [
'traps_id' => $trapsId,
'traps_group_id' => $trapsGroupId,
];
$this->generateObjectInFile($relation);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate-remote/Relations/ViewImgDirRelation.php | centreon/www/class/config-generate-remote/Relations/ViewImgDirRelation.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace ConfigGenerateRemote\Relations;
use ConfigGenerateRemote\Abstracts\AbstractObject;
use Exception;
/**
* Class
*
* @class ViewImgDirRelation
* @package ConfigGenerateRemote\Relations
*/
class ViewImgDirRelation extends AbstractObject
{
/** @var string */
protected $table = 'view_img_dir_relation';
/** @var string */
protected $generateFilename = 'view_img_dir_relation.infile';
/** @var string[] */
protected $attributesWrite = [
'dir_dir_parent_id',
'img_img_id',
];
/**
* Add relation
*
* @param int $mediaId
* @param int $dirId
*
* @throws Exception
* @return void
*/
public function addRelation(int $mediaId, int $dirId): void
{
$relation = [
'dir_dir_parent_id' => $dirId,
'img_img_id' => $mediaId,
];
$this->generateObjectInFile($relation, $mediaId . '.' . $dirId);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate-remote/Relations/MacroHost.php | centreon/www/class/config-generate-remote/Relations/MacroHost.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace ConfigGenerateRemote\Relations;
use CentreonDB;
use CentreonDbException;
use CentreonLog;
use ConfigGenerateRemote\Abstracts\AbstractObject;
use Exception;
use PDO;
use Pimple\Container;
/**
* Class
*
* @class MacroHost
* @package ConfigGenerateRemote\Relations
*/
class MacroHost extends AbstractObject
{
/** @var string */
protected $table = 'on_demand_macro_host';
/** @var string */
protected $generateFilename = 'on_demand_macro_host.infile';
/** @var string[] */
protected $attributesWrite = [
'host_host_id',
'host_macro_name',
'host_macro_value',
'is_password',
'description',
];
/** @var CentreonDB */
private CentreonDB $databaseConnection;
/**
* @param Container $dependencyInjector
*/
public function __construct(Container $dependencyInjector)
{
try {
parent::__construct($dependencyInjector);
if (! isset($this->backendInstance->db)) {
throw new Exception('Database connection is not set');
}
$this->databaseConnection = $this->backendInstance->db;
} catch (Exception $ex) {
CentreonLog::create()->error(
logTypeId: CentreonLog::TYPE_BUSINESS_LOG,
message: 'Cannot connect to database: ' . $ex->getMessage(),
exception: $ex
);
}
}
/**
* Get host macro from host id
*
* @param int $hostId
*
* @throws Exception
* @return array<array{
* "host_macro_id":int,
* "host_macro_name":string,
* "host_macro_value":string,
* "is_password":null|int,
* "description":null|string,
* "host_host_id":int
* }>
*/
public function getHostMacroByHostId(int $hostId): array
{
try {
$statement = $this->databaseConnection->prepareQuery(
'SELECT host_macro_id, host_macro_name, host_macro_value, is_password, description, host_host_id
FROM on_demand_macro_host
WHERE host_host_id = :host_id'
);
$this->databaseConnection->executePreparedQuery($statement, ['host_id' => $hostId]);
$macros = $statement->fetchAll(PDO::FETCH_ASSOC);
$this->writeMacrosHost($hostId, $macros);
CentreonLog::create()->info(
logTypeId: CentreonLog::TYPE_BUSINESS_LOG,
message: 'Host macros generated',
customContext: [$macros]
);
return $macros;
} catch (CentreonDbException $ex) {
CentreonLog::create()->error(
logTypeId: CentreonLog::TYPE_BUSINESS_LOG,
message: $ex->getMessage(),
customContext: ['host_id' => $hostId],
exception: $ex,
);
return [];
}
}
/**
* Generate host macros
*
* @param int $hostId
* @param array<array{
* "host_macro_id":int,
* "host_macro_name":string,
* "host_macro_value":string,
* "is_password":null|int,
* "description":null|string,
* "host_host_id":int
* }> $macros
*
* @throws Exception
*/
private function writeMacrosHost(int $hostId, array $macros): void
{
if ($this->checkGenerate($hostId)) {
return;
}
foreach ($macros as $value) {
$this->generateObjectInFile($value, $hostId);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate-remote/Relations/ExtendedServiceInformation.php | centreon/www/class/config-generate-remote/Relations/ExtendedServiceInformation.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace ConfigGenerateRemote\Relations;
use ConfigGenerateRemote\Abstracts\AbstractObject;
use Exception;
/**
* Class
*
* @class ExtendedServiceInformation
* @package ConfigGenerateRemote\Relations
*/
class ExtendedServiceInformation extends AbstractObject
{
/** @var string */
protected $table = 'extended_service_information';
/** @var string */
protected $generateFilename = 'extended_service_information.infile';
/** @var string[] */
protected $attributesWrite = [
'service_service_id',
'esi_notes',
'esi_notes_url',
'esi_action_url',
'esi_icon_image',
'esi_icon_image_alt',
'graph_id',
];
/**
* Add relation
*
* @param array $object
* @param int $serviceId
*
* @throws Exception
* @return void
*/
public function add(array $object, int $serviceId)
{
if ($this->checkGenerate($serviceId)) {
return null;
}
$object['service_service_id'] = $serviceId;
$this->generateObjectInFile($object, $serviceId);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate-remote/Relations/HostCategoriesRelation.php | centreon/www/class/config-generate-remote/Relations/HostCategoriesRelation.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace ConfigGenerateRemote\Relations;
use ConfigGenerateRemote\Abstracts\AbstractObject;
use Exception;
/**
* Class
*
* @class HostCategoriesRelation
* @package ConfigGenerateRemote\Relations
*/
class HostCategoriesRelation extends AbstractObject
{
protected $table = 'hostcategories_relation';
protected $generateFilename = 'hostcategories_relation.infile';
protected $attributesWrite = [
'hostcategories_hc_id',
'host_host_id',
];
/**
* Add relation
*
* @param int $hcId
* @param int $hostId
*
* @throws Exception
* @return void
*/
public function addRelation(int $hcId, int $hostId): void
{
$relation = [
'hostcategories_hc_id' => $hcId,
'host_host_id' => $hostId,
];
$this->generateObjectInFile($relation);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate-remote/Relations/ContactServiceRelation.php | centreon/www/class/config-generate-remote/Relations/ContactServiceRelation.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace ConfigGenerateRemote\Relations;
use ConfigGenerateRemote\Abstracts\AbstractObject;
use Exception;
/**
* Class
*
* @class ContactServiceRelation
* @package ConfigGenerateRemote\Relations
*/
class ContactServiceRelation extends AbstractObject
{
/** @var string */
protected $table = 'contact_service_relation';
/** @var string */
protected $generateFilename = 'contact_service_relation.infile';
/** @var string[] */
protected $attributesWrite = [
'service_service_id',
'contact_id',
];
/**
* Add relation
*
* @param int $serviceId
* @param int $contactId
*
* @throws Exception
* @return void
*/
public function addRelation(int $serviceId, int $contactId): void
{
$relation = [
'service_service_id' => $serviceId,
'contact_id' => $contactId,
];
$this->generateObjectInFile($relation);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate-remote/Relations/NagiosServer.php | centreon/www/class/config-generate-remote/Relations/NagiosServer.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace ConfigGenerateRemote\Relations;
use ConfigGenerateRemote\Abstracts\AbstractObject;
use Exception;
/**
* Class
*
* @class NagiosServer
* @package ConfigGenerateRemote\Relations
*/
class NagiosServer extends AbstractObject
{
/** @var string */
protected $table = 'nagios_server';
/** @var string */
protected $generateFilename = 'nagios_server.infile';
/** @var string[] */
protected $attributesWrite = [
'id',
'name',
'localhost',
'is_default',
'last_restart',
'ns_ip_address',
'ns_activate',
'ns_status',
'engine_start_command',
'engine_stop_command',
'engine_restart_command',
'engine_reload_command',
'nagios_bin',
'nagiostats_bin',
'nagios_perfdata',
'broker_reload_command',
'centreonbroker_cfg_path',
'centreonbroker_module_path',
'centreonconnector_path',
'ssh_port',
'gorgone_communication_type',
'gorgone_port',
'init_script_centreontrapd',
'snmp_trapd_path_conf',
'engine_name',
'engine_version',
'centreonbroker_logs_path',
'remote_id',
'remote_server_use_as_proxy',
];
/**
* Add relation
*
* @param array $object
* @param int $id
*
* @throws Exception
* @return void
*/
public function add(array $object, int $id)
{
if ($this->checkGenerate($id)) {
return null;
}
$this->generateObjectInFile($object, $id);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate-remote/Relations/ContactHostRelation.php | centreon/www/class/config-generate-remote/Relations/ContactHostRelation.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace ConfigGenerateRemote\Relations;
use ConfigGenerateRemote\Abstracts\AbstractObject;
use Exception;
/**
* Class
*
* @class ContactHostRelation
* @package ConfigGenerateRemote\Relations
*/
class ContactHostRelation extends AbstractObject
{
/** @var string */
protected $table = 'contact_host_relation';
/** @var string */
protected $generateFilename = 'contact_host_relation.infile';
/** @var string[] */
protected $attributesWrite = [
'host_host_id',
'contact_id',
];
/**
* Add relation
*
* @param int $hostId
* @param int $contactId
*
* @throws Exception
* @return void
*/
public function addRelation(int $hostId, int $contactId): void
{
$relation = [
'host_host_id' => $hostId,
'contact_id' => $contactId,
];
$this->generateObjectInFile($relation);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate-remote/Relations/BrokerInfo.php | centreon/www/class/config-generate-remote/Relations/BrokerInfo.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace ConfigGenerateRemote\Relations;
use ConfigGenerateRemote\Abstracts\AbstractObject;
use PDO;
/**
* Class
*
* @class BrokerInfo
* @package ConfigGenerateRemote\Relations
*/
class BrokerInfo extends AbstractObject
{
/** @var string */
protected $table = 'cfg_centreonbroker_info';
/** @var string */
protected $generateFilename = 'cfg_centreonbroker_info.infile';
/** @var null */
protected $stmtBrokerInfo = null;
/** @var string[] */
protected $attributesWrite = [
'config_id',
'config_key',
'config_value',
'config_group',
'config_group_id',
'grp_level',
'subgrp_id',
'parent_grp_id',
'fieldIndex',
];
/** @var int */
private $useCache = 1;
/** @var int */
private $doneCache = 0;
/** @var array */
private $brokerInfoCache = [];
/**
* BrokerInfo constructor
*
* @param \Pimple\Container $dependencyInjector
*/
public function __construct(\Pimple\Container $dependencyInjector)
{
parent::__construct($dependencyInjector);
$this->buildCache();
}
/**
* Generate broker info configs
*
* @param int $configId
* @param array $brokerInfoCache
*
* @throws \Exception
* @return void
*/
public function generateObject(int $configId, array $brokerInfoCache): void
{
foreach ($brokerInfoCache[$configId] as $value) {
$this->generateObjectInFile($value);
}
}
/**
* Get broker information config
*
* @param int $configId
*
* @throws \Exception
* @return array
*/
public function getBrokerInfoByConfigId(int $configId)
{
// Get from the cache
if (isset($this->brokerInfoCache[$configId])) {
$this->generateObject($configId, $this->brokerInfoCache);
return $this->brokerInfoCache[$configId];
}
if ($this->useCache === 1) {
return [];
}
// We get unitary
if (is_null($this->stmtBrokerInfo)) {
$this->stmtBrokerInfo = $this->backendInstance->db->prepare(
'SELECT *
FROM cfg_centreonbroker_info
WHERE config_id = :config_id'
);
}
$this->stmtBrokerInfo->bindParam(':config_id', $configId, PDO::PARAM_INT);
$this->stmtBrokerInfo->execute();
$brokerInfoCache = [$config_id => []];
foreach ($this->stmtBrokerInfo->fetchAll(PDO::FETCH_ASSOC) as &$value) {
$brokerInfoCache[$config_id] = $value;
}
$this->generateObject($configId, $brokerInfoCache);
return $brokerInfoCache;
}
/**
* Build cache of broker info
*
* @return void
*/
private function cacheBrokerInfo(): void
{
$stmt = $this->backendInstance->db->prepare(
'SELECT *
FROM cfg_centreonbroker_info'
);
$stmt->execute();
$values = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($values as &$value) {
if (! isset($this->brokerInfoCache[$value['config_id']])) {
$this->brokerInfoCache[$value['config_id']] = [];
}
$this->brokerInfoCache[$value['config_id']][] = $value;
}
}
/**
* Build cache
*
* @return void
*/
private function buildCache(): void
{
if ($this->doneCache === 0) {
$this->cacheBrokerInfo();
$this->doneCache = 1;
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate-remote/Relations/ViewImageDir.php | centreon/www/class/config-generate-remote/Relations/ViewImageDir.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace ConfigGenerateRemote\Relations;
use ConfigGenerateRemote\Abstracts\AbstractObject;
use Exception;
/**
* Class
*
* @class ViewImageDir
* @package ConfigGenerateRemote\Relations
*/
class ViewImageDir extends AbstractObject
{
/** @var string */
protected $table = 'view_img_dir';
/** @var string */
protected $generateFilename = 'view_image_dir.infile';
/** @var string[] */
protected $attributesWrite = [
'dir_id',
'dir_name',
'dir_alias',
'dir_comment',
];
/**
* Add relation
*
* @param array $object
* @param int $dirId
*
* @throws Exception
* @return void
*/
public function add(array $object, int $dirId)
{
if ($this->checkGenerate($dirId)) {
return null;
}
$this->generateObjectInFile($object, $dirId);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate-remote/Relations/TrapsMatching.php | centreon/www/class/config-generate-remote/Relations/TrapsMatching.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace ConfigGenerateRemote\Relations;
use ConfigGenerateRemote\Abstracts\AbstractObject;
use ConfigGenerateRemote\ServiceCategory;
use Exception;
use PDO;
use Pimple\Container;
/**
* Class
*
* @class TrapsMatching
* @package ConfigGenerateRemote\Relations
*/
class TrapsMatching extends AbstractObject
{
/** @var string */
protected $table = 'traps_matching_properties';
/** @var string */
protected $generateFilename = 'traps_matching_properties.infile';
/** @var null */
protected $stmtTrap = null;
/** @var string[] */
protected $attributesWrite = [
'tmo_id',
'trap_id',
'tmo_order',
'tmo_regexp',
'tmo_string',
'tmo_status',
'severity_id',
];
/** @var int */
private $useCache = 1;
/** @var int */
private $doneCache = 0;
/** @var array */
private $trapMatchCache = [];
/**
* TrapsMatching constructor
*
* @param Container $dependencyInjector
*/
public function __construct(Container $dependencyInjector)
{
parent::__construct($dependencyInjector);
$this->buildCache();
}
/**
* Generate object
*
* @param int $trapId
* @param array $trapMatchCache
*
* @throws Exception
* @return void
*/
public function generateObject($trapId, $trapMatchCache): void
{
foreach ($trapMatchCache as $value) {
if ($this->checkGenerate($value['tmo_id'])) {
continue;
}
$this->generateObjectInFile($value, $value['tmo_id']);
ServiceCategory::getInstance($this->dependencyInjector)->generateObject($value['severity_id']);
}
}
/**
* Get trap matching from trap id
*
* @param int $trapId
*
* @throws Exception
* @return void
*/
public function getTrapMatchingByTrapId(int $trapId)
{
// Get from the cache
if (isset($this->trapMatchCache[$trapId])) {
$this->generateObject($trapId, $this->trapMatchCache[$trapId]);
return $this->trapMatchCache[$trapId];
}
if ($this->useCache == 1) {
return null;
}
// We get unitary
if (is_null($this->stmtTrap)) {
$this->stmtTrap = $this->backendInstance->db->prepare(
'SELECT *
FROM traps_matching_properties
WHERE trap_id = :trap_id'
);
}
$this->stmtTrap->bindParam(':trap_id', $trapId, PDO::PARAM_INT);
$this->stmtTrap->execute();
$trapMatchCache = [];
foreach ($this->stmtTrap->fetchAll(PDO::FETCH_ASSOC) as &$value) {
$trapMatchCache[$value['traps_id']] = $value;
}
$this->generateObject($trapId, $trapMatchCache[$trapId]);
return $trapMatchCache;
}
/**
* Build cache for trap matches
*
* @return void
*/
private function cacheTrapMatch(): void
{
$stmt = $this->backendInstance->db->prepare(
'SELECT *
FROM traps_matching_properties'
);
$stmt->execute();
$values = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($values as &$value) {
if (! isset($this->trapMatchCache[$value['trap_id']])) {
$this->trapMatchCache[$value['trap_id']] = [];
}
$this->trapMatchCache[$value['trap_id']][] = &$value;
}
}
/**
* Build cache
*
* @return void
*/
private function buildCache()
{
if ($this->doneCache == 1) {
return 0;
}
$this->cacheTrapMatch();
$this->doneCache = 1;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate-remote/Relations/HostGroupRelation.php | centreon/www/class/config-generate-remote/Relations/HostGroupRelation.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace ConfigGenerateRemote\Relations;
use ConfigGenerateRemote\Abstracts\AbstractObject;
use Exception;
/**
* Class
*
* @class HostGroupRelation
* @package ConfigGenerateRemote\Relations
*/
class HostGroupRelation extends AbstractObject
{
/** @var string */
protected $table = 'hostgroup_relation';
/** @var string */
protected $generateFilename = 'hostgroup_relation.infile';
/** @var string[] */
protected $attributesWrite = [
'host_host_id',
'hostgroup_hg_id',
];
/**
* Add relation
*
* @param int $hgId
* @param int $hostId
*
* @throws Exception
* @return void
*/
public function addRelation(int $hgId, int $hostId)
{
if ($this->checkGenerate($hgId . '.' . $hostId)) {
return null;
}
$relation = [
'hostgroup_hg_id' => $hgId,
'host_host_id' => $hostId,
];
$this->generateObjectInFile($relation, $hgId . '.' . $hostId);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate-remote/Relations/HostPollerRelation.php | centreon/www/class/config-generate-remote/Relations/HostPollerRelation.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace ConfigGenerateRemote\Relations;
use ConfigGenerateRemote\Abstracts\AbstractObject;
use Exception;
/**
* Class
*
* @class HostPollerRelation
* @package ConfigGenerateRemote\Relations
*/
class HostPollerRelation extends AbstractObject
{
protected $table = 'ns_host_relation';
protected $generateFilename = 'ns_host_relation.infile';
protected $attributesWrite = [
'nagios_server_id',
'host_host_id',
];
/**
* Add relation between host and poller
*
* @param int $pollerId
* @param int $hostId
*
* @throws Exception
* @return void
*/
public function addRelation(int $pollerId, int $hostId): void
{
$relation = [
'nagios_server_id' => $pollerId,
'host_host_id' => $hostId,
];
$this->generateObjectInFile($relation, $hostId . '.' . $serviceId);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate/timeperiod.class.php | centreon/www/class/config-generate/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
*
*/
/**
* Class
*
* @class Timeperiod
*/
class Timeperiod extends AbstractObject
{
/** @var string */
protected $generate_filename = 'timeperiods.cfg';
/** @var string */
protected string $object_name = 'timeperiod';
/** @var string */
protected $attributes_select = '
tp_id,
tp_name as timeperiod_name,
tp_alias as alias,
tp_sunday as sunday,
tp_monday as monday,
tp_tuesday as tuesday,
tp_wednesday as wednesday,
tp_thursday as thursday,
tp_friday as friday,
tp_saturday as saturday
';
/** @var string[] */
protected $attributes_write = ['name', 'timeperiod_name', 'alias', 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];
/** @var string[] */
protected $attributes_array = ['use', 'exclude'];
/** @var string[] */
protected $attributes_hash = ['exceptions'];
/** @var null[] */
protected $stmt_extend = ['include' => null, 'exclude' => null];
/** @var null */
private $timeperiods = null;
/**
* @throws PDOException
* @return void
*/
public function getTimeperiods(): void
{
$query = "SELECT {$this->attributes_select} FROM timeperiod";
$stmt = $this->backend_instance->db->prepare($query);
$stmt->execute();
$this->timeperiods = $stmt->fetchAll(PDO::FETCH_GROUP | PDO::FETCH_UNIQUE | PDO::FETCH_ASSOC);
}
/**
* @param $timeperiod_id
*
* @throws PDOException
* @return mixed|null
*/
public function generateFromTimeperiodId($timeperiod_id)
{
if (is_null($timeperiod_id)) {
return null;
}
if (is_null($this->timeperiods)) {
$this->getTimeperiods();
}
if (! isset($this->timeperiods[$timeperiod_id])) {
return null;
}
if ($this->checkGenerate($timeperiod_id)) {
return $this->timeperiods[$timeperiod_id]['timeperiod_name'];
}
$this->timeperiods[$timeperiod_id]['name'] = $this->timeperiods[$timeperiod_id]['timeperiod_name'];
$this->getTimeperiodExceptionFromId($timeperiod_id);
$this->getTimeperiodExtendFromId($timeperiod_id, 'exclude', 'exclude');
$this->getTimeperiodExtendFromId($timeperiod_id, 'include', 'use');
$this->generateObjectInFile($this->timeperiods[$timeperiod_id], $timeperiod_id);
return $this->timeperiods[$timeperiod_id]['timeperiod_name'];
}
/**
* @param $timeperiod_id
*
* @throws PDOException
* @return int|void
*/
protected function getTimeperiodExceptionFromId($timeperiod_id)
{
if (isset($this->timeperiods[$timeperiod_id]['exceptions'])) {
return 1;
}
$query = 'SELECT days, timerange FROM timeperiod_exceptions WHERE timeperiod_id = :timeperiod_id';
$stmt = $this->backend_instance->db->prepare($query);
$stmt->bindParam(':timeperiod_id', $timeperiod_id, PDO::PARAM_INT);
$stmt->execute();
$exceptions = $stmt->fetchAll(PDO::FETCH_ASSOC);
$this->timeperiods[$timeperiod_id]['exceptions'] = [];
foreach ($exceptions as $exception) {
$this->timeperiods[$timeperiod_id]['exceptions'][$exception['days']] = $exception['timerange'];
}
}
/**
* @param $timeperiod_id
* @param $db_label
* @param $label
*
* @throws PDOException
* @return void
*/
protected function getTimeperiodExtendFromId($timeperiod_id, $db_label, $label)
{
if (! isset($this->timeperiods[$timeperiod_id][$label . '_cache'])) {
if (is_null($this->stmt_extend[$db_label])) {
$query = 'SELECT timeperiod_' . $db_label . '_id as period_id FROM timeperiod_' . $db_label
. '_relations WHERE timeperiod_id = :timeperiod_id';
$this->stmt_extend[$db_label] = $this->backend_instance->db->prepare($query);
}
$this->stmt_extend[$db_label]->bindParam(':timeperiod_id', $timeperiod_id, PDO::PARAM_INT);
$this->stmt_extend[$db_label]->execute();
$this->timeperiods[$timeperiod_id][$label . '_cache']
= $this->stmt_extend[$db_label]->fetchAll(PDO::FETCH_COLUMN);
}
$this->timeperiods[$timeperiod_id][$label] = [];
foreach ($this->timeperiods[$timeperiod_id][$label . '_cache'] as $period_id) {
$this->timeperiods[$timeperiod_id][$label][] = $this->generateFromTimeperiodId($period_id);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate/hostgroup.class.php | centreon/www/class/config-generate/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
*
*/
/**
* Class
*
* @class Hostgroup
*/
class Hostgroup extends AbstractObject
{
private const TAG_TYPE = 'hostgroup';
private const HOSTGROUP_FILENAME = 'hostgroups.cfg';
private const HOSTGROUP_OBJECT_NAME = 'hostgroup';
private const TAG_FILENAME = 'tags.cfg';
private const TAG_OBJECT_NAME = 'tag';
/** @var string */
protected $generate_filename = self::HOSTGROUP_FILENAME;
/** @var string */
protected string $object_name = self::HOSTGROUP_OBJECT_NAME;
/** @var string */
protected $attributes_select = '
hg_id,
hg_name as hostgroup_name,
hg_alias as alias
';
/** @var null */
protected $stmt_hg = null;
/** @var array */
private $hg = [];
/**
* @param $hg_id
* @param $host_id
* @param $host_name
*
* @throws PDOException
* @return int
*/
public function addHostInHg($hg_id, $host_id, $host_name)
{
if (! isset($this->hg[$hg_id])) {
$this->getHostgroupFromId($hg_id);
}
if (is_null($this->hg[$hg_id]) || isset($this->hg[$hg_id]['members'][$host_id])) {
return 1;
}
$this->hg[$hg_id]['members'][$host_id] = $host_name;
return 0;
}
/**
* Generate host groups / tags and write in file
*/
public function generateObjects(): void
{
$this->generateHostGroups();
$this->generateTags();
}
/**
* @return array
*/
public function getHostgroups()
{
$result = [];
foreach ($this->hg as $id => &$value) {
if (is_null($value) || count($value['members']) == 0) {
continue;
}
$result[$id] = &$value;
}
return $result;
}
/**
* @throws Exception
* @return void
*/
public function reset(): void
{
parent::reset();
foreach ($this->hg as &$value) {
if (! is_null($value)) {
$value['members'] = [];
}
}
}
/**
* @param $hg_id
* @param $attr
*
* @return mixed|null
*/
public function getString($hg_id, $attr)
{
return $this->hg[$hg_id][$attr] ?? null;
}
/**
* @param $hg_id
*
* @throws PDOException
* @return void
*/
private function getHostgroupFromId($hg_id): void
{
if (is_null($this->stmt_hg)) {
$this->stmt_hg = $this->backend_instance->db->prepare(
"SELECT {$this->attributes_select}
FROM hostgroup
WHERE hg_id = :hg_id AND hg_activate = '1'"
);
}
$this->stmt_hg->bindParam(':hg_id', $hg_id, PDO::PARAM_INT);
$this->stmt_hg->execute();
if ($hostGroup = $this->stmt_hg->fetch(PDO::FETCH_ASSOC)) {
$this->hg[$hg_id] = $hostGroup;
$this->hg[$hg_id]['members'] = [];
}
}
/**
* Generate host groups and write in file
*/
private function generateHostGroups(): void
{
$this->generate_filename = self::HOSTGROUP_FILENAME;
$this->object_name = self::HOSTGROUP_OBJECT_NAME;
$this->attributes_write = [
'hostgroup_id',
'hostgroup_name',
'alias',
];
$this->attributes_array = [
'members',
];
// reset cache to allow export of same ids
parent::reset();
foreach ($this->hg as $id => &$value) {
if (count($value['members']) == 0) {
continue;
}
$value['hostgroup_id'] = $value['hg_id'];
$this->generateObjectInFile($value, $id);
}
}
/**
* Generate tags and write in file
*/
private function generateTags(): void
{
$this->generate_filename = self::TAG_FILENAME;
$this->object_name = self::TAG_OBJECT_NAME;
$this->attributes_write = [
'id',
'tag_name',
'type',
];
$this->attributes_array = [];
// reset cache to allow export of same ids
parent::reset();
foreach ($this->hg as $id => $value) {
if (count($value['members']) == 0) {
continue;
}
$tag = [
'id' => $value['hostgroup_id'],
'tag_name' => $value['hostgroup_name'],
'type' => self::TAG_TYPE,
];
$this->generateObjectInFile($tag, $id);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate/AgentConfiguration.php | centreon/www/class/config-generate/AgentConfiguration.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
use Core\AgentConfiguration\Application\Repository\ReadAgentConfigurationRepositoryInterface;
use Core\AgentConfiguration\Domain\Model\AgentConfiguration as ModelAgentConfiguration;
use Core\AgentConfiguration\Domain\Model\ConfigurationParameters\CmaConfigurationParameters;
use Core\AgentConfiguration\Domain\Model\ConfigurationParameters\TelegrafConfigurationParameters;
use Core\AgentConfiguration\Domain\Model\ConnectionModeEnum;
use Core\AgentConfiguration\Domain\Model\Type;
use Core\Host\Application\Repository\ReadHostRepositoryInterface;
use Core\Security\Token\Application\Repository\ReadTokenRepositoryInterface;
use Core\Security\Token\Domain\Model\JwtToken;
use Core\Security\Token\Domain\Model\Token;
/**
* @phpstan-import-type _TelegrafParameters from TelegrafConfigurationParameters
* @phpstan-import-type _CmaParameters from CmaConfigurationParameters
*/
class AgentConfiguration extends AbstractObjectJSON
{
public function __construct(
private readonly Backend $backend,
private readonly ReadAgentConfigurationRepositoryInterface $readAgentConfigurationRepository,
private readonly ReadTokenRepositoryInterface $readTokenRepository,
private readonly ReadHostRepositoryInterface $readHostRepository,
) {
$this->generate_filename = 'otl_server.json';
}
public function generateFromPollerId(int $pollerId): void
{
$this->generate($pollerId);
}
private function generate(int $pollerId): void
{
$agentConfiguration = $this->readAgentConfigurationRepository->findByPollerId($pollerId);
$configuration = [];
if ($agentConfiguration !== null) {
match ($agentConfiguration->getType()) {
Type::TELEGRAF => $configuration = $this->formatTelegraphConfiguration(
$agentConfiguration->getConfiguration()->getData(),
$agentConfiguration->getConnectionMode()
),
Type::CMA => $configuration = $this->formatCmaConfiguration(
$agentConfiguration->getConfiguration()->getData(),
$agentConfiguration->getConnectionMode()
),
default => throw new Exception('The type of the agent configuration not exists'),
};
}
$this->generateFile($configuration, false);
$this->writeFile($this->backend->getPath());
}
/**
* Format the configuration for OpenTelemetry.
*
* The configuration is based on the data from the AgentConfiguration table.
* It returns an array with the configuration for the OpenTelemetry HTTP server.
*
* @param _TelegrafParameters|_CmaParameters $data the data from the AgentConfiguration table
* @param array<JwtToken> $tokens
* @param ConnectionModeEnum $connectionMode
*
* @return array<string, array<string, string>> the configuration for the OpenTelemetry HTTP server
*/
private function formatOtelConfiguration(array $data, array $tokens, ConnectionModeEnum $connectionMode): array
{
return [
'host' => ModelAgentConfiguration::DEFAULT_HOST,
'port' => $data['port'] ?? ModelAgentConfiguration::DEFAULT_PORT,
'encryption' => match ($connectionMode) {
ConnectionModeEnum::SECURE => 'full',
ConnectionModeEnum::INSECURE => 'insecure',
ConnectionModeEnum::NO_TLS => 'no',
default => 'full',
},
'public_cert' => ! empty($data['otel_public_certificate'])
? $data['otel_public_certificate']
: '',
'private_key' => ! empty($data['otel_private_key'])
? $data['otel_private_key']
: '',
'ca_certificate' => ! empty($data['otel_ca_certificate'])
? $data['otel_ca_certificate']
: '',
'trusted_tokens' => array_map(
static fn (JwtToken $token): string => $token->getToken(),
array_values($tokens)
),
];
}
/**
* Format the configuration for Centreon Monitoring Agent.
*
* @param _CmaParameters $data
*
* @return array
*/
private function formatCmaConfiguration(array $data, ConnectionModeEnum $connectionMode): array
{
$tokens = $this->filterTokens($data['tokens'] ?? []);
$configuration = [
'otel_server' => $this->formatOtelConfiguration($data, $tokens, $connectionMode),
'centreon_agent' => [
'check_interval' => CmaConfigurationParameters::DEFAULT_CHECK_INTERVAL,
'export_period' => CmaConfigurationParameters::DEFAULT_EXPORT_PERIOD,
],
];
if ($data['poller_initiated'] === true) {
$hostIds = array_map(static fn (array $host): int => $host['id'], $data['hosts']);
$hosts = $this->readHostRepository->findByIds($hostIds);
$tokenNames = array_filter(
array_map(
static fn (array $host): ?string => $host['token'] !== null ? $host['token']['name'] : null,
$data['hosts']
)
);
$tokens = $tokenNames !== []
? $this->readTokenRepository->findByNames($tokenNames)
: [];
$tokens = array_filter(
$tokens,
static fn (Token $token): bool => ! (
$token->isRevoked()
|| ($token->getExpirationDate() !== null && $token->getExpirationDate() < new DateTimeImmutable())
)
);
$configuration['centreon_agent']['reverse_connections'] = array_map(
static fn (array $host): array => [
'host' => $host['address'],
'port' => $host['port'],
'encryption' => match ($connectionMode) {
ConnectionModeEnum::SECURE => 'full',
ConnectionModeEnum::INSECURE => 'insecure',
ConnectionModeEnum::NO_TLS => 'no',
default => 'full',
},
'ca_certificate' => $host['poller_ca_certificate'] ?? '',
'ca_name' => $host['poller_ca_name'] ?? '',
'token' => isset($tokens[$host['token']['name']])
? $tokens[$host['token']['name']]->getToken()
: '',
],
array_filter(
$data['hosts'],
static fn (array $host): bool => $hosts[$host['id']] ? true : false
)
);
}
return $configuration;
}
/**
* Format the configuration for Telegraf.
*
* The configuration is based on the data from the AgentConfiguration table.
* It returns an array with the configuration for the Telegraf HTTP server.
*
* @param _TelegrafParameters $data the data from the AgentConfiguration table
* @param ConnectionModeEnum $connectionMode
*
* @return array<string, array<string, mixed>> the configuration for the Telegraf HTTP server
*/
private function formatTelegraphConfiguration(array $data, ConnectionModeEnum $connectionMode): array
{
$tokens = $this->filterTokens($data['tokens'] ?? []);
$otelConfiguration = $this->formatOtelConfiguration($data, $tokens, $connectionMode);
return [
'otel_server' => $otelConfiguration,
'telegraf_conf_server' => [
'http_server' => [
'port' => $data['conf_server_port'],
'encryption' => match ($connectionMode) {
ConnectionModeEnum::SECURE => 'full',
ConnectionModeEnum::INSECURE => 'insecure',
ConnectionModeEnum::NO_TLS => 'no',
default => 'full',
},
'public_cert' => $data['conf_certificate'] ?? '',
'private_key' => $data['conf_private_key'] ?? '',
],
],
];
}
/**
* @param array<JwtToken> $tokens
*
* @return array<JwtToken>
*/
private function filterTokens(array $dataTokens): array
{
$tokens = $dataTokens !== []
? $this->readTokenRepository->findByNames(array_map(
static fn (array $token): string => $token['name'],
$dataTokens
))
: [];
return array_filter(
$tokens,
static fn (Token $token): bool => ! (
$token->isRevoked()
|| ($token->getExpirationDate() !== null && $token->getExpirationDate() < new DateTimeImmutable())
)
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate/servicegroup.class.php | centreon/www/class/config-generate/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
*
*/
use Pimple\Container;
/**
* Class
*
* @class Servicegroup
*/
class Servicegroup extends AbstractObject
{
private const TAG_TYPE = 'servicegroup';
private const SERVICEGROUP_FILENAME = 'servicegroups.cfg';
private const SERVICEGROUP_OBJECT_NAME = 'servicegroup';
private const TAG_FILENAME = 'tags.cfg';
private const TAG_OBJECT_NAME = 'tag';
/** @var string */
protected $generate_filename = self::SERVICEGROUP_FILENAME;
/** @var string */
protected string $object_name = self::SERVICEGROUP_OBJECT_NAME;
/** @var string */
protected $attributes_select = '
sg_id,
sg_name as servicegroup_name,
sg_alias as alias
';
/** @var null */
protected $stmt_sg = null;
/** @var null */
protected $stmt_service_sg = null;
/** @var null */
protected $stmt_stpl_sg = null;
/** @var int */
private $use_cache = 1;
/** @var int */
private $done_cache = 0;
/** @var array */
private $sg = [];
/** @var array */
private $sg_relation_cache = [];
/**
* Servicegroup constructor
*
* @param Container $dependencyInjector
*
* @throws PDOException
*/
public function __construct(Container $dependencyInjector)
{
parent::__construct($dependencyInjector);
$this->buildCache();
}
/**
* @param $sg_id
* @param $service_id
* @param $service_description
* @param $host_id
* @param $host_name
*
* @throws PDOException
* @return int
*/
public function addServiceInSg($sg_id, $service_id, $service_description, $host_id, $host_name)
{
if (! isset($this->sg[$sg_id])) {
$this->getServicegroupFromId($sg_id);
}
if (is_null($this->sg[$sg_id]) || isset($this->sg[$sg_id]['members_cache'][$host_id . '_' . $service_id])) {
return 1;
}
$this->sg[$sg_id]['members_cache'][$host_id . '_' . $service_id] = [$host_name, $service_description];
return 0;
}
/**
* @param $service_id
*
* @throws PDOException
* @return array|mixed
*/
public function getServiceGroupsForStpl($service_id)
{
// Get from the cache
if (isset($this->sg_relation_cache[$service_id])) {
return $this->sg_relation_cache[$service_id];
}
if ($this->done_cache == 1) {
return [];
}
if (is_null($this->stmt_stpl_sg)) {
// Meaning, linked with the host or hostgroup (for the null expression)
$this->stmt_stpl_sg = $this->backend_instance->db->prepare(
"SELECT servicegroup_sg_id, host_host_id, service_service_id
FROM servicegroup_relation sgr, servicegroup sg
WHERE service_service_id = :service_id
AND sgr.servicegroup_sg_id = sg.sg_id AND sg.sg_activate = '1'"
);
}
$this->stmt_stpl_sg->bindParam(':service_id', $service_id, PDO::PARAM_INT);
$this->stmt_stpl_sg->execute();
$this->sg_relation_cache[$service_id] = array_merge(
$this->stmt_stpl_sg->fetchAll(PDO::FETCH_ASSOC),
$this->sg_relation_cache[$service_id]
);
return $this->sg_relation_cache[$service_id];
}
/**
* @param $host_id
* @param $service_id
*
* @throws PDOException
* @return array|mixed
*/
public function getServiceGroupsForService($host_id, $service_id)
{
// Get from the cache
if (isset($this->sg_relation_cache[$service_id])) {
return $this->sg_relation_cache[$service_id];
}
if ($this->done_cache == 1) {
return [];
}
if (is_null($this->stmt_service_sg)) {
// Meaning, linked with the host or hostgroup (for the null expression)
$this->stmt_service_sg = $this->backend_instance->db->prepare(
"SELECT servicegroup_sg_id, host_host_id, service_service_id
FROM servicegroup_relation sgr, servicegroup sg
WHERE service_service_id = :service_id AND (host_host_id = :host_id OR host_host_id IS NULL)
AND sgr.servicegroup_sg_id = sg.sg_id AND sg.sg_activate = '1'"
);
}
$this->stmt_service_sg->bindParam(':service_id', $service_id, PDO::PARAM_INT);
$this->stmt_service_sg->bindParam(':host_id', $host_id, PDO::PARAM_INT);
$this->stmt_service_sg->execute();
$this->sg_relation_cache[$service_id] = array_merge(
$this->stmt_service_sg->fetchAll(PDO::FETCH_ASSOC),
$this->sg_relation_cache[$service_id]
);
return $this->sg_relation_cache[$service_id];
}
/**
* Generate service groups / tags and write in file
*/
public function generateObjects(): void
{
$this->generateServiceGroups();
$this->generateTags();
}
/**
* @return array
*/
public function getServicegroups()
{
$result = [];
foreach ($this->sg as $id => &$value) {
if (is_null($value) || count($value['members_cache']) == 0) {
continue;
}
$result[$id] = &$value;
}
return $result;
}
/**
* @throws Exception
* @return void
*/
public function reset(): void
{
parent::reset();
foreach ($this->sg as &$value) {
if (! is_null($value)) {
$value['members_cache'] = [];
$value['members'] = [];
}
}
}
/**
* @param $sg_id
* @param $attr
*
* @return mixed|null
*/
public function getString($sg_id, $attr)
{
return $this->sg[$sg_id][$attr] ?? null;
}
/**
* @param $sg_id
*
* @throws PDOException
* @return void
*/
private function getServicegroupFromId($sg_id): void
{
if (is_null($this->stmt_sg)) {
$this->stmt_sg = $this->backend_instance->db->prepare("SELECT
{$this->attributes_select}
FROM servicegroup
WHERE sg_id = :sg_id AND sg_activate = '1'
");
}
$this->stmt_sg->bindParam(':sg_id', $sg_id, PDO::PARAM_INT);
$this->stmt_sg->execute();
if ($serviceGroup = $this->stmt_sg->fetch(PDO::FETCH_ASSOC)) {
$this->sg[$sg_id] = $serviceGroup;
$this->sg[$sg_id]['members_cache'] = [];
$this->sg[$sg_id]['members'] = [];
}
}
/**
* @throws PDOException
* @return int|void
*/
private function buildCache()
{
if ($this->done_cache == 1) {
return 0;
}
$stmt = $this->backend_instance->db->prepare(
"SELECT service_service_id, servicegroup_sg_id, host_host_id
FROM servicegroup_relation sgr, servicegroup sg
WHERE sgr.servicegroup_sg_id = sg.sg_id AND sg.sg_activate = '1'"
);
$stmt->execute();
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $value) {
if (isset($this->sg_relation_cache[$value['service_service_id']])) {
$this->sg_relation_cache[$value['service_service_id']][] = $value;
} else {
$this->sg_relation_cache[$value['service_service_id']] = [$value];
}
}
$this->done_cache = 1;
}
/**
* Generate service groups and write in file
*/
private function generateServiceGroups(): void
{
$this->generate_filename = self::SERVICEGROUP_FILENAME;
$this->object_name = self::SERVICEGROUP_OBJECT_NAME;
$this->attributes_write = [
'servicegroup_id',
'servicegroup_name',
'alias',
];
$this->attributes_array = [
'members',
];
// reset cache to allow export of same ids
parent::reset();
foreach ($this->sg as $id => &$value) {
if (count($value['members_cache']) == 0) {
continue;
}
$value['servicegroup_id'] = $value['sg_id'];
foreach ($value['members_cache'] as $content) {
array_push($this->sg[$id]['members'], $content[0], $content[1]);
}
$this->generateObjectInFile($this->sg[$id], $id);
}
}
/**
* Generate tags and write in file
*/
private function generateTags(): void
{
$this->generate_filename = self::TAG_FILENAME;
$this->object_name = self::TAG_OBJECT_NAME;
$this->attributes_write = [
'id',
'tag_name',
'type',
];
$this->attributes_array = [];
// reset cache to allow export of same ids
parent::reset();
foreach ($this->sg as $id => &$value) {
if (count($value['members_cache']) == 0) {
continue;
}
$tag = [
'id' => $value['servicegroup_id'],
'tag_name' => $value['servicegroup_name'],
'type' => self::TAG_TYPE,
];
$this->generateObjectInFile($tag, $id);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate/contactgroup.class.php | centreon/www/class/config-generate/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
*
*/
use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException;
use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
/**
* Class
*
* @class Contactgroup
*/
class Contactgroup extends AbstractObject
{
/** @var int */
protected $use_cache = 1;
/** @var array */
protected $cg_cache = [];
/** @var null */
protected $cg = null;
/** @var string */
protected $generate_filename = 'contactgroups.cfg';
/** @var string */
protected string $object_name = 'contactgroup';
/** @var string */
protected $attributes_select = '
cg_id,
cg_name as contactgroup_name,
cg_alias as alias
';
/** @var string[] */
protected $attributes_write = ['contactgroup_name', 'alias'];
/** @var string[] */
protected $attributes_array = ['members'];
/** @var null */
protected $stmt_cg = null;
/** @var null */
protected $stmt_contact = null;
/** @var null */
protected $stmt_cg_service = null;
/** @var int */
private $done_cache = 0;
/** @var array */
private $cg_service_linked_cache = [];
/**
* @param int $serviceId
*
* @throws PDOException
* @return array
*/
public function getCgForService(int $serviceId): array
{
$this->buildCache();
// Get from the cache
if (isset($this->cg_service_linked_cache[$serviceId])) {
return $this->cg_service_linked_cache[$serviceId];
}
if ($this->done_cache == 1) {
return [];
}
if (is_null($this->stmt_cg_service)) {
$this->stmt_cg_service = $this->backend_instance->db->prepare("
SELECT csr.contactgroup_cg_id
FROM contactgroup_service_relation csr, contactgroup
WHERE csr.service_service_id = :service_id
AND csr.contactgroup_cg_id = contactgroup.cg_id
AND cg_activate = '1'
");
}
$this->stmt_cg_service->bindParam(':service_id', $serviceId, PDO::PARAM_INT);
$this->stmt_cg_service->execute();
$this->cg_service_linked_cache[$serviceId] = $this->stmt_cg_service->fetchAll(PDO::FETCH_COLUMN);
return $this->cg_service_linked_cache[$serviceId];
}
/**
* @param int $cgId
*
* @throws PDOException
* @return array
*/
public function getCgFromId(int $cgId): array
{
if (is_null($this->stmt_cg)) {
$this->stmt_cg = $this->backend_instance->db->prepare("
SELECT {$this->attributes_select}
FROM contactgroup
WHERE cg_id = :cg_id AND cg_activate = '1'
");
}
$this->stmt_cg->bindParam(':cg_id', $cgId, PDO::PARAM_INT);
$this->stmt_cg->execute();
$results = $this->stmt_cg->fetchAll(PDO::FETCH_ASSOC);
$this->cg[$cgId] = array_pop($results);
return $this->cg[$cgId];
}
/**
* @param int $cgId
*
* @throws LogicException
* @throws PDOException
* @throws ServiceCircularReferenceException
* @throws ServiceNotFoundException
*/
public function getContactFromCgId(int $cgId): void
{
if (! isset($this->cg[$cgId]['members_cache'])) {
if (is_null($this->stmt_contact)) {
$this->stmt_contact = $this->backend_instance->db->prepare('
SELECT contact_contact_id
FROM contactgroup_contact_relation
WHERE contactgroup_cg_id = :cg_id
');
}
$this->stmt_contact->bindParam(':cg_id', $cgId, PDO::PARAM_INT);
$this->stmt_contact->execute();
$this->cg[$cgId]['members_cache'] = $this->stmt_contact->fetchAll(PDO::FETCH_COLUMN);
}
$contact = Contact::getInstance($this->dependencyInjector);
$this->cg[$cgId]['members'] = [];
foreach ($this->cg[$cgId]['members_cache'] as $contact_id) {
$member = $contact->generateFromContactId($contact_id);
// Can have contact template in a contact group ???!!
if (! is_null($member) && ! $contact->isTemplate($contact_id)) {
$this->cg[$cgId]['members'][] = $member;
}
}
}
/**
* @param int $cgId
*
* @throws LogicException
* @throws PDOException
* @throws ServiceCircularReferenceException
* @throws ServiceNotFoundException
* @return string|null contactgroup_name
*/
public function generateFromCgId(int $cgId): ?string
{
if (is_null($cgId)) {
return null;
}
$this->buildCache();
if ($this->use_cache == 1) {
if (! isset($this->cg_cache[$cgId])) {
return null;
}
$this->cg[$cgId] = &$this->cg_cache[$cgId];
} elseif (! isset($this->cg[$cgId])) {
$this->getCgFromId($cgId);
}
if (is_null($this->cg[$cgId])) {
return null;
}
if ($this->checkGenerate($cgId)) {
return $this->cg[$cgId]['contactgroup_name'];
}
$this->getContactFromCgId($cgId);
$this->generateObjectInFile($this->cg[$cgId], $cgId);
return $this->cg[$cgId]['contactgroup_name'];
}
/**
* @throws PDOException
* @return void
*/
protected function getCgCache()
{
$stmt = $this->backend_instance->db->prepare("SELECT
{$this->attributes_select}
FROM contactgroup
WHERE cg_activate = '1'
");
$stmt->execute();
$this->cg_cache = $stmt->fetchAll(PDO::FETCH_GROUP | PDO::FETCH_UNIQUE | PDO::FETCH_ASSOC);
}
/**
* @see Contactgroup::getCgCache()
* @see Contactgroup::getCgForServiceCache()
*/
protected function buildCache(): void
{
if ($this->done_cache == 1) {
return;
}
$this->getCgCache();
$this->getCgForServiceCache();
$this->done_cache = 1;
}
/**
* @see Contactgroup::$cg_service_linked_cache
*/
private function getCgForServiceCache(): void
{
$stmt = $this->backend_instance->db->prepare("
SELECT csr.contactgroup_cg_id, service_service_id
FROM contactgroup_service_relation csr, contactgroup
WHERE csr.contactgroup_cg_id = contactgroup.cg_id
AND cg_activate = '1'
");
$stmt->execute();
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $value) {
if (isset($this->cg_service_linked_cache[$value['service_service_id']])) {
$this->cg_service_linked_cache[$value['service_service_id']][] = $value['contactgroup_cg_id'];
} else {
$this->cg_service_linked_cache[$value['service_service_id']] = [$value['contactgroup_cg_id']];
}
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate/media.class.php | centreon/www/class/config-generate/media.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 Media
*/
class Media extends AbstractObject
{
/** @var null */
private $medias = null;
/**
* @param $media_id
*
* @throws PDOException
* @return string|null
*/
public function getMediaPathFromId($media_id)
{
if (is_null($this->medias)) {
$this->getMedias();
}
$result = null;
if (! is_null($media_id) && isset($this->medias[$media_id])) {
$result = $this->medias[$media_id]['dir_name'] . '/' . $this->medias[$media_id]['img_path'];
}
return $result;
}
/**
* @throws PDOException
* @return void
*/
private function getMedias(): void
{
$query = 'SELECT img_id, img_name, img_path, dir_name FROM view_img, view_img_dir_relation, view_img_dir '
. 'WHERE view_img.img_id = view_img_dir_relation.img_img_id '
. 'AND view_img_dir_relation.dir_dir_parent_id = view_img_dir.dir_id';
$stmt = $this->backend_instance->db->prepare($query);
$stmt->execute();
$this->medias = $stmt->fetchAll(PDO::FETCH_GROUP | PDO::FETCH_UNIQUE | PDO::FETCH_ASSOC);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate/servicecategory.class.php | centreon/www/class/config-generate/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
*
*/
use Pimple\Container;
/**
* Class
*
* @class ServiceCategory
*/
final class ServiceCategory extends AbstractObject
{
private const TAG_TYPE = 'servicecategory';
/** @var string */
protected string $object_name = 'tag';
/** @var array<int,mixed> */
private array $serviceCategories = [];
/** @var array<int,int[]>|null */
private array|null $serviceCategoriesRelationsCache = null;
/**
* @param Container $dependencyInjector
*/
protected function __construct(Container $dependencyInjector)
{
parent::__construct($dependencyInjector);
$this->generate_filename = 'tags.cfg';
$this->attributes_write = [
'id',
'tag_name',
'type',
];
}
/**
* Get service categories linked to service
*
* @param int $serviceId
* @return int[]
*/
public function getServiceCategoriesByServiceId(int $serviceId): array
{
if ($this->serviceCategoriesRelationsCache === null) {
$this->buildCache();
}
return $this->serviceCategoriesRelationsCache[$serviceId] ?? [];
}
/**
* Add a service to members of a service category
*
* @param int $serviceCategoryId
* @param int $serviceId
* @param string $serviceDescription
*
* @throws PDOException
*/
public function insertServiceToServiceCategoryMembers(
int $serviceCategoryId,
int $serviceId,
string $serviceDescription,
): void {
if (! isset($this->serviceCategories[$serviceCategoryId])) {
$this->addServiceCategoryToList($serviceCategoryId);
}
if (
isset($this->serviceCategories[$serviceCategoryId])
&& ! isset($this->serviceCategories[$serviceCategoryId]['members'][$serviceId])
) {
$this->serviceCategories[$serviceCategoryId]['members'][$serviceId] = $serviceDescription;
}
}
/**
* Write servicecategories in configuration file
*/
public function generateObjects(): void
{
foreach ($this->serviceCategories as $id => &$value) {
if (! isset($value['members']) || count($value['members']) === 0) {
continue;
}
$value['type'] = self::TAG_TYPE;
$this->generateObjectInFile($value, $id);
}
}
/**
* Reset instance
*/
public function reset(): void
{
parent::reset();
foreach ($this->serviceCategories as &$value) {
if (! is_null($value)) {
$value['members'] = [];
}
}
}
/**
* @param int $serviceId
* @return int[]
*/
public function getIdsByServiceId(int $serviceId): array
{
$serviceCategoryIds = [];
foreach ($this->serviceCategories as $id => $value) {
if (isset($value['members']) && in_array($serviceId, array_keys($value['members']))) {
$serviceCategoryIds[] = (int) $id;
}
}
return $serviceCategoryIds;
}
/**
* Build cache for service categories
*/
private function buildCache(): void
{
$stmt = $this->backend_instance->db->prepare(
"SELECT service_categories.sc_id, service_service_id
FROM service_categories, service_categories_relation
WHERE level IS NULL
AND sc_activate = '1'
AND service_categories_relation.sc_id = service_categories.sc_id"
);
$stmt->execute();
$this->serviceCategoriesRelationsCache = [];
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $value) {
$this->serviceCategoriesRelationsCache[(int) $value['service_service_id']][] = (int) $value['sc_id'];
}
}
/**
* Retrieve a categorie from its id
*
* @param int $serviceCategoryId
*
* @throws PDOException
* @return self
*/
private function addServiceCategoryToList(int $serviceCategoryId): self
{
$stmt = $this->backend_instance->db->prepare(
"SELECT sc_id as id, sc_name as tag_name
FROM service_categories
WHERE sc_id = :serviceCategoryId AND level IS NULL AND sc_activate = '1'"
);
$stmt->bindParam(':serviceCategoryId', $serviceCategoryId, PDO::PARAM_INT);
$stmt->execute();
if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$this->serviceCategories[$serviceCategoryId] = $row;
$this->serviceCategories[$serviceCategoryId]['members'] = [];
}
return $this;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate/SingletonTrait.php | centreon/www/class/config-generate/SingletonTrait.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
use Pimple\Container;
/**
* Trait
*
* @class SingletonTrait
*/
trait SingletonTrait
{
/**
* @param Container $dependencyInjector
* @return static
*/
public static function getInstance(Container $dependencyInjector): static
{
/**
* @var array<string, static> $instances
*/
static $instances = [];
/**
* @var class-string<static> $calledClass
*/
$calledClass = static::class;
if (! isset($instances[$calledClass])) {
$instances[$calledClass] = new $calledClass($dependencyInjector);
}
return $instances[$calledClass];
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate/timezone.class.php | centreon/www/class/config-generate/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
*
*/
/**
* Class
*
* @class Timezone
*/
class Timezone extends AbstractObject
{
/** @var null */
private $aTimezone = null;
/** @var null */
private $defaultTimezone = null;
/**
* @throws PDOException
* @return mixed|null
*/
public function getDefaultTimezone()
{
if (! is_null($this->defaultTimezone)) {
return $this->defaultTimezone;
}
$stmt = $this->backend_instance->db->prepare("SELECT `value` from options WHERE `key` = 'gmt'");
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (count($results) > 0 && isset($this->aTimezone[$results[0]['value']])) {
$this->defaultTimezone = $this->aTimezone[$results[0]['value']];
}
return $this->defaultTimezone;
}
/**
* @param $iTimezone
* @param $returnDefault
*
* @throws PDOException
* @return mixed|null
*/
public function getTimezoneFromId($iTimezone, $returnDefault = false)
{
if (is_null($this->aTimezone)) {
$this->getTimezone();
}
$result = null;
if (! is_null($iTimezone) && isset($this->aTimezone[$iTimezone])) {
$result = $this->aTimezone[$iTimezone];
} elseif ($returnDefault === true) {
$result = $this->getDefaultTimezone();
}
return $result;
}
/**
* @throws PDOException
* @return void|null
*/
private function getTimezone()
{
if (! is_null($this->aTimezone)) {
return $this->aTimezone;
}
$this->aTimezone = [];
$stmt = $this->backend_instance->db->prepare('SELECT
timezone_id,
timezone_name
FROM timezone');
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($results as $res) {
$this->aTimezone[$res['timezone_id']] = $res['timezone_name'];
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate/vault.class.php | centreon/www/class/config-generate/vault.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 Pimple\Container;
use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException;
use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
/**
* Class
*
* @class Vault
*/
class Vault extends AbstractObjectJSON
{
/** @var null */
protected $vaultConfiguration = null;
/**
* Vault constructor
*
* @param Container $dependencyInjector
*
* @throws LogicException
* @throws ServiceCircularReferenceException
* @throws ServiceNotFoundException
*/
public function __construct(Container $dependencyInjector)
{
parent::__construct($dependencyInjector);
// Get Centeron Vault Storage configuration
$kernel = Kernel::createForWeb();
$readVaultConfigurationRepository = $kernel->getContainer()->get(
Core\Security\Vault\Application\Repository\ReadVaultConfigurationRepositoryInterface::class
);
$uuidGenerator = $kernel->getContainer()->get(Utility\Interfaces\UUIDGeneratorInterface::class);
$logger = $kernel->getContainer()->get(Logger::class);
$this->vaultConfiguration = $readVaultConfigurationRepository->find();
}
/**
* @param $poller
*
* @throws RuntimeException
* @return void
*/
public function generateFromPoller($poller): void
{
$this->generate($poller['id'], $poller['localhost']);
}
/**
* @param $poller_id
* @param $localhost
*
* @throws RuntimeException
* @return void
*/
private function generate($poller_id, $localhost): void
{
if ($this->vaultConfiguration === null) {
return;
}
// Base parameters
$object[$this->vaultConfiguration->getName()] = [
'vault-address' => $this->vaultConfiguration->getAddress(),
'vault-port' => $this->vaultConfiguration->getPort(),
'vault-protocol' => 'https',
];
// Generate file
$this->generate_filename = 'centreonvault.json';
$this->generateFile($object, false);
$this->writeFile($this->backend_instance->getPath());
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate/backend.class.php | centreon/www/class/config-generate/backend.class.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
use Pimple\Container;
// file centreon.config.php may not exist in test environment
$configFile = realpath(__DIR__ . '/../../../config/centreon.config.php');
if ($configFile !== false) {
require_once $configFile;
}
define('TMP_DIR_PREFIX', 'tmpdir_');
define('TMP_DIR_SUFFIX', '.d');
/**
* Class
*
* @class Backend
*/
class Backend
{
/** @var CentreonDBStatement */
public $stmt_central_poller;
/** @var string */
public $generate_path = '/var/cache/centreon/config';
/** @var string */
public $engine_sub = 'engine';
/** @var string */
public $broker_sub = 'broker';
public $vmware_sub = 'vmware';
/** @var CentreonDB|null */
public $db = null;
/** @var CentreonDB|null */
public $db_cs = null;
/** @var Backend|null */
private static $_instance = null;
/** @var string|null */
private $tmp_file = null;
/** @var string|null */
private $tmp_dir = null;
/** @var string|null */
private $full_path = null;
/** @var string */
private $whoaim = 'unknown';
/** @var string|null */
private $poller_id = null;
/** @var string|null */
private $central_poller_id = null;
/**
* Backend constructor
*
* @param Container $dependencyInjector
*/
private function __construct(Container $dependencyInjector)
{
$this->generate_path = _CENTREON_CACHEDIR_ . '/config';
$this->db = $dependencyInjector['configuration_db'];
$this->db_cs = $dependencyInjector['realtime_db'];
}
/**
* @param Container $dependencyInjector
*
* @return Backend|null
*/
public static function getInstance(Container $dependencyInjector)
{
if (is_null(self::$_instance)) {
self::$_instance = new Backend($dependencyInjector);
}
return self::$_instance;
}
/**
* @param $paths
*
* @throws Exception
* @return string
*/
public function createDirectories($paths)
{
$dir = '';
$dir_append = '';
foreach ($paths as $path) {
$dir .= $dir_append . $path;
$dir_append .= '/';
if (file_exists($dir)) {
if (! is_dir($dir)) {
throw new Exception("Generation path '" . $dir . "' is not a directory.");
}
if (posix_getuid() === fileowner($dir)) {
chmod($dir, 0770);
}
} elseif (! mkdir($dir, 0770, true)) {
throw new Exception("Cannot create directory '" . $dir . "'");
}
}
return $dir;
}
/**
* @return string
*/
public function getEngineGeneratePath()
{
return $this->generate_path . '/' . $this->engine_sub;
}
/**
* @param $poller_id
* @param $engine
*
* @throws Exception
* @return void
*/
public function initPath($poller_id, $engine = 1): void
{
switch ($engine) {
case 1:
$this->createDirectories([$this->generate_path, $this->engine_sub]);
$this->full_path = $this->generate_path . '/' . $this->engine_sub;
break;
case 2:
$this->createDirectories([$this->generate_path, $this->broker_sub]);
$this->full_path = $this->generate_path . '/' . $this->broker_sub;
break;
case 3:
$this->createDirectories([$this->generate_path, $this->vmware_sub]);
$this->full_path = $this->generate_path . '/' . $this->vmware_sub;
break;
default:
throw new Exception('Invalid engine type');
}
if (is_dir($this->full_path . '/' . $poller_id) && ! is_writable($this->full_path . '/' . $poller_id)) {
throw new Exception("Not writeable directory '" . $this->full_path . '/' . $poller_id . "'");
}
if (! is_writable($this->full_path)) {
throw new Exception("Not writeable directory '" . $this->full_path . "'");
}
$this->tmp_file = basename(tempnam($this->full_path, TMP_DIR_PREFIX));
$this->tmp_dir = $this->tmp_file . TMP_DIR_SUFFIX;
$this->full_path .= '/' . $this->tmp_dir;
if (! mkdir($this->full_path)) {
throw new Exception("Cannot create directory '" . $this->full_path . "'");
}
// rights cannot be set in mkdir function (2nd argument) because current sgid bit on parent directory override it
chmod($this->full_path, 0770);
}
/**
* @return null
*/
public function getPath()
{
return $this->full_path;
}
/**
* @param $poller_id
*
* @return void
*/
public function movePath($poller_id): void
{
$subdir = dirname($this->full_path);
$this->deleteDir($subdir . '/' . $poller_id);
unlink($subdir . '/' . $this->tmp_file);
rename($this->full_path, $subdir . '/' . $poller_id);
}
/**
* @return void
*/
public function cleanPath(): void
{
$subdir = dirname($this->full_path);
if (is_dir($this->full_path)) {
$this->deleteDir($this->full_path);
}
@unlink($subdir . '/' . $this->tmp_file);
}
/**
* @param $username
*
* @return void
*/
public function setUserName($username): void
{
$this->whoaim = $username;
}
/**
* @return string
*/
public function getUserName()
{
return $this->whoaim;
}
/**
* @param $poller_id
*
* @return void
*/
public function setPollerId($poller_id): void
{
$this->poller_id = $poller_id;
}
/**
* @return null
*/
public function getPollerId()
{
return $this->poller_id;
}
/**
* @throws PDOException
* @return mixed|null
*/
public function getCentralPollerId()
{
if (! is_null($this->central_poller_id)) {
return $this->central_poller_id;
}
$this->stmt_central_poller = $this->db->prepare("SELECT id
FROM nagios_server
WHERE localhost = '1' AND ns_activate = '1'
");
$this->stmt_central_poller->execute();
if ($this->stmt_central_poller->rowCount()) {
$row = $this->stmt_central_poller->fetch(PDO::FETCH_ASSOC);
$this->central_poller_id = $row['id'];
return $this->central_poller_id;
}
throw new Exception('Cannot get central poller id');
}
/**
* @param $path
*
* @return bool
*/
private function deleteDir($path)
{
if (is_dir($path) === true) {
$files = array_diff(scandir($path), ['.', '..']);
foreach ($files as $file) {
$this->deleteDir(realpath($path) . '/' . $file);
}
return rmdir($path);
}
if (is_file($path) === true) {
return unlink($path);
}
return false;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate/service.class.php | centreon/www/class/config-generate/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 __DIR__ . '/abstract/service.class.php';
/**
* Class
*
* @class Service
*/
class Service extends AbstractService
{
public const VERTICAL_NOTIFICATION = 1;
public const CLOSE_NOTIFICATION = 2;
public const CUMULATIVE_NOTIFICATION = 3;
/** @var null */
public $poller_id = null; // for by poller cache
/** @var array|null */
protected $service_cache = null;
/** @var array */
protected $generated_services = []; // for index_data build and escalation
/** @var string */
protected $generate_filename = 'services.cfg';
/** @var string */
protected string $object_name = 'service';
/** @var int */
private $use_cache = 0;
/** @var int */
private $use_cache_poller = 1;
/** @var int */
private $done_cache = 0;
/**
* @return void
*/
public function use_cache(): void
{
$this->use_cache = 1;
}
/**
* @param int $serviceId
* @param array $attr
*/
public function addServiceCache(int $serviceId, $attr = []): void
{
$this->service_cache[$serviceId] = $attr;
}
/**
* @param int $hostId
* @param int $serviceId
*/
public function addGeneratedServices(int $hostId, int $serviceId): void
{
if (! isset($this->generated_services[$hostId])) {
$this->generated_services[$hostId] = [];
}
$this->generated_services[$hostId][] = $serviceId;
}
/**
* @return array
*/
public function getGeneratedServices(): array
{
return $this->generated_services;
}
/**
* @param int $hostId
* @param string $hostName
* @param int|null $serviceId
* @param int $byHg default 0
* @return string|null service description
*/
public function generateFromServiceId(
int $hostId,
string $hostName,
?int $serviceId,
int $byHg = 0,
array $serviceMacros = [],
array $serviceTemplateMacros = [],
): ?string {
if (is_null($serviceId)) {
return null;
}
$this->buildCache();
if (($this->use_cache == 0 || $byHg == 1) && ! isset($this->service_cache[$serviceId])) {
$this->getServiceFromId($serviceId);
}
if (! isset($this->service_cache[$serviceId]) || is_null($this->service_cache[$serviceId])) {
return null;
}
// We skip anomalydetection services represented by enum value '3'
if ($this->service_cache[$serviceId]['register'] === '3') {
return null;
}
if ($this->checkGenerate($hostId . '.' . $serviceId)) {
return $this->service_cache[$serviceId]['service_description'];
}
// we reset notifications for service multiples and hg
$this->service_cache[$serviceId]['contacts'] = '';
$this->service_cache[$serviceId]['contact_groups'] = '';
$this->getImages($this->service_cache[$serviceId]);
$this->formatMacros($this->service_cache[$serviceId], $serviceMacros);
$this->service_cache[$serviceId]['macros']['_SERVICE_ID'] = $serviceId;
// useful for servicegroup on servicetemplate
$service_template = ServiceTemplate::getInstance($this->dependencyInjector);
$service_template->resetLoop();
$service_template->current_host_id = $hostId;
$service_template->current_host_name = $hostName;
$service_template->current_service_id = $serviceId;
$service_template->current_service_description = $this->service_cache[$serviceId]['service_description'];
$this->getServiceTemplates($this->service_cache[$serviceId], $serviceTemplateMacros);
$this->getServiceCommands($this->service_cache[$serviceId]);
$this->getServicePeriods($this->service_cache[$serviceId]);
$this->getContactGroups($this->service_cache[$serviceId]);
$this->getContacts($this->service_cache[$serviceId]);
$this->manageNotificationInheritance($this->service_cache[$serviceId]);
if (is_null($this->service_cache[$serviceId]['notifications_enabled'])
|| (int) $this->service_cache[$serviceId]['notifications_enabled'] !== 0) {
$this->getContactsFromHost(
$hostId,
$serviceId,
$this->service_cache[$serviceId]['service_use_only_contacts_from_host'] == '1'
);
}
// Set ServiceCategories
$serviceCategory = ServiceCategory::getInstance($this->dependencyInjector);
$this->insertServiceInServiceCategoryMembers($serviceCategory, $serviceId);
$this->service_cache[$serviceId]['category_tags'] = $serviceCategory->getIdsByServiceId($serviceId);
$this->getSeverity($hostId, $serviceId);
$this->getServiceGroups($serviceId, $hostId, $hostName);
$this->generateObjectInFile(
$this->service_cache[$serviceId] + ['host_name' => $hostName],
$hostId . '.' . $serviceId
);
$this->addGeneratedServices($hostId, $serviceId);
$this->clean($this->service_cache[$serviceId]);
return $this->service_cache[$serviceId]['service_description'];
}
/**
* @param $pollerId
*
* @return void
*/
public function set_poller($pollerId): void
{
$this->poller_id = $pollerId;
}
/**
* @param int $serviceId
* @return array
*/
public function getCgAndContacts(int $serviceId): array
{
$this->getServiceFromId($serviceId);
$this->getContactGroups($this->service_cache[$serviceId]);
$this->getContacts($this->service_cache[$serviceId]);
$serviceTplInstance = ServiceTemplate::getInstance($this->dependencyInjector);
$serviceTplId = $this->service_cache[$serviceId]['service_template_model_stm_id'] ?? null;
$loop = [];
while (! is_null($serviceTplId)) {
if (isset($loop[$serviceTplId])) {
break;
}
$loop[$serviceTplId] = 1;
$serviceTplInstance->getServiceFromId($serviceTplId);
if (is_null($serviceTplInstance->service_cache[$serviceTplId])) {
break;
}
$serviceTplInstance->getContactGroups($serviceTplInstance->service_cache[$serviceTplId]);
$serviceTplInstance->getContacts($serviceTplInstance->service_cache[$serviceTplId]);
$serviceTplId = $serviceTplInstance->service_cache[$serviceTplId]['service_template_model_stm_id'] ?? null;
}
return $this->manageNotificationInheritance($this->service_cache[$serviceId], false);
}
/**
* @throws Exception
* @return void
*/
public function reset(): void
{
// We reset it by poller (dont need all. We save memory)
if ($this->use_cache_poller == 1) {
$this->service_cache = [];
$this->done_cache = 0;
}
$this->generated_services = [];
parent::reset();
}
/**
* @param int $serviceId
*
* @return array|null
*/
public function getServiceFromCache(int $serviceId): ?array
{
if ($this->service_cache !== null && ! array_key_exists($serviceId, $this->service_cache)) {
return null;
}
return $this->service_cache[$serviceId];
}
/**
* @param int $serviceId
* @param int $hostId
* @param string $hostName
*/
protected function getServiceGroups(int $serviceId, int $hostId, string $hostName): void
{
$servicegroup = Servicegroup::getInstance($this->dependencyInjector);
$this->service_cache[$serviceId]['sg'] = $servicegroup->getServiceGroupsForService($hostId, $serviceId);
$this->service_cache[$serviceId]['group_tags'] = [];
foreach ($this->service_cache[$serviceId]['sg'] as &$value) {
if (is_null($value['host_host_id']) || $hostId == $value['host_host_id']) {
$this->service_cache[$serviceId]['group_tags'][] = $value['servicegroup_sg_id'];
$servicegroup->addServiceInSg(
$value['servicegroup_sg_id'],
$serviceId,
$this->service_cache[$serviceId]['service_description'],
$hostId,
$hostName
);
}
}
}
/**
* @param int $hostId
* @param int $serviceId
* @param bool $isOnlyContactHost
*/
protected function getContactsFromHost(int $hostId, int $serviceId, bool $isOnlyContactHost): void
{
if ($isOnlyContactHost) {
$host = Host::getInstance($this->dependencyInjector);
$this->service_cache[$serviceId]['contacts'] = $host->getString($hostId, 'contacts');
$this->service_cache[$serviceId]['contact_groups'] = $host->getString($hostId, 'contact_groups');
$this->service_cache[$serviceId]['contact_from_host'] = 1;
} elseif (
empty($this->service_cache[$serviceId]['contacts'])
&& empty($this->service_cache[$serviceId]['contact_groups'])
) {
$this->service_cache[$serviceId]['contact_from_host'] = 0;
$host = Host::getInstance($this->dependencyInjector);
$this->service_cache[$serviceId]['contacts'] = $host->getString($hostId, 'contacts');
$this->service_cache[$serviceId]['contact_groups'] = $host->getString($hostId, 'contact_groups');
$this->service_cache[$serviceId]['contact_from_host'] = 1;
}
}
/**
* @param array $service
* @param bool $generate
* @return array
*/
protected function manageNotificationInheritance(array &$service, bool $generate = true): array
{
$results = ['cg' => [], 'contact' => []];
if (! is_null($service['notifications_enabled']) && (int) $service['notifications_enabled'] === 0) {
return $results;
}
if (isset($service['service_use_only_contacts_from_host'])
&& $service['service_use_only_contacts_from_host'] == 1
) {
$service['contact_groups'] = '';
$service['contacts'] = '';
return $results;
}
$mode = $this->getInheritanceMode();
if ($mode === self::CUMULATIVE_NOTIFICATION) {
$results = $this->manageCumulativeInheritance($service);
} elseif ($mode === self::CLOSE_NOTIFICATION) {
$results['cg'] = $this->manageCloseInheritance($service, 'contact_groups');
$results['contact'] = $this->manageCloseInheritance($service, 'contacts');
} else {
$results['cg'] = $this->manageVerticalInheritance($service, 'contact_groups', 'cg_additive_inheritance');
$results['contact'] = $this->manageVerticalInheritance(
$service,
'contacts',
'contact_additive_inheritance'
);
}
if ($generate) {
$this->setContacts($service, $results['contact']);
$this->setContactGroups($service, $results['cg']);
}
return $results;
}
/**
* @param int $hostId
* @param int $serviceId
*/
protected function getSeverity(int $hostId, int $serviceId): void
{
$this->service_cache[$serviceId]['severity_from_host'] = 0;
$this->getSeverityInServiceChain($serviceId);
// Get from the hosts
if (is_null($this->service_cache[$serviceId]['severity_id'])) {
$this->service_cache[$serviceId]['severity_from_host'] = 1;
$severity = Host::getInstance($this->dependencyInjector)->getSeverityForService($hostId);
if (! is_null($severity)) {
$serviceSeverity = Severity::getInstance($this->dependencyInjector)
->getServiceSeverityMappingHostSeverityByName($severity['hc_name']);
if (! is_null($serviceSeverity)) {
$this->service_cache[$serviceId]['macros']['_CRITICALITY_LEVEL'] = $serviceSeverity['level'];
$this->service_cache[$serviceId]['macros']['_CRITICALITY_ID'] = $serviceSeverity['sc_id'];
$this->service_cache[$serviceId]['macros']['severity'] = $serviceSeverity['sc_id'];
}
}
}
}
/**
* @param $service
*
* @return void
*/
protected function clean(&$service)
{
if ($service['severity_from_host'] == 1) {
unset($service['macros']['_CRITICALITY_LEVEL'], $service['macros']['_CRITICALITY_ID'], $service['macros']['severity']);
}
}
/**
* @throws PDOException
* @return void
*/
private function generateServiceCacheByPollerCache(): void
{
$query = "SELECT {$this->attributes_select} FROM ns_host_relation, host_service_relation, service "
. 'LEFT JOIN extended_service_information ON extended_service_information.service_service_id = '
. 'service.service_id WHERE ns_host_relation.nagios_server_id = :server_id '
. 'AND ns_host_relation.host_host_id = host_service_relation.host_host_id '
. "AND host_service_relation.service_service_id = service.service_id AND service_activate = '1'";
$stmt = $this->backend_instance->db->prepare($query);
$stmt->bindParam(':server_id', $this->poller_id, PDO::PARAM_INT);
$stmt->execute();
while (($value = $stmt->fetch(PDO::FETCH_ASSOC))) {
$this->service_cache[$value['service_id']] = $value;
}
}
/**
* @throws PDOException
* @return void
*/
private function generateServiceCache(): void
{
$query = "SELECT {$this->attributes_select} FROM service "
. 'LEFT JOIN extended_service_information ON extended_service_information.service_service_id = '
. "service.service_id WHERE service_register = '1' AND service_activate = '1'";
$stmt = $this->backend_instance->db->prepare($query);
$stmt->execute();
$this->service_cache = $stmt->fetchAll(PDO::FETCH_GROUP | PDO::FETCH_UNIQUE | PDO::FETCH_ASSOC);
}
/**
* @param int $serviceId
*/
private function getServiceFromId(int $serviceId): void
{
if (is_null($this->stmt_service)) {
$query = "SELECT {$this->attributes_select} FROM service "
. 'LEFT JOIN extended_service_information ON extended_service_information.service_service_id = '
. "service.service_id WHERE service_id = :service_id AND service_activate = '1'";
$this->stmt_service = $this->backend_instance->db->prepare($query);
}
$this->stmt_service->bindParam(':service_id', $serviceId, PDO::PARAM_INT);
$this->stmt_service->execute();
$results = $this->stmt_service->fetchAll(PDO::FETCH_ASSOC);
$this->service_cache[$serviceId] = array_pop($results);
}
/**
* @param $service (passing by Reference)
* @return array
*/
private function manageCumulativeInheritance(array &$service): array
{
$results = ['cg' => $service['contact_groups_cache'], 'contact' => $service['contacts_cache']];
$servicesTpl = ServiceTemplate::getInstance($this->dependencyInjector)->service_cache;
$serviceId = $this->service_cache[$service['service_id']]['service_template_model_stm_id'] ?? null;
$serviceIdTopLevel = $serviceId;
if (! is_null($serviceIdTopLevel) && ! isset($servicesTpl[$serviceIdTopLevel]['contacts_computed_cache'])) {
$contacts = [];
$cg = [];
$loop = [];
while (! is_null($serviceId)) {
if (isset($loop[$serviceId]) || ! isset($servicesTpl[$serviceId])) {
break;
}
$loop[$serviceId] = 1;
// if notifications_enabled is disabled. We don't go in branch
if (! is_null($servicesTpl[$serviceId]['notifications_enabled'])
&& (int) $servicesTpl[$serviceId]['notifications_enabled'] === 0) {
break;
}
if (count($servicesTpl[$serviceId]['contact_groups_cache']) > 0) {
$cg = array_merge($cg, $servicesTpl[$serviceId]['contact_groups_cache']);
}
if (count($servicesTpl[$serviceId]['contacts_cache']) > 0) {
$contacts = array_merge($contacts, $servicesTpl[$serviceId]['contacts_cache']);
}
$serviceId = $servicesTpl[$serviceId]['service_template_model_stm_id'] ?? null;
}
$servicesTpl[$serviceIdTopLevel]['contacts_computed_cache'] = array_unique($contacts);
$servicesTpl[$serviceIdTopLevel]['contact_groups_computed_cache'] = array_unique($cg);
}
if (! is_null($serviceIdTopLevel)) {
$results['cg'] = array_unique(
array_merge(
$results['cg'],
$servicesTpl[$serviceIdTopLevel]['contact_groups_computed_cache']
),
SORT_NUMERIC
);
$results['contact'] = array_unique(
array_merge(
$results['contact'],
$servicesTpl[$serviceIdTopLevel]['contacts_computed_cache']
),
SORT_NUMERIC
);
}
return $results;
}
/**
* @param array $service (passing by Reference)
* @param string $attribute
* @return array
*/
private function manageCloseInheritance(array &$service, string $attribute): array
{
if (count($service[$attribute . '_cache']) > 0) {
return $service[$attribute . '_cache'];
}
$servicesTpl = ServiceTemplate::getInstance($this->dependencyInjector)->service_cache;
$serviceId = $this->service_cache[$service['service_id']]['service_template_model_stm_id'] ?? null;
$serviceIdTopLevel = $serviceId;
if (! is_null($serviceIdTopLevel) && ! isset($servicesTpl[$serviceIdTopLevel][$attribute . '_computed_cache'])) {
$servicesTpl[$serviceIdTopLevel][$attribute . '_computed_cache'] = [];
$loop = [];
while (! is_null($serviceId)) {
if (isset($loop[$serviceId])) {
break;
}
$loop[$serviceId] = 1;
// if notifications_enabled is disabled. We don't go in branch
if (! is_null($servicesTpl[$serviceId]['notifications_enabled'])
&& (int) $servicesTpl[$serviceId]['notifications_enabled'] === 0) {
break;
}
if (count($servicesTpl[$serviceId][$attribute . '_cache']) > 0) {
$servicesTpl[$serviceIdTopLevel][$attribute . '_computed_cache']
= $servicesTpl[$serviceId][$attribute . '_cache'];
break;
}
$serviceId = $servicesTpl[$serviceId]['service_template_model_stm_id'] ?? null;
}
return $servicesTpl[$serviceIdTopLevel][$attribute . '_computed_cache'];
}
return [];
}
/**
* @param array $service
* @param string $attribute
* @param string $attributeAdditive
* @return array
*/
private function manageVerticalInheritance(array &$service, string $attribute, string $attributeAdditive): array
{
$results = $service[$attribute . '_cache'];
if (count($results) > 0
&& (is_null($service[$attributeAdditive]) || $service[$attributeAdditive] != 1)) {
return $results;
}
$servicesTpl = ServiceTemplate::getInstance($this->dependencyInjector)->service_cache;
$serviceId = $this->service_cache[$service['service_id']]['service_template_model_stm_id'] ?? null;
$serviceIdTopLevel = $serviceId;
$computedCache = [];
if (! is_null($serviceIdTopLevel) && ! isset($servicesTpl[$serviceIdTopLevel][$attribute . '_computed_cache'])) {
$loop = [];
while (! is_null($serviceId)) {
if (isset($loop[$serviceId])) {
break;
}
$loop[$serviceId] = 1;
if (! is_null($servicesTpl[$serviceId]['notifications_enabled'])
&& (int) $servicesTpl[$serviceId]['notifications_enabled'] === 0) {
break;
}
if (count($servicesTpl[$serviceId][$attribute . '_cache']) > 0) {
$computedCache = array_merge($computedCache, $servicesTpl[$serviceId][$attribute . '_cache']);
if (is_null($servicesTpl[$serviceId][$attributeAdditive])
|| $servicesTpl[$serviceId][$attributeAdditive] != 1) {
break;
}
}
$serviceId = $servicesTpl[$serviceId]['service_template_model_stm_id'] ?? null;
}
$servicesTpl[$serviceIdTopLevel][$attribute . '_computed_cache'] = array_unique($computedCache);
}
if (! is_null($serviceIdTopLevel)) {
$results = array_unique(
array_merge($results, $servicesTpl[$serviceIdTopLevel][$attribute . '_computed_cache']),
SORT_NUMERIC
);
}
return $results;
}
/**
* @param array $service
* @param array $cg
*/
private function setContactGroups(array &$service, array $cg = []): void
{
$cgInstance = Contactgroup::getInstance($this->dependencyInjector);
$cgResult = '';
$cgResultAppend = '';
foreach ($cg as $cgId) {
$tmp = $cgInstance->generateFromCgId($cgId);
if (! is_null($tmp)) {
$cgResult .= $cgResultAppend . $tmp;
$cgResultAppend = ',';
}
}
if ($cgResult != '') {
$service['contact_groups'] = $cgResult;
}
}
/**
* @param array $service
* @param array $contacts
*/
private function setContacts(array &$service, array $contacts = []): void
{
$contactInstance = Contact::getInstance($this->dependencyInjector);
$contactResult = '';
$contactResultAppend = '';
foreach ($contacts as $contactId) {
$tmp = $contactInstance->generateFromContactId($contactId);
if (! is_null($tmp)) {
$contactResult .= $contactResultAppend . $tmp;
$contactResultAppend = ',';
}
}
if ($contactResult != '') {
$service['contacts'] = $contactResult;
}
}
/**
* @param int $serviceIdArg
*/
private function getSeverityInServiceChain(int $serviceIdArg): void
{
if (isset($this->service_cache[$serviceIdArg]['severity_id'])) {
return;
}
$this->service_cache[$serviceIdArg]['severity_id'] = Severity::getInstance($this->dependencyInjector)
->getServiceSeverityByServiceId($serviceIdArg);
$severity = Severity::getInstance($this->dependencyInjector)
->getServiceSeverityById($this->service_cache[$serviceIdArg]['severity_id']);
if (! is_null($severity)) {
$this->service_cache[$serviceIdArg]['macros']['_CRITICALITY_LEVEL'] = $severity['level'];
$this->service_cache[$serviceIdArg]['macros']['_CRITICALITY_ID'] = $severity['sc_id'];
$this->service_cache[$serviceIdArg]['macros']['severity'] = $severity['sc_id'];
return;
}
// Check from service templates
$loop = [];
$servicesTpl = &ServiceTemplate::getInstance($this->dependencyInjector)->service_cache;
$servicesTopTpl = $this->service_cache[$serviceIdArg]['service_template_model_stm_id'] ?? null;
$serviceId = $servicesTopTpl;
$severityId = null;
while (! is_null($serviceId)) {
if (isset($loop[$serviceId])) {
break;
}
if (isset($servicesTpl[$serviceId]['severity_id_from_below'])) {
$this->service_cache[$serviceIdArg]['severity_id'] = $servicesTpl[$serviceId]['severity_id_from_below'];
break;
}
$loop[$serviceId] = 1;
if (isset($servicesTpl[$serviceId]['severity_id'])
&& ! is_null($servicesTpl[$serviceId]['severity_id'])
) {
$this->service_cache[$serviceIdArg]['severity_id'] = $servicesTpl[$serviceId]['severity_id'];
$servicesTpl[$servicesTopTpl]['severity_id_from_below'] = $servicesTpl[$serviceId]['severity_id'];
break;
}
$serviceId = $servicesTpl[$serviceId]['service_template_model_stm_id'] ?? null;
}
return;
}
/**
* @throws PDOException
* @return void
*/
private function buildCache(): void
{
if ($this->done_cache == 1 || ($this->use_cache == 0 && $this->use_cache_poller == 0)) {
return;
}
if ($this->use_cache_poller == 1) {
$this->generateServiceCacheByPollerCache();
} else {
$this->generateServiceCache();
}
$this->done_cache = 1;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate/engine.class.php | centreon/www/class/config-generate/engine.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 Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException;
use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
/**
* Class
*
* @class Engine
*/
class Engine extends AbstractObject
{
/** @var array */
public $cfg_file;
/** @var array|null */
protected $engine = null;
/** @var string|null */
protected $generate_filename = null; // it's in 'cfg_nagios' table
/** @var string */
protected string $object_name;
/** @var string */
protected $attributes_select = '
nagios_id,
use_timezone,
cfg_dir,
cfg_file as cfg_filename,
log_file,
status_file,
status_update_interval,
external_command_buffer_slots,
command_check_interval,
command_file,
state_retention_file,
retention_update_interval,
sleep_time,
service_inter_check_delay_method,
host_inter_check_delay_method,
service_interleave_factor,
max_concurrent_checks,
max_service_check_spread,
max_host_check_spread,
check_result_reaper_frequency,
auto_rescheduling_interval,
auto_rescheduling_window,
enable_flap_detection,
low_service_flap_threshold,
high_service_flap_threshold,
low_host_flap_threshold,
high_host_flap_threshold,
service_check_timeout,
host_check_timeout,
event_handler_timeout,
notification_timeout,
service_freshness_check_interval,
host_freshness_check_interval,
instance_heartbeat_interval,
date_format,
illegal_object_name_chars,
illegal_macro_output_chars,
admin_email,
admin_pager,
event_broker_options,
cached_host_check_horizon,
cached_service_check_horizon,
additional_freshness_latency,
debug_file,
debug_level,
debug_level_opt,
debug_verbosity,
max_debug_file_size,
log_pid,
global_host_event_handler as global_host_event_handler_id,
global_service_event_handler as global_service_event_handler_id,
enable_notifications,
execute_service_checks,
accept_passive_service_checks,
execute_host_checks,
accept_passive_host_checks,
enable_event_handlers,
check_external_commands,
use_retained_program_state,
use_retained_scheduling_info,
use_syslog,
log_notifications,
log_service_retries,
log_host_retries,
log_event_handlers,
log_external_commands,
log_passive_checks,
auto_reschedule_checks,
soft_state_dependencies,
check_for_orphaned_services,
check_for_orphaned_hosts,
check_service_freshness,
check_host_freshness,
use_regexp_matching,
use_true_regexp_matching,
enable_predictive_host_dependency_checks,
enable_predictive_service_dependency_checks,
host_down_disable_service_checks,
enable_environment_macros,
enable_macros_filter,
macros_filter,
logger_version,
broker_module_cfg_file
';
/** @var string[] */
protected $attributes_write = [
'use_timezone',
'resource_file',
'log_file',
'status_file',
'status_update_interval',
'external_command_buffer_slots',
'command_check_interval',
'command_file',
'state_retention_file',
'retention_update_interval',
'sleep_time',
'service_inter_check_delay_method',
'host_inter_check_delay_method',
'service_interleave_factor',
'max_concurrent_checks',
'max_service_check_spread',
'max_host_check_spread',
'check_result_reaper_frequency',
'auto_rescheduling_interval',
'auto_rescheduling_window',
'low_service_flap_threshold',
'high_service_flap_threshold',
'low_host_flap_threshold',
'high_host_flap_threshold',
'service_check_timeout',
'host_check_timeout',
'event_handler_timeout',
'notification_timeout',
'service_freshness_check_interval',
'host_freshness_check_interval',
'date_format',
'illegal_object_name_chars',
'illegal_macro_output_chars',
'admin_email',
'admin_pager',
'event_broker_options',
'cached_host_check_horizon',
'cached_service_check_horizon',
'additional_freshness_latency',
'debug_file',
'debug_level',
'debug_verbosity',
'max_debug_file_size',
'log_pid', // centengine
'global_host_event_handler',
'global_service_event_handler',
'macros_filter',
'enable_macros_filter',
'grpc_port',
'log_v2_enabled',
'log_legacy_enabled',
'log_v2_logger',
'log_level_functions',
'log_level_config',
'log_level_events',
'log_level_checks',
'log_level_notifications',
'log_level_eventbroker',
'log_level_external_command',
'log_level_commands',
'log_level_downtimes',
'log_level_comments',
'log_level_macros',
'log_level_process',
'log_level_runtime',
'log_level_otl',
'broker_module_cfg_file',
];
/** @var string[] */
protected $attributes_default = [
'instance_heartbeat_interval',
'enable_notifications',
'execute_service_checks',
'accept_passive_service_checks',
'execute_host_checks',
'accept_passive_host_checks',
'enable_event_handlers',
'check_external_commands',
'use_retained_program_state',
'use_retained_scheduling_info',
'use_syslog',
'log_notifications',
'log_service_retries',
'log_host_retries',
'log_event_handlers',
'log_external_commands',
'log_passive_checks',
'auto_reschedule_checks',
'soft_state_dependencies',
'check_for_orphaned_services',
'check_for_orphaned_hosts',
'check_service_freshness',
'check_host_freshness',
'enable_flap_detection',
'use_regexp_matching',
'use_true_regexp_matching',
'enable_predictive_host_dependency_checks',
'enable_predictive_service_dependency_checks',
'host_down_disable_service_checks',
'enable_environment_macros',
];
/** @var string[] */
protected $attributes_array = [
'cfg_file',
'broker_module',
'interval_length',
];
/** @var CentreonDBStatement|null */
protected $stmt_engine = null;
/** @var CentreonDBStatement|null */
protected $stmt_broker = null;
/** @var CentreonDBStatement|null */
protected $stmt_interval_length = null;
/** @var array */
protected $add_cfg_files = [];
/**
* @param $poller
*
* @throws LogicException
* @throws PDOException
* @throws ServiceCircularReferenceException
* @throws ServiceNotFoundException
* @return void
*/
public function generateFromPoller($poller): void
{
Connector::getInstance($this->dependencyInjector)->generateObjects($poller['centreonconnector_path']);
Resource::getInstance($this->dependencyInjector)->generateFromPollerId($poller['id']);
$this->generate($poller['id']);
}
/**
* @param $cfg_path
*
* @return void
*/
public function addCfgPath($cfg_path): void
{
$this->add_cfg_files[] = $cfg_path;
}
/**
* @return void
*/
public function reset(): void
{
$this->add_cfg_files = [];
}
/**
* @param $poller_id
*
* @return void
*/
private function buildCfgFile($poller_id): void
{
$this->engine['cfg_dir'] = preg_replace('/\/$/', '', $this->engine['cfg_dir']);
$this->cfg_file = [
'target' => [
'cfg_file' => [],
'path' => $this->engine['cfg_dir'],
'resource_file' => $this->engine['cfg_dir'] . '/resource.cfg',
],
'debug' => [
'cfg_file' => [],
'path' => $this->backend_instance->getEngineGeneratePath() . '/' . $poller_id,
'resource_file' => $this->backend_instance->getEngineGeneratePath() . '/' . $poller_id . '/resource.cfg',
],
];
foreach ($this->cfg_file as &$value) {
$value['cfg_file'][] = $value['path'] . '/hostTemplates.cfg';
$value['cfg_file'][] = $value['path'] . '/hosts.cfg';
$value['cfg_file'][] = $value['path'] . '/serviceTemplates.cfg';
$value['cfg_file'][] = $value['path'] . '/services.cfg';
$value['cfg_file'][] = $value['path'] . '/commands.cfg';
$value['cfg_file'][] = $value['path'] . '/contactgroups.cfg';
$value['cfg_file'][] = $value['path'] . '/contacts.cfg';
$value['cfg_file'][] = $value['path'] . '/hostgroups.cfg';
$value['cfg_file'][] = $value['path'] . '/servicegroups.cfg';
$value['cfg_file'][] = $value['path'] . '/timeperiods.cfg';
$value['cfg_file'][] = $value['path'] . '/escalations.cfg';
$value['cfg_file'][] = $value['path'] . '/dependencies.cfg';
$value['cfg_file'][] = $value['path'] . '/connectors.cfg';
$value['cfg_file'][] = $value['path'] . '/meta_commands.cfg';
$value['cfg_file'][] = $value['path'] . '/meta_timeperiod.cfg';
$value['cfg_file'][] = $value['path'] . '/meta_host.cfg';
$value['cfg_file'][] = $value['path'] . '/meta_services.cfg';
$value['cfg_file'][] = $value['path'] . '/tags.cfg';
$value['cfg_file'][] = $value['path'] . '/severities.cfg';
foreach ($this->add_cfg_files as $add_cfg_file) {
$value['cfg_file'][] = $value['path'] . '/' . $add_cfg_file;
}
}
}
/**
* @throws PDOException
* @return void
*/
private function getBrokerModules(): void
{
$pollerId = $this->engine['nagios_id'];
if (is_null($this->stmt_broker)) {
$this->stmt_broker = $this->backend_instance->db->prepare(
'SELECT broker_module FROM cfg_nagios_broker_module '
. 'WHERE cfg_nagios_id = :id '
. 'ORDER BY bk_mod_id ASC'
);
}
$this->stmt_broker->bindParam(':id', $pollerId, PDO::PARAM_INT);
$this->stmt_broker->execute();
$this->engine['broker_module'] = $this->stmt_broker->fetchAll(PDO::FETCH_COLUMN);
$pollerStmt = $this->backend_instance->db_cs->prepare('SELECT `version` FROM instances WHERE instance_id = :id ');
$pollerStmt->bindParam(':id', $pollerId, PDO::PARAM_INT);
$pollerStmt->execute();
$pollerVersion = $pollerStmt->fetchColumn();
if ($pollerVersion === false) {
// Unknown version, both broker_module and broker_module_cfg_file configurations are needed
$this->engine['broker_module'][] = '/usr/lib64/nagios/cbmod.so ' . $this->engine['broker_module_cfg_file'];
} elseif (version_compare($pollerVersion, '25.05.0', '<')) {
// Version is less than 25.05.0, add the legacy broker module and remove the cfg file reference
$this->engine['broker_module'][] = '/usr/lib64/nagios/cbmod.so ' . $this->engine['broker_module_cfg_file'];
unset($this->engine['broker_module_cfg_file']);
}
}
/**
* @throws PDOException
* @return void
*/
private function getIntervalLength(): void
{
if (is_null($this->stmt_interval_length)) {
$this->stmt_interval_length = $this->backend_instance->db->prepare(
'SELECT `value` FROM options '
. "WHERE `key` = 'interval_length'"
);
}
$this->stmt_interval_length->execute();
$this->engine['interval_length'] = $this->stmt_interval_length->fetchAll(PDO::FETCH_COLUMN);
}
/**
* If log V2 enabled, set logger V2 configuration and unset logger legacy elements
*
* @throws PDOException
* @return void
*/
private function setLoggerCfg(): void
{
$this->engine['log_v2_enabled'] = $this->engine['logger_version'] === 'log_v2_enabled' ? 1 : 0;
$this->engine['log_legacy_enabled'] = $this->engine['logger_version'] === 'log_legacy_enabled' ? 1 : 0;
if ($this->engine['log_v2_enabled'] === 1) {
$stmt = $this->backend_instance->db->prepare(
'SELECT log_v2_logger, log_level_functions, log_level_config, log_level_events, log_level_checks,
log_level_notifications, log_level_eventbroker, log_level_external_command, log_level_commands,
log_level_downtimes, log_level_comments, log_level_macros, log_level_process, log_level_runtime,
log_level_otl
FROM cfg_nagios_logger
WHERE cfg_nagios_id = :id'
);
$stmt->bindParam(':id', $this->engine['nagios_id'], PDO::PARAM_INT);
$stmt->execute();
$loggerCfg = $stmt->fetch(PDO::FETCH_ASSOC);
$this->engine = array_merge($this->engine, $loggerCfg);
}
}
/**
* @throws LogicException
* @throws ServiceCircularReferenceException
* @throws ServiceNotFoundException
* @return void
*/
private function setEngineNotificationState(): void
{
$featureFlags = $this->kernel->getContainer()->get(Core\Common\Infrastructure\FeatureFlags::class);
$this->engine['enable_notifications']
= $featureFlags->isEnabled('notification') === false
&& $this->engine['enable_notifications'] === '1'
? '1'
: '0';
}
/**
* @param $poller_id
*
* @throws LogicException
* @throws PDOException
* @throws ServiceCircularReferenceException
* @throws ServiceNotFoundException
* @return void
*/
private function generate($poller_id): void
{
if (is_null($this->stmt_engine)) {
$this->stmt_engine = $this->backend_instance->db->prepare(
"SELECT {$this->attributes_select} FROM cfg_nagios "
. "WHERE nagios_server_id = :poller_id AND nagios_activate = '1'"
);
}
$this->stmt_engine->bindParam(':poller_id', $poller_id, PDO::PARAM_INT);
$this->stmt_engine->execute();
$result = $this->stmt_engine->fetchAll(PDO::FETCH_ASSOC);
$this->engine = array_pop($result);
$this->setEngineNotificationState();
if (is_null($this->engine)) {
throw new Exception(
"Cannot get engine configuration for poller id (maybe not activate) '" . $poller_id . "'"
);
}
$this->buildCfgFile($poller_id);
$this->setLoggerCfg();
$this->getBrokerModules();
$this->getIntervalLength();
$object = $this->engine;
$timezoneInstance = Timezone::getInstance($this->dependencyInjector);
$timezone = $timezoneInstance->getTimezoneFromId($object['use_timezone'], true);
$object['use_timezone'] = null;
if (! is_null($timezone)) {
$object['use_timezone'] = ':' . $timezone;
}
$command_instance = Command::getInstance($this->dependencyInjector);
$object['global_host_event_handler']
= $command_instance->generateFromCommandId($object['global_host_event_handler_id']);
$object['global_service_event_handler']
= $command_instance->generateFromCommandId($object['global_service_event_handler_id']);
$object['grpc_port'] = 50000 + $poller_id;
$this->generate_filename = 'centengine.DEBUG';
$object['cfg_file'] = $this->cfg_file['debug']['cfg_file'];
$object['resource_file'] = $this->cfg_file['debug']['resource_file'];
$this->generateFile($object);
$this->close_file();
$this->generate_filename = $this->engine['cfg_filename'];
// Need to reset to go in another file
$object['cfg_file'] = $this->cfg_file['target']['cfg_file'];
$object['resource_file'] = $this->cfg_file['target']['resource_file'];
$this->generateFile($object);
$this->close_file();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate/meta_timeperiod.class.php | centreon/www/class/config-generate/meta_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
*
*/
/**
* Class
*
* @class MetaTimeperiod
*/
class MetaTimeperiod extends AbstractObject
{
/** @var string */
protected $generate_filename = 'meta_timeperiod.cfg';
/** @var string */
protected string $object_name = 'timeperiod';
/** @var string[] */
protected $attributes_write = ['timeperiod_name', 'alias', 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];
/**
* @throws Exception
* @return int|void
*/
public function generateObjects()
{
if ($this->checkGenerate(0)) {
return 0;
}
$object = [];
$object['timeperiod_name'] = 'meta_timeperiod';
$object['alias'] = 'meta_timeperiod';
$object['sunday'] = '00:00-24:00';
$object['monday'] = '00:00-24:00';
$object['tuesday'] = '00:00-24:00';
$object['wednesday'] = '00:00-24:00';
$object['thursday'] = '00:00-24:00';
$object['friday'] = '00:00-24:00';
$object['saturday'] = '00:00-24:00';
$this->generateObjectInFile($object, 0);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate/broker.class.php | centreon/www/class/config-generate/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
*
*/
use App\Kernel;
use Core\Common\Application\UseCase\VaultTrait;
use Core\MonitoringServer\Application\Repository\ReadMonitoringServerRepositoryInterface;
use Pimple\Container;
use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException;
use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
/**
* Class
*
* @class Broker
*/
class Broker extends AbstractObjectJSON
{
use VaultTrait;
private const STREAM_BBDO_SERVER = 'bbdo_server';
private const STREAM_BBDO_CLIENT = 'bbdo_client';
/** @var array|null */
protected $engine = null;
/** @var mixed|null */
protected $broker = null;
/** @var string|null */
protected $generate_filename = null;
/** @var string|null */
protected $object_name = null;
/** @var string */
protected $attributes_select = '
config_id,
config_name,
config_filename,
config_write_timestamp,
config_write_thread_id,
ns_nagios_server,
event_queue_max_size,
event_queues_total_size,
command_file,
cache_directory,
stats_activate,
daemon,
log_directory,
log_filename,
log_max_size,
pool_size,
bbdo_version
';
/** @var string */
protected $attributes_select_parameters = '
config_group,
config_group_id,
config_id,
config_key,
config_value,
grp_level,
subgrp_id,
parent_grp_id,
fieldIndex
';
/** @var string */
protected $attributes_engine_parameters = '
id,
name,
centreonbroker_module_path,
centreonbroker_cfg_path,
centreonbroker_logs_path
';
/** @var string[] */
protected $exclude_parameters = ['blockId'];
/** @var string[] */
protected $authorized_empty_field = ['db_password'];
/** @var CentreonDBStatement|null */
protected $stmt_engine = null;
/** @var CentreonDBStatement|null */
protected $stmt_broker = null;
/** @var CentreonDBStatement|null */
protected $stmt_broker_parameters = null;
/** @var CentreonDBStatement|null */
protected $stmt_engine_parameters = null;
/** @var array|null */
protected $cacheExternalValue = null;
/** @var array|null */
protected $cacheLogValue = null;
/** @var object|null */
protected $readVaultConfigurationRepository = null;
private ReadMonitoringServerRepositoryInterface $readMonitoringServerRepository;
/**
* Broker constructor
*
* @param Container $dependencyInjector
*
* @throws LogicException
* @throws ServiceCircularReferenceException
* @throws ServiceNotFoundException
*/
public function __construct(Container $dependencyInjector)
{
parent::__construct($dependencyInjector);
// Get Centeron Vault Storage configuration
$kernel = Kernel::createForWeb();
$this->readVaultConfigurationRepository = $kernel->getContainer()->get(
Core\Security\Vault\Application\Repository\ReadVaultConfigurationRepositoryInterface::class
);
$this->readMonitoringServerRepository = $kernel->getContainer()->get(
ReadMonitoringServerRepositoryInterface::class
);
}
/**
* @param $poller
*
* @throws PDOException
* @throws RuntimeException
* @return void
*/
public function generateFromPoller($poller): void
{
$this->generate($poller['id'], $poller['localhost']);
}
/**
* @throws PDOException
* @return void
*/
private function getExternalValues(): void
{
if (! is_null($this->cacheExternalValue)) {
return;
}
$this->cacheExternalValue = [];
$stmt = $this->backend_instance->db->prepare("
SELECT CONCAT(cf.fieldname, '_', cttr.cb_tag_id, '_', ctfr.cb_type_id) as name, external
FROM cb_field cf, cb_type_field_relation ctfr, cb_tag_type_relation cttr
WHERE cf.external IS NOT NULL
AND cf.cb_field_id = ctfr.cb_field_id
AND ctfr.cb_type_id = cttr.cb_type_id
");
$stmt->execute();
while (($row = $stmt->fetch(PDO::FETCH_ASSOC))) {
$this->cacheExternalValue[$row['name']] = $row['external'];
}
}
/**
* @throws PDOException
* @return void
*/
private function getLogsValues(): void
{
if (! is_null($this->cacheLogValue)) {
return;
}
$this->cacheLogValue = [];
$stmt = $this->backend_instance->db->prepare('
SELECT relation.`id_centreonbroker`, log.`name`, lvl.`name` as level
FROM `cfg_centreonbroker_log` relation
INNER JOIN `cb_log` log
ON relation.`id_log` = log.`id`
INNER JOIN `cb_log_level` lvl
ON relation.`id_level` = lvl.`id`
');
$stmt->execute();
while (($row = $stmt->fetch(PDO::FETCH_ASSOC))) {
$this->cacheLogValue[$row['id_centreonbroker']][$row['name']] = $row['level'];
}
}
/**
* @param $poller_id
* @param $localhost
* @param mixed $pollerId
*
* @throws PDOException
* @throws RuntimeException
* @return void
*/
private function generate($pollerId, $localhost): void
{
$this->getExternalValues();
if (is_null($this->stmt_broker)) {
$this->stmt_broker = $this->backend_instance->db->prepare("
SELECT {$this->attributes_select}
FROM cfg_centreonbroker
WHERE ns_nagios_server = :poller_id
AND config_activate = '1'
");
}
$this->stmt_broker->bindParam(':poller_id', $pollerId, PDO::PARAM_INT);
$this->stmt_broker->execute();
$this->getEngineParameters($pollerId);
if (is_null($this->stmt_broker_parameters)) {
$this->stmt_broker_parameters = $this->backend_instance->db->prepare("SELECT
{$this->attributes_select_parameters}
FROM cfg_centreonbroker_info
WHERE config_id = :config_id
ORDER BY config_group, config_group_id
");
}
$watchdog = [];
$anomalyDetectionLuaOutputGroupID = -1;
$result = $this->stmt_broker->fetchAll(PDO::FETCH_ASSOC);
foreach ($result as $row) {
$this->generate_filename = $row['config_filename'];
$object = [];
$config_name = $row['config_name'];
$cache_directory = $row['cache_directory'];
$stats_activate = $row['stats_activate'];
// Base parameters
$object['broker_id'] = (int) $row['config_id'];
$object['broker_name'] = $row['config_name'];
$object['poller_id'] = (int) $this->engine['id'];
$object['poller_name'] = $this->engine['name'];
$object['module_directory'] = (string) $this->engine['broker_modules_path'];
$object['log_timestamp'] = filter_var($row['config_write_timestamp'], FILTER_VALIDATE_BOOLEAN);
$object['log_thread_id'] = filter_var($row['config_write_thread_id'], FILTER_VALIDATE_BOOLEAN);
$object['event_queue_max_size'] = (int) $row['event_queue_max_size'];
if (! empty($row['event_queues_total_size'])) {
$object['event_queues_total_size'] = (int) $row['event_queues_total_size'];
}
$object['command_file'] = (string) $row['command_file'];
$object['cache_directory'] = (string) $cache_directory;
$object['bbdo_version'] = (string) $row['bbdo_version'];
if (! empty($row['pool_size'])) {
$object['pool_size'] = (int) $row['pool_size'];
}
if ($row['daemon'] == '1') {
$watchdog['cbd'][] = [
'name' => $row['config_name'],
'configuration_file' => $this->engine['broker_cfg_path'] . '/' . $row['config_filename'],
'run' => true,
'reload' => true,
];
}
$this->stmt_broker_parameters->bindParam(':config_id', $row['config_id'], PDO::PARAM_INT);
$this->stmt_broker_parameters->execute();
$resultParameters = $this->stmt_broker_parameters->fetchAll(PDO::FETCH_GROUP | PDO::FETCH_ASSOC);
// logger
$object['log']['directory'] = HtmlAnalyzer::sanitizeAndRemoveTags($row['log_directory']);
$object['log']['filename'] = HtmlAnalyzer::sanitizeAndRemoveTags($row['log_filename']);
$object['log']['max_size'] = filter_var($row['log_max_size'], FILTER_VALIDATE_INT);
$this->getLogsValues();
$logs = $this->cacheLogValue[$object['broker_id']];
$object['log']['loggers'] = $logs;
$reindexedObjectKeys = [];
// Flow parameters
foreach ($resultParameters as $key => $value) {
// We search the BlockId
$blockId = 0;
for ($i = count($value); $i > 0; $i--) {
if (isset($value[$i]['config_key']) && $value[$i]['config_key'] == 'blockId') {
$blockId = $value[$i]['config_value'];
$configGroupId = $value[$i]['config_group_id'];
break;
}
}
$subValuesToCastInArray = [];
$rrdCacheOption = null;
$rrdCached = null;
foreach ($value as $subvalue) {
if (
! isset($subvalue['fieldIndex'])
|| $subvalue['fieldIndex'] == ''
|| is_null($subvalue['fieldIndex'])
) {
if (in_array($subvalue['config_key'], $this->exclude_parameters)) {
continue;
}
if (trim($subvalue['config_value']) == ''
&& ! in_array(
$subvalue['config_key'],
$this->authorized_empty_field
)
) {
continue;
}
if ($subvalue['config_key'] === 'category') {
$object[$key][$subvalue['config_group_id']]['filters'][$subvalue['config_key']][]
= $subvalue['config_value'];
} elseif (in_array($subvalue['config_key'], ['rrd_cached_option', 'rrd_cached'])) {
if ($subvalue['config_key'] === 'rrd_cached_option') {
$rrdCacheOption = $subvalue['config_value'];
} elseif ($subvalue['config_key'] === 'rrd_cached') {
$rrdCached = $subvalue['config_value'];
}
if ($rrdCached && $rrdCacheOption) {
if ($rrdCacheOption === 'tcp') {
$object[$key][$subvalue['config_group_id']]['port'] = $rrdCached;
} elseif ($rrdCacheOption === 'unix') {
$object[$key][$subvalue['config_group_id']]['path'] = $rrdCached;
}
}
} else {
$object[$key][$subvalue['config_group_id']][$subvalue['config_key']]
= $subvalue['config_value'];
// We override with external values
if (isset($this->cacheExternalValue[$subvalue['config_key'] . '_' . $blockId])) {
$object[$key][$subvalue['config_group_id']][$subvalue['config_key']]
= $this->getInfoDb(
$this->cacheExternalValue[$subvalue['config_key'] . '_' . $blockId]
);
}
// Let broker insert in index data in pollers
if (
$subvalue['config_key'] === 'type'
&& $subvalue['config_value'] === 'storage'
&& ! $localhost
) {
$object[$key][$subvalue['config_group_id']]['insert_in_index_data'] = 'yes';
}
}
} else {
$res = explode('__', $subvalue['config_key'], 3);
$object[$key][$subvalue['config_group_id']][$res[0]][(int) $subvalue['fieldIndex']][$res[1]]
= $subvalue['config_value'];
$subValuesToCastInArray[$subvalue['config_group_id']][] = $res[0];
if ((strcmp(
$object[$key][$subvalue['config_group_id']]['name'],
'forward-to-anomaly-detection'
) == 0)
&& (strcmp(
$object[$key][$subvalue['config_group_id']]['path'],
'/usr/share/centreon-broker/lua/centreon-anomaly-detection.lua'
) == 0)
) {
$anomalyDetectionLuaOutputGroupID = $subvalue['config_group_id'];
}
}
}
// Check if we need to add values from external
foreach ($this->cacheExternalValue as $key2 => $value2) {
if (preg_match('/^(.+)_' . $blockId . '$/', $key2, $matches)) {
if (! isset($object[$configGroupId][$key][$matches[1]])) {
$object[$key][$configGroupId][$matches[1]]
= $this->getInfoDb($value2);
}
}
}
// cast into arrays instead of objects with integer as key
foreach ($subValuesToCastInArray as $configGroupId => $subValues) {
foreach ($subValues as $subValue) {
$object[$key][$configGroupId][$subValue]
= array_values($object[$key][$configGroupId][$subValue]);
}
}
$reindexedObjectKeys[] = $key;
}
// Stats parameters
if ($stats_activate == '1') {
$object['stats'] = [
[
'type' => 'stats',
'name' => $config_name . '-stats',
'json_fifo' => $cache_directory . '/' . $config_name . '-stats.json',
],
];
}
if ($anomalyDetectionLuaOutputGroupID >= 0) {
$luaParameters = $this->generateAnomalyDetectionLuaParameters();
if ($luaParameters !== []) {
$object['output'][$anomalyDetectionLuaOutputGroupID]['lua_parameter'] = array_merge_recursive(
$object['output'][$anomalyDetectionLuaOutputGroupID]['lua_parameter'],
$luaParameters
);
}
$anomalyDetectionLuaOutputGroupID = -1;
}
// gRPC parameters
$object['grpc'] = [
'port' => 51000 + (int) $row['config_id'],
];
// Force as list-array eventually wrong indexed object keys (input, output)
foreach ($reindexedObjectKeys as $key) {
if (is_array($object[$key])) {
$object[$key] = array_values($object[$key]);
}
}
// Remove unnecessary element form inputs and output for stream types bbdo
$object = $this->cleanBbdoStreams($object);
// Add vault path if vault if defined
if ($this->readVaultConfigurationRepository->exists()) {
$object['vault_configuration'] = $this->readVaultConfigurationRepository->getLocation();
}
if ($this->isVaultEnabled && $this->readVaultRepository !== null) {
foreach ($object['output'] as $outputIndex => $output) {
$this->processVaultOutput($output, $outputIndex, $object);
}
}
$shouldBeEncrypted = $this->readMonitoringServerRepository->isEncryptionReady($pollerId);
foreach ($object['output'] as &$output) {
if (
($output['type'] === 'sql' || $output['type'] === 'storage')
&& array_key_exists('db_password', $output)
) {
$output['db_password'] = $shouldBeEncrypted
? 'encrypt::' . $this->engineContextEncryption->crypt($output['db_password'])
: $output['db_password'];
}
if (! isset($output['lua_parameter']) || ! is_array($output['lua_parameter'])) {
continue;
}
foreach ($output['lua_parameter'] as &$luaParameter) {
if (
isset($luaParameter['type'], $luaParameter['value'])
&& $luaParameter['type'] === 'password'
&& is_string($luaParameter['value'])
) {
$luaParameter['value'] = $shouldBeEncrypted
? 'encrypt::' . $this->engineContextEncryption->crypt($luaParameter['value'])
: $luaParameter['value'];
}
}
}
// Generate file
$this->generateFile($object);
$this->writeFile($this->backend_instance->getPath());
}
// Manage path of cbd watchdog log
$watchdogLogsPath = $this->engine['broker_logs_path'] === null || empty(trim($this->engine['broker_logs_path']))
? '/var/log/centreon-broker/watchdog.log'
: trim($this->engine['broker_logs_path']) . '/watchdog.log';
$watchdog['log'] = $watchdogLogsPath;
$this->generate_filename = 'watchdog.json';
$this->generateFile($watchdog);
$this->writeFile($this->backend_instance->getPath());
}
/**
* Remove unnecessary element form inputs and output for stream types bbdo
*
* @param array<string,mixed> $config
* @return array<string,mixed>
*/
private function cleanBbdoStreams(array $config): array
{
if (isset($config['input'])) {
foreach ($config['input'] as $key => $inputCfg) {
if ($inputCfg['type'] === self::STREAM_BBDO_SERVER) {
unset($config['input'][$key]['compression'], $config['input'][$key]['retention']);
if ($config['input'][$key]['encryption'] === 'no') {
unset($config['input'][$key]['private_key'], $config['input'][$key]['certificate']);
}
}
if ($inputCfg['type'] === self::STREAM_BBDO_CLIENT) {
unset($config['input'][$key]['compression']);
if ($config['input'][$key]['encryption'] === 'no') {
unset($config['input'][$key]['ca_certificate'], $config['input'][$key]['ca_name']);
}
}
}
}
if (isset($config['output'])) {
foreach ($config['output'] as $key => $inputCfg) {
if ($inputCfg['type'] === self::STREAM_BBDO_SERVER && $config['output'][$key]['encrypt'] === 'no') {
unset($config['output'][$key]['private_key'], $config['output'][$key]['certificate']);
}
if ($inputCfg['type'] === self::STREAM_BBDO_CLIENT && $config['output'][$key]['encrypt'] === 'no') {
unset($config['output'][$key]['ca_certificate'], $config['output'][$key]['ca_name']);
}
}
}
return $config;
}
/**
* @param $poller_id
*
* @throws PDOException
* @return void
*/
private function getEngineParameters($poller_id): void
{
if (is_null($this->stmt_engine_parameters)) {
$this->stmt_engine_parameters = $this->backend_instance->db->prepare("SELECT
{$this->attributes_engine_parameters}
FROM nagios_server
WHERE id = :poller_id
");
}
$this->stmt_engine_parameters->bindParam(':poller_id', $poller_id, PDO::PARAM_INT);
$this->stmt_engine_parameters->execute();
try {
$row = $this->stmt_engine_parameters->fetch(PDO::FETCH_ASSOC);
$this->engine['id'] = $row['id'];
$this->engine['name'] = $row['name'];
$this->engine['broker_modules_path'] = $row['centreonbroker_module_path'];
$this->engine['broker_cfg_path'] = $row['centreonbroker_cfg_path'];
$this->engine['broker_logs_path'] = $row['centreonbroker_logs_path'];
} catch (Exception $e) {
throw new Exception('Exception received : ' . $e->getMessage() . "\n");
}
}
/**
* @param $string
*
* @throws PDOException
* @return array|false|mixed|string
*/
private function getInfoDb($string)
{
// Default values
$s_db = 'centreon';
$s_rpn = null;
// Parse string
$configs = explode(':', $string);
foreach ($configs as $config) {
if (! str_contains($config, '=')) {
continue;
}
[$key, $value] = explode('=', $config);
switch ($key) {
case 'D':
$s_db = $value;
break;
case 'T':
$s_table = $value;
break;
case 'C':
$s_column = $value;
break;
case 'F':
$s_filter = $value;
break;
case 'K':
$s_key = $value;
break;
case 'CK':
$s_column_key = $value;
break;
case 'RPN':
$s_rpn = $value;
break;
}
}
// Construct query
if (! isset($s_table) || ! isset($s_column)) {
return false;
}
$query = 'SELECT `' . $s_column . '` FROM `' . $s_table . '`';
if (isset($s_column_key, $s_key)) {
$query .= ' WHERE `' . $s_column_key . "` = '" . $s_key . "'";
}
// Execute the query
switch ($s_db) {
case 'centreon':
$db = $this->backend_instance->db;
break;
case 'centreon_storage':
$db = $this->backend_instance->db_cs;
break;
}
$stmt = $db->prepare($query);
$stmt->execute();
$infos = [];
while (($row = $stmt->fetch(PDO::FETCH_ASSOC))) {
$val = $row[$s_column];
if (! is_null($s_rpn)) {
$val = (string) $this->rpnCalc($s_rpn, $val);
}
$infos[] = $val;
}
if (count($infos) == 0) {
return '';
}
if (count($infos) == 1) {
return $infos[0];
}
return $infos;
}
/**
* @param $rpn
* @param $val
*
* @return float|int|mixed|string
*/
private function rpnCalc($rpn, $val)
{
if (! is_numeric($val)) {
return $val;
}
try {
$val = array_reduce(
preg_split('/\s+/', $val . ' ' . $rpn),
[$this, 'rpnOperation']
);
return $val[0];
} catch (InvalidArgumentException $e) {
return $val;
}
}
/**
* @param $result
* @param $item
*
* @throws InvalidArgumentException
* @return array|mixed
*/
private function rpnOperation($result, $item)
{
if (in_array($item, ['+', '-', '*', '/'])) {
if (count($result) < 2) {
throw new InvalidArgumentException('Not enough arguments to apply operator');
}
$a = $result[0];
$b = $result[1];
$result = [];
$result[0] = eval("return {$a} {$item} {$b};");
} elseif (is_numeric($item)) {
$result[] = $item;
} else {
throw new InvalidArgumentException('Unrecognized symbol ' . $item);
}
return $result;
}
/**
* Method retrieving the Centreon Platform UUID generated during web installation
*
* @return string|null
*/
private function getCentreonPlatformUuid(): ?string
{
global $pearDB;
$result = $pearDB->query("SELECT `value` FROM informations WHERE `key` = 'uuid'");
if (! $record = $result->fetch(PDO::FETCH_ASSOC)) {
return null;
}
return $record['value'];
}
/**
* Generate complete proxy url.
*
* @throws PDOException
*
* @return array with lua parameters
*/
private function generateAnomalyDetectionLuaParameters(): array
{
global $pearDB;
$sql = <<<'SQL'
SELECT
`key`,
`value`
FROM
`options`
WHERE
`key` IN (
'saas_token', 'saas_use_proxy', 'saas_url',
'proxy_url', 'proxy_port', 'proxy_user', 'proxy_password'
)
SQL;
/**
* @var array{
* saas_token?: null|string,
* saas_use_proxy?: null|string,
* saas_url?: null|string,
* proxy_url?: null|string,
* proxy_port?: null|string,
* proxy_user?: null|string,
* proxy_password?: null|string
* } $options
*/
$options = $pearDB->query($sql)->fetchAll(PDO::FETCH_KEY_PAIR) ?: [];
$luaParameters = [];
if (array_key_exists('saas_token', $options)) {
$luaParameters[] = [
'type' => 'string',
'name' => 'token',
'value' => $options['saas_token'],
];
}
if (array_key_exists('saas_url', $options)) {
$luaParameters[] = [
'type' => 'string',
'name' => 'destination',
'value' => $options['saas_url'],
];
}
if (
($options['saas_use_proxy'] ?? null) === '1'
&& ($proxyUrl = $options['proxy_url'] ?? null)
) {
$proxyScheme = parse_url($proxyUrl, PHP_URL_SCHEME);
$proxy = ($proxyScheme ?: 'http') . '://';
if (! empty($options['proxy_user']) && ! empty($options['proxy_password'])) {
$proxy .= $options['proxy_user'] . ':' . $options['proxy_password'] . '@';
}
if ($proxyScheme) {
$proxy .= parse_url($proxyUrl, PHP_URL_HOST);
} else {
$proxy .= parse_url($proxyUrl, PHP_URL_PATH);
}
if (! empty($options['proxy_port'])) {
$proxy .= ':' . $options['proxy_port'];
}
$luaParameters[] = [
'type' => 'string',
'name' => 'proxy',
'value' => $proxy,
];
}
$luaParameters[] = [
'type' => 'string',
'name' => 'centreon_platform_uuid',
'value' => $this->getCentreonPlatformUuid(),
];
return $luaParameters;
}
/**
* Process vault output and update object with vault data.
*
* @param array $output
* @param int $outputIndex
* @param array $object
* @return void
*/
private function processVaultOutput(array &$output, int $outputIndex, array &$object): void
{
foreach ($output as $outputKey => $outputValue) {
if (is_string($outputValue) && $this->isAVaultPath($outputValue)) {
$this->updateVaultData($output, $outputKey, $outputValue, $object['output'][$outputIndex]);
}
if ($outputKey === 'lua_parameter' && is_array($outputValue)) {
$this->processLuaParameters($output, $outputKey, $outputValue, $object['output'][$outputIndex]);
}
}
}
/**
* Update vault data for a given key.
*
* @param array $output
* @param string $outputKey
* @param string $outputValue
* @param array $outputReference
* @return void
*/
private function updateVaultData(
array &$output,
string $outputKey,
string $outputValue,
array &$outputReference,
): void {
$vaultData = $this->readVaultRepository->findFromPath($outputValue);
$vaultKey = $output['name'] . '_' . $outputKey;
if (array_key_exists($vaultKey, $vaultData)) {
$outputReference[$outputKey] = $vaultData[$vaultKey];
}
}
/**
* Process Lua parameters and update with vault data if applicable.
*
* @param array $output
* @param string $outputKey
* @param array $luaParameters
* @param array $outputReference
* @return void
*/
private function processLuaParameters(
array &$output,
string $outputKey,
array $luaParameters,
array &$outputReference,
): void {
foreach ($luaParameters as $parameterIndex => $luaParameter) {
if ($luaParameter['type'] === 'password'
&& is_string($luaParameter['value'])
&& $this->isAVaultPath($luaParameter['value'])
) {
$vaultData = $this->readVaultRepository->findFromPath($luaParameter['value']);
$vaultKey = $output['name'] . '_' . $outputKey . '_' . $luaParameter['name'];
if (array_key_exists($vaultKey, $vaultData)) {
$outputReference[$outputKey][$parameterIndex]['value'] = $vaultData[$vaultKey];
}
}
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate/hostcategory.class.php | centreon/www/class/config-generate/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
*
*/
use Pimple\Container;
/**
* Class
*
* @class HostCategory
*/
final class HostCategory extends AbstractObject
{
private const TAG_TYPE = 'hostcategory';
/** @var string */
protected string $object_name = 'tag';
/** @var array<int,mixed> */
private array $hostCategories = [];
/**
* @param Container $dependencyInjector
*/
protected function __construct(Container $dependencyInjector)
{
parent::__construct($dependencyInjector);
$this->generate_filename = 'tags.cfg';
$this->attributes_write = [
'id',
'tag_name',
'type',
];
}
/**
* Add a host to members of a host category
*
* @param int $hostCategoryId
* @param int $hostId
* @param string $hostName
*
* @throws PDOException
*/
public function insertHostToCategoryMembers(int $hostCategoryId, int $hostId, string $hostName): void
{
if (! isset($this->hostCategories[$hostCategoryId])) {
$this->addHostCategoryToList($hostCategoryId);
}
if (
isset($this->hostCategories[$hostCategoryId])
&& ! isset($this->hostCategories[$hostCategoryId]['members'][$hostId])
) {
$this->hostCategories[$hostCategoryId]['members'][$hostId] = $hostName;
}
}
/**
* Write hostcategories in configuration file
*/
public function generateObjects(): void
{
foreach ($this->hostCategories as $id => &$value) {
if (! isset($value['members']) || count($value['members']) === 0) {
continue;
}
$value['type'] = self::TAG_TYPE;
$this->generateObjectInFile($value, $id);
}
}
/**
* Reset instance
*/
public function reset(): void
{
parent::reset();
foreach ($this->hostCategories as &$value) {
if (! is_null($value)) {
$value['members'] = [];
}
}
}
/**
* @param int $hostId
* @return int[]
*/
public function getIdsByHostId(int $hostId): array
{
$hostCategoryIds = [];
foreach ($this->hostCategories as $id => $value) {
if (isset($value['members']) && in_array($hostId, array_keys($value['members']))) {
$hostCategoryIds[] = (int) $id;
}
}
return $hostCategoryIds;
}
/**
* @param int $hostCategoryId
*
* @throws PDOException
* @return self
*/
private function addHostCategoryToList(int $hostCategoryId): self
{
$stmt = $this->backend_instance->db->prepare(
"SELECT hc_id as id, hc_name as tag_name
FROM hostcategories
WHERE hc_id = :hc_id
AND level IS NULL
AND hc_activate = '1'"
);
$stmt->bindParam(':hc_id', $hostCategoryId, PDO::PARAM_INT);
$stmt->execute();
if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$this->hostCategories[$hostCategoryId] = $row;
$this->hostCategories[$hostCategoryId]['members'] = [];
}
return $this;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate/meta_service.class.php | centreon/www/class/config-generate/meta_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
*
*/
use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException;
use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
/**
* Class
*
* @class MetaService
*/
class MetaService extends AbstractObject
{
/** @var string */
protected $generate_filename = 'meta_services.cfg';
/** @var string */
protected string $object_name = 'service';
/** @var string */
protected $attributes_select = '
meta_id,
meta_name as display_name,
check_period as check_period_id,
max_check_attempts,
normal_check_interval,
retry_check_interval,
notification_interval,
notification_period as notification_period_id,
notification_options,
notifications_enabled
';
/** @var string[] */
protected $attributes_write = ['service_description', 'display_name', 'host_name', 'check_command', 'max_check_attempts', 'normal_check_interval', 'retry_check_interval', 'active_checks_enabled', 'passive_checks_enabled', 'check_period', 'notification_interval', 'notification_period', 'notification_options', 'register'];
/** @var string[] */
protected $attributes_default = ['notifications_enabled'];
/** @var string[] */
protected $attributes_hash = ['macros'];
/** @var string[] */
protected $attributes_array = ['contact_groups', 'contacts'];
/** @var int */
private $has_meta_services = 0;
/** @var array */
private $meta_services = [];
/** @var array */
private $generated_services = []; // for index_data build
/** @var null */
private $stmt_cg = null;
/** @var null */
private $stmt_contact = null;
/**
* @throws LogicException
* @throws PDOException
* @throws ServiceCircularReferenceException
* @throws ServiceNotFoundException
* @return int|void
*/
public function generateObjects()
{
$this->buildCacheMetaServices();
if (count($this->meta_services) == 0) {
return 0;
}
$host_id = MetaHost::getInstance($this->dependencyInjector)->getHostIdByHostName('_Module_Meta');
if (is_null($host_id)) {
return 0;
}
MetaCommand::getInstance($this->dependencyInjector)->generateObjects();
MetaTimeperiod::getInstance($this->dependencyInjector)->generateObjects();
MetaHost::getInstance($this->dependencyInjector)->generateObject($host_id);
$this->has_meta_services = 1;
foreach ($this->meta_services as $meta_id => &$meta_service) {
$meta_service['macros'] = ['_SERVICE_ID' => $meta_service['service_id']];
$this->getCtFromMetaId($meta_id);
$this->getCgFromMetaId($meta_id);
$meta_service['check_period'] = Timeperiod::getInstance($this->dependencyInjector)
->generateFromTimeperiodId($meta_service['check_period_id']);
$meta_service['notification_period'] = Timeperiod::getInstance($this->dependencyInjector)
->generateFromTimeperiodId($meta_service['notification_period_id']);
$meta_service['register'] = 1;
$meta_service['active_checks_enabled'] = 1;
$meta_service['passive_checks_enabled'] = 0;
$meta_service['host_name'] = '_Module_Meta';
$meta_service['service_description'] = 'meta_' . $meta_id;
$meta_service['display_name'] = html_entity_decode($meta_service['display_name']);
$meta_service['check_command'] = 'check_meta!' . $meta_id;
$this->generated_services[] = $meta_id;
$this->generateObjectInFile($meta_service, $meta_id);
}
}
/**
* @return array
*/
public function getMetaServices()
{
return $this->meta_services;
}
/**
* @return int
*/
public function hasMetaServices()
{
return $this->has_meta_services;
}
/**
* @return array
*/
public function getGeneratedServices()
{
return $this->generated_services;
}
/**
* @param $meta_id
*
* @throws LogicException
* @throws PDOException
* @throws ServiceCircularReferenceException
* @throws ServiceNotFoundException
* @return void
*/
private function getCtFromMetaId($meta_id): void
{
if (is_null($this->stmt_contact)) {
$this->stmt_contact = $this->backend_instance->db->prepare('SELECT
contact_id
FROM meta_contact
WHERE meta_id = :meta_id
');
}
$this->stmt_contact->bindParam(':meta_id', $meta_id);
$this->stmt_contact->execute();
$this->meta_services[$meta_id]['contacts'] = [];
foreach ($this->stmt_contact->fetchAll(PDO::FETCH_COLUMN) as $ct_id) {
$this->meta_services[$meta_id]['contacts'][]
= Contact::getInstance($this->dependencyInjector)->generateFromContactId($ct_id);
}
}
/**
* @param $meta_id
*
* @throws LogicException
* @throws PDOException
* @throws ServiceCircularReferenceException
* @throws ServiceNotFoundException
* @return void
*/
private function getCgFromMetaId($meta_id): void
{
if (is_null($this->stmt_cg)) {
$this->stmt_cg = $this->backend_instance->db->prepare('SELECT
cg_cg_id
FROM meta_contactgroup_relation
WHERE meta_id = :meta_id
');
}
$this->stmt_cg->bindParam(':meta_id', $meta_id);
$this->stmt_cg->execute();
$this->meta_services[$meta_id]['contact_groups'] = [];
foreach ($this->stmt_cg->fetchAll(PDO::FETCH_COLUMN) as $cg_id) {
$this->meta_services[$meta_id]['contact_groups'][]
= Contactgroup::getInstance($this->dependencyInjector)->generateFromCgId($cg_id);
}
}
/**
* @param $meta_id
* @param $meta_name
*
* @throws PDOException
* @return mixed
*/
private function getServiceIdFromMetaId($meta_id, $meta_name)
{
$composed_name = 'meta_' . $meta_id;
$query = 'SELECT service_id FROM service '
. "WHERE service_register = '2' "
. 'AND service_description = :meta_composed_name '
. 'AND display_name = :meta_name';
$stmt = $this->backend_instance->db->prepare($query);
$stmt->bindValue(':meta_composed_name', $composed_name);
$stmt->bindValue(':meta_name', html_entity_decode($meta_name));
$stmt->execute();
if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$service_id = $row['service_id'];
}
if (! isset($service_id)) {
throw new Exception('Service id of Meta Module could not be found');
}
return $service_id;
}
/**
* @throws PDOException
* @return void
*/
private function buildCacheMetaServices(): void
{
$query = "SELECT {$this->attributes_select} FROM meta_service WHERE meta_activate = '1'";
$stmt = $this->backend_instance->db->prepare($query);
$stmt->execute();
$this->meta_services = $stmt->fetchAll(PDO::FETCH_GROUP | PDO::FETCH_UNIQUE | PDO::FETCH_ASSOC);
foreach ($this->meta_services as $meta_id => $meta_infos) {
$this->meta_services[$meta_id]['service_id'] = $this->getServiceIdFromMetaId(
$meta_id,
$meta_infos['display_name']
);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate/meta_host.class.php | centreon/www/class/config-generate/meta_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
*
*/
/**
* Class
*
* @class MetaHost
*/
class MetaHost extends AbstractObject
{
/** @var string */
protected $generate_filename = 'meta_host.cfg';
/** @var string */
protected string $object_name = 'host';
/** @var string[] */
protected $attributes_write = ['host_name', 'alias', 'address', 'check_command', 'max_check_attempts', 'check_interval', 'active_checks_enabled', 'passive_checks_enabled', 'check_period', 'notification_interval', 'notification_period', 'notification_options', 'notifications_enabled', 'register'];
/** @var string[] */
protected $attributes_hash = ['macros'];
/**
* @param $host_name
*
* @throws PDOException
* @return mixed|null
*/
public function getHostIdByHostName($host_name)
{
$stmt = $this->backend_instance->db->prepare('SELECT
host_id
FROM host
WHERE host_name = :host_name
');
$stmt->bindParam(':host_name', $host_name, PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_COLUMN);
return array_pop($result);
}
/**
* @param $host_id
*
* @throws Exception
* @return int|void
*/
public function generateObject($host_id)
{
if ($this->checkGenerate($host_id)) {
return 0;
}
$object = [];
$object['host_name'] = '_Module_Meta';
$object['alias'] = 'Meta Service Calculate Module For Centreon';
$object['address'] = '127.0.0.1';
$object['check_command'] = 'check_meta_host_alive';
$object['max_check_attempts'] = 3;
$object['check_interval'] = 1;
$object['active_checks_enabled'] = 0;
$object['passive_checks_enabled'] = 0;
$object['check_period'] = 'meta_timeperiod';
$object['notification_interval'] = 60;
$object['notification_period'] = 'meta_timeperiod';
$object['notification_period'] = 'meta_timeperiod';
$object['notification_options'] = 'd';
$object['notifications_enabled'] = 0;
$object['register'] = 1;
$object['macros'] = ['_HOST_ID' => $host_id];
$this->generateObjectInFile($object, $host_id);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate/escalation.class.php | centreon/www/class/config-generate/escalation.class.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
use Pimple\Container;
use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException;
use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
/**
* Class
*
* @class Escalation
*/
class Escalation extends AbstractObject
{
/** @var */
public $hg_build;
/** @var */
public $sg_build;
/** @var string */
protected $generate_filename = 'escalations.cfg';
/** @var string */
protected string $object_name = 'hostescalation';
/** @var string */
protected $attributes_select = "
esc_id,
esc_name as ';escalation_name',
first_notification,
last_notification,
notification_interval,
escalation_period as escalation_period_id,
escalation_options1 as escalation_options_host,
escalation_options2 as escalation_options_service,
host_inheritance_to_services,
hostgroup_inheritance_to_services
";
/** @var string[] */
protected $attributes_write = [';escalation_name', 'first_notification', 'last_notification', 'notification_interval', 'escalation_period', 'escalation_options'];
/** @var string[] */
protected $attributes_array = ['hostgroup_name', 'host_name', 'servicegroup_name', 'service_description', 'contact_groups'];
/** @var Host|null */
protected $host_instance = null;
/** @var Service|null */
protected $service_instance = null;
/** @var Hostgroup|null */
protected $hg_instance = null;
/** @var Servicegroup|null */
protected $sg_instance = null;
/** @var null */
protected $stmt_escalation = null;
/** @var null */
protected $stmt_cg = null;
/** @var null */
protected $stmt_host = null;
/** @var null */
protected $stmt_service = null;
/** @var null */
protected $stmt_hg = null;
/** @var null */
protected $stmt_sg = null;
/** @var null */
protected $stmt_meta = null;
/** @var int */
private $use_cache = 1;
/** @var int */
private $done_cache = 0;
/** @var int */
private $has_escalation = 1; // by default, we have.
/** @var array */
private $escalation_cache = [];
/** @var array */
private $escalation_linked_cg_cache = [];
/** @var array */
private $escalation_linked_host_cache = [];
/** @var array */
private $escalation_linked_hg_cache = [];
/** @var array */
private $escalation_linked_service_cache = [];
/** @var array */
private $escalation_linked_sg_cache = [];
/** @var array */
private $escalation_linked_meta_cache = [];
/** @var array */
private $hosts_build = [];
/** @var array */
private $services_build = [];
/**
* Escalation constructor
*
* @param Container $dependencyInjector
*
* @throws PDOException
*/
public function __construct(Container $dependencyInjector)
{
parent::__construct($dependencyInjector);
$this->host_instance = Host::getInstance($this->dependencyInjector);
$this->service_instance = Service::getInstance($this->dependencyInjector);
$this->hg_instance = Hostgroup::getInstance($this->dependencyInjector);
$this->sg_instance = Servicegroup::getInstance($this->dependencyInjector);
$this->buildCache();
}
/**
* @throws LogicException
* @throws PDOException
* @throws ServiceCircularReferenceException
* @throws ServiceNotFoundException
* @return void
*/
public function doHostService(): void
{
$services = $this->service_instance->getGeneratedServices();
foreach ($services as $host_id => &$values) {
$this->addHost($host_id);
foreach ($values as $service_id) {
$this->addService($host_id, $service_id);
}
}
$this->generateHosts();
$this->generateServices();
}
/**
* @throws LogicException
* @throws PDOException
* @throws ServiceCircularReferenceException
* @throws ServiceNotFoundException
* @return void
*/
public function doHostgroup(): void
{
$hostgroups = $this->hg_instance->getHostgroups();
foreach ($hostgroups as $hg_id => &$value) {
$this->addHostgroup($hg_id, $value);
}
$this->generateHostgroups();
}
/**
* @throws LogicException
* @throws PDOException
* @throws ServiceCircularReferenceException
* @throws ServiceNotFoundException
* @return void
*/
public function doServicegroup(): void
{
$servicegroups = $this->sg_instance->getServicegroups();
foreach ($servicegroups as $sg_id => &$value) {
$this->addServicegroup($sg_id);
}
$this->generateServicegroups();
}
/**
* @throws LogicException
* @throws PDOException
* @throws ServiceCircularReferenceException
* @throws ServiceNotFoundException
* @return int|void
*/
public function doMetaService()
{
if (! MetaService::getInstance($this->dependencyInjector)->hasMetaServices()) {
return 0;
}
$this->object_name = 'serviceescalation';
foreach (MetaService::getInstance($this->dependencyInjector)->getGeneratedServices() as $meta_id) {
$escalation = $this->getEscalationFromMetaId($meta_id);
foreach ($escalation as $escalation_id) {
$object = $this->getEscalationFromId($escalation_id);
$object['host_name'] = ['_Module_Meta'];
$object['service_description'] = ['meta_' . $meta_id];
$object['escalation_options'] = $object['escalation_options_service'];
// Dont care of the id (we set 0)
$this->generateSubObjects($object, $escalation_id);
$this->generateObjectInFile($object, 0);
}
}
}
/**
* @throws LogicException
* @throws PDOException
* @throws ServiceCircularReferenceException
* @throws ServiceNotFoundException
* @return int|void
*/
public function generateObjects()
{
if ($this->has_escalation == 0) {
return 0;
}
$this->doHostgroup();
$this->doHostService();
$this->doServicegroup();
$this->doMetaService();
}
/**
* @throws Exception
* @return void
*/
public function reset(): void
{
$this->hosts_build = [];
$this->services_build = [];
$this->hg_build = [];
$this->sg_build = [];
parent::reset();
}
/**
* @throws PDOException
* @return void
*/
private function getEscalationCache(): void
{
$stmt = $this->backend_instance->db->prepare("SELECT
{$this->attributes_select}
FROM escalation
");
$stmt->execute();
$this->escalation_cache = $stmt->fetchAll(PDO::FETCH_GROUP | PDO::FETCH_UNIQUE | PDO::FETCH_ASSOC);
$stmt = $this->backend_instance->db->prepare('SELECT
escalation_esc_id, contactgroup_cg_id
FROM escalation_contactgroup_relation
');
$stmt->execute();
$this->escalation_linked_cg_cache = $stmt->fetchAll(PDO::FETCH_GROUP | PDO::FETCH_COLUMN);
if (count($this->escalation_cache) == 0) {
$this->has_escalation = 0;
}
}
/**
* @throws PDOException
* @return int|void
*/
private function getEscalationLinkedCache()
{
if ($this->has_escalation == 0) {
return 0;
}
$stmt = $this->backend_instance->db->prepare('SELECT
host_host_id, escalation_esc_id
FROM escalation_host_relation
');
$stmt->execute();
$this->escalation_linked_host_cache = $stmt->fetchAll(PDO::FETCH_GROUP | PDO::FETCH_COLUMN);
$stmt = $this->backend_instance->db->prepare('SELECT
hostgroup_hg_id, escalation_esc_id
FROM escalation_hostgroup_relation
');
$stmt->execute();
$this->escalation_linked_hg_cache = $stmt->fetchAll(PDO::FETCH_GROUP | PDO::FETCH_COLUMN);
$stmt = $this->backend_instance->db->prepare('SELECT
servicegroup_sg_id, escalation_esc_id
FROM escalation_servicegroup_relation
');
$stmt->execute();
$this->escalation_linked_sg_cache = $stmt->fetchAll(PDO::FETCH_GROUP | PDO::FETCH_COLUMN);
$stmt = $this->backend_instance->db->prepare('SELECT
meta_service_meta_id, escalation_esc_id
FROM escalation_meta_service_relation
');
$stmt->execute();
$this->escalation_linked_meta_cache = $stmt->fetchAll(PDO::FETCH_GROUP | PDO::FETCH_COLUMN);
$stmt = $this->backend_instance->db->prepare("SELECT
CONCAT(host_host_id, '_', service_service_id), escalation_esc_id
FROM escalation_service_relation
");
$stmt->execute();
$this->escalation_linked_service_cache = $stmt->fetchAll(PDO::FETCH_GROUP | PDO::FETCH_COLUMN);
}
/**
* @throws PDOException
* @return int|void
*/
private function buildCache()
{
if ($this->done_cache == 1) {
return 0;
}
$this->getEscalationCache();
$this->getEscalationLinkedCache();
$this->done_cache = 1;
}
/**
* @param $escalation
* @param $esc_id
*
* @throws LogicException
* @throws PDOException
* @throws ServiceCircularReferenceException
* @throws ServiceNotFoundException
* @return void
*/
private function generateSubObjects(&$escalation, $esc_id): void
{
$period = Timeperiod::getInstance($this->dependencyInjector);
$cg = Contactgroup::getInstance($this->dependencyInjector);
$escalation['escalation_period'] = $period->generateFromTimeperiodId($escalation['escalation_period_id']);
$escalation['contact_groups'] = [];
foreach ($this->escalation_linked_cg_cache[$esc_id] as $cg_id) {
$escalation['contact_groups'][] = $cg->generateFromCgId($cg_id);
}
}
/**
* @param $escalation_id
*
* @throws PDOException
* @return mixed|null
*/
private function getEscalationFromId($escalation_id)
{
if (isset($this->escalation_cache[$escalation_id])) {
return $this->escalation_cache[$escalation_id];
}
if ($this->use_cache == 1) {
return null;
}
if (is_null($this->stmt_escalation)) {
$this->stmt_escalation = $this->backend_instance->db->prepare("SELECT
{$this->attributes_select}
FROM escalation
WHERE esc_id = :esc_id
");
}
$this->stmt_escalation->bindParam(':esc_id', $escalation_id, PDO::PARAM_INT);
$this->stmt_escalation->execute();
$this->escalation_cache[$escalation_id] = array_pop($this->stmt_escalation->fetchAll(PDO::FETCH_ASSOC));
if (is_null($this->escalation_cache[$escalation_id])) {
return null;
}
if (is_null($this->stmt_cg)) {
$this->stmt_cg = $this->backend_instance->db->prepare('SELECT
contactgroup_cg_id
FROM escalation_contactgroup_relation
WHERE escalation_esc_id = :esc_id
');
}
$this->stmt_cg->bindParam(':esc_id', $escalation_id, PDO::PARAM_INT);
$this->stmt_cg->execute();
$this->escalation_linked_cg_cache[$escalation_id] = $this->stmt_cg->fetchAll(PDO::FETCH_COLUMN);
return $this->escalation_cache[$escalation_id];
}
/**
* @param $host_id
*
* @throws PDOException
* @return int|void
*/
private function addHost($host_id)
{
if ($this->use_cache == 0) {
if (is_null($this->stmt_host)) {
$this->stmt_host = $this->backend_instance->db->prepare('SELECT
escalation_esc_id
FROM escalation_host_relation
WHERE host_host_id = :host_id
');
}
$this->stmt_host->bindParam(':host_id', $host_id, PDO::PARAM_INT);
$this->stmt_host->execute();
$this->escalation_linked_host_cache[$host_id] = $this->stmt_host->fetchAll(PDO::FETCH_COLUMN);
}
if (! isset($this->escalation_linked_host_cache[$host_id])) {
return 0;
}
foreach ($this->escalation_linked_host_cache[$host_id] as $escalation_id) {
if (! isset($this->hosts_build[$escalation_id])) {
$this->hosts_build[$escalation_id] = [];
}
$this->hosts_build[$escalation_id][] = $this->host_instance->getString($host_id, 'host_name');
if (isset($this->escalation_cache[$escalation_id]['host_inheritance_to_services'])
&& $this->escalation_cache[$escalation_id]['host_inheritance_to_services'] == 1
) {
$services = $this->service_instance->getGeneratedServices();
// host without services
if (! isset($services[$host_id])) {
continue;
}
foreach ($services[$host_id] as $service_id) {
if (! isset($this->services_build[$escalation_id])) {
$this->services_build[$escalation_id] = [$host_id => []];
}
$this->services_build[$escalation_id][$host_id][$service_id] = 1;
}
}
}
}
/**
* @param $hg_id
* @param $hostgroup
*
* @throws PDOException
* @return int|void
*/
private function addHostgroup($hg_id, $hostgroup)
{
if ($this->use_cache == 0) {
if (is_null($this->stmt_hg)) {
$this->stmt_hg = $this->backend_instance->db->prepare('SELECT
escalation_esc_id
FROM escalation_hostgroup_relation
WHERE hostgroup_hg_id = :hg_id
');
}
$this->stmt_hg->bindParam(':hg_id', $hg_id, PDO::PARAM_INT);
$this->stmt_hg->execute();
$this->escalation_linked_hg_cache[$hg_id] = $this->stmt_hg->fetchAll(PDO::FETCH_COLUMN);
}
if (! isset($this->escalation_linked_hg_cache[$hg_id])) {
return 0;
}
foreach ($this->escalation_linked_hg_cache[$hg_id] as $escalation_id) {
if (isset($this->escalation_cache[$escalation_id]['hostgroup_inheritance_to_services'])
&& $this->escalation_cache[$escalation_id]['hostgroup_inheritance_to_services'] == 1
) {
$services = $this->service_instance->getGeneratedServices();
foreach ($hostgroup['members'] as $host_name) {
$host_id = $this->host_instance->getHostIdByHostName($host_name);
// host without services
if (! isset($services[$host_id])) {
continue;
}
foreach ($services[$host_id] as $service_id) {
if (! isset($this->services_build[$escalation_id])) {
$this->services_build[$escalation_id] = [$host_id => []];
}
$this->services_build[$escalation_id][$host_id][$service_id] = 1;
}
}
}
if (! isset($this->hg_build[$escalation_id])) {
$this->hg_build[$escalation_id] = [];
}
$hostgroup_name = $this->hg_instance->getString($hg_id, 'hostgroup_name');
if (! is_null($hostgroup_name)) {
$this->hg_build[$escalation_id][] = $hostgroup_name;
}
}
}
/**
* @param $host_id
* @param $service_id
*
* @throws PDOException
* @return int|void
*/
private function addService($host_id, $service_id)
{
if ($this->use_cache == 0) {
if (is_null($this->stmt_service)) {
$this->stmt_service = $this->backend_instance->db->prepare('SELECT
escalation_esc_id
FROM escalation_service_relation
WHERE host_host_id = :host_id AND service_service_id = :service_id
');
}
$this->stmt_service->bindParam(':host_id', $host_id, PDO::PARAM_INT);
$this->stmt_service->bindParam(':service_id', $service_id, PDO::PARAM_INT);
$this->stmt_service->execute();
$this->escalation_linked_service_cache[$host_id . '_' . $service_id]
= $this->stmt_service->fetchAll(PDO::FETCH_COLUMN);
}
if (! isset($this->escalation_linked_service_cache[$host_id . '_' . $service_id])) {
return 0;
}
foreach ($this->escalation_linked_service_cache[$host_id . '_' . $service_id] as $escalation_id) {
if (! isset($this->services_build[$escalation_id])) {
$this->services_build[$escalation_id] = [$host_id => []];
}
$this->services_build[$escalation_id][$host_id][$service_id] = 1;
}
}
/**
* @param $sg_id
*
* @throws PDOException
* @return int|void
*/
private function addServicegroup($sg_id)
{
if ($this->use_cache == 0) {
if (is_null($this->stmt_sg)) {
$this->stmt_sg = $this->backend_instance->db->prepare('SELECT
escalation_esc_id
FROM escalation_servicegroup_relation
WHERE servicegroup_sg_id = :sg_id
');
}
$this->stmt_sg->bindParam(':sg_id', $sg_id, PDO::PARAM_INT);
$this->stmt_sg->execute();
$this->escalation_linked_sg_cache[$sg_id] = $this->stmt_sg->fetchAll(PDO::FETCH_COLUMN);
}
if (! isset($this->escalation_linked_sg_cache[$sg_id])) {
return 0;
}
foreach ($this->escalation_linked_sg_cache[$sg_id] as $escalation_id) {
if (! isset($this->sg_build[$escalation_id])) {
$this->sg_build[$escalation_id] = [];
}
$servicegroup_name = $this->sg_instance->getString($sg_id, 'servicegroup_name');
if (! is_null($servicegroup_name)) {
$this->sg_build[$escalation_id][] = $servicegroup_name;
}
}
}
/**
* @param $meta_id
*
* @throws PDOException
* @return array|false|mixed
*/
private function getEscalationFromMetaId($meta_id)
{
if ($this->use_cache == 0) {
if (is_null($this->stmt_meta)) {
$this->stmt_service = $this->backend_instance->db->prepare('SELECT
escalation_esc_id
FROM escalation_meta_service_relation
WHERE meta_service_meta_id = :meta_id
');
}
$this->stmt_service->bindParam(':meta_id', $meta_id, PDO::PARAM_INT);
$this->stmt_service->execute();
$this->escalation_linked_meta_cache[$meta_id] = $this->stmt_service->fetchAll(PDO::FETCH_COLUMN);
}
if (! isset($this->escalation_linked_meta_cache[$meta_id])) {
return [];
}
return $this->escalation_linked_meta_cache[$meta_id];
}
/**
* @throws LogicException
* @throws PDOException
* @throws ServiceCircularReferenceException
* @throws ServiceNotFoundException
* @return void
*/
private function generateHosts(): void
{
$this->object_name = 'hostescalation';
foreach ($this->hosts_build as $escalation_id => $values) {
$object = $this->getEscalationFromId($escalation_id);
$object['host_name'] = &$values;
$object['escalation_options'] = $object['escalation_options_host'];
// Dont care of the id (we set 0)
$this->generateSubObjects($object, $escalation_id);
$this->generateObjectInFile($object, 0);
}
}
/**
* @throws LogicException
* @throws PDOException
* @throws ServiceCircularReferenceException
* @throws ServiceNotFoundException
* @return void
*/
private function generateServices(): void
{
$this->object_name = 'serviceescalation';
foreach ($this->services_build as $escalation_id => $hosts) {
foreach ($hosts as $host_id => $services) {
foreach ($services as $service_id => $service) {
$object = $this->getEscalationFromId($escalation_id);
$object['host_name'] = [$this->host_instance->getString($host_id, 'host_name')];
$object['service_description'] = [$this->service_instance->getString($service_id, 'service_description')];
$object['escalation_options'] = $object['escalation_options_service'];
// Dont care of the id (we set 0)
$this->generateSubObjects($object, $escalation_id);
$this->generateObjectInFile($object, 0);
}
}
}
}
/**
* @throws LogicException
* @throws PDOException
* @throws ServiceCircularReferenceException
* @throws ServiceNotFoundException
* @return void
*/
private function generateHostgroups(): void
{
$this->object_name = 'hostescalation';
foreach ($this->hg_build as $escalation_id => $values) {
$object = $this->getEscalationFromId($escalation_id);
// No hosgroup enabled
if (count($values) == 0) {
continue;
}
$object['hostgroup_name'] = &$values;
$object['escalation_options'] = $object['escalation_options_host'];
// Dont care of the id (we set 0)
$this->generateSubObjects($object, $escalation_id);
$this->generateObjectInFile($object, 0);
}
}
/**
* @throws LogicException
* @throws PDOException
* @throws ServiceCircularReferenceException
* @throws ServiceNotFoundException
* @return void
*/
private function generateServicegroups(): void
{
$this->object_name = 'serviceescalation';
foreach ($this->sg_build as $escalation_id => $values) {
$object = $this->getEscalationFromId($escalation_id);
// No servicegroup enabled
if (count($values) == 0) {
continue;
}
$object['servicegroup_name'] = &$values;
$object['escalation_options'] = $object['escalation_options_service'];
// Dont care of the id (we set 0)
$this->generateSubObjects($object, $escalation_id);
$this->generateObjectInFile($object, 0);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate/severity.class.php | centreon/www/class/config-generate/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
*
*/
use Pimple\Container;
/**
* Class
*
* @class Severity
*/
class Severity extends AbstractObject
{
/** @var null */
protected $stmt_host = null;
/** @var null */
protected $stmt_service = null;
/** @var null */
protected $stmt_hc_name = null;
/** @var string */
protected $generate_filename = 'severities.cfg';
/** @var string */
protected string $object_name = 'severity';
/** @var string[] */
protected $attributesSelectHost = [
'hc_id' => 'id',
'hc_name' => 'severity_name',
'level' => 'level',
'icon_id' => 'icon_id',
];
/** @var string[] */
protected $attributesSelectService = [
'sc_id' => 'id',
'sc_name' => 'severity_name',
'level' => 'level',
'icon_id' => 'icon_id',
];
/** @var string[] */
protected $attributes_write = [
'id',
'severity_name',
'level',
'icon_id',
'type',
];
/** @var int */
private $use_cache = 1;
/** @var int */
private $done_cache = 0;
/** @var array */
private $service_severity_cache = [];
/** @var array */
private $service_severity_by_name_cache = [];
/** @var array */
private $service_linked_cache = [];
/** @var array */
private $host_severity_cache = [];
/** @var array */
private $host_linked_cache = [];
/** @var array */
private $host_severities = [];
/** @var array */
private $service_severities = [];
/**
* Severity constructor
*
* @param Container $dependencyInjector
*
* @throws PDOException
*/
public function __construct(Container $dependencyInjector)
{
parent::__construct($dependencyInjector);
$this->buildCache();
}
/**
* @param $host_id
*
* @throws PDOException
* @return mixed|string|null
*/
public function getHostSeverityByHostId($host_id)
{
// Get from the cache
if (isset($this->host_linked_cache[$host_id])) {
return $this->host_linked_cache[$host_id];
}
if ($this->done_cache == 1) {
return null;
}
// We get unitary
if (is_null($this->stmt_host)) {
$this->stmt_host = $this->backend_instance->db->prepare(
"SELECT hc_id, hc_name, level
FROM hostcategories_relation, hostcategories
WHERE hostcategories_relation.host_host_id = :host_id
AND hostcategories_relation.hostcategories_hc_id = hostcategories.hc_id
AND level IS NOT NULL AND hc_activate = '1'
ORDER BY level DESC
LIMIT 1"
);
}
$this->stmt_host->bindParam(':host_id', $host_id, PDO::PARAM_INT);
$this->stmt_host->execute();
$hostsCategories = $this->stmt_host->fetchAll(PDO::FETCH_ASSOC);
$severity = array_pop($hostsCategories);
if (is_null($severity)) {
$this->host_linked_cache[$host_id] = null;
return null;
}
$this->host_linked_cache[$host_id] = $severity['hc_id'];
$this->host_severity_cache[$severity['hc_id']] = &$severity;
return $severity['hc_id'];
}
/**
* @param $hc_id
*
* @return mixed|null
*/
public function getHostSeverityById($hc_id)
{
if (is_null($hc_id)) {
return null;
}
if (! isset($this->host_severity_cache[$hc_id])) {
return null;
}
$this->host_severities[$hc_id] = $this->host_severity_cache[$hc_id];
return $this->host_severity_cache[$hc_id];
}
/**
* @param $service_id
*
* @throws PDOException
* @return mixed|string|null
*/
public function getServiceSeverityByServiceId($service_id)
{
// Get from the cache
if (isset($this->service_linked_cache[$service_id])) {
return $this->service_linked_cache[$service_id];
}
if ($this->done_cache == 1) {
return null;
}
// We get unitary
if (is_null($this->stmt_service)) {
$this->stmt_service = $this->backend_instance->db->prepare(
"SELECT service_categories.sc_id, sc_name, level
FROM service_categories_relation, service_categories
WHERE service_categories_relation.service_service_id = :service_id
AND service_categories_relation.sc_id = service_categories.sc_id
AND level IS NOT NULL AND sc_activate = '1'
ORDER BY level DESC
LIMIT 1"
);
}
$this->stmt_service->bindParam(':service_id', $service_id, PDO::PARAM_INT);
$this->stmt_service->execute();
$serviceCategories = $this->stmt_service->fetchAll(PDO::FETCH_ASSOC);
$severity = array_pop($serviceCategories);
if (is_null($severity)) {
$this->service_linked_cache[$service_id] = null;
return null;
}
$this->service_linked_cache[$service_id] = $severity['sc_id'];
$this->service_severity_by_name_cache[$severity['sc_name']] = &$severity;
$this->service_severity_cache[$severity['sc_id']] = &$severity;
return $severity['sc_id'];
}
/**
* @param $sc_id
*
* @return mixed|null
*/
public function getServiceSeverityById($sc_id)
{
if (is_null($sc_id)) {
return null;
}
if (! isset($this->service_severity_cache[$sc_id])) {
return null;
}
$this->service_severities[$sc_id] = $this->service_severity_cache[$sc_id];
return $this->service_severity_cache[$sc_id];
}
/**
* @param $hc_name
*
* @throws PDOException
* @return mixed|null
*/
public function getServiceSeverityMappingHostSeverityByName($hc_name)
{
if (isset($this->service_severity_by_name_cache[$hc_name])) {
$this->service_severities[$this->service_severity_by_name_cache[$hc_name]['sc_id']] = $this->service_severity_by_name_cache[$hc_name];
return $this->service_severity_by_name_cache[$hc_name];
}
if ($this->done_cache == 1) {
return null;
}
// We get unitary
if (is_null($this->stmt_hc_name)) {
$this->stmt_hc_name = $this->backend_instance->db->prepare(
"SELECT sc_name, sc_id, level
FROM service_categories
WHERE sc_name = :sc_name AND level IS NOT NULL AND sc_activate = '1'"
);
}
$this->stmt_hc_name->bindParam(':sc_name', $hc_name, PDO::PARAM_STR);
$this->stmt_hc_name->execute();
$serviceCategories = $this->stmt_hc_name->fetchAll(PDO::FETCH_ASSOC);
$severity = array_pop($serviceCategories);
if (is_null($severity)) {
$this->service_severity_by_name_cache[$hc_name] = null;
return null;
}
$this->service_severity_by_name_cache[$hc_name] = &$severity;
$this->service_severity_cache[$severity['sc_id']] = &$severity;
$this->service_severities[$severity['sc_id']] = $this->service_severity_cache[$severity['sc_id']];
return $severity;
}
/**
* Export cached objects in corresponding export file
*/
public function generateObjects(): void
{
$this->generateServiceSeverityObjects();
$this->generateHostSeverityObjects();
}
/**
* Reset instance
*/
public function reset(): void
{
$this->host_severities = [];
$this->service_severities = [];
parent::reset();
}
/**
* @throws PDOException
* @return void
*/
private function cacheHostSeverity(): void
{
$stmt = $this->backend_instance->db->prepare(
"SELECT hc_name, hc_id, level, icon_id
FROM hostcategories
WHERE level IS NOT NULL AND hc_activate = '1'"
);
$stmt->execute();
$values = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($values as &$value) {
$this->host_severity_cache[$value['hc_id']] = &$value;
}
}
/**
* @throws PDOException
* @return void
*/
private function cacheHostSeverityLinked(): void
{
$stmt = $this->backend_instance->db->prepare(
'SELECT hc_id, host_host_id '
. 'FROM hostcategories, hostcategories_relation '
. 'WHERE level IS NOT NULL '
. 'AND hc_activate = "1" '
. 'AND hostcategories_relation.hostcategories_hc_id = hostcategories.hc_id'
);
$stmt->execute();
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $value) {
if (isset($this->host_linked_cache[$value['host_host_id']])) {
if (
$this->host_severity_cache[$value['hc_id']]['level']
< $this->host_severity_cache[$this->host_linked_cache[$value['host_host_id']]]
) {
$this->host_linked_cache[$value['host_host_id']] = $value['hc_id'];
}
} else {
$this->host_linked_cache[$value['host_host_id']] = $value['hc_id'];
}
}
}
/**
* @throws PDOException
* @return void
*/
private function cacheServiceSeverity(): void
{
$stmt = $this->backend_instance->db->prepare(
"SELECT sc_name, sc_id, level, icon_id
FROM service_categories
WHERE level IS NOT NULL AND sc_activate = '1'"
);
$stmt->execute();
$values = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($values as &$value) {
$this->service_severity_by_name_cache[$value['sc_name']] = &$value;
$this->service_severity_cache[$value['sc_id']] = &$value;
}
}
/**
* @throws PDOException
* @return void
*/
private function cacheServiceSeverityLinked(): void
{
$stmt = $this->backend_instance->db->prepare(
'SELECT service_categories.sc_id, service_service_id '
. 'FROM service_categories, service_categories_relation '
. 'WHERE level IS NOT NULL '
. 'AND sc_activate = "1" '
. 'AND service_categories_relation.sc_id = service_categories.sc_id'
);
$stmt->execute();
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $value) {
if (isset($this->service_linked_cache[$value['service_service_id']])) {
if (
$this->service_severity_cache[$value['sc_id']]['level']
< $this->service_severity_cache[$this->service_linked_cache[$value['service_service_id']]]
) {
$this->service_linked_cache[$value['service_service_id']] = $value['sc_id'];
}
} else {
$this->service_linked_cache[$value['service_service_id']] = $value['sc_id'];
}
}
}
/**
* @throws PDOException
* @return int|void
*/
private function buildCache()
{
if ($this->done_cache == 1) {
return 0;
}
$this->cacheHostSeverity();
$this->cacheHostSeverityLinked();
$this->cacheServiceSeverity();
$this->cacheServiceSeverityLinked();
$this->done_cache = 1;
}
/**
* Export service severities in corresponding export file
*/
private function generateServiceSeverityObjects(): void
{
foreach ($this->service_severities as $id => $value) {
if (is_null($value)) {
continue;
}
$severity = ['type' => 'service'];
foreach ($this->attributesSelectService as $selectAttr => $writeAttr) {
$severity[$writeAttr] = $value[$selectAttr];
}
$this->generateObjectInFile($severity, $id);
}
}
/**
* Export host severities in corresponding export file
*/
private function generateHostSeverityObjects(): void
{
foreach ($this->host_severities as $id => $value) {
if (is_null($value)) {
continue;
}
$severity = ['type' => 'host'];
foreach ($this->attributesSelectHost as $selectAttr => $writeAttr) {
$severity[$writeAttr] = $value[$selectAttr];
}
$this->generateObjectInFile($severity, $id);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate/meta_command.class.php | centreon/www/class/config-generate/meta_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
*
*/
/**
* Class
*
* @class MetaCommand
*/
class MetaCommand extends AbstractObject
{
/** @var string */
protected $generate_filename = 'meta_commands.cfg';
/** @var string */
protected string $object_name = 'command';
/** @var string[] */
protected $attributes_write = ['command_name', 'command_line'];
/**
* @throws Exception
* @return int|void
*/
public function generateObjects()
{
if ($this->checkGenerate(0)) {
return 0;
}
$object = [];
$object['command_name'] = 'check_meta';
$object['command_line'] = '$CENTREONPLUGINS$/centreon_centreon_central.pl '
. '--plugin=apps::centreon::local::plugin --mode=metaservice --centreon-config=/etc/centreon/conf.pm '
. '--meta-id $ARG1$';
$this->generateObjectInFile($object, 0);
$object['command_name'] = 'check_meta_host_alive';
$object['command_line'] = '$CENTREONPLUGINS$/centreon_centreon_central.pl '
. '--plugin=apps::centreon::local::plugin --mode=dummy --status=\'0\' --output=\'This is a dummy check\'';
$this->generateObjectInFile($object, 0);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate/dependency.class.php | centreon/www/class/config-generate/dependency.class.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
use Pimple\Container;
/**
* Class
*
* @class Dependency
*/
class Dependency extends AbstractObject
{
/** @var */
public $dependency_cache;
/** @var string */
protected $generate_filename = 'dependencies.cfg';
/** @var string */
protected string $object_name = 'hostdependency';
/** @var string */
protected $attributes_select = "
dep_id,
dep_name as ';dependency_name',
execution_failure_criteria,
notification_failure_criteria,
inherits_parent
";
/** @var string[] */
protected $attributes_write = [';dependency_name', 'execution_failure_criteria', 'notification_failure_criteria', 'inherits_parent'];
/** @var string[] */
protected $attributes_array = ['dependent_host_name', 'host_name', 'dependent_service_description', 'service_description', 'dependent_hostgroup_name', 'hostgroup_name', 'dependent_servicegroup_name', 'servicegroup_name'];
/** @var Host|null */
protected $host_instance = null;
/** @var Service|null */
protected $service_instance = null;
/** @var Hostgroup|null */
protected $hg_instance = null;
/** @var Servicegroup|null */
protected $sg_instance = null;
// Not done system without cache. TODO
/** @var int */
private $use_cache = 1;
/** @var int */
private $done_cache = 0;
/** @var int */
private $has_dependency = 1; // by default, we have.
/** @var array */
private $generated_dependencies = [];
/** @var array */
private $dependency_linked_host_parent_cache = [];
/** @var array */
private $dependency_linked_host_child_cache = [];
/** @var array */
private $dependency_linked_hg_parent_cache = [];
/** @var array */
private $dependency_linked_hg_child_cache = [];
/** @var array */
private $dependency_linked_service_parent_cache = [];
/** @var array */
private $dependency_linked_service_child_cache = [];
/** @var array */
private $dependency_linked_sg_parent_cache = [];
/** @var array */
private $dependency_linked_sg_child_cache = [];
/** @var array */
private $dependency_linked_meta_parent_cache = [];
/** @var array */
private $dependency_linked_meta_child_cache = [];
/**
* Dependency constructor
*
* @param Container $dependencyInjector
*
* @throws PDOException
*/
public function __construct(Container $dependencyInjector)
{
parent::__construct($dependencyInjector);
$this->host_instance = Host::getInstance($this->dependencyInjector);
$this->service_instance = Service::getInstance($this->dependencyInjector);
$this->hg_instance = Hostgroup::getInstance($this->dependencyInjector);
$this->sg_instance = Servicegroup::getInstance($this->dependencyInjector);
$this->buildCache();
}
/**
* @throws Exception
* @return void
*/
public function doHost(): void
{
$this->object_name = 'hostdependency';
foreach ($this->dependency_cache as $dp_id => $dependency) {
$dependency['host_name'] = [];
if (isset($this->dependency_linked_host_parent_cache[$dp_id])) {
foreach ($this->dependency_linked_host_parent_cache[$dp_id] as $value) {
if ($this->host_instance->checkGenerate($value)) {
$dependency['host_name'][] = $this->host_instance->getString($value, 'host_name');
}
}
}
$dependency['dependent_host_name'] = [];
if (isset($this->dependency_linked_host_child_cache[$dp_id])) {
foreach ($this->dependency_linked_host_child_cache[$dp_id] as $value) {
if ($this->host_instance->checkGenerate($value)) {
$dependency['dependent_host_name'][] = $this->host_instance->getString($value, 'host_name');
}
}
}
if (count($dependency['host_name']) == 0 || count($dependency['dependent_host_name']) == 0) {
continue;
}
$this->generateObjectInFile($dependency, 0);
}
}
/**
* @throws Exception
* @return void
*/
public function doService(): void
{
$this->object_name = 'servicedependency';
foreach ($this->dependency_cache as $dp_id => $dependency) {
if (! isset($this->dependency_linked_service_parent_cache[$dp_id])) {
continue;
}
foreach ($this->dependency_linked_service_parent_cache[$dp_id] as $value) {
if (! isset($this->dependency_linked_service_child_cache[$dp_id])) {
continue;
}
if ($this->service_instance->checkGenerate(
$value['host_host_id'] . '.' . $value['service_service_id']
)) {
$dependency['host_name'] = [$this->host_instance->getString($value['host_host_id'], 'host_name')];
$dependency['service_description'] = [$this->service_instance->getString($value['service_service_id'], 'service_description')];
foreach ($this->dependency_linked_service_child_cache[$dp_id] as $value2) {
if ($this->service_instance->checkGenerate(
$value2['host_host_id'] . '.' . $value2['service_service_id']
)) {
$dependency['dependent_host_name'] = [$this->host_instance->getString($value2['host_host_id'], 'host_name')];
$dependency['dependent_service_description'] = [$this->service_instance->getString($value2['service_service_id'], 'service_description')];
$this->generateObjectInFile($dependency, 0);
}
}
}
}
}
}
/**
* @throws Exception
* @return int|void
*/
public function doMetaService()
{
$meta_instance = MetaService::getInstance($this->dependencyInjector);
if (! $meta_instance->hasMetaServices()) {
return 0;
}
$this->object_name = 'servicedependency';
foreach ($this->dependency_cache as $dp_id => $dependency) {
if (! isset($this->dependency_linked_meta_parent_cache[$dp_id])) {
continue;
}
foreach ($this->dependency_linked_meta_parent_cache[$dp_id] as $meta_id) {
if (! isset($this->dependency_linked_meta_child_cache[$dp_id])) {
continue;
}
if ($meta_instance->checkGenerate($meta_id)) {
$dependency['host_name'] = ['_Module_Meta'];
$dependency['service_description'] = ['meta_' . $meta_id];
foreach ($this->dependency_linked_meta_child_cache[$dp_id] as $meta_id2) {
if ($meta_instance->checkGenerate($meta_id2)) {
$dependency['dependent_host_name'] = ['_Module_Meta'];
$dependency['dependent_service_description'] = ['meta_' . $meta_id2];
$this->generateObjectInFile($dependency, 0);
}
}
}
}
}
}
/**
* @throws Exception
* @return void
*/
public function doHostgroup(): void
{
$this->object_name = 'hostdependency';
foreach ($this->dependency_cache as $dp_id => $dependency) {
$dependency['hostgroup_name'] = [];
if (isset($this->dependency_linked_hg_parent_cache[$dp_id])) {
foreach ($this->dependency_linked_hg_parent_cache[$dp_id] as $value) {
if ($this->hg_instance->checkGenerate($value)) {
$dependency['hostgroup_name'][] = $this->hg_instance->getString($value, 'hostgroup_name');
}
}
}
$dependency['dependent_hostgroup_name'] = [];
if (isset($this->dependency_linked_hg_child_cache[$dp_id])) {
foreach ($this->dependency_linked_hg_child_cache[$dp_id] as $value) {
if ($this->hg_instance->checkGenerate($value)) {
$dependency['dependent_hostgroup_name'][] = $this->hg_instance->getString(
$value,
'hostgroup_name'
);
}
}
}
if (count($dependency['dependent_hostgroup_name']) == 0 || count($dependency['hostgroup_name']) == 0) {
continue;
}
$this->generateObjectInFile($dependency, 0);
}
}
/**
* @throws Exception
* @return void
*/
public function doServicegroup(): void
{
$this->object_name = 'servicedependency';
foreach ($this->dependency_cache as $dp_id => $dependency) {
$dependency['servicegroup_name'] = [];
if (isset($this->dependency_linked_sg_parent_cache[$dp_id])) {
foreach ($this->dependency_linked_sg_parent_cache[$dp_id] as $value) {
if ($this->sg_instance->checkGenerate($value)) {
$dependency['servicegroup_name'][] = $this->sg_instance->getString($value, 'servicegroup_name');
}
}
}
$dependency['dependent_servicegroup_name'] = [];
if (isset($this->dependency_linked_sg_child_cache[$dp_id])) {
foreach ($this->dependency_linked_sg_child_cache[$dp_id] as $value) {
if ($this->sg_instance->checkGenerate($value)) {
$dependency['dependent_servicegroup_name'][] = $this->sg_instance->getString(
$value,
'servicegroup_name'
);
}
}
}
if (count($dependency['dependent_servicegroup_name']) == 0
|| count($dependency['servicegroup_name']) == 0) {
continue;
}
$this->generateObjectInFile($dependency, 0);
}
}
/**
* @throws Exception
* @return int|void
*/
public function generateObjects()
{
if ($this->has_dependency == 0) {
return 0;
}
$this->doHost();
$this->doService();
$this->doHostgroup();
$this->doServicegroup();
$this->doMetaService();
}
/**
* @throws Exception
* @return void
*/
public function reset(): void
{
$this->generated_dependencies = [];
parent::reset();
}
/**
* @return int
*/
public function hasDependency()
{
return $this->has_dependency;
}
/**
* @return array
*/
public function getGeneratedDependencies()
{
return $this->generated_dependencies;
}
/**
* @throws PDOException
* @return void
*/
private function getDependencyCache(): void
{
$stmt = $this->backend_instance->db->prepare("SELECT
{$this->attributes_select}
FROM dependency
");
$stmt->execute();
$this->dependency_cache = $stmt->fetchAll(PDO::FETCH_GROUP | PDO::FETCH_UNIQUE | PDO::FETCH_ASSOC);
if (count($this->dependency_cache) == 0) {
$this->has_dependency = 0;
}
}
/**
* @throws PDOException
* @return int|void
*/
private function getDependencyLinkedCache()
{
if ($this->has_dependency == 0) {
return 0;
}
// Host dependency
$stmt = $this->backend_instance->db->prepare('SELECT
dependency_dep_id, host_host_id
FROM dependency_hostParent_relation
');
$stmt->execute();
$this->dependency_linked_host_parent_cache = $stmt->fetchAll(PDO::FETCH_GROUP | PDO::FETCH_COLUMN);
$stmt = $this->backend_instance->db->prepare('SELECT
dependency_dep_id, host_host_id
FROM dependency_hostChild_relation
');
$stmt->execute();
$this->dependency_linked_host_child_cache = $stmt->fetchAll(PDO::FETCH_GROUP | PDO::FETCH_COLUMN);
// Hostgroup dependency
$stmt = $this->backend_instance->db->prepare('SELECT
dependency_dep_id, hostgroup_hg_id
FROM dependency_hostgroupParent_relation
');
$stmt->execute();
$this->dependency_linked_hg_parent_cache = $stmt->fetchAll(PDO::FETCH_GROUP | PDO::FETCH_COLUMN);
$stmt = $this->backend_instance->db->prepare('SELECT
dependency_dep_id, hostgroup_hg_id
FROM dependency_hostgroupChild_relation
');
$stmt->execute();
$this->dependency_linked_hg_child_cache = $stmt->fetchAll(PDO::FETCH_GROUP | PDO::FETCH_COLUMN);
// Servicegroup dependency
$stmt = $this->backend_instance->db->prepare('SELECT
dependency_dep_id, servicegroup_sg_id
FROM dependency_servicegroupParent_relation
');
$stmt->execute();
$this->dependency_linked_sg_parent_cache = $stmt->fetchAll(PDO::FETCH_GROUP | PDO::FETCH_COLUMN);
$stmt = $this->backend_instance->db->prepare('SELECT
dependency_dep_id, servicegroup_sg_id
FROM dependency_servicegroupChild_relation
');
$stmt->execute();
$this->dependency_linked_sg_child_cache = $stmt->fetchAll(PDO::FETCH_GROUP | PDO::FETCH_COLUMN);
// Metaservice dependency
$stmt = $this->backend_instance->db->prepare('SELECT
dependency_dep_id, meta_service_meta_id
FROM dependency_metaserviceParent_relation
');
$stmt->execute();
$this->dependency_linked_meta_parent_cache = $stmt->fetchAll(PDO::FETCH_GROUP | PDO::FETCH_COLUMN);
$stmt = $this->backend_instance->db->prepare('SELECT
dependency_dep_id, meta_service_meta_id
FROM dependency_metaserviceChild_relation
');
$stmt->execute();
$this->dependency_linked_meta_child_cache = $stmt->fetchAll(PDO::FETCH_GROUP | PDO::FETCH_COLUMN);
// Service dependency
$stmt = $this->backend_instance->db->prepare('SELECT
dependency_dep_id, host_host_id, service_service_id
FROM dependency_serviceParent_relation
');
$stmt->execute();
$this->dependency_linked_service_parent_cache = $stmt->fetchAll(PDO::FETCH_GROUP | PDO::FETCH_ASSOC);
$stmt = $this->backend_instance->db->prepare('SELECT
dependency_dep_id, host_host_id, service_service_id
FROM dependency_serviceChild_relation
');
$stmt->execute();
$this->dependency_linked_service_child_cache = $stmt->fetchAll(PDO::FETCH_GROUP | PDO::FETCH_ASSOC);
}
/**
* @throws PDOException
* @return int|void
*/
private function buildCache()
{
if ($this->done_cache == 1) {
return 0;
}
$this->getDependencyCache();
$this->getDependencyLinkedCache();
$this->done_cache = 1;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate/command.class.php | centreon/www/class/config-generate/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
*
*/
/**
* Class
*
* @class Command
*/
class Command extends AbstractObject
{
/** @var string */
protected $generate_filename = 'commands.cfg';
/** @var string */
protected string $object_name = 'command';
/** @var string */
protected $attributes_select = '
command_id,
command_name,
command.command_line as command_line_base,
connector.name as connector,
enable_shell
';
/** @var string[] */
protected $attributes_write = ['command_name', 'command_line', 'connector'];
/** @var null */
private $commands = null;
/** @var null */
private $mail_bin = null;
/**
* @param $command_id
*
* @throws LogicException
* @throws PDOException
* @throws Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException
* @throws Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException
* @return mixed|null
*/
public function generateFromCommandId($command_id)
{
$name = null;
if (is_null($this->commands)) {
$this->createCommandsCache();
}
if (! isset($this->commands[$command_id])) {
return null;
}
if ($this->checkGenerate($command_id)) {
return $this->commands[$command_id]['command_name'];
}
if (is_null($this->mail_bin)) {
$this->getMailBin();
}
// enable_shell is 0 we remove it
$command_line = html_entity_decode($this->commands[$command_id]['command_line_base'] ?? '');
$command_line = str_replace('#BR#', '\\n', $command_line);
$command_line = str_replace('@MAILER@', $this->mail_bin, $command_line);
$command_line = str_replace("\n", " \\\n", $command_line);
$command_line = str_replace("\r", '', $command_line);
if (
$this->isVaultEnabled
&& preg_match('/\\$CENTREONPLUGINS\\$\\/centreon/', $command_line)
) {
$command_line .= ' --pass-manager=centreonvault';
}
if (! is_null($this->commands[$command_id]['enable_shell'])
&& $this->commands[$command_id]['enable_shell'] == 1
) {
$command_line = '/bin/sh -c ' . escapeshellarg($command_line);
}
$this->generateObjectInFile(
array_merge($this->commands[$command_id], ['command_line' => $command_line]),
$command_id
);
return $this->commands[$command_id]['command_name'];
}
/**
* Get information of command.
*
* @param int $commandId
* @return array{
* command_name: string,
* command_line_base: string,
* connector: string|null,
* enable_shell: string
* }|null
*/
public function findCommandById(int $commandId): ?array
{
if (is_null($this->commands)) {
$this->createCommandsCache();
}
return $this->commands[$commandId] ?? null;
}
/**
* Create the cache of commands.
*/
private function createCommandsCache(): void
{
$query = "SELECT {$this->attributes_select} FROM command "
. "LEFT JOIN connector ON connector.id = command.connector_id AND connector.enabled = '1' "
. "AND command.command_activate = '1'";
$stmt = $this->backend_instance->db->prepare($query);
$stmt->execute();
$this->commands = $stmt->fetchAll(PDO::FETCH_GROUP | PDO::FETCH_UNIQUE | PDO::FETCH_ASSOC);
}
/**
* @throws PDOException
* @return void
*/
private function getMailBin(): void
{
$stmt = $this->backend_instance->db->prepare("SELECT
options.value
FROM options
WHERE options.key = 'mailer_path_bin'
");
$stmt->execute();
$this->mail_bin = ($row = $stmt->fetch(PDO::FETCH_ASSOC)) ? $row['value'] : '';
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate/host.class.php | centreon/www/class/config-generate/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
*
*/
use Core\Host\Application\InheritanceManager;
use Core\Host\Application\Repository\ReadHostRepositoryInterface;
use Core\Macro\Application\Repository\ReadHostMacroRepositoryInterface;
use Core\Macro\Application\Repository\ReadServiceMacroRepositoryInterface;
use Core\Macro\Domain\Model\Macro;
use Core\MonitoringServer\Application\Repository\ReadMonitoringServerRepositoryInterface;
use Core\Service\Application\Repository\ReadServiceRepositoryInterface;
use Core\Service\Domain\Model\ServiceInheritance;
require_once __DIR__ . '/abstract/host.class.php';
require_once __DIR__ . '/abstract/service.class.php';
/**
* Class
*
* @class Host
*/
class Host extends AbstractHost
{
public const VERTICAL_NOTIFICATION = 1;
public const CLOSE_NOTIFICATION = 2;
public const CUMULATIVE_NOTIFICATION = 3;
/** @var array */
protected $hosts_by_name = [];
/** @var array|null */
protected $hosts = null;
/** @var string */
protected $generate_filename = 'hosts.cfg';
/** @var string */
protected string $object_name = 'host';
/** @var null|PDOStatement */
protected $stmt_hg = null;
/** @var null|PDOStatement */
protected $stmt_parent = null;
/** @var null|PDOStatement */
protected $stmt_service = null;
/** @var null|PDOStatement */
protected $stmt_service_sg = null;
/** @var array */
protected $generated_parentship = [];
/** @var array */
protected $generatedHosts = [];
/**
* @param $host_id
*
* @return mixed
*/
public function getSeverityForService($host_id)
{
return $this->hosts[$host_id]['severity_id_for_services'];
}
/**
* @param $host_id
* @param $attr
*
* @return void
*/
public function addHost($host_id, $attr = []): void
{
$this->hosts[$host_id] = $attr;
}
/**
* @param $host
* @param $generateConfigurationFile
* @param Macro[] $hostTemplateMacros
*
* @throws LogicException
* @throws PDOException
* @throws Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException
* @throws Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException
* @return void
*/
public function processingFromHost(&$host, $generateConfigurationFile = true, array $hostTemplateMacros = []): void
{
$this->getImages($host);
$this->getHostTimezone($host);
$this->getHostTemplates($host, $generateConfigurationFile, $hostTemplateMacros);
$this->getHostCommands($host);
$this->getHostPeriods($host);
$this->getContactGroups($host);
$this->getContacts($host);
$this->getHostGroups($host);
// Set HostCategories
$hostCategory = HostCategory::getInstance($this->dependencyInjector);
$this->insertHostInHostCategoryMembers($hostCategory, $host);
$host['category_tags'] = $hostCategory->getIdsByHostId($host['host_id']);
$this->getParents($host);
$this->manageNotificationInheritance($host, $generateConfigurationFile);
}
/**
* @param $host
* @param mixed $serviceTemplateMacros
*
* @throws LogicException
* @throws PDOException
* @throws Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException
* @throws Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException
* @return void
*/
public function generateFromHostId(&$host, array $hostMacros, array $hostTemplateMacros, array $serviceMacros, $serviceTemplateMacros): void
{
$this->processingFromHost($host, hostTemplateMacros: $hostTemplateMacros);
$this->formatMacros($host, $hostMacros);
$this->getSeverity($host['host_id']);
$this->getServices($host, $serviceMacros, $serviceTemplateMacros);
$this->getServicesByHg($host);
$this->generateObjectInFile($host, $host['host_id']);
$this->addGeneratedHost($host['host_id']);
}
/**
* @param $pollerId
* @param $localhost
*
* @throws LogicException
* @throws PDOException
* @throws Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException
* @throws Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException
* @return void
*/
public function generateFromPollerId($pollerId, $localhost = 0): void
{
if (is_null($this->hosts)) {
$this->getHosts($pollerId);
}
Service::getInstance($this->dependencyInjector)->set_poller($pollerId);
/** @var ReadMonitoringServerRepositoryInterface $readMonitoringServerRepository */
$readMonitoringServerRepository = $this->kernel->getContainer()->get(ReadMonitoringServerRepositoryInterface::class);
$isPollerEncryptionReady = $readMonitoringServerRepository->isEncryptionReady($pollerId);
foreach ($this->hosts as $host_id => &$host) {
$this->hosts_by_name[$host['host_name']] = $host_id;
$host['host_id'] = $host_id;
[$hostMacros, $hostTemplateMacros] = $this->findHostRelatedMacros($host_id, $isPollerEncryptionReady);
[$serviceMacros, $serviceTemplateMacros] = $this->findServiceRelatedMacros($host_id, $isPollerEncryptionReady);
$this->generateFromHostId($host, $hostMacros, $hostTemplateMacros, $serviceMacros, $serviceTemplateMacros);
}
if ($localhost == 1) {
MetaService::getInstance($this->dependencyInjector)->generateObjects();
}
Hostgroup::getInstance($this->dependencyInjector)->generateObjects();
Servicegroup::getInstance($this->dependencyInjector)->generateObjects();
Escalation::getInstance($this->dependencyInjector)->generateObjects();
Dependency::getInstance($this->dependencyInjector)->generateObjects();
Severity::getInstance($this->dependencyInjector)->generateObjects();
HostCategory::getInstance($this->dependencyInjector)->generateObjects();
ServiceCategory::getInstance($this->dependencyInjector)->generateObjects();
}
/**
* @param $host_name
*
* @return mixed|null
*/
public function getHostIdByHostName($host_name)
{
return $this->hosts_by_name[$host_name] ?? null;
}
/**
* @return array
*/
public function getGeneratedParentship()
{
return $this->generated_parentship;
}
/**
* @param $hostId
*
* @return void
*/
public function addGeneratedHost($hostId): void
{
$this->generatedHosts[] = $hostId;
}
/**
* @return array
*/
public function getGeneratedHosts()
{
return $this->generatedHosts;
}
/**
* @param int $hostId
* @return array
*/
public function getCgAndContacts(int $hostId): array
{
// we pass null because it can be a meta_host with host_register = '2'
$host = $this->getHostById($hostId, null);
$this->getContacts($host);
$this->getContactGroups($host);
$this->getHostTemplates($host, false);
$hostTplInstance = HostTemplate::getInstance($this->dependencyInjector);
$stack = $host['htpl'];
$loop = [];
while (($hostTplId = array_shift($stack))) {
if (isset($loop[$hostTplId])) {
continue;
}
$loop[$hostTplId] = 1;
$hostTplInstance->addCacheHostTpl($hostTplId);
if (! is_null($hostTplInstance->hosts[$hostTplId])) {
$hostTplInstance->getHostTemplates($hostTplInstance->hosts[$hostTplId], false);
$hostTplInstance->getContactGroups($hostTplInstance->hosts[$hostTplId]);
$hostTplInstance->getContacts($hostTplInstance->hosts[$hostTplId]);
$stack = array_merge($hostTplInstance->hosts[$hostTplId]['htpl'], $stack);
}
}
return $this->manageNotificationInheritance($host, false);
}
/**
* @throws Exception
* @return void
*/
public function reset(): void
{
$this->hosts_by_name = [];
$this->hosts = null;
$this->generated_parentship = [];
$this->generatedHosts = [];
parent::reset();
}
/**
* Warning: is to be run AFTER running formatMacros to not override severity export.
*
* @param $host_id_arg
*
* @throws PDOException
* @return void
*/
protected function getSeverity($host_id_arg)
{
$host_id = null;
$loop = [];
$severity_instance = Severity::getInstance($this->dependencyInjector);
$severity_id = $severity_instance->getHostSeverityByHostId($host_id_arg);
$this->hosts[$host_id_arg]['severity'] = $severity_instance->getHostSeverityById($severity_id);
if (! is_null($this->hosts[$host_id_arg]['severity'])) {
$macros = [
'_CRITICALITY_LEVEL' => $this->hosts[$host_id_arg]['severity']['level'],
'_CRITICALITY_ID' => $this->hosts[$host_id_arg]['severity']['hc_id'],
'severity' => $this->hosts[$host_id_arg]['severity']['hc_id'],
];
$this->hosts[$host_id_arg]['macros'] = array_merge(
$this->hosts[$host_id_arg]['macros'] ?? [],
$macros
);
}
$hosts_tpl = &HostTemplate::getInstance($this->dependencyInjector)->hosts;
$stack = $this->hosts[$host_id_arg]['htpl'];
while ((is_null($severity_id) && (! is_null($stack) && ($host_id = array_shift($stack))))) {
if (isset($loop[$host_id])) {
continue;
}
$loop[$host_id] = 1;
if (isset($hosts_tpl[$host_id]['severity_id'])) {
$severity_id = $hosts_tpl[$host_id]['severity_id'];
break;
}
if (isset($hosts_tpl[$host_id]['severity_id_from_below'])) {
$severity_id = $hosts_tpl[$host_id]['severity_id_from_below'];
break;
}
$stack2 = $hosts_tpl[$host_id]['htpl'];
while ((is_null($severity_id) && (! is_null($stack2) && ($host_id2 = array_shift($stack2))))) {
if (isset($loop[$host_id2])) {
continue;
}
$loop[$host_id2] = 1;
if (isset($hosts_tpl[$host_id2]['severity_id'])) {
$severity_id = $hosts_tpl[$host_id2]['severity_id'];
break;
}
$stack2 = array_merge($hosts_tpl[$host_id2]['htpl'] ?? [], $stack2);
}
if ($severity_id) {
$hosts_tpl[$host_id]['severity_id_from_below'] = $severity_id;
}
}
// For applied on services without severity
$this->hosts[$host_id_arg]['severity_id_for_services'] = $severity_instance->getHostSeverityById($severity_id);
}
private function findHostRelatedMacros(int $hostId, bool $isPollerEncryptionReady): array
{
/** @var ReadHostRepositoryInterface $readHostRepository */
$readHostRepository = $this->kernel->getContainer()->get(ReadHostRepositoryInterface::class);
/** @var ReadHostMacroRepositoryInterface $readHostMacroRepository */
$readHostMacroRepository = $this->kernel->getContainer()->get(ReadHostMacroRepositoryInterface::class);
$templateParents = $readHostRepository->findParents($hostId);
$inheritanceLine = InheritanceManager::findInheritanceLine($hostId, $templateParents);
$existingHostMacros = $readHostMacroRepository->findByHostIds(array_merge([$hostId], $inheritanceLine));
array_walk(
$existingHostMacros,
fn (Macro &$macro, int|string $key, bool $isPollerEncryptionReady) => $macro->setShouldBeEncrypted($isPollerEncryptionReady),
$isPollerEncryptionReady
);
return Macro::resolveInheritance($existingHostMacros, $inheritanceLine, $hostId);
}
private function findServiceRelatedMacros(int $hostId, bool $isPollerEncryptionReady): array
{
/** @var ReadServiceRepositoryInterface $readServiceRepository */
$readServiceRepository = $this->kernel->getContainer()->get(ReadServiceRepositoryInterface::class);
/** @var ReadServiceMacroRepositoryInterface $readServiceMacroRepository */
$readServiceMacroRepository = $this->kernel->getContainer()->get(ReadServiceMacroRepositoryInterface::class);
$services = $readServiceRepository->findServiceIdsLinkedToHostId($hostId);
$serviceMacros = [];
$serviceTemplateMacros = [];
foreach ($services as $serviceId) {
$serviceTemplateInheritances = $readServiceRepository->findParents($serviceId);
$inheritanceLine = ServiceInheritance::createInheritanceLine(
$serviceId,
$serviceTemplateInheritances
);
$existingMacros = $readServiceMacroRepository->findByServiceIds($serviceId, ...$inheritanceLine);
[$directMacros, $indirectMacros] = Macro::resolveInheritance($existingMacros, $inheritanceLine, $serviceId);
$serviceMacros = array_merge($serviceMacros, array_values($directMacros));
$serviceTemplateMacros = array_merge($serviceTemplateMacros, array_values($indirectMacros));
}
array_walk(
$serviceMacros,
fn (Macro &$macro, int|string $key, bool $isPollerEncryptionReady) => $macro->setShouldBeEncrypted($isPollerEncryptionReady),
$isPollerEncryptionReady
);
array_walk(
$serviceTemplateMacros,
fn (Macro &$macro, int|string $key, bool $isPollerEncryptionReady) => $macro->setShouldBeEncrypted($isPollerEncryptionReady),
$isPollerEncryptionReady
);
return [$serviceMacros, $serviceTemplateMacros];
}
/**
* @param $poller_id
*
* @throws PDOException
* @return void
*/
private function getHosts($poller_id): void
{
// We use host_register = 1 because we don't want _Module_* hosts
$stmt = $this->backend_instance->db->prepare("SELECT
{$this->attributes_select}
FROM ns_host_relation, host
LEFT JOIN extended_host_information ON extended_host_information.host_host_id = host.host_id
WHERE ns_host_relation.nagios_server_id = :server_id
AND ns_host_relation.host_host_id = host.host_id
AND host.host_activate = '1' AND host.host_register = '1'");
$stmt->bindParam(':server_id', $poller_id, PDO::PARAM_INT);
$stmt->execute();
$this->hosts = $stmt->fetchAll(PDO::FETCH_GROUP | PDO::FETCH_UNIQUE | PDO::FETCH_ASSOC);
}
/**
* @param $host
*
* @throws PDOException
* @return void
*/
private function getHostGroups(&$host): void
{
$host['group_tags'] ??= [];
if (! isset($host['hg'])) {
if (is_null($this->stmt_hg)) {
$this->stmt_hg = $this->backend_instance->db->prepare(
"SELECT hostgroup_hg_id
FROM hostgroup_relation hgr, hostgroup hg
WHERE host_host_id = :host_id AND hg.hg_id = hgr.hostgroup_hg_id AND hg.hg_activate = '1'"
);
}
$this->stmt_hg->bindParam(':host_id', $host['host_id'], PDO::PARAM_INT);
$this->stmt_hg->execute();
$host['hg'] = $this->stmt_hg->fetchAll(PDO::FETCH_COLUMN);
}
$hostgroup = Hostgroup::getInstance($this->dependencyInjector);
foreach ($host['hg'] as $hostGroupId) {
$host['group_tags'][] = $hostGroupId;
$hostgroup->addHostInHg($hostGroupId, $host['host_id'], $host['host_name']);
}
}
/**
* @param $host
*
* @throws PDOException
* @return void
*/
private function getParents(&$host): void
{
if (is_null($this->stmt_parent)) {
$this->stmt_parent = $this->backend_instance->db->prepare('SELECT
host_parent_hp_id
FROM host_hostparent_relation
WHERE host_host_id = :host_id
');
}
$this->stmt_parent->bindParam(':host_id', $host['host_id'], PDO::PARAM_INT);
$this->stmt_parent->execute();
$result = $this->stmt_parent->fetchAll(PDO::FETCH_COLUMN);
$host['parents'] = [];
foreach ($result as $parent_id) {
if (isset($this->hosts[$parent_id])) {
$host['parents'][] = $this->hosts[$parent_id]['host_name'];
}
}
}
/**
* @param $host
* @param Macro[] $serviceMacros
*
* @throws PDOException
* @return void
*/
private function getServices(&$host, array $serviceMacros, array $serviceTemplateMacros): void
{
if (is_null($this->stmt_service)) {
$this->stmt_service = $this->backend_instance->db->prepare('SELECT
service_service_id
FROM host_service_relation
WHERE host_host_id = :host_id AND service_service_id IS NOT NULL
');
}
$this->stmt_service->bindParam(':host_id', $host['host_id'], PDO::PARAM_INT);
$this->stmt_service->execute();
$host['services_cache'] = $this->stmt_service->fetchAll(PDO::FETCH_COLUMN);
$service = Service::getInstance($this->dependencyInjector);
foreach ($host['services_cache'] as $service_id) {
$service->generateFromServiceId(
$host['host_id'],
$host['host_name'],
$service_id,
serviceMacros: $serviceMacros,
serviceTemplateMacros: $serviceTemplateMacros
);
}
}
/**
* @param $host
*
* @throws PDOException
* @return int|void
*/
private function getServicesByHg(&$host)
{
if (count($host['hg']) == 0) {
return 1;
}
if (is_null($this->stmt_service_sg)) {
$query = 'SELECT service_service_id FROM host_service_relation '
. 'JOIN hostgroup_relation ON (hostgroup_relation.hostgroup_hg_id = '
. 'host_service_relation.hostgroup_hg_id) WHERE hostgroup_relation.host_host_id = :host_id';
$this->stmt_service_sg = $this->backend_instance->db->prepare($query);
}
$this->stmt_service_sg->bindParam(':host_id', $host['host_id'], PDO::PARAM_INT);
$this->stmt_service_sg->execute();
$host['services_hg_cache'] = $this->stmt_service_sg->fetchAll(PDO::FETCH_COLUMN);
$service = Service::getInstance($this->dependencyInjector);
foreach ($host['services_hg_cache'] as $service_id) {
$service->generateFromServiceId($host['host_id'], $host['host_name'], $service_id, 1);
}
}
/**
* @param array $host (passing by Reference)
* @return array
*/
private function manageCumulativeInheritance(array &$host): array
{
$results = ['cg' => [], 'contact' => []];
$hostsTpl = HostTemplate::getInstance($this->dependencyInjector)->hosts;
foreach ($host['htpl'] as $hostIdTopLevel) {
$stack = [$hostIdTopLevel];
$loop = [];
if (! isset($hostsTpl[$hostIdTopLevel]['contacts_computed_cache'])) {
$contacts = [];
$cg = [];
while (($hostId = array_shift($stack))) {
if (isset($loop[$hostId]) || ! isset($hostsTpl[$hostId])) {
continue;
}
$loop[$hostId] = 1;
// if notifications_enabled is disabled. We don't go in branch
if (
! is_null($hostsTpl[$hostId]['notifications_enabled'])
&& (int) $hostsTpl[$hostId]['notifications_enabled'] === 0
) {
continue;
}
if (count($hostsTpl[$hostId]['contact_groups_cache']) > 0) {
$cg = array_merge($cg, $hostsTpl[$hostId]['contact_groups_cache']);
}
if (count($hostsTpl[$hostId]['contacts_cache']) > 0) {
$contacts = array_merge($contacts, $hostsTpl[$hostId]['contacts_cache']);
}
$stack = array_merge($hostsTpl[$hostId]['htpl'], $stack);
}
$hostsTpl[$hostIdTopLevel]['contacts_computed_cache'] = array_unique($contacts);
$hostsTpl[$hostIdTopLevel]['contact_groups_computed_cache'] = array_unique($cg);
}
$results['cg'] = array_merge(
$results['cg'],
$hostsTpl[$hostIdTopLevel]['contact_groups_computed_cache']
);
$results['contact'] = array_merge(
$results['contact'],
$hostsTpl[$hostIdTopLevel]['contacts_computed_cache']
);
}
$results['cg'] = array_unique(array_merge($results['cg'], $host['contact_groups_cache']), SORT_NUMERIC);
$results['contact'] = array_unique(array_merge($results['contact'], $host['contacts_cache']), SORT_NUMERIC);
return $results;
}
/**
* @param array $host (passing by Reference)
* @param string $attribute
* @return array
*/
private function manageCloseInheritance(array &$host, string $attribute): array
{
if (count($host[$attribute . '_cache']) > 0) {
return $host[$attribute . '_cache'];
}
$hostsTpl = HostTemplate::getInstance($this->dependencyInjector)->hosts;
foreach ($host['htpl'] as $hostIdTopLevel) {
$stack = [$hostIdTopLevel];
$loop = [];
if (! isset($hostsTpl[$hostIdTopLevel][$attribute . '_computed_cache'])) {
$hostsTpl[$hostIdTopLevel][$attribute . '_computed_cache'] = [];
while (($hostId = array_shift($stack))) {
if (isset($loop[$hostId])) {
continue;
}
$loop[$hostId] = 1;
if (
! is_null($hostsTpl[$hostId]['notifications_enabled'])
&& (int) $hostsTpl[$hostId]['notifications_enabled'] === 0
) {
continue;
}
if (count($hostsTpl[$hostId][$attribute . '_cache']) > 0) {
$hostsTpl[$hostIdTopLevel][$attribute . '_computed_cache']
= $hostsTpl[$hostId][$attribute . '_cache'];
break;
}
$stack = array_merge($hostsTpl[$hostId]['htpl'], $stack);
}
}
if (count($hostsTpl[$hostIdTopLevel][$attribute . '_computed_cache']) > 0) {
return $hostsTpl[$hostIdTopLevel][$attribute . '_computed_cache'];
}
}
return [];
}
/**
* @param array $host
* @param string $attribute
* @param string $attributeAdditive
* @return array
*/
private function manageVerticalInheritance(array &$host, string $attribute, string $attributeAdditive): array
{
$results = $host[$attribute . '_cache'];
if (
count($results) > 0
&& (is_null($host[$attributeAdditive]) || $host[$attributeAdditive] != 1)
) {
return $results;
}
$hostsTpl = HostTemplate::getInstance($this->dependencyInjector)->hosts;
$hostIdCache = null;
foreach ($host['htpl'] as $hostIdTopLevel) {
$computedCache = [];
if (! isset($hostsTpl[$hostIdTopLevel][$attribute . '_computed_cache'])) {
$stack = [[$hostIdTopLevel, 1]];
$loop = [];
$currentLevelCatch = null;
while (([$hostId, $level] = array_shift($stack))) {
if (! is_null($currentLevelCatch) && $currentLevelCatch >= $level) {
break;
}
if (isset($loop[$hostId])) {
continue;
}
$loop[$hostId] = 1;
if (
! is_null($hostsTpl[$hostId]['notifications_enabled'])
&& (int) $hostsTpl[$hostId]['notifications_enabled'] === 0
) {
continue;
}
if (count($hostsTpl[$hostId][$attribute . '_cache']) > 0) {
$computedCache = array_merge($computedCache, $hostsTpl[$hostId][$attribute . '_cache']);
$currentLevelCatch = $level;
if (
is_null($hostsTpl[$hostId][$attributeAdditive])
|| $hostsTpl[$hostId][$attributeAdditive] != 1
) {
break;
}
}
foreach (array_reverse($hostsTpl[$hostId]['htpl']) as $htplId) {
array_unshift($stack, [$htplId, $level + 1]);
}
}
$hostsTpl[$hostIdTopLevel][$attribute . '_computed_cache'] = array_unique($computedCache);
}
if (count($hostsTpl[$hostIdTopLevel][$attribute . '_computed_cache']) > 0) {
$hostIdCache = $hostIdTopLevel;
break;
}
}
if (! is_null($hostIdCache)) {
$results = array_unique(
array_merge($results, $hostsTpl[$hostIdCache][$attribute . '_computed_cache']),
SORT_NUMERIC
);
}
return $results;
}
/**
* @param array $host
* @param array $cg
*/
private function setContactGroups(array &$host, array $cg = []): void
{
$cgInstance = Contactgroup::getInstance($this->dependencyInjector);
$cgResult = '';
$cgResultAppend = '';
foreach ($cg as $cgId) {
$tmp = $cgInstance->generateFromCgId($cgId);
if (! is_null($tmp)) {
$cgResult .= $cgResultAppend . $tmp;
$cgResultAppend = ',';
}
}
if ($cgResult != '') {
$host['contact_groups'] = $cgResult;
}
}
/**
* @param array $host
* @param array $contacts
*/
private function setContacts(array &$host, array $contacts = []): void
{
$contactInstance = Contact::getInstance($this->dependencyInjector);
$contactResult = '';
$contactResultAppend = '';
foreach ($contacts as $contactId) {
$tmp = $contactInstance->generateFromContactId($contactId);
if (! is_null($tmp)) {
$contactResult .= $contactResultAppend . $tmp;
$contactResultAppend = ',';
}
}
if ($contactResult != '') {
$host['contacts'] = $contactResult;
}
}
/**
* @param array $host
* @param bool $generate
* @return array
*/
private function manageNotificationInheritance(array &$host, bool $generate = true): array
{
$results = ['cg' => [], 'contact' => []];
if (! is_null($host['notifications_enabled']) && (int) $host['notifications_enabled'] === 0) {
return $results;
}
$mode = $this->getInheritanceMode();
if ($mode === self::CUMULATIVE_NOTIFICATION) {
$results = $this->manageCumulativeInheritance($host);
} elseif ($mode === self::CLOSE_NOTIFICATION) {
$results['cg'] = $this->manageCloseInheritance($host, 'contact_groups');
$results['contact'] = $this->manageCloseInheritance($host, 'contacts');
} else {
$results['cg'] = $this->manageVerticalInheritance($host, 'contact_groups', 'cg_additive_inheritance');
$results['contact'] = $this->manageVerticalInheritance($host, 'contacts', 'contact_additive_inheritance');
}
if ($generate) {
$this->setContacts($host, $results['contact']);
$this->setContactGroups($host, $results['cg']);
}
return $results;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate/servicetemplate.class.php | centreon/www/class/config-generate/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 __DIR__ . '/abstract/service.class.php';
/**
* Class
*
* @class ServiceTemplate
*/
class ServiceTemplate extends AbstractService
{
/** @var array */
public $service_cache = [];
/** @var null */
public $current_host_id = null;
/** @var null */
public $current_host_name = null;
/** @var null */
public $current_service_description = null;
/** @var null */
public $current_service_id = null;
/** @var null */
protected $hosts = null;
/** @var string */
protected $generate_filename = 'serviceTemplates.cfg';
/** @var string */
protected string $object_name = 'service';
/** @var array */
protected $loop_tpl = [];
/** @var string */
protected $attributes_select = '
service_id,
service_template_model_stm_id,
command_command_id as check_command_id,
command_command_id_arg as check_command_arg,
timeperiod_tp_id as check_period_id,
timeperiod_tp_id2 as notification_period_id,
command_command_id2 as event_handler_id,
command_command_id_arg2 as event_handler_arg,
service_description as name,
service_alias as service_description,
display_name,
service_is_volatile as is_volatile,
service_max_check_attempts as max_check_attempts,
service_normal_check_interval as check_interval,
service_retry_check_interval as retry_interval,
service_active_checks_enabled as active_checks_enabled,
service_passive_checks_enabled as passive_checks_enabled,
initial_state,
service_obsess_over_service as obsess_over_service,
service_check_freshness as check_freshness,
service_freshness_threshold as freshness_threshold,
service_event_handler_enabled as event_handler_enabled,
service_low_flap_threshold as low_flap_threshold,
service_high_flap_threshold as high_flap_threshold,
service_flap_detection_enabled as flap_detection_enabled,
service_process_perf_data as process_perf_data,
service_retain_status_information as retain_status_information,
service_retain_nonstatus_information as retain_nonstatus_information,
service_notification_interval as notification_interval,
service_notification_options as notification_options,
service_notifications_enabled as notifications_enabled,
contact_additive_inheritance,
cg_additive_inheritance,
service_first_notification_delay as first_notification_delay,
service_recovery_notification_delay as recovery_notification_delay,
service_stalking_options as stalking_options,
service_register as register,
service_use_only_contacts_from_host,
esi_notes as notes,
esi_notes_url as notes_url,
esi_action_url as action_url,
esi_icon_image as icon_image_id,
esi_icon_image_alt as icon_image_alt,
service_acknowledgement_timeout as acknowledgement_timeout
';
/** @var string[] */
protected $attributes_write = ['service_description', 'name', 'display_name', 'contacts', 'contact_groups', 'check_command', 'check_period', 'notification_period', 'event_handler', 'max_check_attempts', 'check_interval', 'retry_interval', 'initial_state', 'freshness_threshold', 'low_flap_threshold', 'high_flap_threshold', 'flap_detection_options', 'notification_interval', 'notification_options', 'first_notification_delay', 'recovery_notification_delay', 'stalking_options', 'register', 'notes', 'notes_url', 'action_url', 'icon_image', 'icon_id', 'icon_image_alt', 'acknowledgement_timeout'];
/**
* @param int $serviceId
*
* @throws PDOException
*/
public function getServiceFromId(int $serviceId): void
{
if (is_null($this->stmt_service)) {
$this->stmt_service = $this->backend_instance->db->prepare(
'SELECT ' . $this->attributes_select . ' '
. 'FROM service '
. 'LEFT JOIN extended_service_information '
. 'ON extended_service_information.service_service_id = service.service_id '
. "WHERE service_id = :service_id AND service_activate = '1' "
);
}
$this->stmt_service->bindParam(':service_id', $serviceId, PDO::PARAM_INT);
$this->stmt_service->execute();
$results = $this->stmt_service->fetchAll(PDO::FETCH_ASSOC);
$this->service_cache[$serviceId] = array_pop($results);
}
/**
* @param $service_id
* @param mixed $serviceTemplateMacros
*
* @throws PDOException
* @return mixed|null
*/
public function generateFromServiceId($service_id, $serviceTemplateMacros)
{
if (is_null($service_id)) {
return null;
}
if (! isset($this->service_cache[$service_id])) {
$this->getServiceFromId($service_id);
}
if (is_null($this->service_cache[$service_id])) {
return null;
}
if ($this->checkGenerate($service_id)) {
if (! isset($this->loop_tpl[$service_id])) {
$this->loop_tpl[$service_id] = 1;
// Need to go in only to check servicegroup <-> stpl link
$this->getServiceTemplates($this->service_cache[$service_id], $serviceTemplateMacros);
$this->getServiceGroups($service_id);
}
return $this->service_cache[$service_id]['name'];
}
// avoid loop. we return nothing
if (isset($this->loop_tpl[$service_id])) {
return null;
}
$this->loop_tpl[$service_id] = 1;
$this->getImages($this->service_cache[$service_id]);
$this->formatMacros($this->service_cache[$service_id], $serviceTemplateMacros);
$this->getServiceTemplates($this->service_cache[$service_id], $serviceTemplateMacros);
$this->getServiceCommands($this->service_cache[$service_id]);
$this->getServicePeriods($this->service_cache[$service_id]);
$this->getContactGroups($this->service_cache[$service_id]);
$this->getContacts($this->service_cache[$service_id]);
$this->getServiceGroups($service_id);
// Set ServiceCategories
$serviceCategory = ServiceCategory::getInstance($this->dependencyInjector);
$this->insertServiceInServiceCategoryMembers($serviceCategory, $service_id);
$this->service_cache[$service_id]['category_tags'] = $serviceCategory->getIdsByServiceId($service_id);
$this->getSeverity($service_id);
$this->generateObjectInFile($this->service_cache[$service_id], $service_id);
return $this->service_cache[$service_id]['name'];
}
/**
* @return void
*/
public function resetLoop(): void
{
$this->loop_tpl = [];
}
/**
* @throws Exception
* @return void
*/
public function reset(): void
{
$this->current_host_id = null;
$this->current_host_name = null;
$this->current_service_description = null;
$this->current_service_id = null;
$this->loop_stpl = [];
$this->service_cache = [];
parent::reset();
}
/**
* @param $serviceId
*
* @throws PDOException
* @return void
*/
private function getServiceGroups($serviceId): void
{
$host = Host::getInstance($this->dependencyInjector);
$servicegroup = Servicegroup::getInstance($this->dependencyInjector);
$this->service_cache[$serviceId]['sg'] = $servicegroup->getServiceGroupsForStpl($serviceId);
$this->service_cache[$serviceId]['group_tags'] = [];
foreach ($this->service_cache[$serviceId]['sg'] as &$sg) {
if ($host->isHostTemplate($this->current_host_id, $sg['host_host_id'])) {
$this->service_cache[$serviceId]['group_tags'][] = $sg['servicegroup_sg_id'];
$servicegroup->addServiceInSg(
$sg['servicegroup_sg_id'],
$this->current_service_id,
$this->current_service_description,
$this->current_host_id,
$this->current_host_name
);
}
}
}
/**
* @param $service_id
*
* @throws PDOException
* @return int|void
*/
private function getSeverity($service_id)
{
if (isset($this->service_cache[$service_id]['severity_id'])) {
return 0;
}
$this->service_cache[$service_id]['severity_id']
= Severity::getInstance($this->dependencyInjector)->getServiceSeverityByServiceId($service_id);
$severity = Severity::getInstance($this->dependencyInjector)
->getServiceSeverityById($this->service_cache[$service_id]['severity_id']);
if (! is_null($severity)) {
$macros = [
'_CRITICALITY_LEVEL' => $severity['level'],
'_CRITICALITY_ID' => $severity['sc_id'],
'severity' => $severity['sc_id'],
];
$this->service_cache[$service_id]['macros'] = array_merge(
$this->service_cache[$service_id]['macros'] ?? [],
$macros
);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate/macro.class.php | centreon/www/class/config-generate/macro.class.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
use Core\Common\Application\UseCase\VaultTrait;
use Pimple\Container;
use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException;
use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
/**
* Class
*
* @class Macro
*/
class Macro extends AbstractObject
{
use VaultTrait;
/** @var */
public $stmt_host;
/** @var null */
protected $generate_filename = null;
/** @var string */
protected string $object_name;
/** @var null */
protected $stmt_service = null;
/** @var int */
private $use_cache = 1;
/** @var int */
private $done_cache = 0;
/** @var array */
private $macro_service_cache = [];
private $macroHostCache = [];
/** @var array<int, bool> */
private $pollersEncryptionReadyStatusByHosts = [];
/**
* Macro constructor
*
* @param Container $dependencyInjector
*
* @throws LogicException
* @throws PDOException
* @throws ServiceCircularReferenceException
* @throws ServiceNotFoundException
*/
public function __construct(Container $dependencyInjector)
{
parent::__construct($dependencyInjector);
$this->setPollersEncryptionReadyStatusByHosts();
}
private function setPollersEncryptionReadyStatusByHosts(): void
{
$result = $this->backend_instance->db->fetchAllAssociativeIndexed(
<<<'SQL'
SELECT nsr.host_host_id, ns.is_encryption_ready FROM ns_host_relation nsr
INNER JOIN nagios_server ns ON ns.id = nsr.nagios_server_id
SQL
);
foreach ($result as $hostId => $value) {
$this->pollersEncryptionReadyStatusByHosts[$hostId] = (bool) $value['is_encryption_ready'];
}
}
/**
* @param array{int, array{string, string}} $macros Macros on format [ResourceId => [MacroName, MacroValue]]
* @return array{int, string} vault path indexed by service id
*/
private function getVaultPathByResources(array $macros): array
{
$vaultPathByResources = [];
foreach ($macros as $resourceId => $macroInformation) {
foreach ($macroInformation as $macroValue) {
/**
* Check that the value is a vault path and that we haven't store it already
* As macros are stored by resources in vault. All the macros for the same service has the same vault path
*/
if ($this->isAVaultPath($macroValue) && ! array_key_exists($resourceId, $vaultPathByResources)) {
$vaultPathByResources[$resourceId] = $macroValue;
}
}
}
return $vaultPathByResources;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate/AdditionalConnectorVmWareV6.class.php | centreon/www/class/config-generate/AdditionalConnectorVmWareV6.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 Assert\AssertionFailedException;
use Core\AdditionalConnectorConfiguration\Application\Repository\ReadAccRepositoryInterface;
use Core\AdditionalConnectorConfiguration\Domain\Model\Type;
use Core\AdditionalConnectorConfiguration\Domain\Model\VmWareV6\{VSphereServer, VmWareConfig};
use Core\Common\Application\UseCase\VaultTrait;
use Core\MonitoringServer\Application\Repository\ReadMonitoringServerRepositoryInterface;
use Pimple\Container;
/**
* Class
*
* @class AdditionalConnectorVmWareV6
*/
class AdditionalConnectorVmWareV6 extends AbstractObjectJSON
{
use VaultTrait;
public const CENTREON_SYSTEM_USER = 'centreon';
/**
* AdditionalConnectorVmWareV6 constructor
*
* @param Backend $backend
* @param ReadAccRepositoryInterface $readAdditionalConnectorRepository
*/
public function __construct(
Container $dependencyInjector,
private readonly Backend $backend,
private readonly ReadAccRepositoryInterface $readAdditionalConnectorRepository,
private readonly ReadMonitoringServerRepositoryInterface $readyMonitoringServerRepository,
) {
parent::__construct($dependencyInjector);
}
/**
* @param int $pollerId
*
* @throws AssertionFailedException
* @return void
*/
public function generateFromPollerId(int $pollerId): void
{
$this->generate($pollerId);
}
/**
* Write the file ACC configuration centreon_vmware.json file in the given directory
*
* @param $dir
*
* @throws RuntimeException|Exception
*/
protected function writeFile($dir)
{
$fullFile = $dir . '/' . $this->generate_filename;
if ($handle = fopen($fullFile, 'w')) {
$content = is_array($this->content) ? json_encode($this->content) : $this->content;
if (! fwrite($handle, $content)) {
throw new RuntimeException('Cannot write to file "' . $fullFile . '"');
}
fclose($handle);
/**
* Change VMWare files owner to '660 apache centreon'
* RW for centreon group are necessary for Gorgone Daemon.
*/
chmod($fullFile, 0660);
chgrp($fullFile, self::CENTREON_SYSTEM_USER);
} else {
throw new Exception('Cannot open file ' . $fullFile);
}
}
/**
* Generate VM Ware v6 configuration file for plugins.
*
* @param int $pollerId
*
* @throws Exception|AssertionFailedException
*/
private function generate(int $pollerId): void
{
$additionalConnectorsVMWareV6 = $this->readAdditionalConnectorRepository
->findByPollerAndType($pollerId, Type::VMWARE_V6->value);
$shouldBeEncrypted = $this->readyMonitoringServerRepository->isEncryptionReady($pollerId);
// Cast to object to ensure that an empty JSON and not an empty array is write in file if no ACC exists.
$object = (object) [];
if ($additionalConnectorsVMWareV6 !== null) {
$ACCParameters = $additionalConnectorsVMWareV6->getParameters()->getDecryptedData();
$VSphereServers = array_map(function (array $parameters) use (&$vaultData): VSphereServer {
if (
$this->isVaultEnabled
&& $this->readVaultRepository !== null
&& $this->isAVaultPath($parameters['password'])
) {
$vaultData ??= $this->readVaultRepository->findFromPath($parameters['password']);
$parameters['name'] . '_' . 'password';
if (array_key_exists($parameters['name'] . '_' . 'password', $vaultData)) {
$parameters['password'] = $vaultData[$parameters['name'] . '_' . 'password'];
}
if (array_key_exists($parameters['name'] . '_' . 'username', $vaultData)) {
$parameters['username'] = $vaultData[$parameters['name'] . '_' . 'username'];
}
}
return new VSphereServer(
name: $parameters['name'],
url: $parameters['url'],
username: $parameters['username'],
password: $parameters['password']
);
}, $ACCParameters['vcenters']);
$vmWareConfig = new VmWareConfig(vSphereServers: $VSphereServers, port: $ACCParameters['port']);
$object = [
'vsphere_server' => array_map(
fn (VSphereServer $vSphereServer): array => [
'name' => $vSphereServer->getName(),
'url' => $vSphereServer->getUrl(),
'username' => $shouldBeEncrypted
? 'encrypt::' . $this->engineContextEncryption->crypt($vSphereServer->getUsername())
: $vSphereServer->getUsername(),
'password' => $shouldBeEncrypted
? 'encrypt::' . $this->engineContextEncryption->crypt($vSphereServer->getPassword())
: $vSphereServer->getPassword(),
],
$vmWareConfig->getVSphereServers()
),
'port' => $vmWareConfig->getPort(),
];
}
$this->generate_filename = 'centreon_vmware.json';
$this->generateFile($object, false);
$this->writeFile($this->backend->getPath());
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate/hosttemplate.class.php | centreon/www/class/config-generate/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
*
*/
use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException;
use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
require_once __DIR__ . '/abstract/host.class.php';
/**
* Class
*
* @class HostTemplate
*/
class HostTemplate extends AbstractHost
{
/** @var array|null */
public $hosts = null;
/** @var string */
protected $generate_filename = 'hostTemplates.cfg';
/** @var string */
protected string $object_name = 'host';
/** @var string */
protected $attributes_select = '
host_id,
command_command_id as check_command_id,
command_command_id_arg1 as check_command_arg,
timeperiod_tp_id as check_period_id,
timeperiod_tp_id2 as notification_period_id,
command_command_id2 as event_handler_id,
command_command_id_arg2 as event_handler_arg,
host_name as name,
host_alias as alias,
host_location,
display_name,
host_max_check_attempts as max_check_attempts,
host_check_interval as check_interval,
host_retry_check_interval as retry_interval,
host_active_checks_enabled as active_checks_enabled,
host_passive_checks_enabled as passive_checks_enabled,
initial_state,
host_obsess_over_host as obsess_over_host,
host_check_freshness as check_freshness,
host_freshness_threshold as freshness_threshold,
host_event_handler_enabled as event_handler_enabled,
host_low_flap_threshold as low_flap_threshold,
host_high_flap_threshold as high_flap_threshold,
host_flap_detection_enabled as flap_detection_enabled,
flap_detection_options,
host_process_perf_data as process_perf_data,
host_retain_status_information as retain_status_information,
host_retain_nonstatus_information as retain_nonstatus_information,
host_notification_interval as notification_interval,
host_notification_options as notification_options,
host_notifications_enabled as notifications_enabled,
contact_additive_inheritance,
cg_additive_inheritance,
host_first_notification_delay as first_notification_delay,
host_recovery_notification_delay as recovery_notification_delay,
host_stalking_options as stalking_options,
host_snmp_community,
host_snmp_version,
host_register as register,
ehi_notes as notes,
ehi_notes_url as notes_url,
ehi_action_url as action_url,
ehi_icon_image as icon_image_id,
ehi_icon_image_alt as icon_image_alt,
ehi_statusmap_image as statusmap_image_id,
ehi_2d_coords as 2d_coords,
ehi_3d_coords as 3d_coords,
host_acknowledgement_timeout as acknowledgement_timeout
';
/** @var string[] */
protected $attributes_write = ['name', 'alias', 'display_name', 'timezone', 'contacts', 'contact_groups', 'check_command', 'check_period', 'notification_period', 'event_handler', 'max_check_attempts', 'check_interval', 'retry_interval', 'initial_state', 'freshness_threshold', 'low_flap_threshold', 'high_flap_threshold', 'flap_detection_options', 'notification_interval', 'notification_options', 'first_notification_delay', 'recovery_notification_delay', 'stalking_options', 'register', 'notes', 'notes_url', 'action_url', 'icon_image', 'icon_id', 'icon_image_alt', 'statusmap_image', '2d_coords', '3d_coords', 'acknowledgement_timeout'];
/** @var string[] */
protected $attributes_array = [
'use',
'category_tags',
];
/**
* @param int $hostId
*
* @throws PDOException
*/
public function addCacheHostTpl(int $hostId): void
{
// We use host_register = 1 because we don't want _Module_* hosts
$stmt = $this->backend_instance->db->prepare("
SELECT {$this->attributes_select}
FROM host
LEFT JOIN extended_host_information ON extended_host_information.host_host_id = host.host_id
WHERE host.host_id = :host_id
AND host.host_activate = '1'
AND host.host_register = '0'");
$stmt->bindParam(':host_id', $hostId, PDO::PARAM_INT);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if (isset($row['host_id'])) {
$this->hosts[$row['host_id']] = $row;
}
}
/**
* @param $host_id
* @param $hostTemplateMacros
*
* @throws LogicException
* @throws PDOException
* @throws ServiceCircularReferenceException
* @throws ServiceNotFoundException
* @return mixed|null
* @return mixed|null
*/
public function generateFromHostId($host_id, $hostTemplateMacros = [])
{
if (is_null($this->hosts)) {
$this->getHosts();
}
if (! isset($this->hosts[$host_id])) {
return null;
}
if ($this->checkGenerate($host_id)) {
return $this->hosts[$host_id]['name'];
}
// Avoid infinite loop!
if (isset($this->loop_htpl[$host_id])) {
return $this->hosts[$host_id]['name'];
}
$this->loop_htpl[$host_id] = 1;
$this->hosts[$host_id]['host_id'] = $host_id;
$this->getImages($this->hosts[$host_id]);
$this->getHostTimezone($this->hosts[$host_id]);
$this->getHostTemplates($this->hosts[$host_id], hostTemplateMacros: $hostTemplateMacros);
$this->getHostCommands($this->hosts[$host_id]);
$this->getHostPeriods($this->hosts[$host_id]);
// Set HostCategories
$hostCategory = HostCategory::getInstance($this->dependencyInjector);
$this->insertHostInHostCategoryMembers($hostCategory, $this->hosts[$host_id]);
$this->hosts[$host_id]['category_tags'] = $hostCategory->getIdsByHostId($host_id);
$this->getContactGroups($this->hosts[$host_id]);
$this->getContacts($this->hosts[$host_id]);
$this->formatMacros($this->hosts[$host_id], $hostTemplateMacros);
$this->getSeverity($host_id);
$this->generateObjectInFile($this->hosts[$host_id], $host_id);
return $this->hosts[$host_id]['name'];
}
/**
* @throws Exception
* @return void
*/
public function reset(): void
{
$this->loop_htpl = [];
parent::reset();
}
/**
* @throws PDOException
* @return void
*/
private function getHosts(): void
{
$stmt = $this->backend_instance->db->prepare(
"SELECT {$this->attributes_select}
FROM host
LEFT JOIN extended_host_information ON extended_host_information.host_host_id = host.host_id
WHERE host.host_register = '0' AND host.host_activate = '1'"
);
$stmt->execute();
$this->hosts = $stmt->fetchAll(PDO::FETCH_GROUP | PDO::FETCH_UNIQUE | PDO::FETCH_ASSOC);
}
/**
* Warning: is to be run AFTER running formatMacros to not override severity export.
*
* @param $host_id
*
* @throws PDOException
* @return int|void
*/
private function getSeverity($host_id)
{
if (isset($this->hosts[$host_id]['severity_id'])) {
return 0;
}
$this->hosts[$host_id]['severity_id']
= Severity::getInstance($this->dependencyInjector)->getHostSeverityByHostId($host_id);
$severity
= Severity::getInstance($this->dependencyInjector)
->getHostSeverityById($this->hosts[$host_id]['severity_id']);
if (! is_null($severity)) {
$macros = [
'_CRITICALITY_LEVEL' => $severity['level'],
'_CRITICALITY_ID' => $severity['hc_id'],
'severity' => $severity['hc_id'],
];
$this->hosts[$host_id]['macros'] = array_merge($this->hosts[$host_id]['macros'] ?? [], $macros);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate/contact.class.php | centreon/www/class/config-generate/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
*
*/
use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException;
use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
/**
* Class
*
* @class Contact
*/
class Contact extends AbstractObject
{
public const ENABLE_NOTIFICATIONS = '1';
public const DEFAULT_NOTIFICATIONS = '2';
public const CONTACT_OBJECT = '1';
/** @var int */
protected $use_cache = 1;
/** @var array */
protected $contacts_cache = [];
/** @var array */
protected $contacts = [];
/** @var string */
protected $generate_filename = 'contacts.cfg';
/** @var string */
protected string $object_name = 'contact';
/** @var string */
protected $attributes_select = '
contact_id,
contact_template_id,
timeperiod_tp_id as host_notification_period_id,
timeperiod_tp_id2 as service_notification_period_id,
contact_name,
contact_alias as alias,
contact_host_notification_options as host_notification_options,
contact_service_notification_options as service_notification_options,
contact_email as email,
contact_pager as pager,
contact_address1 as address1,
contact_address2 as address2,
contact_address3 as address3,
contact_address4 as address4,
contact_address5 as address5,
contact_address6 as address6,
contact_enable_notifications as enable_notifications,
contact_register as register,
contact_location
';
/** @var string[] */
protected $attributes_write = ['name', 'contact_name', 'alias', 'email', 'pager', 'address1', 'address2', 'address3', 'address4', 'address5', 'address6', 'host_notification_period', 'service_notification_period', 'host_notification_options', 'service_notification_options', 'register', 'timezone'];
/** @var string[] */
protected $attributes_default = ['host_notifications_enabled', 'service_notifications_enabled'];
/** @var string[] */
protected $attributes_array = ['host_notification_commands', 'service_notification_commands', 'use'];
/** @var null */
protected $stmt_contact = null;
/** @var null[] */
protected $stmt_commands = ['host' => null, 'service' => null];
/** @var null */
protected $stmt_contact_service = null;
/** @var int */
private $done_cache = 0;
/** @var array */
private $contacts_service_linked_cache = [];
/**
* @param int $serviceId
*
* @throws PDOException
* @return array
*/
public function getContactForService(int $serviceId): array
{
$this->buildCache();
// Get from the cache
if (isset($this->contacts_service_linked_cache[$serviceId])) {
return $this->contacts_service_linked_cache[$serviceId];
}
if ($this->done_cache == 1) {
return [];
}
if (is_null($this->stmt_contact_service)) {
$this->stmt_contact_service = $this->backend_instance->db->prepare("
SELECT csr.contact_id
FROM contact_service_relation csr, contact
WHERE csr.service_service_id = :service_id
AND csr.contact_id = contact.contact_id
AND contact_activate = '1'
");
}
$this->stmt_contact_service->bindParam(':service_id', $serviceId, PDO::PARAM_INT);
$this->stmt_contact_service->execute();
$this->contacts_service_linked_cache[$serviceId] = $this->stmt_contact_service->fetchAll(PDO::FETCH_COLUMN);
return $this->contacts_service_linked_cache[$serviceId];
}
/**
* @param $contact_id
*
* @throws LogicException
* @throws PDOException
* @throws ServiceCircularReferenceException
* @throws ServiceNotFoundException
* @return mixed|null
*/
public function generateFromContactId($contact_id)
{
if (is_null($contact_id)) {
return null;
}
$this->buildCache();
if ($this->use_cache == 1) {
if (! isset($this->contacts_cache[$contact_id])) {
return null;
}
$this->contacts[$contact_id] = $this->contacts_cache[$contact_id];
} elseif (! isset($this->contacts[$contact_id])) {
$this->getContactFromId($contact_id);
}
if (is_null($this->contacts[$contact_id])) {
return null;
}
if ($this->contacts[$contact_id]['register'] == 0 && ! isset($this->contacts[$contact_id]['name'])) {
$this->contacts[$contact_id]['name'] = $this->contacts[$contact_id]['contact_name'];
unset($this->contacts[$contact_id]['contact_name']);
}
if ($this->checkGenerate($contact_id)) {
return $this->contacts[$contact_id]['register'] == 1
? $this->contacts[$contact_id]['contact_name']
: $this->contacts[$contact_id]['name'];
}
$this->contacts[$contact_id]['use'] = [
$this->generateFromContactId($this->contacts[$contact_id]['contact_template_id']),
];
if (
$this->contacts[$contact_id]['register'] === self::CONTACT_OBJECT
&& ! $this->shouldContactBeNotified($contact_id)
) {
return null;
}
$this->getContactNotificationCommands($contact_id, 'host');
$this->getContactNotificationCommands($contact_id, 'service');
$period = Timeperiod::getInstance($this->dependencyInjector);
$this->contacts[$contact_id]['host_notification_period']
= $period->generateFromTimeperiodId($this->contacts[$contact_id]['host_notification_period_id']);
$this->contacts[$contact_id]['service_notification_period']
= $period->generateFromTimeperiodId($this->contacts[$contact_id]['service_notification_period_id']);
$this->contacts[$contact_id]['host_notifications_enabled']
= $this->contacts[$contact_id]['enable_notifications'];
$this->contacts[$contact_id]['service_notifications_enabled']
= $this->contacts[$contact_id]['enable_notifications'];
$oTimezone = Timezone::getInstance($this->dependencyInjector);
$sTimezone = $oTimezone->getTimezoneFromId($this->contacts[$contact_id]['contact_location']);
if (! is_null($sTimezone)) {
$this->contacts[$contact_id]['timezone'] = ':' . $sTimezone;
}
$this->generateObjectInFile($this->contacts[$contact_id], $contact_id);
return $this->contacts[$contact_id]['register'] == 1
? $this->contacts[$contact_id]['contact_name']
: $this->contacts[$contact_id]['name'];
}
/**
* @param $contact_id
*
* @return int
*/
public function isTemplate($contact_id)
{
if ($this->contacts[$contact_id]['register'] == 0) {
return 1;
}
return 0;
}
/**
* @param int $contactId
*
* @throws PDOException
*/
protected function getContactFromId(int $contactId): void
{
if (is_null($this->stmt_contact)) {
$this->stmt_contact = $this->backend_instance->db->prepare("
SELECT {$this->attributes_select}
FROM contact
WHERE contact_id = :contact_id AND contact_activate = '1'
");
}
$this->stmt_contact->bindParam(':contact_id', $contactId, PDO::PARAM_INT);
$this->stmt_contact->execute();
$results = $this->stmt_contact->fetchAll(PDO::FETCH_ASSOC);
$this->contacts[$contactId] = array_pop($results);
if ($this->contacts[$contactId] !== null) {
$this->contacts[$contactId]['host_notifications_enabled']
= $this->contacts[$contactId]['enable_notifications'];
$this->contacts[$contactId]['service_notifications_enabled']
= $this->contacts[$contactId]['enable_notifications'];
}
}
/**
* @param $contact_id
* @param $label
*
* @throws LogicException
* @throws PDOException
* @throws ServiceCircularReferenceException
* @throws ServiceNotFoundException
* @return void
*/
protected function getContactNotificationCommands($contact_id, $label)
{
if (! isset($this->contacts[$contact_id][$label . '_commands_cache'])) {
if (is_null($this->stmt_commands[$label])) {
$this->stmt_commands[$label] = $this->backend_instance->db->prepare('
SELECT command_command_id
FROM contact_' . $label . 'commands_relation
WHERE contact_contact_id = :contact_id
');
}
$this->stmt_commands[$label]->bindParam(':contact_id', $contact_id, PDO::PARAM_INT);
$this->stmt_commands[$label]->execute();
$this->contacts[$contact_id][$label . '_commands_cache']
= $this->stmt_commands[$label]->fetchAll(PDO::FETCH_COLUMN);
}
$command = Command::getInstance($this->dependencyInjector);
$this->contacts[$contact_id][$label . '_notification_commands'] = [];
foreach ($this->contacts[$contact_id][$label . '_commands_cache'] as $command_id) {
$this->contacts[$contact_id][$label . '_notification_commands'][]
= $command->generateFromCommandId($command_id);
}
}
/**
* @param int $contactId
* @return bool
*/
protected function shouldContactBeNotified(int $contactId): bool
{
if ($this->contacts[$contactId]['enable_notifications'] === self::ENABLE_NOTIFICATIONS) {
return true;
}
if (
$this->contacts[$contactId]['contact_template_id'] !== null
&& $this->contacts[$contactId]['enable_notifications'] === self::DEFAULT_NOTIFICATIONS
) {
return $this->shouldContactBeNotified($this->contacts[$contactId]['contact_template_id']);
}
return false;
}
/**
* @see Contact::getContactCache()
* @see Contact::getContactForServiceCache()
*/
protected function buildCache(): void
{
if ($this->done_cache == 1) {
return;
}
$this->getContactCache();
$this->getContactForServiceCache();
$this->done_cache = 1;
}
/**
* @throws PDOException
* @return void
*/
private function getContactCache(): void
{
$stmt = $this->backend_instance->db->prepare("SELECT
{$this->attributes_select}
FROM contact
WHERE contact_activate = '1'
");
$stmt->execute();
$this->contacts_cache = $stmt->fetchAll(PDO::FETCH_GROUP | PDO::FETCH_UNIQUE | PDO::FETCH_ASSOC);
}
/**
* @see Contact::$contacts_service_linked_cache
*/
private function getContactForServiceCache(): void
{
$stmt = $this->backend_instance->db->prepare("
SELECT csr.contact_id, service_service_id
FROM contact_service_relation csr, contact
WHERE csr.contact_id = contact.contact_id
AND contact_activate = '1'
");
$stmt->execute();
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $value) {
if (isset($this->contacts_service_linked_cache[$value['service_service_id']])) {
$this->contacts_service_linked_cache[$value['service_service_id']][] = $value['contact_id'];
} else {
$this->contacts_service_linked_cache[$value['service_service_id']] = [$value['contact_id']];
}
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate/generate.class.php | centreon/www/class/config-generate/generate.class.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
// file centreon.config.php may not exist in test environment
use App\Kernel;
use Core\AdditionalConnectorConfiguration\Application\Repository\ReadAccRepositoryInterface;
use Core\AgentConfiguration\Application\Repository\ReadAgentConfigurationRepositoryInterface;
use Core\Host\Application\Repository\ReadHostRepositoryInterface;
use Core\MonitoringServer\Application\Repository\ReadMonitoringServerRepositoryInterface;
use Core\MonitoringServer\Application\Repository\WriteMonitoringServerRepositoryInterface;
use Core\Security\Token\Application\Repository\ReadTokenRepositoryInterface;
use Pimple\Container;
use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException;
use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
$configFile = realpath(__DIR__ . '/../../../config/centreon.config.php');
if ($configFile !== false) {
require_once $configFile;
}
require_once __DIR__ . '/abstract/object.class.php';
require_once __DIR__ . '/abstract/objectJSON.class.php';
require_once __DIR__ . '/backend.class.php';
require_once __DIR__ . '/broker.class.php';
require_once __DIR__ . '/command.class.php';
require_once __DIR__ . '/connector.class.php';
require_once __DIR__ . '/contact.class.php';
require_once __DIR__ . '/contactgroup.class.php';
require_once __DIR__ . '/dependency.class.php';
require_once __DIR__ . '/engine.class.php';
require_once __DIR__ . '/escalation.class.php';
require_once __DIR__ . '/host.class.php';
require_once __DIR__ . '/hostcategory.class.php';
require_once __DIR__ . '/hostgroup.class.php';
require_once __DIR__ . '/hosttemplate.class.php';
require_once __DIR__ . '/macro.class.php';
require_once __DIR__ . '/media.class.php';
require_once __DIR__ . '/meta_command.class.php';
require_once __DIR__ . '/meta_host.class.php';
require_once __DIR__ . '/meta_service.class.php';
require_once __DIR__ . '/meta_timeperiod.class.php';
require_once __DIR__ . '/resource.class.php';
require_once __DIR__ . '/service.class.php';
require_once __DIR__ . '/servicecategory.class.php';
require_once __DIR__ . '/servicegroup.class.php';
require_once __DIR__ . '/servicetemplate.class.php';
require_once __DIR__ . '/severity.class.php';
require_once __DIR__ . '/timeperiod.class.php';
require_once __DIR__ . '/timezone.class.php';
require_once __DIR__ . '/vault.class.php';
require_once __DIR__ . '/AdditionalConnectorVmWareV6.class.php';
require_once __DIR__ . '/AgentConfiguration.php';
/**
* Class
*
* @class Generate
*/
class Generate
{
private const GENERATION_FOR_ENGINE = 1;
private const GENERATION_FOR_BROKER = 2;
/** @var Container|null */
protected $dependencyInjector = null;
/** @var array */
private $poller_cache = [];
/** @var Backend|null */
private $backend_instance = null;
/** @var null */
private $current_poller = null;
/** @var null */
private $installed_modules = null;
/** @var null */
private $module_objects = null;
private ReadAccRepositoryInterface $readAdditionalConnectorRepository;
private ReadAgentConfigurationRepositoryInterface $readAgentConfigurationRepository;
private ReadTokenRepositoryInterface $readTokenRepository;
private ReadHostRepositoryInterface $readHostRepository;
private ReadMonitoringServerRepositoryInterface $readMonitoringServerRepository;
private WriteMonitoringServerRepositoryInterface $writeMonitoringServerRepository;
/**
* Generate constructor
*
* @param Container $dependencyInjector
*/
public function __construct(Container $dependencyInjector)
{
$this->dependencyInjector = $dependencyInjector;
$this->backend_instance = Backend::getInstance($this->dependencyInjector);
$kernel = Kernel::createForWeb();
$this->readAdditionalConnectorRepository = $kernel->getContainer()->get(ReadAccRepositoryInterface::class)
?? throw new Exception('ReadAccRepositoryInterface not found');
$this->readAgentConfigurationRepository = $kernel->getContainer()
->get(ReadAgentConfigurationRepositoryInterface::class)
?? throw new Exception('ReadAgentConfigurationRepositoryInterface not found');
$this->readTokenRepository = $kernel->getContainer()
->get(ReadTokenRepositoryInterface::class)
?? throw new Exception('ReadTokenRepositoryInterface not found');
$this->readHostRepository = $kernel->getContainer()
->get(ReadHostRepositoryInterface::class)
?? throw new Exception('ReadHostRepositoryInterface not found');
$this->readMonitoringServerRepository = $kernel->getContainer()->get(ReadMonitoringServerRepositoryInterface::class)
?? throw new Exception('ReadMonitoringServerRepositoryInterface not found');
$this->writeMonitoringServerRepository = $kernel->getContainer()->get(WriteMonitoringServerRepositoryInterface::class)
?? throw new Exception('WriteMonitoringServerRepositoryInterface not found');
$this->writeMonitoringServerRepository->updateAllEncryptionReadyFromRealtime();
}
/**
* @throws Exception
* @return void
*/
public function resetObjectsEngine(): void
{
Host::getInstance($this->dependencyInjector)->reset();
HostTemplate::getInstance($this->dependencyInjector)->reset();
Service::getInstance($this->dependencyInjector)->reset();
ServiceTemplate::getInstance($this->dependencyInjector)->reset();
Command::getInstance($this->dependencyInjector)->reset();
Contact::getInstance($this->dependencyInjector)->reset();
Contactgroup::getInstance($this->dependencyInjector)->reset();
Hostgroup::getInstance($this->dependencyInjector)->reset();
HostCategory::getInstance($this->dependencyInjector)->reset();
Servicegroup::getInstance($this->dependencyInjector)->reset();
Severity::getInstance($this->dependencyInjector)->reset();
ServiceCategory::getInstance($this->dependencyInjector)->reset();
Timeperiod::getInstance($this->dependencyInjector)->reset();
Escalation::getInstance($this->dependencyInjector)->reset();
Dependency::getInstance($this->dependencyInjector)->reset();
MetaCommand::getInstance($this->dependencyInjector)->reset();
MetaTimeperiod::getInstance($this->dependencyInjector)->reset();
MetaService::getInstance($this->dependencyInjector)->reset();
MetaHost::getInstance($this->dependencyInjector)->reset();
Connector::getInstance($this->dependencyInjector)->reset();
Resource::getInstance($this->dependencyInjector)->reset();
Engine::getInstance($this->dependencyInjector)->reset();
Broker::getInstance($this->dependencyInjector)->reset();
(new AdditionalConnectorVmWareV6(
$this->dependencyInjector,
$this->backend_instance,
$this->readAdditionalConnectorRepository,
$this->readMonitoringServerRepository
))->reset();
(new AgentConfiguration(
$this->backend_instance,
$this->readAgentConfigurationRepository,
$this->readTokenRepository,
$this->readHostRepository
))->reset();
$this->resetModuleObjects();
}
/**
* @param $poller_name
*
* @throws Exception
* @return void
*/
public function configPollerFromName($poller_name): void
{
try {
$this->getPollerFromName($poller_name);
$this->configPoller();
} catch (Exception $e) {
throw new Exception('Exception received : ' . $e->getMessage() . ' [file: ' . $e->getFile()
. '] [line: ' . $e->getLine() . "]\n");
$this->backend_instance->cleanPath();
}
}
/**
* @param $poller_id
* @param $username
*
* @throws Exception
* @return void
*/
public function configPollerFromId($poller_id, $username = 'unknown'): void
{
try {
if (is_null($this->current_poller)) {
$this->getPollerFromId($poller_id);
}
$this->configPoller($username);
} catch (Exception $e) {
throw new Exception('Exception received : ' . $e->getMessage() . ' [file: ' . $e->getFile()
. '] [line: ' . $e->getLine() . "]\n");
$this->backend_instance->cleanPath();
}
}
/**
* @param $username
*
* @throws PDOException
* @return void
*/
public function configPollers($username = 'unknown'): void
{
$query = 'SELECT id, localhost, centreonconnector_path FROM '
. "nagios_server WHERE ns_activate = '1'";
$stmt = $this->backend_instance->db->prepare($query);
$stmt->execute();
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $value) {
$this->current_poller = $value;
$this->configPollerFromId($this->current_poller['id'], $username);
}
}
/**
* @throws PDOException
* @return void|null
*/
public function getInstalledModules()
{
if (! is_null($this->installed_modules)) {
return $this->installed_modules;
}
$this->installed_modules = [];
$stmt = $this->backend_instance->db->prepare('SELECT name FROM modules_informations');
$stmt->execute();
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $value) {
$this->installed_modules[] = $value['name'];
}
}
/**
* @throws PDOException
* @return void
*/
public function getModuleObjects(): void
{
$this->getInstalledModules();
foreach ($this->installed_modules as $module) {
if ($files = glob(_CENTREON_PATH_ . 'www/modules/' . $module . '/generate_files/*.class.php')) {
foreach ($files as $full_file) {
require_once $full_file;
$file_name = str_replace('.class.php', '', basename($full_file));
if (class_exists(ucfirst($file_name))) {
$this->module_objects[] = ucfirst($file_name);
}
}
}
}
}
/**
* @param int $type (1: engine, 2: broker)
*
* @throws PDOException
* @return void
*/
public function generateModuleObjects(int $type = self::GENERATION_FOR_ENGINE): void
{
if (is_null($this->module_objects)) {
$this->getModuleObjects();
}
if (is_array($this->module_objects)) {
foreach ($this->module_objects as $module_object) {
$externalModule = $module_object::getInstance($this->dependencyInjector);
if (
$externalModule instanceof ExternalModuleGenerationInterface
&& (
($type === self::GENERATION_FOR_ENGINE && $externalModule->isEngineObject() === true)
|| ($type === self::GENERATION_FOR_BROKER && $externalModule->isBrokerObject() === true)
)
) {
$externalModule->generateFromPollerId(
(int) $this->current_poller['id'],
(bool) $this->current_poller['localhost']
);
}
}
}
}
/**
* @throws PDOException
* @return void
*/
public function resetModuleObjects(): void
{
if (is_null($this->module_objects)) {
$this->getModuleObjects();
}
if (is_array($this->module_objects)) {
foreach ($this->module_objects as $module_object) {
$externalModule = $module_object::getInstance($this->dependencyInjector);
if ($externalModule instanceof ExternalModuleGenerationInterface) {
$externalModule->reset();
}
}
}
}
/**
* Reset the cache and the instance
*/
public function reset(): void
{
$this->poller_cache = [];
$this->current_poller = null;
$this->installed_modules = null;
$this->module_objects = null;
}
/**
* Insert services in index_data
*
* @param bool $isLocalhost (FALSE by default)
*
* @throws PDOException
* @return void
*/
private function generateIndexData($isLocalhost = false): void
{
$serviceInstance = Service::getInstance($this->dependencyInjector);
$hostInstance = Host::getInstance($this->dependencyInjector);
$services = $serviceInstance->getGeneratedServices();
$bulkLimit = 2000;
$valuesQueries = [];
$bindParams = [];
$bulkCount = 0;
$bulkInsert = function () use (&$valuesQueries, &$bindParams, &$bulkCount): void {
$stmt = $this->backend_instance->db_cs->prepare(
'INSERT INTO index_data (host_id, service_id, host_name, service_description) VALUES '
. implode(',', $valuesQueries)
. ' ON DUPLICATE KEY UPDATE '
. ' host_name=VALUES(host_name), service_description=VALUES(service_description) '
);
foreach ($bindParams as $bindKey => [$bindValue, $bindType]) {
$stmt->bindValue($bindKey, $bindValue, $bindType);
}
$stmt->execute();
$valuesQueries = [];
$bindParams = [];
$bulkCount = 0;
};
foreach ($services as $hostId => &$values) {
$hostName = $hostInstance->getString($hostId, 'host_name');
foreach ($values as $serviceId) {
$serviceDescription = $serviceInstance->getString($serviceId, 'service_description');
$bindParams[":host_id_{$hostId}"] = [$hostId, PDO::PARAM_INT];
$bindParams[":service_id_{$serviceId}"] = [$serviceId, PDO::PARAM_INT];
$bindParams[":host_name_{$hostId}"] = [$hostName, PDO::PARAM_STR];
$bindParams[":service_description_{$serviceId}"] = [$serviceDescription, PDO::PARAM_STR];
$valuesQueries[] = "(
:host_id_{$hostId},
:service_id_{$serviceId},
:host_name_{$hostId},
:service_description_{$serviceId}
)";
$bulkCount++;
if ($bulkCount === $bulkLimit) {
$bulkInsert();
}
}
}
// Meta services
if ($isLocalhost) {
$metaServices = MetaService::getInstance($this->dependencyInjector)->getMetaServices();
$hostId = MetaHost::getInstance($this->dependencyInjector)->getHostIdByHostName('_Module_Meta');
foreach ($metaServices as $metaId => $metaService) {
$bindParams[":host_id_{$hostId}"] = [$hostId, PDO::PARAM_INT];
$bindParams[":meta_service_id_{$metaId}"] = [$metaService['service_id'], PDO::PARAM_INT];
$bindParams[":host_name_{$hostId}"] = ['_Module_Meta', PDO::PARAM_STR];
$bindParams[":meta_service_description_{$metaId}"] = ['meta_' . $metaId, PDO::PARAM_STR];
$valuesQueries[] = "(
:host_id_{$hostId},
:meta_service_id_{$metaId},
:host_name_{$hostId},
:meta_service_description_{$metaId}
)";
$bulkCount++;
if ($bulkCount === $bulkLimit) {
$bulkInsert();
}
}
}
if ($bulkCount > 0) {
$bulkInsert();
}
}
/**
* Insert services created by modules in index_data
*
* @param bool $isLocalhost (FALSE by default)
*
* @throws PDOException
* @return void
*/
private function generateModulesIndexData($isLocalhost = false): void
{
if (is_null($this->module_objects)) {
$this->getModuleObjects();
}
if (is_array($this->module_objects)) {
foreach ($this->module_objects as $module_object) {
$moduleInstance = $module_object::getInstance($this->dependencyInjector);
if (
$moduleInstance->isEngineObject() == true
&& method_exists($moduleInstance, 'generateModuleIndexData')
) {
$moduleInstance->generateModuleIndexData($isLocalhost);
}
}
}
}
/**
* @param $poller_id
*
* @throws PDOException
* @return void
*/
private function getPollerFromId($poller_id): void
{
$query = 'SELECT id, localhost, centreonconnector_path FROM nagios_server '
. 'WHERE id = :poller_id';
$stmt = $this->backend_instance->db->prepare($query);
$stmt->bindParam(':poller_id', $poller_id, PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$this->current_poller = array_pop($result);
if (is_null($this->current_poller)) {
throw new Exception("Cannot find poller id '" . $poller_id . "'");
}
}
/**
* @param $poller_name
*
* @throws PDOException
* @return void
*/
private function getPollerFromName($poller_name): void
{
$query = 'SELECT id, localhost, centreonconnector_path FROM nagios_server '
. 'WHERE name = :poller_name';
$stmt = $this->backend_instance->db->prepare($query);
$stmt->bindParam(':poller_name', $poller_name, PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$this->current_poller = array_pop($result);
if (is_null($this->current_poller)) {
throw new Exception("Cannot find poller name '" . $poller_name . "'");
}
}
/**
* @param $username
*
* @throws LogicException
* @throws PDOException
* @throws ServiceCircularReferenceException
* @throws ServiceNotFoundException
* @return void
*/
private function configPoller($username = 'unknown'): void
{
$this->backend_instance->setUserName($username);
$this->backend_instance->initPath($this->current_poller['id']);
$this->backend_instance->setPollerId($this->current_poller['id']);
$this->resetObjectsEngine();
(new AgentConfiguration(
$this->backend_instance,
$this->readAgentConfigurationRepository,
$this->readTokenRepository,
$this->readHostRepository
))->generateFromPollerId($this->current_poller['id']);
Vault::getInstance($this->dependencyInjector)->generateFromPoller($this->current_poller);
Host::getInstance($this->dependencyInjector)->generateFromPollerId(
$this->current_poller['id'],
$this->current_poller['localhost']
);
$this->generateModuleObjects(self::GENERATION_FOR_ENGINE);
Engine::getInstance($this->dependencyInjector)->generateFromPoller($this->current_poller);
$this->backend_instance->movePath($this->current_poller['id']);
$this->backend_instance->initPath($this->current_poller['id'], 2);
$this->generateModuleObjects(self::GENERATION_FOR_BROKER);
Broker::getInstance($this->dependencyInjector)->generateFromPoller($this->current_poller);
$this->backend_instance->movePath($this->current_poller['id']);
$this->generateIndexData($this->current_poller['localhost'] === '1');
$this->generateModulesIndexData($this->current_poller['localhost'] === '1');
$this->backend_instance->initPath($this->current_poller['id'], 3);
(new AdditionalConnectorVmWareV6(
$this->dependencyInjector,
$this->backend_instance,
$this->readAdditionalConnectorRepository,
$this->readMonitoringServerRepository
))->generateFromPollerId($this->current_poller['id']);
$this->backend_instance->movePath($this->current_poller['id']);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate/connector.class.php | centreon/www/class/config-generate/connector.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 Connector extends AbstractObject
{
protected $generate_filename = 'connectors.cfg';
protected string $object_name = 'connector';
protected $attributes_select = '
id,
name as connector_name,
command_line as connector_line
';
protected $attributes_write = ['connector_name', 'connector_line'];
private $connectors = null;
public function generateObjects($connector_path)
{
if (is_null($connector_path)) {
return 0;
}
$this->getConnectors();
foreach ($this->connectors as $connector) {
$connector['connector_line'] = $connector_path . '/' . $connector['connector_line'];
$this->generateObjectInFile($connector, $connector['id']);
}
}
private function getConnectors(): void
{
$stmt = $this->backend_instance->db->prepare("SELECT
{$this->attributes_select}
FROM connector
WHERE enabled = '1'
");
$stmt->execute();
$this->connectors = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate/resource.class.php | centreon/www/class/config-generate/resource.class.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
use Core\Common\Application\UseCase\VaultTrait;
use Core\MonitoringServer\Application\Repository\ReadMonitoringServerRepositoryInterface;
use Pimple\Container;
/**
* Class
*
* @class Resource
*/
class Resource extends AbstractObject
{
use VaultTrait;
/** @var string */
protected $generate_filename = 'resource.cfg';
/** @var string */
protected string $object_name;
/** @var null */
protected $stmt = null;
/** @var string[] */
protected $attributes_hash = ['resources'];
/** @var null */
private $connectors = null;
/**
* Macro constructor
*
* @param Container $dependencyInjector
*
* @throws LogicException
* @throws PDOException
* @throws ServiceCircularReferenceException
* @throws ServiceNotFoundException
*/
public function __construct(Container $dependencyInjector)
{
parent::__construct($dependencyInjector);
}
/**
* @param $poller_id
*
* @throws PDOException
* @return int|void
*/
public function generateFromPollerId($poller_id)
{
if (is_null($poller_id)) {
return 0;
}
if (is_null($this->stmt)) {
$this->stmt = $this->backend_instance->db->prepare(
<<<'SQL'
SELECT cr.resource_name, cr.resource_line, cr.is_password, ns.is_encryption_ready
FROM cfg_resource_instance_relations cfgri
INNER JOIN cfg_resource cr
ON cr.resource_id = cfgri.resource_id
INNER JOIN nagios_server ns
ON ns.id = cfgri.instance_id
WHERE cfgri.instance_id = :poller_id
AND cfgri.resource_id = cr.resource_id
AND cr.resource_activate = '1';
SQL
);
}
$this->stmt->bindParam(':poller_id', $poller_id, PDO::PARAM_INT);
$this->stmt->execute();
$object = ['resources' => []];
$vaultPaths = [];
$isPassword = [];
$results = $this->stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($results as $value) {
if ((bool) $value['is_password'] === true) {
$isPassword[$value['resource_name']] = true;
}
$object['resources'][$value['resource_name']] = $value['resource_line'];
if ($this->isAVaultPath($value['resource_line'])) {
$vaultPaths[] = $value['resource_line'];
}
}
if ($this->isVaultEnabled && $this->readVaultRepository !== null) {
$vaultData = $this->readVaultRepository->findFromPaths($vaultPaths);
foreach ($vaultData as $vaultValues) {
foreach ($vaultValues as $vaultKey => $vaultValue) {
if (array_key_exists($vaultKey, $object['resources']) || array_key_exists('$' . $vaultKey . '$', $object['resources'])) {
$object['resources'][$vaultKey] = $vaultValue;
}
}
}
}
$readMonitoringServerRepository = $this->kernel->getContainer()->get(ReadMonitoringServerRepositoryInterface::class);
$shouldBeEncrypted = $readMonitoringServerRepository->isEncryptionReady($poller_id);
foreach ($object['resources'] as $macroKey => &$macroValue) {
if (isset($isPassword[$macroKey])) {
$macroValue = $shouldBeEncrypted
? 'encrypt::' . $this->engineContextEncryption->crypt($macroValue)
: $macroValue;
}
}
$this->generateFile($object);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate/abstract/object.class.php | centreon/www/class/config-generate/abstract/object.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 Core\Common\Application\Repository\ReadVaultRepositoryInterface;
use Core\Common\Infrastructure\FeatureFlags;
use Core\Security\Vault\Application\Repository\ReadVaultConfigurationRepositoryInterface;
use Pimple\Container;
use Security\Interfaces\EncryptionInterface;
use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException;
use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
/**
* Class
*
* @class AbstractObject
*/
abstract class AbstractObject
{
protected const VAULT_PATH_REGEX = '/^secret::[^:]*::/';
public EncryptionInterface $engineContextEncryption;
/** @var string */
protected string $object_name;
/** @var Backend|null */
protected $backend_instance = null;
/** @var string */
protected $generate_subpath = 'nagios';
/** @var null */
protected $generate_filename = null;
/** @var array */
protected $exported = [];
/** @var null */
protected $fp = null;
/** @var array */
protected $attributes_write = [];
/** @var array */
protected $attributes_array = [];
/** @var array */
protected $attributes_hash = [];
/** @var array */
protected $attributes_default = [];
/** @var null */
protected $notificationOption = null;
/** @var bool */
protected $engine = true;
/** @var bool */
protected $broker = false;
/** @var Container */
protected $dependencyInjector;
/** @var bool */
protected $isVaultEnabled = false;
/** @var null|ReadVaultRepositoryInterface */
protected $readVaultRepository = null;
protected Kernel $kernel;
/**
* AbstractObject constructor
*
* @param Container $dependencyInjector
*/
protected function __construct(Container $dependencyInjector)
{
$this->kernel = Kernel::createForWeb();
$this->dependencyInjector = $dependencyInjector;
$this->backend_instance = Backend::getInstance($this->dependencyInjector);
$this->engineContextEncryption = $this->kernel->getContainer()->get(EncryptionInterface::class);
$engineContext = file_get_contents('/etc/centreon-engine/engine-context.json');
try {
$this->getVaultConfigurationStatus();
if ($engineContext === false || empty($engineContext)) {
CentreonLog::create()->error(
logTypeId: CentreonLog::TYPE_BUSINESS_LOG,
message: "Unable to parse content of '/etc/centreon-engine/engine-context.json'"
);
throw new RuntimeException('/etc/centreon/engine-context.json does not exists or is empty');
}
$engineContext = json_decode($engineContext, true, flags: JSON_THROW_ON_ERROR);
$this->engineContextEncryption->setSecondKey($engineContext['salt']);
} catch (JsonException|RuntimeException $ex) {
CentreonLog::create()->error(
logTypeId: CentreonLog::TYPE_BUSINESS_LOG,
message: "Unable to parse content of '/etc/centreon-engine/engine-context.json'",
exception: $ex
);
throw $ex;
} catch (ServiceCircularReferenceException|ServiceNotFoundException $ex) {
CentreonLog::create()->error(
logTypeId: CentreonLog::TYPE_BUSINESS_LOG,
message: 'Unable to get Vault configuration status',
exception: $ex
);
throw $ex;
}
}
/**
* @param Container $dependencyInjector
* @return static
*/
public static function getInstance(Container $dependencyInjector): static
{
/**
* @var array<string, static>
*/
static $instances = [];
/**
* @var class-string<static>
*/
$calledClass = static::class;
if (! isset($instances[$calledClass])) {
$instances[$calledClass] = new $calledClass($dependencyInjector);
}
return $instances[$calledClass];
}
/**
* @return void
*/
public function close_file(): void
{
if (! is_null($this->fp)) {
fclose($this->fp);
}
$this->fp = null;
}
/**
* @throws Exception
* @return void
*/
public function reset(): void
{
$this->close_file();
$this->exported = [];
$this->openFileForUpdate(
$this->backend_instance->getPath() . DIRECTORY_SEPARATOR . $this->generate_filename
);
}
/**
* Get the global inheritance option of notification
* 1 = vertical, 2 = close, 3 = cumulative
*
* @throws PDOException
* @return int
*/
public function getInheritanceMode(): int
{
if (is_null($this->notificationOption)) {
$stmtNotification = $this->backend_instance->db->query(
"SELECT `value` FROM options WHERE `key` = 'inheritance_mode'"
);
$value = $stmtNotification->fetch();
$this->notificationOption = (int) $value['value'];
}
return $this->notificationOption;
}
/**
* @param $id
*
* @return int
*/
public function checkGenerate($id)
{
if (isset($this->exported[$id])) {
return 1;
}
return 0;
}
/**
* @return array
*/
public function getExported()
{
return $this->exported ?? [];
}
/**
* @return bool
*/
public function isEngineObject(): bool
{
return $this->engine;
}
/**
* @return bool
*/
public function isBrokerObject(): bool
{
return $this->broker;
}
/**
* open file for update and move pointer to the end
* write header if file is created
*
* @param string $filePath
*
* @throws Exception
*/
protected function openFileForUpdate(string $filePath): void
{
$alreadyExists = file_exists($filePath);
if (! ($this->fp = @fopen($filePath, 'a+'))) {
throw new Exception("Cannot open file (writing permission) '" . $filePath . "'");
}
if (posix_getuid() === fileowner($filePath)) {
chmod($filePath, 0660);
}
if (! $alreadyExists) {
$this->setHeader();
}
}
/**
* @param $object
*
* @return void
*/
protected function writeObject($object)
{
$object_file = "\n";
$object_file .= 'define ' . $this->object_name . " {\n";
foreach ($this->attributes_write as &$attr) {
if (isset($object[$attr]) && ! is_null($object[$attr]) && $object[$attr] != '') {
$object_file .= sprintf(" %-30s %s \n", $attr, $object[$attr]);
}
}
foreach ($this->attributes_default as &$attr) {
if (isset($object[$attr]) && ! is_null($object[$attr]) && $object[$attr] != 2) {
$object_file .= sprintf(" %-30s %s \n", $attr, $object[$attr]);
}
}
foreach ($this->attributes_array as &$attr) {
if (isset($object[$attr]) && ! is_null($object[$attr])) {
$str = '';
$str_append = '';
foreach ($object[$attr] as &$value) {
if (! is_null($value)) {
$str .= $str_append . $value;
$str_append = ',';
}
}
if ($str != '') {
$object_file .= sprintf(" %-30s %s \n", $attr, $str);
}
}
}
foreach ($this->attributes_hash as &$attr) {
if (! isset($object[$attr])) {
continue;
}
foreach ($object[$attr] as $key => &$value) {
$object_file .= sprintf(" %-30s %s \n", $key, $value);
}
}
$object_file .= "}\n";
fwrite($this->fp, $this->toUTF8($object_file));
}
/**
* @param $object
* @param $id
*
* @throws Exception
* @return void
*/
protected function generateObjectInFile($object, $id)
{
if (is_null($this->fp)) {
$this->openFileForUpdate(
$this->backend_instance->getPath() . DIRECTORY_SEPARATOR . $this->generate_filename
);
}
$this->writeObject($object);
$this->exported[$id] = 1;
}
/**
* @param $object
*
* @throws Exception
* @return void
*/
protected function generateFile($object)
{
if (is_null($this->fp)) {
$this->openFileForUpdate(
$this->backend_instance->getPath() . DIRECTORY_SEPARATOR . $this->generate_filename
);
}
$this->writeNoObject($object);
}
/**
* Get Centreon Vault Configuration Status
*
* @throws ServiceCircularReferenceException
* @throws ServiceNotFoundException
* @return void
*/
private function getVaultConfigurationStatus(): void
{
$readVaultConfigurationRepository = $this->kernel->getContainer()->get(
ReadVaultConfigurationRepositoryInterface::class
);
$featureFlag = $this->kernel->getContainer()->get(FeatureFlags::class);
$vaultConfiguration = $readVaultConfigurationRepository->find();
if ($vaultConfiguration !== null && $featureFlag->isEnabled('vault')) {
$this->isVaultEnabled = true;
$this->readVaultRepository = $this->kernel->getContainer()->get(ReadVaultRepositoryInterface::class);
}
}
/**
* @return void
*/
private function setHeader(): void
{
$header
= "###################################################################\n"
. "# #\n"
. "# GENERATED BY CENTREON #\n"
. "# #\n"
. "# Developed by : #\n"
. "# - Julien Mathis #\n"
. "# - Romain Le Merlus #\n"
. "# #\n"
. "# www.centreon.com #\n"
. "# For information : contact@centreon.com #\n"
. "###################################################################\n"
. "# #\n"
. '# Last modification ' . sprintf("%-38s#\n", date('Y-m-d H:i'))
. '# By ' . sprintf("%-53s#\n", $this->backend_instance->getUserName())
. "# #\n"
. "###################################################################\n";
fwrite($this->fp, $this->toUTF8($header));
}
/**
* @param $str
*
* @return array|false|mixed|mixed[]|string|string[]|null
*/
private function toUTF8($str)
{
$finalString = $str;
if (mb_detect_encoding($finalString, 'UTF-8', true) !== 'UTF-8') {
$finalString = mb_convert_encoding($finalString, 'UTF-8');
}
return $finalString;
}
/**
* @param $object
*
* @return void
*/
private function writeNoObject($object): void
{
foreach ($this->attributes_array as &$attr) {
if (isset($object[$attr]) && ! is_null($object[$attr]) && is_array($object[$attr])) {
foreach ($object[$attr] as $v) {
fwrite($this->fp, $this->toUTF8($attr . '=' . $v . "\n"));
}
}
}
foreach ($this->attributes_hash as &$attr) {
if (! isset($object[$attr])) {
continue;
}
foreach ($object[$attr] as $key => &$value) {
fwrite($this->fp, $this->toUTF8($key . '=' . $value . "\n"));
}
}
foreach ($this->attributes_write as &$attr) {
if (isset($object[$attr]) && ! is_null($object[$attr]) && $object[$attr] != '') {
fwrite($this->fp, $this->toUTF8($attr . '=' . $object[$attr] . "\n"));
}
}
foreach ($this->attributes_default as &$attr) {
if (isset($object[$attr]) && ! is_null($object[$attr]) && $object[$attr] != 2) {
fwrite($this->fp, $this->toUTF8($attr . '=' . $object[$attr] . "\n"));
}
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate/abstract/JsonFormat.class.php | centreon/www/class/config-generate/abstract/JsonFormat.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);
/**
* Class
*
* @class JsonFormat
*/
abstract class JsonFormat
{
/** @var mixed */
protected mixed $cacheData = null;
/** @var string|null */
protected ?string $filePath = null;
/**
* @param mixed $data
*
* @return void
*/
public function setContent(mixed $data): void
{
$this->cacheData = $data;
}
/**
* Defines the path of the file where the data should be written.
*
* @param string $filePath
*/
public function setFilePath(string $filePath): void
{
$this->filePath = $filePath;
}
/**
* Writes the content of the cache only if it is not empty.
*
* @throws Exception
* @return int Number of bytes written
*/
public function flushContent(): int
{
if (empty($this->filePath)) {
throw new Exception('No file path defined');
}
if (! empty($this->cacheData)) {
$data = json_encode($this->cacheData, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
$this->cacheData = null;
$writtenBytes = file_put_contents($this->filePath, $data);
if ($writtenBytes === false) {
$file = $this->retrieveLastDirectory() . DIRECTORY_SEPARATOR . pathinfo($this->filePath)['basename'];
throw new Exception(
sprintf('Error while writing the \'%s\' file ', $file)
);
}
return $writtenBytes;
}
return 0;
}
/**
* Retrieve the last directory.
* (ex: /var/log/centreon/file.log => centreon)
*
* @return string
*/
private function retrieveLastDirectory(): string
{
if ($this->filePath === null) {
return '';
}
$directories = explode('/', pathinfo($this->filePath)['dirname']);
return array_pop($directories);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate/abstract/service.class.php | centreon/www/class/config-generate/abstract/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
*
*/
use Core\Common\Application\UseCase\VaultTrait;
use Core\Macro\Domain\Model\Macro as MacroDomain;
use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException;
use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
require_once __DIR__ . '/object.class.php';
/**
* Class
*
* @class AbstractService
*/
abstract class AbstractService extends AbstractObject
{
use VaultTrait;
/** @var array */
protected $service_cache;
// no flap_detection_options attribute
/** @var string */
protected $attributes_select = '
service_id,
service_template_model_stm_id,
command_command_id as check_command_id,
command_command_id_arg as check_command_arg,
timeperiod_tp_id as check_period_id,
timeperiod_tp_id2 as notification_period_id,
command_command_id2 as event_handler_id,
command_command_id_arg2 as event_handler_arg,
service_description,
service_alias as name,
display_name,
service_is_volatile as is_volatile,
service_max_check_attempts as max_check_attempts,
service_normal_check_interval as check_interval,
service_retry_check_interval as retry_interval,
service_active_checks_enabled as active_checks_enabled,
service_passive_checks_enabled as passive_checks_enabled,
initial_state,
service_obsess_over_service as obsess_over_service,
service_check_freshness as check_freshness,
service_freshness_threshold as freshness_threshold,
service_event_handler_enabled as event_handler_enabled,
service_low_flap_threshold as low_flap_threshold,
service_high_flap_threshold as high_flap_threshold,
service_flap_detection_enabled as flap_detection_enabled,
service_process_perf_data as process_perf_data,
service_retain_status_information as retain_status_information,
service_retain_nonstatus_information as retain_nonstatus_information,
service_notification_interval as notification_interval,
service_notification_options as notification_options,
service_notifications_enabled as notifications_enabled,
contact_additive_inheritance,
service_use_only_contacts_from_host,
cg_additive_inheritance,
service_first_notification_delay as first_notification_delay,
service_recovery_notification_delay as recovery_notification_delay,
service_stalking_options as stalking_options,
service_register as register,
esi_notes as notes,
esi_notes_url as notes_url,
esi_action_url as action_url,
esi_icon_image as icon_image_id,
esi_icon_image_alt as icon_image_alt,
service_acknowledgement_timeout as acknowledgement_timeout
';
/** @var string[] */
protected $attributes_write = ['host_name', 'service_description', 'display_name', 'contacts', 'contact_groups', 'check_command', 'check_period', 'notification_period', 'event_handler', 'max_check_attempts', 'check_interval', 'retry_interval', 'initial_state', 'freshness_threshold', 'low_flap_threshold', 'high_flap_threshold', 'flap_detection_options', 'notification_interval', 'notification_options', 'first_notification_delay', 'recovery_notification_delay', 'stalking_options', 'register', 'notes', 'notes_url', 'action_url', 'icon_image', 'icon_id', 'icon_image_alt', 'acknowledgement_timeout'];
/** @var string[] */
protected $attributes_default = ['is_volatile', 'active_checks_enabled', 'passive_checks_enabled', 'event_handler_enabled', 'flap_detection_enabled', 'notifications_enabled', 'obsess_over_service', 'check_freshness', 'process_perf_data', 'retain_status_information', 'retain_nonstatus_information'];
/** @var string[] */
protected $attributes_array = [
'use',
'category_tags',
'group_tags',
];
/** @var string[] */
protected $attributes_hash = ['macros'];
/** @var array */
protected $loop_stpl = []; // To be reset
/** @var CentreonDBStatement|null */
protected $stmt_macro = null;
/** @var CentreonDBStatement|null */
protected $stmt_stpl = null;
/** @var CentreonDBStatement|null */
protected $stmt_contact = null;
/** @var CentreonDBStatement|null */
protected $stmt_service = null;
/**
* @param $service_id
* @param $attr
*
* @return mixed|null
*/
public function getString($service_id, $attr)
{
return $this->service_cache[$service_id][$attr] ?? null;
}
/**
* @param $service
*
* @throws PDOException
* @return void
*/
protected function getImages(&$service)
{
$media = Media::getInstance($this->dependencyInjector);
if (! isset($service['icon_image'])) {
$service['icon_image'] = $media->getMediaPathFromId($service['icon_image_id']);
$service['icon_id'] = $service['icon_image_id'];
}
}
/**
* Format Macros for export.
*
* @param array<string, mixed> $service
* @param MacroDomain[] $serviceMacros
*/
protected function formatMacros(array &$service, array $serviceMacros)
{
$service['macros'] = [];
if ($this->isVaultEnabled && $this->readVaultRepository !== null) {
$vaultPathByServices = $this->getVaultPathByResources($serviceMacros);
$vaultData = $this->readVaultRepository->findFromPaths($vaultPathByServices);
foreach ($vaultData as $serviceId => $macros) {
foreach ($macros as $macroName => $value) {
if (str_starts_with($macroName, '_SERVICE')) {
$newName = preg_replace('/^_SERVICE/', '', $macroName);
$vaultData[$serviceId][$newName] = $value;
unset($vaultData[$serviceId][$macroName]);
}
}
}
foreach ($serviceMacros as $serviceMacro) {
$serviceId = $serviceMacro->getOwnerId();
$macroName = $serviceMacro->getName();
if (isset($vaultData[$serviceId][$macroName])) {
$serviceMacro->setValue($vaultData[$serviceId][$macroName]);
}
}
}
foreach ($serviceMacros as $serviceMacro) {
if ($serviceMacro->getOwnerId() === $service['service_id']) {
if ($serviceMacro->shouldBeEncrypted()) {
if ($serviceMacro->isPassword()) {
$service['macros']['_' . $serviceMacro->getName()] = 'encrypt::'
. $this->engineContextEncryption->crypt($serviceMacro->getValue());
} else {
$service['macros']['_' . $serviceMacro->getName()] = 'raw::' . $serviceMacro->getValue();
}
} else {
$service['macros']['_' . $serviceMacro->getName()] = $serviceMacro->getValue();
}
}
}
$service['macros']['_SERVICE_ID'] = $service['service_id'];
}
/**
* @param $service
* @param mixed $serviceTemplateMacros
*
* @throws PDOException
* @return void
*/
protected function getServiceTemplates(&$service, $serviceTemplateMacros = [])
{
$service['use'] = [ServiceTemplate::getInstance($this->dependencyInjector)
->generateFromServiceId($service['service_template_model_stm_id'], $serviceTemplateMacros)];
}
/**
* @param array $service (passing by Reference)
*
* @throws PDOException
*/
protected function getContacts(array &$service): void
{
if (! isset($service['contacts_cache'])) {
$contact = Contact::getInstance($this->dependencyInjector);
$service['contacts_cache'] = $contact->getContactForService($service['service_id']);
}
}
/**
* @param array $service (passing by Reference)
*
* @throws PDOException
*/
protected function getContactGroups(array &$service): void
{
if (! isset($service['contact_groups_cache'])) {
$cg = Contactgroup::getInstance($this->dependencyInjector);
$service['contact_groups_cache'] = $cg->getCgForService($service['service_id']);
}
}
/**
* @param $service_id
* @param $command_label
*
* @return mixed|null
*/
protected function findCommandName($service_id, $command_label)
{
$loop = [];
$services_tpl = ServiceTemplate::getInstance($this->dependencyInjector)->service_cache;
$service_id = $this->service_cache[$service_id]['service_template_model_stm_id'] ?? null;
while (! is_null($service_id)) {
if (isset($loop[$service_id])) {
break;
}
$loop[$service_id] = 1;
if (isset($services_tpl[$service_id][$command_label])
&& ! is_null($services_tpl[$service_id][$command_label])
) {
return $services_tpl[$service_id][$command_label];
}
$service_id = $services_tpl[$service_id]['service_template_model_stm_id'] ?? null;
}
return null;
}
/**
* @param $service
* @param $result_name
* @param $command_id_label
* @param $command_arg_label
*
* @throws LogicException
* @throws PDOException
* @throws ServiceCircularReferenceException
* @throws ServiceNotFoundException
* @return int
*/
protected function getServiceCommand(&$service, $result_name, $command_id_label, $command_arg_label)
{
$command_name = Command::getInstance($this->dependencyInjector)
->generateFromCommandId($service[$command_id_label]);
$command_arg = '';
if (isset($service[$result_name])) {
return 1;
}
$service[$result_name] = $command_name;
if (isset($service[$command_arg_label])
&& ! is_null($service[$command_arg_label])
&& $service[$command_arg_label] != ''
) {
$command_arg = $service[$command_arg_label];
if (is_null($command_name)) {
// Find Command Name in templates
$command_name = $this->findCommandName($service['service_id'], $result_name);
// Can have 'args after'. We replace
if (! is_null($command_name)) {
$command_name = preg_replace('/!.*/', '', $command_name);
$service[$result_name] = $command_name . $command_arg;
}
} else {
$service[$result_name] = $command_name . $command_arg;
}
}
return 0;
}
/**
* @param $service
*
* @throws LogicException
* @throws PDOException
* @throws ServiceCircularReferenceException
* @throws ServiceNotFoundException
* @return void
*/
protected function getServiceCommands(&$service)
{
$this->getServiceCommand($service, 'check_command', 'check_command_id', 'check_command_arg');
$this->getServiceCommand($service, 'event_handler', 'event_handler_id', 'event_handler_arg');
}
/**
* @param $service
*
* @throws PDOException
* @return void
*/
protected function getServicePeriods(&$service)
{
$period = Timeperiod::getInstance($this->dependencyInjector);
// Optional "check_period_id" for Anomaly Detection for instance.
$service['check_period'] = $period->generateFromTimeperiodId($service['check_period_id'] ?? null);
// Mandatory "notification_period_id" field.
$service['notification_period'] = $period->generateFromTimeperiodId($service['notification_period_id']);
}
/**
* @param ServiceCategory $serviceCategory
* @param int $serviceId
*
* @throws PDOException
*/
protected function insertServiceInServiceCategoryMembers(ServiceCategory $serviceCategory, int $serviceId): void
{
$this->service_cache[$serviceId]['serviceCategories']
= $serviceCategory->getServiceCategoriesByServiceId($serviceId);
foreach ($this->service_cache[$serviceId]['serviceCategories'] as $serviceCategoryId) {
if (! is_null($serviceCategoryId)) {
$serviceCategory->insertServiceToServiceCategoryMembers(
$serviceCategoryId,
$serviceId,
$this->service_cache[$serviceId]['service_description']
);
}
}
}
/**
* @param MacroDomain[] $macro
* @return array{int, string} vault path indexed by service id
*/
private function getVaultPathByResources(array $macros): array
{
$vaultPathByResources = [];
foreach ($macros as $macro) {
/**
* Check that the value is a vault path and that we haven't store it already
* As macros are stored by resources in vault. All the macros for the same service has the same vault path
*/
if ($this->isAVaultPath($macro->getValue()) && ! array_key_exists($macro->getOwnerId(), $vaultPathByResources)) {
$vaultPathByResources[$macro->getOwnerId()] = $macro->getValue();
}
}
return $vaultPathByResources;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate/abstract/host.class.php | centreon/www/class/config-generate/abstract/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
*
*/
use Adaptation\Database\Connection\Collection\QueryParameters;
use Adaptation\Database\Connection\ValueObject\QueryParameter;
use Core\Common\Application\UseCase\VaultTrait;
use Core\Macro\Domain\Model\Macro as MacroDomain;
use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException;
use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
require_once __DIR__ . '/object.class.php';
/**
* Class
*
* @class AbstractHost
*/
abstract class AbstractHost extends AbstractObject
{
use VaultTrait;
public const TYPE_HOST = 1;
public const TYPE_TEMPLATE = 0;
public const TYPE_VIRTUAL_HOST = 2;
/** @var array */
protected $hosts;
/** @var string */
protected $attributes_select = '
host_id,
command_command_id as check_command_id,
command_command_id_arg1 as check_command_arg,
timeperiod_tp_id as check_period_id,
timeperiod_tp_id2 as notification_period_id,
command_command_id2 as event_handler_id,
command_command_id_arg2 as event_handler_arg,
host_name,
host_alias as alias,
host_address as address,
display_name,
host_max_check_attempts as max_check_attempts,
host_check_interval as check_interval,
host_retry_check_interval as retry_interval,
host_active_checks_enabled as active_checks_enabled,
host_passive_checks_enabled as passive_checks_enabled,
initial_state,
host_obsess_over_host as obsess_over_host,
host_check_freshness as check_freshness,
host_freshness_threshold as freshness_threshold,
host_event_handler_enabled as event_handler_enabled,
host_low_flap_threshold as low_flap_threshold,
host_high_flap_threshold as high_flap_threshold,
host_flap_detection_enabled as flap_detection_enabled,
flap_detection_options,
host_process_perf_data as process_perf_data,
host_retain_status_information as retain_status_information,
host_retain_nonstatus_information as retain_nonstatus_information,
host_notification_interval as notification_interval,
host_notification_options as notification_options,
host_notifications_enabled as notifications_enabled,
contact_additive_inheritance,
cg_additive_inheritance,
host_first_notification_delay as first_notification_delay,
host_recovery_notification_delay as recovery_notification_delay,
host_stalking_options as stalking_options,
host_snmp_community,
host_snmp_version,
host_register as register,
ehi_notes as notes,
ehi_notes_url as notes_url,
ehi_action_url as action_url,
ehi_icon_image as icon_image_id,
ehi_icon_image_alt as icon_image_alt,
ehi_statusmap_image as statusmap_image_id,
host_location,
host_acknowledgement_timeout as acknowledgement_timeout
';
/** @var string[] */
protected $attributes_write = ['host_name', 'alias', 'address', 'display_name', 'contacts', 'contact_groups', 'check_command', 'check_period', 'notification_period', 'event_handler', 'max_check_attempts', 'check_interval', 'retry_interval', 'initial_state', 'freshness_threshold', 'low_flap_threshold', 'high_flap_threshold', 'flap_detection_options', 'notification_interval', 'notification_options', 'first_notification_delay', 'recovery_notification_delay', 'stalking_options', 'register', 'notes', 'notes_url', 'action_url', 'icon_image', 'icon_id', 'icon_image_alt', 'statusmap_image', 'timezone', 'acknowledgement_timeout'];
/** @var string[] */
protected $attributes_default = ['active_checks_enabled', 'passive_checks_enabled', 'event_handler_enabled', 'flap_detection_enabled', 'notifications_enabled', 'obsess_over_host', 'check_freshness', 'process_perf_data', 'retain_status_information', 'retain_nonstatus_information'];
/** @var string[] */
protected $attributes_array = [
'use',
'parents',
'category_tags',
'group_tags',
];
/** @var string[] */
protected $attributes_hash = ['macros'];
/** @var array */
protected $loop_htpl = []; // To be reset
/** @var null */
protected $stmt_macro = null;
/** @var null */
protected $stmt_htpl = null;
/** @var null */
protected $stmt_contact = null;
/** @var null */
protected $stmt_cg = null;
/**
* @param $host_id
* @param $host_tpl_id
*
* @return int
*/
public function isHostTemplate($host_id, $host_tpl_id)
{
$loop = [];
$stack = [];
$hosts_tpl = HostTemplate::getInstance($this->dependencyInjector)->hosts;
$stack = $this->hosts[$host_id]['htpl'];
while (($host_id = array_shift($stack))) {
if (isset($loop[$host_id])) {
continue;
}
$loop[$host_id] = 1;
if ($host_id == $host_tpl_id) {
return 1;
}
$stack = array_merge($hosts_tpl[$host_id]['htpl'], $stack);
}
return 0;
}
/**
* @param $host_id
* @param $attr
*
* @return mixed|null
*/
public function getString($host_id, $attr)
{
return $this->hosts[$host_id][$attr] ?? null;
}
/**
* @param HostCategory $hostCategory
* @param array<string,mixed> $host
*
* @throws PDOException
*/
public function insertHostInHostCategoryMembers(HostCategory $hostCategory, array &$host): void
{
$host['hostCategories'] = $this->getHostCategoriesByHost($host);
foreach ($host['hostCategories'] as $hostCategoryId) {
$hostCategory->insertHostToCategoryMembers(
$hostCategoryId,
$host['host_id'],
$host['name'] ?? $host['host_name']
);
}
}
/**
* @param int $hostId
* @param int|null $hostType
*
* @throws PDOException
* @return mixed
*/
protected function getHostById(int $hostId, ?int $hostType = self::TYPE_HOST)
{
$query = "SELECT {$this->attributes_select}
FROM host
LEFT JOIN extended_host_information
ON extended_host_information.host_host_id = host.host_id
WHERE host.host_id = :host_id
AND host.host_activate = '1'";
if (! is_null($hostType)) {
$query .= ' AND host.host_register = :host_register';
}
$stmt = $this->backend_instance->db->prepare($query);
$stmt->bindParam(':host_id', $hostId, PDO::PARAM_INT);
if (! is_null($hostType)) {
// host_register is an enum
$stmt->bindParam(':host_register', $hostType, PDO::PARAM_STR);
}
$stmt->execute();
return $stmt->fetch(PDO::FETCH_ASSOC);
}
/**
* @param $host
*
* @throws PDOException
* @return void
*/
protected function getImages(&$host)
{
$media = Media::getInstance($this->dependencyInjector);
if (! isset($host['icon_image'])) {
$host['icon_image'] = $media->getMediaPathFromId($host['icon_image_id']);
$host['icon_id'] = $host['icon_image_id'];
}
if (! isset($host['statusmap_image'])) {
$host['statusmap_image'] = $media->getMediaPathFromId($host['statusmap_image_id']);
}
}
/**
* @param array $host
* @param bool $generate
* @param Macro[] $hostTemplateMacros
*
* @throws LogicException
* @throws PDOException
* @throws ServiceCircularReferenceException
* @throws ServiceNotFoundException
*/
protected function getHostTemplates(array &$host, bool $generate = true, array $hostTemplateMacros = []): void
{
if (! isset($host['htpl'])) {
if (is_null($this->stmt_htpl)) {
$this->stmt_htpl = $this->backend_instance->db->prepare('
SELECT host_tpl_id
FROM host_template_relation
WHERE host_host_id = :host_id
ORDER BY `order` ASC
');
}
$this->stmt_htpl->bindParam(':host_id', $host['host_id'], PDO::PARAM_INT);
$this->stmt_htpl->execute();
$host['htpl'] = $this->stmt_htpl->fetchAll(PDO::FETCH_COLUMN);
}
if (! $generate) {
return;
}
$hostTemplate = HostTemplate::getInstance($this->dependencyInjector);
$host['use'] = [];
foreach ($host['htpl'] as $templateId) {
$host['use'][] = $hostTemplate->generateFromHostId($templateId, $hostTemplateMacros);
}
}
/**
* Format Macros for export.
* Warning: is to be run BEFORE running getSeverity to not override severity export.
*
* @param array<string, mixed> $host
* @param MacroDomain[] $hostMacros
*/
protected function formatMacros(array &$host, array $hostMacros)
{
$host['macros'] = [];
if ($this->isVaultEnabled && $this->readVaultRepository !== null) {
$vaultPathByHosts = $this->getVaultPathByResources(
$hostMacros,
$host['host_id'],
$host['host_snmp_community'] ?? null
);
$vaultData = $this->readVaultRepository->findFromPaths($vaultPathByHosts);
foreach ($vaultData as $hostId => $macros) {
foreach ($macros as $macroName => $value) {
if (str_starts_with($macroName, '_HOST')) {
$newName = preg_replace('/^_HOST/', '', $macroName);
$vaultData[$hostId][$newName] = $value;
unset($vaultData[$hostId][$macroName]);
}
}
}
// Set macro values
foreach ($hostMacros as $hostMacro) {
$hostId = $hostMacro->getOwnerId();
$macroName = $hostMacro->getName();
if (isset($vaultData[$hostId][$macroName])) {
$hostMacro->setValue($vaultData[$hostId][$macroName]);
}
}
}
foreach ($hostMacros as $hostMacro) {
if ($hostMacro->getOwnerId() === $host['host_id']) {
if ($hostMacro->shouldBeEncrypted()) {
if ($hostMacro->isPassword()) {
$host['macros']['_' . $hostMacro->getName()] = 'encrypt::'
. $this->engineContextEncryption->crypt($hostMacro->getValue());
} else {
$host['macros']['_' . $hostMacro->getName()] = 'raw::' . $hostMacro->getValue();
}
} else {
$host['macros']['_' . $hostMacro->getName()] = $hostMacro->getValue();
}
}
}
if (isset($host['host_snmp_community'])) {
$snmpCommunity = $vaultData[$host['host_id']]['SNMPCOMMUNITY'] ?? $host['host_snmp_community'];
$shouldEncrypt = $this->backend_instance->db->fetchAssociative(
<<<'SQL'
SELECT 1 FROM nagios_server ns
INNER JOIN ns_host_relation nsr
ON ns.id = nsr.nagios_server_id
WHERE nsr.host_host_id = :hostId
AND ns.is_encryption_ready = 1
SQL,
QueryParameters::create([QueryParameter::int('hostId', $host['host_id'])])
);
$host['macros']['_SNMPCOMMUNITY'] = $shouldEncrypt !== false
? 'encrypt::' . $this->engineContextEncryption->crypt($snmpCommunity)
: $snmpCommunity;
}
if (! is_null($host['host_snmp_version']) && $host['host_snmp_version'] !== '0') {
$host['macros']['_SNMPVERSION'] = $host['host_snmp_version'];
}
$host['macros']['_HOST_ID'] = $host['host_id'];
}
/**
* @param array $host (passing by Reference)
*
* @throws PDOException
*/
protected function getContacts(array &$host): void
{
if (! isset($host['contacts_cache'])) {
if (is_null($this->stmt_contact)) {
$this->stmt_contact = $this->backend_instance->db->prepare("
SELECT chr.contact_id
FROM contact_host_relation chr, contact
WHERE host_host_id = :host_id
AND chr.contact_id = contact.contact_id
AND contact.contact_activate = '1'
");
}
$this->stmt_contact->bindParam(':host_id', $host['host_id'], PDO::PARAM_INT);
$this->stmt_contact->execute();
$host['contacts_cache'] = $this->stmt_contact->fetchAll(PDO::FETCH_COLUMN);
}
}
/**
* @param array $host (passing by Reference)
*
* @throws PDOException
*/
protected function getContactGroups(array &$host): void
{
if (! isset($host['contact_groups_cache'])) {
if (is_null($this->stmt_cg)) {
$this->stmt_cg = $this->backend_instance->db->prepare("
SELECT contactgroup_cg_id
FROM contactgroup_host_relation, contactgroup
WHERE host_host_id = :host_id
AND contactgroup_cg_id = cg_id
AND cg_activate = '1'
");
}
$this->stmt_cg->bindParam(':host_id', $host['host_id'], PDO::PARAM_INT);
$this->stmt_cg->execute();
$host['contact_groups_cache'] = $this->stmt_cg->fetchAll(PDO::FETCH_COLUMN);
}
}
/**
* @param $host_id
* @param $command_label
*
* @return mixed|null
*/
protected function findCommandName($host_id, $command_label)
{
$loop = [];
$stack = [];
$hosts_tpl = HostTemplate::getInstance($this->dependencyInjector)->hosts;
$stack = $this->hosts[$host_id]['htpl'];
while (($host_id = array_shift($stack))) {
if (isset($loop[$host_id])) {
continue;
}
$loop[$host_id] = 1;
if (isset($hosts_tpl[$host_id][$command_label]) && ! is_null($hosts_tpl[$host_id][$command_label])) {
return $hosts_tpl[$host_id][$command_label];
}
$stack = array_merge($hosts_tpl[$host_id]['htpl'], $stack);
}
return null;
}
/**
* @param $host
*
* @throws PDOException
* @return void
*/
protected function getHostTimezone(&$host)
{
$oTimezone = Timezone::getInstance($this->dependencyInjector);
$timezone = $oTimezone->getTimezoneFromId($host['host_location']);
if (! is_null($timezone)) {
$host['timezone'] = ':' . $timezone;
}
}
/**
* @param $host
* @param $result_name
* @param $command_id_label
* @param $command_arg_label
*
* @throws LogicException
* @throws PDOException
* @throws ServiceCircularReferenceException
* @throws ServiceNotFoundException
* @return int
*/
protected function getHostCommand(&$host, $result_name, $command_id_label, $command_arg_label)
{
$command_name = Command::getInstance($this->dependencyInjector)
->generateFromCommandId($host[$command_id_label]);
$command_arg = '';
if (isset($host[$result_name])) {
return 1;
}
$host[$result_name] = $command_name;
if (isset($host[$command_arg_label])
&& ! is_null($host[$command_arg_label]) && $host[$command_arg_label] != ''
) {
$command_arg = $host[$command_arg_label];
if (is_null($command_name)) {
// Find Command Name in templates
$command_name = $this->findCommandName($host['host_id'], $result_name);
// Can have 'args after'. We replace
if (! is_null($command_name)) {
$command_name = preg_replace('/!.*/', '', $command_name);
$host[$result_name] = $command_name . $command_arg;
}
} else {
$host[$result_name] = $command_name . $command_arg;
}
}
return 0;
}
/**
* @param $host
*
* @throws LogicException
* @throws PDOException
* @throws ServiceCircularReferenceException
* @throws ServiceNotFoundException
* @return void
*/
protected function getHostCommands(&$host)
{
$this->getHostCommand($host, 'check_command', 'check_command_id', 'check_command_arg');
$this->getHostCommand($host, 'event_handler', 'event_handler_id', 'event_handler_arg');
}
/**
* @param $host
*
* @throws PDOException
* @return void
*/
protected function getHostPeriods(&$host)
{
$period = Timeperiod::getInstance($this->dependencyInjector);
$host['check_period'] = $period->generateFromTimeperiodId($host['check_period_id']);
$host['notification_period'] = $period->generateFromTimeperiodId($host['notification_period_id']);
}
/**
* @param array<string,mixed> $host
*
* @throws PDOException
* @return array<string,mixed>
*/
private function getHostCategoriesByHost(array $host): array
{
if (isset($host['hostCategories'])) {
return $host['hostCategories'];
}
$stmt = $this->backend_instance->db->prepare(
'SELECT hostcategories_hc_id
FROM hostcategories_relation
WHERE host_host_id = :host_id'
);
$stmt->bindParam(':host_id', $host['host_id'], PDO::PARAM_INT);
$stmt->execute();
return $stmt->fetchAll(PDO::FETCH_COLUMN);
}
/**
* Retrieves a mapping of resource IDs to their vault paths from macros and SNMP community.
*
* @param MacroDomain[] $macros
* @param int $hostId
* @param string|null $snmpCommunity
* @return array<int, string> Vault path indexed by resource (host) ID
*/
private function getVaultPathByResources(array $macros, int $hostId, ?string $snmpCommunity = null): array
{
$vaultPathByResources = [];
// Collect vault paths from macros
foreach ($macros as $macro) {
$ownerId = $macro->getOwnerId();
$value = $macro->getValue();
// Store the vault path if not already stored for this owner
if ($this->isAVaultPath($value) && ! isset($vaultPathByResources[$ownerId])) {
$vaultPathByResources[$ownerId] = $value;
}
}
// If no vault path found in macros, check SNMP community
if ($vaultPathByResources === [] && $snmpCommunity !== null) {
if ($this->isAVaultPath($snmpCommunity)) {
$vaultPathByResources[$hostId] = $snmpCommunity;
}
}
return $vaultPathByResources;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate/abstract/objectJSON.class.php | centreon/www/class/config-generate/abstract/objectJSON.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 Core\Common\Application\Repository\ReadVaultRepositoryInterface;
use Core\Common\Infrastructure\FeatureFlags;
use Core\Security\Vault\Application\Repository\ReadVaultConfigurationRepositoryInterface;
use Pimple\Container;
use Security\Interfaces\EncryptionInterface;
use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException;
use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
/**
* Class
*
* @class AbstractObjectJSON
*/
abstract class AbstractObjectJSON
{
/** @var Backend|null */
protected $backend_instance = null;
/** @var string|null */
protected $generate_filename = null;
/** @var Container */
protected $dependencyInjector;
/** @var array */
protected $content = [];
/** @var bool */
protected $isVaultEnabled = false;
/** @var null|ReadVaultRepositoryInterface */
protected $readVaultRepository = null;
protected Kernel $kernel;
protected EncryptionInterface $engineContextEncryption;
/**
* AbstractObjectJSON constructor
*
* @param Container $dependencyInjector
*/
protected function __construct(Container $dependencyInjector)
{
$this->kernel = Kernel::createForWeb();
$this->dependencyInjector = $dependencyInjector;
$this->backend_instance = Backend::getInstance($this->dependencyInjector);
$this->engineContextEncryption = $this->kernel->getContainer()->get(EncryptionInterface::class);
$engineContext = file_get_contents('/etc/centreon-engine/engine-context.json');
try {
$this->getVaultConfigurationStatus();
if ($engineContext === false || empty($engineContext)) {
CentreonLog::create()->error(
logTypeId: CentreonLog::TYPE_BUSINESS_LOG,
message: "Unable to parse content of '/etc/centreon-engine/engine-context.json'"
);
throw new RuntimeException('/etc/centreon/engine-context.json does not exists or is empty');
}
$engineContext = json_decode($engineContext, true, flags: JSON_THROW_ON_ERROR);
$this->engineContextEncryption->setSecondKey($engineContext['salt']);
} catch (JsonException|RuntimeException $ex) {
CentreonLog::create()->error(
logTypeId: CentreonLog::TYPE_BUSINESS_LOG,
message: "Unable to parse content of '/etc/centreon-engine/engine-context.json'",
exception: $ex
);
throw $ex;
} catch (ServiceCircularReferenceException|ServiceNotFoundException $ex) {
CentreonLog::create()->error(
logTypeId: CentreonLog::TYPE_BUSINESS_LOG,
message: 'Unable to get Vault configuration status',
exception: $ex
);
throw $ex;
}
}
/**
* @param Container $dependencyInjector
* @return static
*/
public static function getInstance(Container $dependencyInjector): static
{
/**
* @var array<string, static>
*/
static $instances = [];
/**
* @var class-string<static>
*/
$calledClass = static::class;
if (! isset($instances[$calledClass])) {
$instances[$calledClass] = new $calledClass($dependencyInjector);
}
return $instances[$calledClass];
}
/**
* @return void
*/
public function reset()
{
}
/**
* @param $dir
*
* @throws RuntimeException
* @return void
*/
protected function writeFile($dir)
{
$full_file = $dir . '/' . $this->generate_filename;
if ($handle = fopen($full_file, 'w')) {
if (! fwrite($handle, $this->content)) {
throw new RuntimeException('Cannot write to file "' . $full_file . '"');
}
fclose($handle);
} else {
throw new Exception('Cannot open file ' . $full_file);
}
}
/**
* @param $object
* @param $brokerType
*
* @return void
*/
protected function generateFile($object, $brokerType = true): void
{
$data = $brokerType ? ['centreonBroker' => $object] : $object;
$this->content = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
}
/**
* Get Centreon Vault Configuration Status
*
* @throws ServiceCircularReferenceException
* @throws ServiceNotFoundException
* @return void
*/
private function getVaultConfigurationStatus(): void
{
$readVaultConfigurationRepository = $this->kernel->getContainer()->get(ReadVaultConfigurationRepositoryInterface::class);
$featureFlag = $this->kernel->getContainer()->get(FeatureFlags::class);
$vaultConfiguration = $readVaultConfigurationRepository->find();
if ($vaultConfiguration !== null && $featureFlag->isEnabled('vault')) {
$this->isVaultEnabled = true;
$this->readVaultRepository = $this->kernel->getContainer()->get(ReadVaultRepositoryInterface::class);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/config-generate/Interface/ExternalModuleGenerationInterface.php | centreon/www/class/config-generate/Interface/ExternalModuleGenerationInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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);
/**
* Interface
*
* @class ExternalModuleGenerationInterface
*/
interface ExternalModuleGenerationInterface
{
/**
* Indicates if this class is designed to generate something for Engine.
*
* @return bool
*/
public function isEngineObject(): bool;
/**
* Indicates if this class is designed to generate something for Broker.
*
* @return bool
*/
public function isBrokerObject(): bool;
/**
* @param int $pollerId
* @param bool $isLocalhost
*/
public function generateFromPollerId(int $pollerId, bool $isLocalhost): void;
/**
* @return void
*/
public function reset(): void;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreon-knowledge/wikiApi.class.php | centreon/www/class/centreon-knowledge/wikiApi.class.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
require_once realpath(__DIR__ . '/../../../config/centreon.config.php');
require_once _CENTREON_PATH_ . '/www/class/centreonDB.class.php';
require_once _CENTREON_PATH_ . '/www/class/centreon-knowledge/wiki.class.php';
/**
* Class
*
* @class WikiApi
*/
class WikiApi
{
public const PROXY_URL = './include/configuration/configKnowledge/proxy/proxy.php';
/** @var never[] */
public $cookies = [];
/** @var CentreonDB */
private $db;
/** @var Wiki */
private $wikiObj;
/** @var string */
private $url;
/** @var string */
private $username;
/** @var string */
private $password;
/** @var float */
private $version;
/** @var CurlHandle|false */
private $curl;
/** @var bool */
private $loggedIn;
/** @var array */
private $tokens;
/** @var mixed */
private $noSslCertificate;
/**
* WikiApi constructor.
*/
public function __construct()
{
$this->db = new CentreonDB();
$this->wikiObj = new Wiki();
$config = $this->wikiObj->getWikiConfig();
$this->url = $config['kb_wiki_url'] . '/api.php';
$this->username = $config['kb_wiki_account'];
$this->password = $config['kb_wiki_password'];
$this->noSslCertificate = $config['kb_wiki_certificate'];
$this->curl = $this->getCurl();
$this->version = $this->getWikiVersion();
}
/**
* @throws Exception
* @return float
*/
public function getWikiVersion()
{
$postfields = ['action' => 'query', 'meta' => 'siteinfo', 'format' => 'json'];
curl_setopt($this->curl, CURLOPT_POSTFIELDS, $postfields);
$result = curl_exec($this->curl);
$result = json_decode($result, true);
$version = $result['query']['general']['generator'];
$version = explode(' ', $version);
if (isset($version[1])) {
return (float) $version[1];
}
throw new Exception('An error occured, please check your Knowledge base configuration');
}
/**
* @throws Exception
* @return bool
*/
public function login()
{
if ($this->loggedIn) {
return $this->loggedIn;
}
// Get Connection Cookie/Token
$postfields = ['action' => 'query', 'meta' => 'tokens', 'format' => 'json', 'type' => 'login'];
curl_setopt($this->curl, CURLOPT_POSTFIELDS, $postfields);
$result = curl_exec($this->curl);
if ($result === false) {
throw new Exception('curl error');
}
$decoded = json_decode($result, true);
$token = $decoded['query']['tokens']['logintoken'];
// Launch Connection
$postfields = [
'action' => 'login',
'lgname' => $this->username,
'format' => 'json',
];
$postfields['lgpassword'] = $this->password;
$postfields['lgtoken'] = $token;
curl_setopt($this->curl, CURLOPT_POSTFIELDS, $postfields);
$result = curl_exec($this->curl);
if ($result === false) {
throw new Exception('curl error');
}
$decoded = json_decode($result, true);
$resultLogin = $decoded['login']['result'];
$this->loggedIn = false;
if ($resultLogin == 'Success') {
$this->loggedIn = true;
}
return $this->loggedIn;
}
/**
* @return void
*/
public function logout(): void
{
$postfields = ['action' => 'logout'];
curl_setopt($this->curl, CURLOPT_POSTFIELDS, $postfields);
curl_exec($this->curl);
}
/**
* @param $method
* @param $title
*
* @return mixed
*/
public function getMethodToken($method = 'delete', $title = '')
{
if ($this->version >= 1.24) {
$postfields = ['action' => 'query', 'meta' => 'tokens', 'type' => 'csrf', 'format' => 'json'];
} elseif ($this->version >= 1.20) {
$postfields = ['action' => 'tokens', 'type' => $method, 'format' => 'json'];
} else {
$postfields = ['action' => 'query', 'prop' => 'info', 'intoken' => $method, 'format' => 'json', 'titles' => $title];
}
curl_setopt($this->curl, CURLOPT_POSTFIELDS, $postfields);
$result = curl_exec($this->curl);
$result = json_decode($result, true);
if ($this->version >= 1.24) {
$this->tokens[$method] = $result['query']['tokens']['csrftoken'];
} elseif ($this->version >= 1.20) {
$this->tokens[$method] = $result['tokens'][$method . 'token'];
} else {
$page = array_pop($result['query']['pages']);
$this->tokens[$method] = $page[$method . 'token'];
}
return $this->tokens[$method];
}
/**
* @param $oldTitle
* @param $newTitle
*
* @throws Exception
* @return true
*/
public function movePage($oldTitle = '', $newTitle = '')
{
$this->login();
$token = $this->getMethodToken('move', $oldTitle);
$postfields = ['action' => 'move', 'from' => $oldTitle, 'to' => $newTitle, 'token' => $token];
curl_setopt($this->curl, CURLOPT_POSTFIELDS, $postfields);
curl_exec($this->curl);
return true;
}
/**
* API Endpoint for deleting Knowledgebase Page
*
* @param string $title
*
* @throws Exception
* @return bool
*/
public function deletePage($title = '')
{
$tries = 0;
$deleteResult = $this->deleteMWPage($title);
while ($tries < 5 && isset($deleteResult->error)) {
$deleteResult = $this->deleteMWPage($title);
$tries++;
}
if (isset($deleteResult->error)) {
return false;
}
return (bool) (isset($deleteResult->delete));
}
/**
* @return array
*/
public function getAllPages()
{
$postfields = ['format' => 'json', 'action' => 'query', 'list' => 'allpages', 'aplimit' => '200'];
$pages = [];
do {
curl_setopt($this->curl, CURLOPT_POSTFIELDS, $postfields);
$result = curl_exec($this->curl);
$result = json_decode($result);
foreach ($result->query->allpages as $page) {
$pages[] = $page->title;
}
// Get next page if exists
$continue = false;
if ($this->version >= 1.31) {
if (isset($result->{'continue'}->apcontinue)) {
$postfields['apfrom'] = $result->{'continue'}->apcontinue;
$continue = true;
}
} elseif (isset($result->{'query-continue'}->allpages->apcontinue)) {
$postfields['apfrom'] = $result->{'query-continue'}->allpages->apcontinue;
$continue = true;
}
} while ($continue === true);
return $pages;
}
/**
* @param int $count
* @return mixed
*/
public function getChangedPages($count = 50)
{
// Connecting to Mediawiki API
$postfields = ['format' => 'json', 'action' => 'query', 'list' => 'recentchanges', 'rclimit' => $count, 'rcprop' => 'title', 'rctype' => 'new|edit'];
curl_setopt($this->curl, CURLOPT_POSTFIELDS, $postfields);
$result = curl_exec($this->curl);
$result = json_decode($result);
return $result->query->recentchanges;
}
/**
* @return array
*/
public function detectCentreonObjects()
{
$pages = $this->getChangedPages();
$hosts = [];
$hostsTemplates = [];
$services = [];
$servicesTemplates = [];
$count = count($pages);
for ($i = 0; $i < $count; $i++) {
$objectFlag = explode(':', $pages[$i]->title);
$type = trim($objectFlag[0]);
switch ($type) {
case 'Host':
if (! in_array($pages[$i]->title, $hosts)) {
$hosts[] = $pages[$i]->title;
}
break;
case 'Host-Template':
if (! in_array($pages[$i]->title, $hostsTemplates)) {
$hostsTemplates[] = $pages[$i]->title;
}
break;
case 'Service':
if (! in_array($pages[$i]->title, $services)) {
$services[] = $pages[$i]->title;
}
break;
case 'Service-Template':
if (! in_array($pages[$i]->title, $servicesTemplates)) {
$servicesTemplates[] = $pages[$i]->title;
}
break;
}
}
return ['hosts' => $hosts, 'hostTemplates' => $hostsTemplates, 'services' => $services, 'serviceTemplates' => $servicesTemplates];
}
/**
* @throws PDOException
* @return void
*/
public function synchronize(): void
{
// Get all pages title that where changed
$listOfObjects = $this->detectCentreonObjects();
foreach ($listOfObjects as $categorie => $object) {
switch ($categorie) {
case 'hosts':
foreach ($object as $entity) {
$objName = str_replace('Host : ', '', $entity);
$objName = str_replace(' ', '_', $objName);
$this->updateLinkForHost($objName);
}
break;
case 'hostTemplates':
foreach ($object as $entity) {
$objName = str_replace('Host-Template : ', '', $entity);
$objName = str_replace(' ', '_', $objName);
$this->updateLinkForHost($objName);
}
break;
case 'services':
foreach ($object as $entity) {
$objName = str_replace('Service : ', '', $entity);
$objName = str_replace(' ', '_', $objName);
if (preg_match('#(.+)_/_(.+)#', $objName, $matches)) {
$this->updateLinkForService($matches[1], $matches[2]);
}
}
break;
case 'serviceTemplates':
foreach ($object as $entity) {
$objName = str_replace('Service-Template : ', '', $entity);
$objName = str_replace(' ', '_', $objName);
$this->updateLinkForServiceTemplate($objName);
}
break;
}
}
}
/**
* @param $hostName
*
* @throws PDOException
*/
public function updateLinkForHost($hostName): void
{
$resHost = $this->db->query(
"SELECT host_id FROM host WHERE host_name LIKE '" . $hostName . "'"
);
$hostRow = $resHost->fetch();
if ($hostRow !== false) {
$url = self::PROXY_URL . '?host_name=$HOSTNAME$';
$statement = $this->db->prepare(
'UPDATE extended_host_information '
. 'SET ehi_notes_url = :url '
. 'WHERE host_host_id = :hostId'
);
$statement->bindValue(':url', $url, PDO::PARAM_STR);
$statement->bindValue(':hostId', $hostRow['host_id'], PDO::PARAM_INT);
$statement->execute();
}
}
/**
* @param $hostName
* @param $serviceDescription
*
* @throws PDOException
*/
public function updateLinkForService($hostName, $serviceDescription): void
{
$resService = $this->db->query(
'SELECT service_id '
. 'FROM service, host, host_service_relation '
. "WHERE host.host_name LIKE '" . $hostName . "' "
. "AND service.service_description LIKE '" . $serviceDescription . "' "
. 'AND host_service_relation.host_host_id = host.host_id '
. 'AND host_service_relation.service_service_id = service.service_id '
);
$serviceRow = $resService->fetch();
if ($serviceRow !== false) {
$url = self::PROXY_URL . '?host_name=$HOSTNAME$&service_description=$SERVICEDESC$';
$statement = $this->db->prepare(
'UPDATE extended_service_information '
. 'SET esi_notes_url = :url '
. 'WHERE service_service_id = :serviceId'
);
$statement->bindValue(':url', $url, PDO::PARAM_STR);
$statement->bindValue(':serviceId', $serviceRow['service_id'], PDO::PARAM_INT);
$statement->execute();
}
}
/**
* @param $serviceName
*
* @throws PDOException
*/
public function updateLinkForServiceTemplate($serviceName): void
{
$resService = $this->db->query(
'SELECT service_id FROM service '
. "WHERE service_description LIKE '" . $serviceName . "' "
);
$serviceTemplateRow = $resService->fetch();
if ($serviceTemplateRow !== false) {
$url = self::PROXY_URL . '?host_name=$HOSTNAME$&service_description=$SERVICEDESC$';
$statement = $this->db->prepare(
'UPDATE extended_service_information '
. 'SET esi_notes_url = :url '
. 'WHERE service_service_id = :serviceId'
);
$statement->bindValue(':url', $url, PDO::PARAM_STR);
$statement->bindValue(':serviceId', $serviceTemplateRow['service_id'], PDO::PARAM_INT);
$statement->execute();
}
}
/**
* @return CurlHandle|false
*/
private function getCurl()
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $this->url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_COOKIEFILE, '');
if ($this->noSslCertificate == 1) {
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
}
return $curl;
}
/**
* make a call to mediawiki api to delete a page
*
* @param string $title
*
* @throws Exception
* @return object
*/
private function deleteMWPage($title = '')
{
$this->login();
$token = $this->getMethodToken('delete', $title);
$postfields = ['action' => 'delete', 'title' => $title, 'token' => $token, 'format' => 'json'];
curl_setopt($this->curl, CURLOPT_POSTFIELDS, $postfields);
$result = curl_exec($this->curl);
return json_decode($result);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreon-knowledge/wiki.class.php | centreon/www/class/centreon-knowledge/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_ . '/bootstrap.php';
require_once realpath(__DIR__ . '/../../../config/centreon.config.php');
require_once _CENTREON_PATH_ . '/www/class/centreonDB.class.php';
require_once __DIR__ . '/../../include/common/vault-functions.php';
use App\Kernel;
use Core\Common\Application\Repository\ReadVaultRepositoryInterface;
use Core\Security\Vault\Application\Repository\ReadVaultConfigurationRepositoryInterface;
use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException;
use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
/**
* Class
*
* @class Wiki
*/
class Wiki
{
/** @var CentreonDB */
private $db;
/** @var array */
private $config = null;
/**
* Wiki constructor
*
* @throws LogicException
* @throws PDOException
* @throws Throwable
* @throws ServiceCircularReferenceException
* @throws ServiceNotFoundException
*/
public function __construct()
{
$this->db = new CentreonDB();
$this->config = $this->getWikiConfig();
}
/**
* @throws LogicException
* @throws PDOException
* @throws Throwable
* @throws ServiceCircularReferenceException
* @throws ServiceNotFoundException
* @return array|mixed
*/
public function getWikiConfig()
{
if (! is_null($this->config)) {
return $this->config;
}
$options = [];
$res = $this->db->query(
"SELECT * FROM `options` WHERE options.key LIKE 'kb_%'"
);
while ($opt = $res->fetch()) {
$options[$opt['key']] = html_entity_decode($opt['value'], ENT_QUOTES, 'UTF-8');
}
$res->closeCursor();
if (! isset($options['kb_wiki_url']) || $options['kb_wiki_url'] == '') {
throw new Exception(
'Wiki is not configured. '
. 'You can disable cron in /etc/cron.d/centreon for wiki synchronization.'
);
}
if (! preg_match('#^http://|https://#', $options['kb_wiki_url'])) {
$options['kb_wiki_url'] = 'http://' . $options['kb_wiki_url'];
}
if (isset($options['kb_wiki_password']) && str_starts_with($options['kb_wiki_password'], 'secret::')) {
$kernel = Kernel::createForWeb();
$readVaultConfigurationRepository = $kernel->getContainer()->get(
ReadVaultConfigurationRepositoryInterface::class
);
$vaultConfiguration = $readVaultConfigurationRepository->find();
if ($vaultConfiguration !== null) {
/** @var ReadVaultRepositoryInterface $readVaultRepository */
$readVaultRepository = $kernel->getContainer()->get(ReadVaultRepositoryInterface::class);
$options['kb_wiki_password'] = findKnowledgeBasePasswordFromVault(
$readVaultRepository,
$options['kb_wiki_password']
);
}
}
return $options;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreon-knowledge/ProceduresProxy.class.php | centreon/www/class/centreon-knowledge/ProceduresProxy.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/include/configuration/configKnowledge/functions.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/centreon-knowledge/wikiApi.class.php';
/**
* Class
*
* @class ProceduresProxy
*/
class ProceduresProxy
{
/** @var procedures */
public $proc;
/** @var CentreonDB */
private $DB;
/** @var mixed */
private $wikiUrl;
/** @var CentreonHost */
private $hostObj;
/** @var CentreonService */
private $serviceObj;
/**
* ProceduresProxy constructor
*
* @param CentreonDB $pearDB
*
* @throws PDOException
*/
public function __construct($pearDB)
{
$this->DB = $pearDB;
$this->hostObj = new CentreonHost($this->DB);
$this->serviceObj = new CentreonService($this->DB);
$conf = getWikiConfig($this->DB);
$this->wikiUrl = $conf['kb_wiki_url'];
$this->proc = new procedures($this->DB);
}
/**
* Get host url
*
* @param string $hostName
*
* @throws PDOException
* @return string|null
*/
public function getHostUrl($hostName): ?string
{
$hostId = $this->getHostId($hostName);
if ($hostId === null) {
return null;
}
$hostProperties = $this->hostObj->getInheritedValues(
$hostId,
[],
1,
['host_name', 'ehi_notes_url']
);
if (isset($hostProperties['ehi_notes_url'])) {
return $this->wikiUrl . '/index.php?title=Host_:_' . $hostProperties['host_name'];
}
$templates = $this->hostObj->getTemplateChain($hostId);
foreach ($templates as $template) {
$inheritedHostProperties = $this->hostObj->getInheritedValues(
$template['id'],
[],
1,
['host_name', 'ehi_notes_url']
);
if (isset($inheritedHostProperties['ehi_notes_url'])) {
return $this->wikiUrl . '/index.php?title=Host-Template_:_' . $inheritedHostProperties['host_name'];
}
}
return null;
}
/**
* Get service url
*
* @param string $hostName
* @param string $serviceDescription
*
* @throws PDOException
* @return string|null
*/
public function getServiceUrl($hostName, $serviceDescription): ?string
{
$serviceDescription = str_replace(' ', '_', $serviceDescription);
$serviceId = $this->getServiceId($hostName, $serviceDescription);
if ($serviceId === null) {
return null;
}
// Check Service
$notesUrl = $this->getServiceNotesUrl($serviceId);
if ($notesUrl !== null) {
return $this->wikiUrl . '/index.php?title=Service_:_' . $hostName . '_/_' . $serviceDescription;
}
// Check service Template
$serviceId = $this->getServiceId($hostName, $serviceDescription);
$templates = $this->serviceObj->getTemplatesChain($serviceId);
foreach (array_reverse($templates) as $templateId) {
$templateDescription = $this->serviceObj->getServiceDesc($templateId);
$notesUrl = $this->getServiceNotesUrl((int) $templateId);
if ($notesUrl !== null) {
return $this->wikiUrl . '/index.php?title=Service-Template_:_' . $templateDescription;
}
}
return $this->getHostUrl($hostName);
}
/**
* @param string $hostName
*
* @throws PDOException
* @return int
*/
private function getHostId($hostName)
{
$statement = $this->DB->prepare('SELECT host_id FROM host WHERE host_name LIKE :hostName');
$statement->bindValue(':hostName', $hostName, PDO::PARAM_STR);
$statement->execute();
$hostId = 0;
if ($row = $statement->fetch()) {
$hostId = $row['host_id'];
}
return $hostId;
}
/**
* Get service id from hostname and service description
*
* @param string $hostName
* @param string $serviceDescription
*
* @throws PDOException
* @return int|null
*/
private function getServiceId($hostName, $serviceDescription): ?int
{
// Get Services attached to hosts
$statement = $this->DB->prepare(
'SELECT s.service_id FROM host h, service s, host_service_relation hsr '
. 'WHERE hsr.host_host_id = h.host_id '
. 'AND hsr.service_service_id = service_id '
. 'AND h.host_name LIKE :hostName '
. 'AND s.service_description LIKE :serviceDescription '
);
$statement->bindValue(':hostName', $hostName, PDO::PARAM_STR);
$statement->bindValue(':serviceDescription', $serviceDescription, PDO::PARAM_STR);
$statement->execute();
if ($row = $statement->fetch()) {
return (int) $row['service_id'];
}
$statement->closeCursor();
// Get Services attached to hostgroups
$statement = $this->DB->prepare(
'SELECT s.service_id FROM hostgroup_relation hgr, host h, service s, host_service_relation hsr '
. 'WHERE hgr.host_host_id = h.host_id '
. 'AND hsr.hostgroup_hg_id = hgr.hostgroup_hg_id '
. 'AND h.host_name LIKE :hostName '
. 'AND service_id = hsr.service_service_id '
. 'AND service_description LIKE :serviceDescription '
);
$statement->bindValue(':hostName', $hostName, PDO::PARAM_STR);
$statement->bindValue(':serviceDescription', $serviceDescription, PDO::PARAM_STR);
$statement->execute();
if ($row = $statement->fetch()) {
return (int) $row['service_id'];
}
$statement->closeCursor();
return null;
}
/**
* Get service notes url
*
* @param int $serviceId
*
* @throws PDOException
* @return string|null
*/
private function getServiceNotesUrl(int $serviceId): ?string
{
$notesUrl = null;
$statement = $this->DB->prepare(
'SELECT esi_notes_url '
. 'FROM extended_service_information '
. 'WHERE service_service_id = :serviceId'
);
$statement->bindValue(':serviceId', $serviceId, PDO::PARAM_INT);
$statement->execute();
if ($row = $statement->fetch()) {
$notesUrl = $row['esi_notes_url'];
}
return $notesUrl;
}
}
| 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.