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/src/Centreon/Domain/Repository/ConnectorRepository.php | centreon/src/Centreon/Domain/Repository/ConnectorRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Domain\Repository;
use Centreon\Infrastructure\CentreonLegacyDB\ServiceEntityRepository;
class ConnectorRepository extends ServiceEntityRepository
{
/**
* Export
*
* @param int[] $pollerIds
* @return array
*/
public function export(array $pollerIds): array
{
// prevent SQL exception
if (! $pollerIds) {
return [];
}
$ids = join(',', $pollerIds);
$sql = <<<SQL
SELECT
c1.*
FROM command AS t1
INNER JOIN connector AS c1 ON c1.id = t1.connector_id
INNER JOIN cfg_nagios AS cn1 ON
cn1.global_service_event_handler = t1.command_id OR
cn1.global_host_event_handler = t1.command_id
WHERE
cn1.nagios_id IN ({$ids})
GROUP BY c1.id
UNION
SELECT
c2.*
FROM command AS t2
INNER JOIN connector AS c2 ON c2.id = t2.connector_id
INNER JOIN poller_command_relations AS pcr2 ON pcr2.command_id = t2.command_id
WHERE
pcr2.poller_id IN ({$ids})
GROUP BY c2.id
UNION
SELECT
c3.*
FROM command AS t3
INNER JOIN connector AS c3 ON c3.id = t3.connector_id
INNER JOIN host AS h3 ON
h3.command_command_id = t3.command_id OR
h3.command_command_id2 = t3.command_id
INNER JOIN ns_host_relation AS nhr3 ON nhr3.host_host_id = h3.host_id
WHERE
nhr3.nagios_server_id IN ({$ids})
GROUP BY c3.id
UNION
SELECT
c4.*
FROM command AS t4
INNER JOIN connector AS c4 ON c4.id = t4.connector_id
INNER JOIN host AS h4 ON
h4.command_command_id = t4.command_id OR
h4.command_command_id2 = t4.command_id
INNER JOIN ns_host_relation AS nhr4 ON nhr4.host_host_id = h4.host_id
WHERE
nhr4.nagios_server_id IN ({$ids})
GROUP BY c4.id
UNION
SELECT
c.*
FROM command AS t
INNER JOIN connector AS c ON c.id = t.connector_id
INNER JOIN service AS s ON
s.command_command_id = t.command_id OR
s.command_command_id2 = t.command_id
INNER JOIN host_service_relation AS hsr ON
hsr.service_service_id = s.service_id
LEFT JOIN hostgroup_relation AS hgr ON hgr.hostgroup_hg_id = hsr.hostgroup_hg_id
LEFT JOIN ns_host_relation AS nhr ON
nhr.host_host_id = hsr.host_host_id OR
nhr.host_host_id = hgr.host_host_id
WHERE
nhr.nagios_server_id IN ({$ids})
GROUP BY c.id
SQL;
$stmt = $this->db->prepare($sql);
$stmt->execute();
$result = [];
while ($row = $stmt->fetch()) {
$result[] = $row;
}
return $result;
}
/**
* Export
*
* @param int[] $list
* @return array
*/
public function exportList(array $list): array
{
// prevent SQL exception
if (! $list) {
return [];
}
$ids = join(',', $list);
$sql = <<<SQL
SELECT
c.*
FROM command AS t
INNER JOIN connector AS c ON c.id = t.connector_id
WHERE
t.command_id IN ({$ids})
GROUP BY c.id
SQL;
$stmt = $this->db->prepare($sql);
$stmt->execute();
$result = [];
while ($row = $stmt->fetch()) {
$result[] = $row;
}
return $result;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Repository/AclResourcesMetaRelationsRepository.php | centreon/src/Centreon/Domain/Repository/AclResourcesMetaRelationsRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Domain\Repository;
use Centreon\Domain\Repository\Interfaces\AclResourceRefreshInterface;
use Centreon\Infrastructure\CentreonLegacyDB\ServiceEntityRepository;
class AclResourcesMetaRelationsRepository extends ServiceEntityRepository implements AclResourceRefreshInterface
{
/**
* Refresh
*/
public function refresh(): void
{
$sql = 'DELETE FROM acl_resources_meta_relations '
. 'WHERE meta_id NOT IN (SELECT t2.meta_id FROM meta_service AS t2)';
$stmt = $this->db->prepare($sql);
$stmt->execute();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Repository/DowntimePeriodRepository.php | centreon/src/Centreon/Domain/Repository/DowntimePeriodRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Domain\Repository;
use Centreon\Infrastructure\CentreonLegacyDB\ServiceEntityRepository;
class DowntimePeriodRepository extends ServiceEntityRepository
{
/**
* Export
*
* @param int[] $pollerIds
* @param array $hostTemplateChain
* @param array $serviceTemplateChain
* @return array
*/
public function export(array $pollerIds, ?array $hostTemplateChain = null, ?array $serviceTemplateChain = null): array
{
if (! $pollerIds) {
return [];
}
$sqlFilter = DowntimeRepository::getFilterSql($pollerIds, $hostTemplateChain, $serviceTemplateChain);
$sql = <<<SQL
SELECT
t.*
FROM downtime_period AS t
WHERE t.dt_id IN ({$sqlFilter})
GROUP BY t.dt_id
SQL;
$sql2 = <<<'SQL'
SQL;
$stmt = $this->db->prepare($sql);
$stmt->execute();
$result = [];
while ($row = $stmt->fetch()) {
$result[] = $row;
}
return $result;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Repository/AclResourcesScRelationsRepository.php | centreon/src/Centreon/Domain/Repository/AclResourcesScRelationsRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Domain\Repository;
use Centreon\Domain\Repository\Interfaces\AclResourceRefreshInterface;
use Centreon\Infrastructure\CentreonLegacyDB\ServiceEntityRepository;
class AclResourcesScRelationsRepository extends ServiceEntityRepository implements AclResourceRefreshInterface
{
/**
* Refresh
*/
public function refresh(): void
{
$sql = 'DELETE FROM acl_resources_sc_relations '
. 'WHERE sc_id NOT IN (SELECT t2.sc_id FROM service_categories AS t2)';
$stmt = $this->db->prepare($sql);
$stmt->execute();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Repository/CommandCategoryRepository.php | centreon/src/Centreon/Domain/Repository/CommandCategoryRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Domain\Repository;
use Centreon\Infrastructure\CentreonLegacyDB\ServiceEntityRepository;
class CommandCategoryRepository extends ServiceEntityRepository
{
/**
* Export
*
* @param int[] $pollerIds
* @return array
*/
public function export(array $pollerIds): array
{
// prevent SQL exception
if (! $pollerIds) {
return [];
}
$ids = join(',', $pollerIds);
$sql = <<<SQL
SELECT
cc1.*
FROM command AS t1
INNER JOIN command_categories_relation AS ccr1 ON ccr1.command_command_id = t1.command_id
INNER JOIN command_categories AS cc1 ON cc1.cmd_category_id = ccr1.category_id
INNER JOIN cfg_nagios AS cn1 ON
cn1.global_service_event_handler = t1.command_id OR
cn1.global_host_event_handler = t1.command_id
WHERE
cn1.nagios_id IN ({$ids})
GROUP BY cc1.cmd_category_id
UNION
SELECT
cc2.*
FROM command AS t2
INNER JOIN command_categories_relation AS ccr2 ON ccr2.command_command_id = t2.connector_id
INNER JOIN command_categories AS cc2 ON cc2.cmd_category_id = ccr2.category_id
INNER JOIN poller_command_relations AS pcr2 ON pcr2.command_id = t2.command_id
WHERE
pcr2.poller_id IN ({$ids})
GROUP BY cc2.cmd_category_id
UNION
SELECT
cc3.*
FROM command AS t3
INNER JOIN command_categories_relation AS ccr3 ON ccr3.command_command_id = t3.connector_id
INNER JOIN command_categories AS cc3 ON cc3.cmd_category_id = ccr3.category_id
INNER JOIN host AS h3 ON
h3.command_command_id = t3.command_id OR
h3.command_command_id2 = t3.command_id
INNER JOIN ns_host_relation AS nhr3 ON nhr3.host_host_id = h3.host_id
WHERE
nhr3.nagios_server_id IN ({$ids})
GROUP BY cc3.cmd_category_id
UNION
SELECT
cc4.*
FROM command AS t4
INNER JOIN command_categories_relation AS ccr4 ON ccr4.command_command_id = t4.connector_id
INNER JOIN command_categories AS cc4 ON cc4.cmd_category_id = ccr4.category_id
INNER JOIN host AS h4 ON
h4.command_command_id = t4.command_id OR
h4.command_command_id2 = t4.command_id
INNER JOIN ns_host_relation AS nhr4 ON nhr4.host_host_id = h4.host_id
WHERE
nhr4.nagios_server_id IN ({$ids})
GROUP BY cc4.cmd_category_id
UNION
SELECT
cc.*
FROM command AS t
INNER JOIN command_categories_relation AS ccr ON ccr.command_command_id = t.connector_id
INNER JOIN command_categories AS cc ON cc.cmd_category_id = ccr.category_id
INNER JOIN service AS s ON
s.command_command_id = t.command_id OR
s.command_command_id2 = t.command_id
INNER JOIN host_service_relation AS hsr ON
hsr.service_service_id = s.service_id
LEFT JOIN hostgroup_relation AS hgr ON hgr.hostgroup_hg_id = hsr.hostgroup_hg_id
LEFT JOIN ns_host_relation AS nhr ON
nhr.host_host_id = hsr.host_host_id OR
nhr.host_host_id = hgr.host_host_id
WHERE
nhr.nagios_server_id IN ({$ids})
GROUP BY cc.cmd_category_id
SQL;
$stmt = $this->db->prepare($sql);
$stmt->execute();
$result = [];
while ($row = $stmt->fetch()) {
$result[] = $row;
}
return $result;
}
/**
* Export
*
* @param int[] $list
* @return array
*/
public function exportList(array $list): array
{
// prevent SQL exception
if (! $list) {
return [];
}
$ids = join(',', $list);
$sql = <<<SQL
SELECT
cc.*
FROM command AS t
INNER JOIN command_categories_relation AS ccr ON ccr.command_command_id = t.command_id
INNER JOIN command_categories AS cc ON cc.cmd_category_id = ccr.category_id
INNER JOIN cfg_nagios AS cn1 ON
cn1.global_service_event_handler = t1.command_id OR
cn1.global_host_event_handler = t1.command_id
WHERE t.command_id IN ({$ids})
GROUP BY cc.cmd_category_id
SQL;
$stmt = $this->db->prepare($sql);
$stmt->execute();
$result = [];
while ($row = $stmt->fetch()) {
$result[] = $row;
}
return $result;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Repository/CommandRepository.php | centreon/src/Centreon/Domain/Repository/CommandRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Domain\Repository;
use Centreon\Domain\Repository\Traits\CheckListOfIdsTrait;
use Centreon\Infrastructure\DatabaseConnection;
use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB;
class CommandRepository extends AbstractRepositoryRDB
{
use CheckListOfIdsTrait;
/**
* @param DatabaseConnection $db
*/
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* Check list of IDs
*
* @return bool
*/
public function checkListOfIds(array $ids): bool
{
return $this->checkListOfIdsTrait($ids, 'command', 'command_id');
}
/**
* Export
*
* @param int[] $pollerIds
* @return array
*/
public function export(array $pollerIds): array
{
// prevent SQL exception
if (! $pollerIds) {
return [];
}
$ids = join(',', $pollerIds);
$sql = <<<SQL
SELECT
t1.*
FROM command AS t1
INNER JOIN cfg_nagios AS cn1 ON
cn1.global_service_event_handler = t1.command_id OR
cn1.global_host_event_handler = t1.command_id
WHERE
cn1.nagios_id IN ({$ids})
GROUP BY t1.command_id
UNION
SELECT
t2.*
FROM command AS t2
INNER JOIN poller_command_relations AS pcr2 ON pcr2.command_id = t2.command_id
WHERE
pcr2.poller_id IN ({$ids})
GROUP BY t2.command_id
UNION
SELECT
t3.*
FROM command AS t3
INNER JOIN host AS h3 ON
h3.command_command_id = t3.command_id OR
h3.command_command_id2 = t3.command_id
INNER JOIN ns_host_relation AS nhr3 ON nhr3.host_host_id = h3.host_id
WHERE
nhr3.nagios_server_id IN ({$ids})
GROUP BY t3.command_id
UNION
SELECT
t4.*
FROM command AS t4
INNER JOIN host AS h4 ON
h4.command_command_id = t4.command_id OR
h4.command_command_id2 = t4.command_id
INNER JOIN ns_host_relation AS nhr4 ON nhr4.host_host_id = h4.host_id
WHERE
nhr4.nagios_server_id IN ({$ids})
GROUP BY t4.command_id
UNION
SELECT
t.*
FROM command AS t
INNER JOIN service AS s ON
s.command_command_id = t.command_id OR
s.command_command_id2 = t.command_id
INNER JOIN host_service_relation AS hsr ON
hsr.service_service_id = s.service_id
LEFT JOIN hostgroup_relation AS hgr ON hgr.hostgroup_hg_id = hsr.hostgroup_hg_id
LEFT JOIN ns_host_relation AS nhr ON
nhr.host_host_id = hsr.host_host_id OR
nhr.host_host_id = hgr.host_host_id
WHERE
nhr.nagios_server_id IN ({$ids})
GROUP BY t.command_id
SQL;
$stmt = $this->db->prepare($sql);
$stmt->execute();
$result = [];
while ($row = $stmt->fetch()) {
$result[] = $row;
}
return $result;
}
/**
* Export
*
* @param int[] $list
* @return array
*/
public function exportList(array $list): array
{
// prevent SQL exception
if (! $list) {
return [];
}
$ids = join(',', $list);
$sql = <<<SQL
SELECT
t.*
FROM command AS t
WHERE t.command_id IN ({$ids})
GROUP BY t.command_id
SQL;
$stmt = $this->db->prepare($sql);
$stmt->execute();
$result = [];
while ($row = $stmt->fetch()) {
$result[] = $row;
}
return $result;
}
public function truncate(): void
{
$sql = <<<'SQL'
TRUNCATE TABLE `command`;
TRUNCATE TABLE `connector`;
TRUNCATE TABLE `command_arg_description`;
TRUNCATE TABLE `command_categories_relation`;
TRUNCATE TABLE `command_categories`;
TRUNCATE TABLE `on_demand_macro_command`;
SQL;
$stmt = $this->db->prepare($sql);
$stmt->execute();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Repository/CfgCentreonBrokerInfoRepository.php | centreon/src/Centreon/Domain/Repository/CfgCentreonBrokerInfoRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Domain\Repository;
use Centreon\Domain\Entity\CfgCentreonBrokerInfo;
use Centreon\Domain\Repository\Interfaces\CfgCentreonBrokerInfoInterface;
use Centreon\Infrastructure\CentreonLegacyDB\ServiceEntityRepository;
/**
* Repository to manage centreon broker flows configuration (input, output...)
*/
class CfgCentreonBrokerInfoRepository extends ServiceEntityRepository implements CfgCentreonBrokerInfoInterface
{
/**
* Get new config group id by config id for a specific flow
* once the config group is got from this method, it is possible to insert a new flow in the broker configuration
*
* @param int $configId the broker configuration id
* @param string $flow the flow type : input, output, log...
* @return int the new config group id
*/
public function getNewConfigGroupId(int $configId, string $flow): int
{
// if there is no config group for a specific flow, first one id is 0
$configGroupId = 0;
$sql = 'SELECT MAX(config_group_id) as max_config_group_id '
. 'FROM cfg_centreonbroker_info cbi '
. 'WHERE config_id = :config_id '
. 'AND config_group = :config_group';
$stmt = $this->db->prepare($sql);
$stmt->bindParam(':config_id', $configId, \PDO::PARAM_INT);
$stmt->bindParam(':config_group', $flow, \PDO::PARAM_STR);
$stmt->execute();
$row = $stmt->fetch();
if (! is_null($row['max_config_group_id'])) {
// to get the new new config group id, we need to increment the max exsting one
$configGroupId = $row['max_config_group_id'] + 1;
}
return $configGroupId;
}
/**
* Insert broker configuration in database (table cfg_centreonbroker_info)
*
* @param CfgCentreonBrokerInfo $brokerInfoEntity the broker info entity
*/
public function add(CfgCentreonBrokerInfo $brokerInfoEntity): void
{
$sql = 'INSERT INTO ' . $brokerInfoEntity::TABLE . ' '
. '(config_id, config_group, config_group_id, config_key, config_value) '
. 'VALUES (:config_id, :config_group, :config_group_id, :config_key, :config_value)';
$stmt = $this->db->prepare($sql);
$stmt->bindValue(':config_id', $brokerInfoEntity->getConfigId(), \PDO::PARAM_INT);
$stmt->bindValue(':config_group', $brokerInfoEntity->getConfigGroup(), \PDO::PARAM_STR);
$stmt->bindValue(':config_group_id', $brokerInfoEntity->getConfigGroupId(), \PDO::PARAM_INT);
$stmt->bindValue(':config_key', $brokerInfoEntity->getConfigKey(), \PDO::PARAM_STR);
$stmt->bindValue(':config_value', $brokerInfoEntity->getConfigValue(), \PDO::PARAM_STR);
$stmt->execute();
}
/**
* Export
*
* @param int[] $pollerIds
* @return array
*/
public function export(array $pollerIds): array
{
// prevent SQL exception
if (! $pollerIds) {
return [];
}
$ids = join(',', $pollerIds);
$sql = <<<SQL
SELECT t.*
FROM cfg_centreonbroker_info AS t
INNER JOIN cfg_centreonbroker AS cci ON cci.config_id = t.config_id
WHERE cci.ns_nagios_server IN ({$ids})
SQL;
$stmt = $this->db->prepare($sql);
$stmt->execute();
$result = [];
while ($row = $stmt->fetch()) {
$result[] = $row;
}
return $result;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Repository/InformationsRepository.php | centreon/src/Centreon/Domain/Repository/InformationsRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Domain\Repository;
use Centreon\Domain\Entity\Informations;
use Centreon\Infrastructure\CentreonLegacyDB\ServiceEntityRepository;
use PDO;
class InformationsRepository extends ServiceEntityRepository
{
/**
* Export options
*
* @return Informations[]
*/
public function getAll(): array
{
$sql = 'SELECT * FROM informations';
$stmt = $this->db->prepare($sql);
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_CLASS, Informations::class);
$result = [];
while ($row = $stmt->fetch()) {
$result[] = $row;
}
return $result;
}
/**
* Find one by given key
* @param string $key
* @return Informations
*/
public function getOneByKey($key): ?Informations
{
$sql = 'SELECT * FROM informations WHERE `key` = :key LIMIT 1';
$stmt = $this->db->prepare($sql);
$stmt->bindParam(':key', $key, PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetch();
$informations = null;
if ($result) {
$informations = new Informations();
$informations->setKey($result['key']);
$informations->setValue($result['value']);
}
return $informations;
}
/**
* Turn on or off remote flag in database
* @param string $flag ('yes' or 'no')
* @return void
*/
public function toggleRemote(string $flag): void
{
$sql = "UPDATE `informations` SET `value`= :state WHERE `key` = 'isRemote'";
$stmt = $this->db->prepare($sql);
$stmt->bindParam(':state', $flag, PDO::PARAM_STR);
$stmt->execute();
$centralState = ($flag === 'yes') ? 'no' : 'yes';
$sql = "UPDATE `informations` SET `value`= :state WHERE `key` = 'isCentral'";
$stmt = $this->db->prepare($sql);
$stmt->bindParam(':state', $centralState, PDO::PARAM_STR);
$stmt->execute();
}
/**
* Authorize Master to make calls to remote for Tasks
* @param string $ip
* @return void
*/
public function authorizeMaster(string $ip): void
{
$sql = "DELETE FROM `informations` WHERE `key` = 'authorizedMaster'";
$stmt = $this->db->prepare($sql);
$stmt->execute();
// resolve the address down to IP
$ipAddress = gethostbyname($ip);
$sql = "INSERT INTO `informations` (`key`, `value`) VALUES ('authorizedMaster', :ip)";
$stmt = $this->db->prepare($sql);
$stmt->bindParam(':ip', $ipAddress, PDO::PARAM_STR);
$stmt->execute();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Repository/HostGroupRelationRepository.php | centreon/src/Centreon/Domain/Repository/HostGroupRelationRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Domain\Repository;
use Centreon\Infrastructure\CentreonLegacyDB\ServiceEntityRepository;
class HostGroupRelationRepository extends ServiceEntityRepository
{
/**
* Export host's groups
*
* @param int[] $pollerIds
* @param array $templateChainList
* @return array
*/
public function export(array $pollerIds, ?array $templateChainList = null): array
{
// prevent SQL exception
if (! $pollerIds) {
return [];
}
$ids = join(',', $pollerIds);
$sql = <<<SQL
SELECT l.* FROM(
SELECT
t.*
FROM hostgroup_relation AS t
INNER JOIN ns_host_relation AS hr ON hr.host_host_id = t.host_host_id
WHERE hr.nagios_server_id IN ({$ids})
GROUP BY t.hgr_id
SQL;
if ($templateChainList) {
$list = join(',', $templateChainList);
$sql .= <<<SQL
UNION
SELECT
tt.*
FROM hostgroup_relation AS tt
WHERE tt.host_host_id IN ({$list})
GROUP BY tt.hgr_id
SQL;
}
$sql .= <<<'SQL'
) AS l
GROUP BY l.hgr_id
SQL;
$stmt = $this->db->prepare($sql);
$stmt->execute();
$result = [];
while ($row = $stmt->fetch()) {
$result[] = $row;
}
return $result;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Repository/AclResourcesHcRelationsRepository.php | centreon/src/Centreon/Domain/Repository/AclResourcesHcRelationsRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Domain\Repository;
use Centreon\Domain\Repository\Interfaces\AclResourceRefreshInterface;
use Centreon\Infrastructure\CentreonLegacyDB\ServiceEntityRepository;
class AclResourcesHcRelationsRepository extends ServiceEntityRepository implements AclResourceRefreshInterface
{
/**
* Refresh
*/
public function refresh(): void
{
$sql = 'DELETE FROM acl_resources_hc_relations '
. 'WHERE hc_id NOT IN (SELECT t2.hc_id FROM hostcategories AS t2)';
$stmt = $this->db->prepare($sql);
$stmt->execute();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Repository/DowntimeHostRelationRepository.php | centreon/src/Centreon/Domain/Repository/DowntimeHostRelationRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Domain\Repository;
use Centreon\Infrastructure\CentreonLegacyDB\ServiceEntityRepository;
class DowntimeHostRelationRepository extends ServiceEntityRepository
{
/**
* Export
*
* @param int[] $pollerIds
* @param array $hostTemplateChain
* @return array
*/
public function export(array $pollerIds, ?array $hostTemplateChain = null): array
{
// prevent SQL exception
if (! $pollerIds) {
return [];
}
$ids = join(',', $pollerIds);
$hostList = join(',', $hostTemplateChain ?? []);
$sqlFilterHostList = $hostList ? " OR t.host_host_id IN ({$hostList})" : '';
$sql = <<<SQL
SELECT
t.*
FROM downtime_host_relation AS t
WHERE t.host_host_id IN (SELECT t1a.host_host_id
FROM
ns_host_relation AS t1a
WHERE
t1a.nagios_server_id IN ({$ids})
GROUP BY t1a.host_host_id){$sqlFilterHostList}
SQL;
$stmt = $this->db->prepare($sql);
$stmt->execute();
$result = [];
while ($row = $stmt->fetch()) {
$result[] = $row;
}
return $result;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Repository/ServiceGroupRelationRepository.php | centreon/src/Centreon/Domain/Repository/ServiceGroupRelationRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Domain\Repository;
use Centreon\Infrastructure\CentreonLegacyDB\ServiceEntityRepository;
class ServiceGroupRelationRepository extends ServiceEntityRepository
{
/**
* Export
*
* @todo restriction by poller
*
* @param int[] $pollerIds
* @param array $templateChainList
* @return array
*/
public function export(array $pollerIds, ?array $templateChainList = null): array
{
// prevent SQL exception
if (! $pollerIds) {
return [];
}
$ids = join(',', $pollerIds);
$sql = <<<SQL
SELECT l.* FROM(
SELECT
t.*
FROM servicegroup_relation AS t
LEFT JOIN hostgroup AS hg ON hg.hg_id = t.hostgroup_hg_id
LEFT JOIN hostgroup_relation AS hgr ON hgr.hostgroup_hg_id = hg.hg_id
INNER JOIN ns_host_relation AS hr ON hr.host_host_id = t.host_host_id OR hr.host_host_id = hgr.host_host_id
WHERE hr.nagios_server_id IN ({$ids})
GROUP BY t.sgr_id
SQL;
if ($templateChainList) {
$list = join(',', $templateChainList);
$sql .= <<<SQL
UNION
SELECT
tt.*
FROM servicegroup_relation AS tt
WHERE tt.service_service_id IN ({$list})
GROUP BY tt.sgr_id
SQL;
}
$sql .= <<<'SQL'
) AS l
GROUP BY l.sgr_id
SQL;
$stmt = $this->db->prepare($sql);
$stmt->execute();
$result = [];
while ($row = $stmt->fetch()) {
$result[] = $row;
}
return $result;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Repository/TimePeriodRepository.php | centreon/src/Centreon/Domain/Repository/TimePeriodRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Domain\Repository;
use Centreon\Infrastructure\CentreonLegacyDB\ServiceEntityRepository;
use PDO;
class TimePeriodRepository extends ServiceEntityRepository
{
/**
* Export
*
* @param int[] $timeperiodList
* @return array
*/
public function export(?array $timeperiodList = null): array
{
if (! $timeperiodList) {
return [];
}
$list = join(',', $timeperiodList);
$sql = <<<SQL
SELECT
t.*
FROM timeperiod AS t
WHERE t.tp_id IN ({$list})
GROUP BY t.tp_id
SQL;
$stmt = $this->db->prepare($sql);
$stmt->execute();
$result = [];
while ($row = $stmt->fetch()) {
$result[] = $row;
}
return $result;
}
public function truncate(): void
{
$sql = <<<'SQL'
TRUNCATE TABLE `timeperiod_exclude_relations`;
TRUNCATE TABLE `timeperiod_include_relations`;
TRUNCATE TABLE `timeperiod_exceptions`;
TRUNCATE TABLE `timeperiod`;
SQL;
$stmt = $this->db->prepare($sql);
$stmt->execute();
}
/**
* Get a chain of the related objects
*
* @param int[] $pollerIds
* @param int[] $hostTemplateChain
* @param int[] $serviceTemplateChain
* @return array
*/
public function getChainByPoller(
array $pollerIds,
?array $hostTemplateChain = null,
?array $serviceTemplateChain = null,
): array {
// prevent SQL exception
if (! $pollerIds) {
return [];
}
$ids = join(',', $pollerIds);
$hostList = join(',', $hostTemplateChain ?? []);
$sqlFilterHostList = $hostList ? " OR h.host_id IN ({$hostList})" : '';
$sqlFilterHostList2 = $hostList ? " OR msr2.host_id IN ({$hostList})" : '';
$serviceList = join(',', $serviceTemplateChain ?? []);
$sqlFilterServiceList = $serviceList ? " OR s3.service_id IN ({$serviceList})" : '';
$sql = <<<SQL
SELECT
t.tp_id
FROM timeperiod AS t
INNER JOIN host AS h ON h.timeperiod_tp_id = t.tp_id OR h.timeperiod_tp_id2 = t.tp_id
LEFT JOIN ns_host_relation AS hr ON hr.host_host_id = h.host_id
WHERE hr.nagios_server_id IN ({$ids}){$sqlFilterHostList}
GROUP BY t.tp_id
UNION
SELECT
t2.tp_id
FROM timeperiod AS t2
INNER JOIN meta_service AS ms2 ON ms2.check_period = t2.tp_id OR ms2.notification_period = t2.tp_id
INNER JOIN meta_service_relation AS msr2 ON msr2.meta_id = ms2.meta_id
LEFT JOIN ns_host_relation AS hr2 ON hr2.host_host_id = msr2.host_id
WHERE hr2.nagios_server_id IN ({$ids}){$sqlFilterHostList2}
GROUP BY t2.tp_id
UNION
SELECT
t3.tp_id
FROM timeperiod AS t3
INNER JOIN service AS s3 ON s3.timeperiod_tp_id = t3.tp_id OR s3.timeperiod_tp_id2 = t3.tp_id
WHERE s3.service_id IN (SELECT t3a.service_service_id
FROM
host_service_relation AS t3a
LEFT JOIN
hostgroup AS hg3a ON hg3a.hg_id = t3a.hostgroup_hg_id
LEFT JOIN
hostgroup_relation AS hgr3a ON hgr3a.hostgroup_hg_id = hg3a.hg_id
INNER JOIN
ns_host_relation AS hr3a ON hr3a.host_host_id = t3a.host_host_id
OR hr3a.host_host_id = hgr3a.host_host_id
WHERE
hr3a.nagios_server_id IN ({$ids})
GROUP BY t3a.service_service_id){$sqlFilterServiceList}
GROUP BY t3.tp_id
SQL;
$stmt = $this->db->prepare($sql);
$stmt->execute();
$result = [];
while ($row = $stmt->fetch()) {
$result[$row['tp_id']] = $row['tp_id'];
$this->getChainByParant($row['tp_id'], $result);
}
return $result;
}
public function getChainByParant($id, &$result)
{
$sql = <<<'SQL'
SELECT
t.timeperiod_include_id AS `id`
FROM timeperiod_include_relations AS t
WHERE t.timeperiod_include_id IS NOT NULL AND t.timeperiod_id = :id
GROUP BY t.timeperiod_include_id
UNION
SELECT
t.timeperiod_exclude_id AS `id`
FROM timeperiod_exclude_relations AS t
WHERE t.timeperiod_exclude_id IS NOT NULL AND t.timeperiod_id = :id
GROUP BY t.timeperiod_exclude_id
SQL;
$stmt = $this->db->prepare($sql);
$stmt->bindValue(':id', $id, PDO::PARAM_INT);
$stmt->execute();
while ($row = $stmt->fetch()) {
$isExisting = array_key_exists($row['id'], $result);
$result[$row['id']] = $row['id'];
if (! $isExisting) {
$this->getChainByParant($row['id'], $result);
}
}
return $result;
}
/**
* Get an array of all time periods IDs that are related as templates
*
* @param int $id ID of time period
* @param array $result This parameter is used forward to data from the recursive method
* @return array
*/
public function getIncludeChainByParent($id, &$result)
{
$sql = 'SELECT t.timeperiod_include_id AS `id` '
. 'FROM timeperiod_include_relations AS t '
. 'WHERE t.timeperiod_include_id IS NOT NULL AND t.timeperiod_id = :id '
. 'GROUP BY t.timeperiod_include_id';
$stmt = $this->db->prepare($sql);
$stmt->bindValue(':id', $id, PDO::PARAM_INT);
$stmt->execute();
while ($row = $stmt->fetch()) {
$isExisting = array_key_exists($row['id'], $result);
$result[$row['id']] = $row['id'];
if (! $isExisting) {
$this->getIncludeChainByParent($row['id'], $result);
}
}
return $result;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Repository/TrapGroupRelationRepository.php | centreon/src/Centreon/Domain/Repository/TrapGroupRelationRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Domain\Repository;
use Centreon\Infrastructure\CentreonLegacyDB\ServiceEntityRepository;
class TrapGroupRelationRepository extends ServiceEntityRepository
{
/**
* Export
*
* @param int[] $pollerIds
* @param array $templateChainList
* @return array
*/
public function export(array $pollerIds, ?array $templateChainList = null): array
{
// prevent SQL exception
if (! $pollerIds) {
return [];
}
$ids = join(',', $pollerIds);
$list = join(',', $templateChainList ?? []);
$sqlFilterList = $list ? " OR tsr.service_id IN ({$list})" : '';
$sqlFilter = TrapRepository::exportFilterSql($pollerIds);
$sql = <<<SQL
SELECT
t.*
FROM traps_group_relation AS t
INNER JOIN traps_service_relation AS tsr ON
tsr.traps_id = t.traps_id AND
(tsr.service_id IN ({$sqlFilter}){$sqlFilterList})
GROUP BY t.traps_id, t.traps_group_id
SQL;
$stmt = $this->db->prepare($sql);
$stmt->execute();
$result = [];
while ($row = $stmt->fetch()) {
$result[] = $row;
}
return $result;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Repository/AclGroupRepository.php | centreon/src/Centreon/Domain/Repository/AclGroupRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Domain\Repository;
use Centreon\Domain\Entity\AclGroup;
use Centreon\Domain\Repository\Traits\CheckListOfIdsTrait;
use Centreon\Infrastructure\CentreonLegacyDB\Interfaces\PaginationRepositoryInterface;
use Centreon\Infrastructure\CentreonLegacyDB\StatementCollector;
use Centreon\Infrastructure\DatabaseConnection;
use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB;
class AclGroupRepository extends AbstractRepositoryRDB implements PaginationRepositoryInterface
{
use CheckListOfIdsTrait;
private const CONCORDANCE_ARRAY = [
'id' => 'acl_group_id',
'name' => 'acl_group_name',
'alias' => 'acl_group_alias',
'changed' => 'acl_group_changed',
'activate' => 'acl_group_activate',
];
/** @var int */
private int $resultCountForPagination = 0;
/**
* @param DatabaseConnection $db
*/
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* {@inheritDoc}
*/
public static function entityClass(): string
{
return AclGroup::class;
}
/**
* Check list of IDs
*
* @return bool
*/
public function checkListOfIds(array $ids): bool
{
return $this->checkListOfIdsTrait($ids, AclGroup::TABLE, AclGroup::ENTITY_IDENTIFICATOR_COLUMN);
}
/**
* {@inheritDoc}
*/
public function getPaginationList($filters = null, ?int $limit = null, ?int $offset = null, $ordering = []): array
{
$request = <<<'SQL_WRAP'
SELECT SQL_CALC_FOUND_ROWS t.* FROM `:db`.`acl_groups` AS `t`
SQL_WRAP;
$collector = new StatementCollector();
$isWhere = false;
if ($filters !== null) {
if ($filters['search'] ?? false) {
$request .= ' WHERE t.' . self::CONCORDANCE_ARRAY['name'] . ' LIKE :search';
$collector->addValue(':search', "%{$filters['search']}%");
$isWhere = true;
}
if (
array_key_exists('ids', $filters)
&& is_array($filters['ids'])
&& $filters['ids'] !== []
) {
$idsListKey = [];
foreach ($filters['ids'] as $index => $id) {
$key = ":id{$index}";
$idsListKey[] = $key;
$collector->addValue($key, $id, \PDO::PARAM_INT);
unset($index, $id);
}
$request .= $isWhere ? ' AND' : ' WHERE';
$request .= ' t.' . self::CONCORDANCE_ARRAY['id'] . ' IN (' . implode(',', $idsListKey) . ')';
}
}
$request .= ' ORDER BY t.' . self::CONCORDANCE_ARRAY['name'] . ' ASC';
if ($limit !== null) {
$request .= ' LIMIT :limit';
$collector->addValue(':limit', $limit, \PDO::PARAM_INT);
if ($offset !== null) {
$request .= ' OFFSET :offset';
$collector->addValue(':offset', $offset, \PDO::PARAM_INT);
}
}
$statement = $this->db->prepare($this->translateDbName($request));
$collector->bind($statement);
$statement->execute();
$foundRecords = $this->db->query('SELECT FOUND_ROWS()');
if ($foundRecords !== false && ($total = $foundRecords->fetchColumn()) !== false) {
$this->resultCountForPagination = $total;
}
$aclGroups = [];
while ($record = $statement->fetch()) {
$aclGroups[] = $this->createAclGroupFromArray($record);
}
return $aclGroups;
}
/**
* {@inheritDoc}
*/
public function getPaginationListTotal(): int
{
return $this->resultCountForPagination;
}
private function createAclGroupFromArray(array $data): AclGroup
{
$aclGroup = new AclGroup();
$aclGroup->setId((int) $data['acl_group_id']);
$aclGroup->setName($data['acl_group_name']);
$aclGroup->setAlias($data['acl_group_alias']);
$aclGroup->setChanged((int) $data['acl_group_changed']);
$aclGroup->setActivate($data['acl_group_activate']);
return $aclGroup;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Repository/TimePeriodExceptionRepository.php | centreon/src/Centreon/Domain/Repository/TimePeriodExceptionRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Domain\Repository;
use Centreon\Infrastructure\CentreonLegacyDB\ServiceEntityRepository;
class TimePeriodExceptionRepository extends ServiceEntityRepository
{
/**
* Export
*
* @param array $timeperiodList
* @return array
*/
public function export(?array $timeperiodList = null): array
{
if (! $timeperiodList) {
return [];
}
$list = join(',', $timeperiodList);
$sql = <<<SQL
SELECT
t.*
FROM timeperiod_exceptions AS t
WHERE t.timeperiod_id IN ({$list})
GROUP BY t.exception_id
SQL;
$stmt = $this->db->prepare($sql);
$stmt->execute();
$result = [];
while ($row = $stmt->fetch()) {
$result[] = $row;
}
return $result;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Repository/ViewImgRepository.php | centreon/src/Centreon/Domain/Repository/ViewImgRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Domain\Repository;
use Centreon\Infrastructure\CentreonLegacyDB\ServiceEntityRepository;
class ViewImgRepository extends ServiceEntityRepository
{
/**
* Export
*
* @param array<mixed> $imgList
* @return array<mixed>
*/
public function export(?array $imgList = null): array
{
$list = $imgList === null ? join(',', []) : join(',', $imgList);
if (! $list) {
return [];
}
$sql = <<<SQL
SELECT
t.*,
GROUP_CONCAT(vid.dir_alias) AS `img_dirs`
FROM `view_img` AS `t`
LEFT JOIN `view_img_dir_relation` AS `vidr` ON t.img_id = vidr.img_img_id
LEFT JOIN `view_img_dir` AS `vid` ON vid.dir_id = vidr.dir_dir_parent_id
WHERE t.img_id IN ({$list})
GROUP BY t.img_id
ORDER BY t.img_id ASC
LIMIT 0, 5000
SQL;
$stmt = $this->db->prepare($sql);
$stmt->execute();
$result = [];
while ($row = $stmt->fetch()) {
$result[] = $row;
}
return $result;
}
public function truncate(): void
{
$sql = <<<'SQL'
TRUNCATE TABLE `view_img_dir_relation`;
TRUNCATE TABLE `view_img_dir`;
TRUNCATE TABLE `view_img`;
SQL;
$stmt = $this->db->prepare($sql);
$stmt->execute();
}
/**
* Get a chain of the related objects
*
* @param int[] $pollerIds
* @param int[] $hostTemplateChain
* @param int[] $serviceTemplateChain
* @return array<mixed>
*/
public function getChainByPoller(
array $pollerIds,
?array $hostTemplateChain = null,
?array $serviceTemplateChain = null,
): array {
// prevent SQL exception
if (! $pollerIds) {
return [];
}
$ids = join(',', $pollerIds);
$hostList = join(',', $hostTemplateChain ?? []);
$sqlFilterHostList = $hostList ? " OR ehi.host_host_id IN ({$hostList})" : '';
$sqlFilterHostList2 = $hostList ? " OR hcr2.host_host_id IN ({$hostList})" : '';
$sqlFilterHostList3 = $hostList ? " OR hcr3.host_host_id IN ({$hostList})" : '';
$serviceList = join(',', $serviceTemplateChain ?? []);
$sqlFilterServiceList = $serviceList ? " OR esi4.service_service_id IN ({$serviceList})" : '';
$sqlFilterServiceList2 = $serviceList ? " OR scr5.service_service_id IN ({$serviceList})" : '';
$sql = <<<SQL
SELECT l.* FROM (
SELECT
t.img_id
FROM view_img AS t
INNER JOIN extended_host_information AS ehi ON ehi.ehi_icon_image = t.img_id
OR ehi.ehi_vrml_image = t.img_id
OR ehi.ehi_statusmap_image = t.img_id
LEFT JOIN ns_host_relation AS hr ON hr.host_host_id = ehi.host_host_id
WHERE hr.nagios_server_id IN ({$ids}){$sqlFilterHostList}
GROUP BY t.img_id
UNION
SELECT
t2.img_id
FROM view_img AS t2
INNER JOIN hostcategories AS hc2 ON hc2.icon_id = t2.img_id
INNER JOIN hostcategories_relation AS hcr2 ON hcr2.hostcategories_hc_id = hc2.hc_id
LEFT JOIN ns_host_relation AS hr2 ON hr2.host_host_id = hcr2.host_host_id
WHERE hr2.nagios_server_id IN ({$ids}){$sqlFilterHostList2}
GROUP BY t2.img_id
UNION
SELECT
t3.img_id
FROM view_img AS t3
INNER JOIN hostgroup AS hg3 ON hg3.hg_icon_image = t3.img_id
INNER JOIN hostgroup_relation AS hcr3 ON hcr3.hostgroup_hg_id = hg3.hg_id
LEFT JOIN ns_host_relation AS hr3 ON hr3.host_host_id = hcr3.host_host_id
WHERE hr3.nagios_server_id IN ({$ids}){$sqlFilterHostList3}
GROUP BY t3.img_id
UNION
SELECT
t4.img_id
FROM view_img AS t4
INNER JOIN extended_service_information AS esi4 ON esi4.esi_icon_image = t4.img_id
WHERE esi4.service_service_id IN (SELECT t4a.service_service_id
FROM
host_service_relation AS t4a
LEFT JOIN
hostgroup AS hg4a ON hg4a.hg_id = t4a.hostgroup_hg_id
LEFT JOIN
hostgroup_relation AS hgr4a ON hgr4a.hostgroup_hg_id = hg4a.hg_id
INNER JOIN
ns_host_relation AS hr4a ON hr4a.host_host_id = t4a.host_host_id
OR hr4a.host_host_id = hgr4a.host_host_id
WHERE
hr4a.nagios_server_id IN ({$ids})
GROUP BY t4a.service_service_id){$sqlFilterServiceList}
GROUP BY t4.img_id
UNION
SELECT
t5.img_id
FROM view_img AS t5
INNER JOIN service_categories AS sc5 ON sc5.icon_id = t5.img_id
INNER JOIN service_categories_relation AS scr5 ON scr5.sc_id = sc5.sc_id
WHERE scr5.service_service_id IN (SELECT t5a.service_service_id
FROM
host_service_relation AS t5a
LEFT JOIN
hostgroup AS hg5a ON hg5a.hg_id = t5a.hostgroup_hg_id
LEFT JOIN
hostgroup_relation AS hgr5a ON hgr5a.hostgroup_hg_id = hg5a.hg_id
INNER JOIN
ns_host_relation AS hr5a ON hr5a.host_host_id = t5a.host_host_id
OR hr5a.host_host_id = hgr5a.host_host_id
WHERE
hr5a.nagios_server_id IN ({$ids})
GROUP BY t5a.service_service_id){$sqlFilterServiceList2}
GROUP BY t5.img_id
) AS l
GROUP BY l.img_id
SQL;
$stmt = $this->db->prepare($sql);
$stmt->execute();
$result = [];
while ($row = $stmt->fetch()) {
$result[$row['img_id']] = $row['img_id'];
}
return $result;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Repository/ExtendedHostInformationRepository.php | centreon/src/Centreon/Domain/Repository/ExtendedHostInformationRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Domain\Repository;
use Centreon\Infrastructure\CentreonLegacyDB\ServiceEntityRepository;
class ExtendedHostInformationRepository extends ServiceEntityRepository
{
/**
* Export host's macros
*
* @param int[] $pollerIds
* @param array $templateChainList
* @return array
*/
public function export(array $pollerIds, ?array $templateChainList = null): array
{
// prevent SQL exception
if (! $pollerIds) {
return [];
}
$ids = join(',', $pollerIds);
$sql = <<<SQL
SELECT l.* FROM(
SELECT
t.*
FROM extended_host_information AS t
INNER JOIN ns_host_relation AS hr ON hr.host_host_id = t.host_host_id
WHERE hr.nagios_server_id IN ({$ids})
GROUP BY t.ehi_id
SQL;
if ($templateChainList) {
$list = join(',', $templateChainList);
$sql .= <<<SQL
UNION
SELECT
tt.*
FROM extended_host_information AS tt
WHERE tt.host_host_id IN ({$list})
GROUP BY tt.ehi_id
SQL;
}
$sql .= <<<'SQL'
) AS l
GROUP BY l.ehi_id
SQL;
$stmt = $this->db->prepare($sql);
$stmt->execute();
$result = [];
while ($row = $stmt->fetch()) {
$result[] = $row;
}
return $result;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Repository/HostCategoryRelationRepository.php | centreon/src/Centreon/Domain/Repository/HostCategoryRelationRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Domain\Repository;
use Centreon\Infrastructure\CentreonLegacyDB\ServiceEntityRepository;
class HostCategoryRelationRepository extends ServiceEntityRepository
{
/**
* Export
*
* @param int[] $pollerIds
* @param array $templateChainList
* @return array
*/
public function export(array $pollerIds, ?array $templateChainList = null): array
{
// prevent SQL exception
if (! $pollerIds) {
return [];
}
$ids = join(',', $pollerIds);
$sql = <<<SQL
SELECT
t.*
FROM hostcategories_relation AS t
LEFT JOIN ns_host_relation AS hr ON hr.host_host_id = t.host_host_id
WHERE hr.nagios_server_id IN ({$ids})
SQL;
if ($templateChainList) {
$list = join(',', $templateChainList);
$sql .= <<<SQL
OR t.host_host_id IN ({$list})
SQL;
}
$stmt = $this->db->prepare($sql);
$stmt->execute();
$result = [];
while ($row = $stmt->fetch()) {
$result[] = $row;
}
return $result;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Repository/CommandCategoryRelationRepository.php | centreon/src/Centreon/Domain/Repository/CommandCategoryRelationRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Domain\Repository;
use Centreon\Infrastructure\CentreonLegacyDB\ServiceEntityRepository;
class CommandCategoryRelationRepository extends ServiceEntityRepository
{
/**
* Export
*
* @param int[] $pollerIds
* @return array
*/
public function export(array $pollerIds): array
{
// prevent SQL exception
if (! $pollerIds) {
return [];
}
$ids = join(',', $pollerIds);
$sql = <<<SQL
SELECT
ccr1.*
FROM command AS t1
INNER JOIN command_categories_relation AS ccr1 ON ccr1.command_command_id = t1.command_id
INNER JOIN cfg_nagios AS cn1 ON
cn1.global_service_event_handler = t1.command_id OR
cn1.global_host_event_handler = t1.command_id
WHERE
cn1.nagios_id IN ({$ids})
GROUP BY ccr1.cmd_cat_id
UNION
SELECT
ccr2.*
FROM command AS t2
INNER JOIN command_categories_relation AS ccr2 ON ccr2.command_command_id = t2.connector_id
INNER JOIN poller_command_relations AS pcr2 ON pcr2.command_id = t2.command_id
WHERE
pcr2.poller_id IN ({$ids})
GROUP BY ccr2.cmd_cat_id
UNION
SELECT
ccr3.*
FROM command AS t3
INNER JOIN command_categories_relation AS ccr3 ON ccr3.command_command_id = t3.connector_id
INNER JOIN command_categories AS cc3 ON cc3.cmd_category_id = ccr3.category_id
INNER JOIN host AS h3 ON
h3.command_command_id = t3.command_id OR
h3.command_command_id2 = t3.command_id
INNER JOIN ns_host_relation AS nhr3 ON nhr3.host_host_id = h3.host_id
WHERE
nhr3.nagios_server_id IN ({$ids})
GROUP BY ccr3.cmd_cat_id
UNION
SELECT
ccr4.*
FROM command AS t4
INNER JOIN command_categories_relation AS ccr4 ON ccr4.command_command_id = t4.connector_id
INNER JOIN host AS h4 ON
h4.command_command_id = t4.command_id OR
h4.command_command_id2 = t4.command_id
INNER JOIN ns_host_relation AS nhr4 ON nhr4.host_host_id = h4.host_id
WHERE
nhr4.nagios_server_id IN ({$ids})
GROUP BY ccr4.cmd_cat_id
UNION
SELECT
ccr.*
FROM command AS t
INNER JOIN command_categories_relation AS ccr ON ccr.command_command_id = t.connector_id
INNER JOIN service AS s ON
s.command_command_id = t.command_id OR
s.command_command_id2 = t.command_id
INNER JOIN host_service_relation AS hsr ON
hsr.service_service_id = s.service_id
LEFT JOIN hostgroup_relation AS hgr ON hgr.hostgroup_hg_id = hsr.hostgroup_hg_id
LEFT JOIN ns_host_relation AS nhr ON
nhr.host_host_id = hsr.host_host_id OR
nhr.host_host_id = hgr.host_host_id
WHERE
nhr.nagios_server_id IN ({$ids})
GROUP BY ccr.cmd_cat_id
SQL;
$stmt = $this->db->prepare($sql);
$stmt->execute();
$result = [];
while ($row = $stmt->fetch()) {
$result[] = $row;
}
return $result;
}
/**
* Export
*
* @param int[] $list
* @return array
*/
public function exportList(array $list): array
{
// prevent SQL exception
if (! $list) {
return [];
}
$ids = join(',', $list);
$sql = <<<SQL
SELECT
t.*
FROM command_categories_relation AS t
WHERE t.command_command_id IN ({$ids})
GROUP BY t.cmd_cat_id
SQL;
$stmt = $this->db->prepare($sql);
$stmt->execute();
$result = [];
while ($row = $stmt->fetch()) {
$result[] = $row;
}
return $result;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Repository/DowntimeHostGroupRelationRepository.php | centreon/src/Centreon/Domain/Repository/DowntimeHostGroupRelationRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Domain\Repository;
use Centreon\Infrastructure\CentreonLegacyDB\ServiceEntityRepository;
class DowntimeHostGroupRelationRepository extends ServiceEntityRepository
{
/**
* Export
*
* @param int[] $pollerIds
* @param array $hostTemplateChain
* @return array
*/
public function export(array $pollerIds, ?array $hostTemplateChain = null): array
{
// prevent SQL exception
if (! $pollerIds) {
return [];
}
$ids = join(',', $pollerIds);
$hostList = join(',', $hostTemplateChain ?? []);
$sqlFilterHostList = $hostList ? " OR hgr.host_host_id IN ({$hostList})" : '';
$sql = <<<SQL
SELECT
t.*
FROM downtime_hostgroup_relation AS t
INNER JOIN hostgroup_relation AS hgr ON hgr.hostgroup_hg_id = t.hg_hg_id
AND hgr.host_host_id IN (SELECT t1a.host_host_id
FROM
ns_host_relation AS t1a
WHERE
t1a.nagios_server_id IN ({$ids})
GROUP BY t1a.host_host_id){$sqlFilterHostList}
GROUP BY t.dt_id, t.hg_hg_id
SQL;
$stmt = $this->db->prepare($sql);
$stmt->execute();
$result = [];
while ($row = $stmt->fetch()) {
$result[] = $row;
}
return $result;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Repository/ViewImgDirRepository.php | centreon/src/Centreon/Domain/Repository/ViewImgDirRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Domain\Repository;
use Centreon\Infrastructure\CentreonLegacyDB\ServiceEntityRepository;
class ViewImgDirRepository extends ServiceEntityRepository
{
/**
* Export
*
* @param array $imgList
* @return array
*/
public function export(?array $imgList = null): array
{
if (! $imgList) {
return [];
}
$list = implode(',', $imgList);
$sql = <<<SQL
SELECT
t.*
FROM view_img_dir AS t
INNER JOIN view_img_dir_relation AS vidr ON vidr.dir_dir_parent_id = t.dir_id
AND vidr.img_img_id IN ({$list})
GROUP BY t.dir_id
SQL;
$stmt = $this->db->prepare($sql);
$stmt->execute();
$result = [];
while ($row = $stmt->fetch()) {
$result[] = $row;
}
return $result;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Repository/AclResourcesHostexRelationsRepository.php | centreon/src/Centreon/Domain/Repository/AclResourcesHostexRelationsRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Domain\Repository;
use Centreon\Domain\Repository\Interfaces\AclResourceRefreshInterface;
use Centreon\Infrastructure\CentreonLegacyDB\ServiceEntityRepository;
class AclResourcesHostexRelationsRepository extends ServiceEntityRepository implements AclResourceRefreshInterface
{
/**
* Refresh
*/
public function refresh(): void
{
$sql = 'DELETE FROM acl_resources_hostex_relations '
. 'WHERE host_host_id NOT IN (SELECT t2.host_id FROM host AS t2)';
$stmt = $this->db->prepare($sql);
$stmt->execute();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Repository/CfgResourceInstanceRelationsRepository.php | centreon/src/Centreon/Domain/Repository/CfgResourceInstanceRelationsRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Domain\Repository;
use Centreon\Infrastructure\CentreonLegacyDB\ServiceEntityRepository;
class CfgResourceInstanceRelationsRepository extends ServiceEntityRepository
{
/**
* Export
*
* @param int[] $pollerIds
* @return array
*/
public function export(array $pollerIds): array
{
// prevent SQL exception
if (! $pollerIds) {
return [];
}
$ids = implode(',', $pollerIds);
$sql = 'SELECT t.* '
. 'FROM cfg_resource_instance_relations AS t '
. "WHERE t.instance_id IN ({$ids})";
$stmt = $this->db->prepare($sql);
$stmt->execute();
$result = [];
while ($row = $stmt->fetch()) {
$result[] = $row;
}
return $result;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Repository/DowntimeRepository.php | centreon/src/Centreon/Domain/Repository/DowntimeRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Domain\Repository;
use Centreon\Infrastructure\CentreonLegacyDB\ServiceEntityRepository;
class DowntimeRepository extends ServiceEntityRepository
{
/**
* Export
*
* @param int[] $pollerIds
* @param array $hostTemplateChain
* @param array $serviceTemplateChain
* @return array
*/
public function export(array $pollerIds, ?array $hostTemplateChain = null, ?array $serviceTemplateChain = null): array
{
if (! $pollerIds) {
return [];
}
$sqlFilter = static::getFilterSql($pollerIds, $hostTemplateChain, $serviceTemplateChain);
$sql = <<<SQL
SELECT
t.*
FROM downtime AS t
WHERE t.dt_id IN ({$sqlFilter})
GROUP BY t.dt_id
SQL;
$stmt = $this->db->prepare($sql);
$stmt->execute();
$result = [];
while ($row = $stmt->fetch()) {
$result[] = $row;
}
return $result;
}
public function truncate(): void
{
$sql = <<<'SQL'
TRUNCATE TABLE `downtime_servicegroup_relation`;
TRUNCATE TABLE `downtime_service_relation`;
TRUNCATE TABLE `downtime_hostgroup_relation`;
TRUNCATE TABLE `downtime_host_relation`;
TRUNCATE TABLE `downtime_cache`;
TRUNCATE TABLE `downtime_period`;
TRUNCATE TABLE `downtime`;
SQL;
$stmt = $this->db->prepare($sql);
$stmt->execute();
}
public static function getFilterSql(
array $pollerIds,
?array $hostTemplateChain = null,
?array $serviceTemplateChain = null,
): string {
// prevent SQL exception
if (! $pollerIds) {
return '';
}
$ids = join(',', $pollerIds);
$hostList = join(',', $hostTemplateChain ?? []);
$sqlFilterHostList = $hostList ? " OR dhr1.host_host_id IN ({$hostList})" : '';
$sqlFilterHostList2 = $hostList ? " OR hgr2.host_host_id IN ({$hostList})" : '';
$sqlFilterHostList3 = $hostList ? " OR dsr3.host_host_id IN ({$hostList})" : '';
$sqlFilterHostList5 = $hostList ? " OR dc5.host_id IN ({$hostList})" : '';
$serviceList = join(',', $serviceTemplateChain ?? []);
$sqlFilterServiceList4 = $serviceList ? " OR dsgr4.sg_sg_id IN ({$serviceList})" : '';
return <<<SQL
SELECT l.* FROM (
SELECT
t1.dt_id
FROM downtime AS t1
INNER JOIN downtime_host_relation AS dhr1 ON dhr1.dt_id = t1.dt_id
AND dhr1.host_host_id IN (SELECT t1a.host_host_id
FROM
ns_host_relation AS t1a
WHERE
t1a.nagios_server_id IN ({$ids})
GROUP BY t1a.host_host_id){$sqlFilterHostList}
GROUP BY t1.dt_id
UNION
SELECT
t2.dt_id
FROM downtime AS t2
INNER JOIN downtime_hostgroup_relation AS dhgr2 ON dhgr2.dt_id = t2.dt_id
INNER JOIN hostgroup_relation AS hgr2 ON hgr2.hostgroup_hg_id = dhgr2.hg_hg_id
AND hgr2.host_host_id IN (SELECT t2a.host_host_id
FROM
ns_host_relation AS t2a
WHERE
t2a.nagios_server_id IN ({$ids})
GROUP BY t2a.host_host_id){$sqlFilterHostList2}
GROUP BY t2.dt_id
UNION
SELECT
t3.dt_id
FROM downtime AS t3
INNER JOIN downtime_service_relation AS dsr3 ON dsr3.dt_id = t3.dt_id
AND dsr3.host_host_id IN (SELECT t3a.host_host_id
FROM
ns_host_relation AS t3a
WHERE
t3a.nagios_server_id IN ({$ids})
GROUP BY t3a.host_host_id){$sqlFilterHostList3}
GROUP BY t3.dt_id
UNION
SELECT
t4.dt_id
FROM downtime AS t4
INNER JOIN downtime_servicegroup_relation AS dsgr4 ON dsgr4.dt_id = t4.dt_id
AND dsgr4.sg_sg_id IN (SELECT t4a.host_host_id
FROM
ns_host_relation AS t4a
WHERE
t4a.nagios_server_id IN ({$ids})
GROUP BY t4a.host_host_id){$sqlFilterServiceList4}
GROUP BY t4.dt_id
UNION
SELECT
t5.dt_id
FROM downtime AS t5
INNER JOIN downtime_cache AS dc5 ON dc5.downtime_id = t5.dt_id
AND dc5.host_id IN (SELECT t5a.host_host_id
FROM
ns_host_relation AS t5a
WHERE
t5a.nagios_server_id IN ({$ids})
GROUP BY t5a.host_host_id){$sqlFilterHostList5}
GROUP BY t5.dt_id
) AS l
GROUP BY l.dt_id
SQL;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Repository/ServiceCategoryRepository.php | centreon/src/Centreon/Domain/Repository/ServiceCategoryRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Domain\Repository;
use Centreon\Infrastructure\CentreonLegacyDB\ServiceEntityRepository;
class ServiceCategoryRepository extends ServiceEntityRepository
{
/**
* Export
* @param int[] $pollerIds
* @param array $templateChainList
* @return array
*/
public function export(array $pollerIds, ?array $templateChainList = null): array
{
// prevent SQL exception
if (! $pollerIds) {
return [];
}
$ids = join(',', $pollerIds);
$sql = <<<SQL
SELECT l.* FROM(
SELECT
t.*
FROM service_categories AS t
INNER JOIN service_categories_relation AS scr ON scr.sc_id = t.sc_id
INNER JOIN host_service_relation AS hsr ON hsr.service_service_id = scr.service_service_id
LEFT JOIN hostgroup AS hg ON hg.hg_id = hsr.hostgroup_hg_id
LEFT JOIN hostgroup_relation AS hgr ON hgr.hostgroup_hg_id = hg.hg_id
INNER JOIN ns_host_relation AS hr ON hr.host_host_id = hsr.host_host_id OR hr.host_host_id = hgr.host_host_id
WHERE hr.nagios_server_id IN ({$ids})
GROUP BY t.sc_id
SQL;
if ($templateChainList) {
$list = join(',', $templateChainList);
$sql .= <<<SQL
UNION
SELECT
tt.*
FROM service_categories AS tt
INNER JOIN service_categories_relation AS _scr ON _scr.sc_id = tt.sc_id AND _scr.service_service_id IN ({$list})
GROUP BY tt.sc_id
SQL;
}
$sql .= <<<'SQL'
) AS l
GROUP BY l.sc_id
SQL;
$stmt = $this->db->prepare($sql);
$stmt->execute();
$result = [];
while ($row = $stmt->fetch()) {
$result[] = $row;
}
return $result;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Repository/AclResourcesPollerRelationsRepository.php | centreon/src/Centreon/Domain/Repository/AclResourcesPollerRelationsRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Domain\Repository;
use Centreon\Domain\Repository\Interfaces\AclResourceRefreshInterface;
use Centreon\Infrastructure\CentreonLegacyDB\ServiceEntityRepository;
class AclResourcesPollerRelationsRepository extends ServiceEntityRepository implements AclResourceRefreshInterface
{
/**
* Refresh
*/
public function refresh(): void
{
$sql = 'DELETE FROM acl_resources_poller_relations '
. 'WHERE poller_id NOT IN (SELECT t2.id FROM nagios_server AS t2)';
$stmt = $this->db->prepare($sql);
$stmt->execute();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Repository/OnDemandMacroHostRepository.php | centreon/src/Centreon/Domain/Repository/OnDemandMacroHostRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Domain\Repository;
use Centreon\Infrastructure\CentreonLegacyDB\ServiceEntityRepository;
class OnDemandMacroHostRepository extends ServiceEntityRepository
{
/**
* Export host's macros
*
* @param int[] $pollerIds
* @param array $templateChainList
* @return array
*/
public function export(array $pollerIds, ?array $templateChainList = null): array
{
// prevent SQL exception
if (! $pollerIds) {
return [];
}
$ids = join(',', $pollerIds);
$sql = <<<SQL
SELECT l.* FROM(
SELECT
t.*
FROM on_demand_macro_host AS t
INNER JOIN ns_host_relation AS hr ON hr.host_host_id = t.host_host_id
WHERE hr.nagios_server_id IN ({$ids})
GROUP BY t.host_macro_id
SQL;
if ($templateChainList) {
$list = join(',', $templateChainList);
$sql .= <<<SQL
UNION
SELECT
tt.*
FROM on_demand_macro_host AS tt
WHERE tt.host_host_id IN ({$list})
GROUP BY tt.host_macro_id
SQL;
}
$sql .= <<<'SQL'
) AS l
GROUP BY l.host_macro_id
SQL;
$stmt = $this->db->prepare($sql);
$stmt->execute();
$result = [];
while ($row = $stmt->fetch()) {
$result[] = $row;
}
return $result;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Repository/DowntimeServiceGroupRelationRepository.php | centreon/src/Centreon/Domain/Repository/DowntimeServiceGroupRelationRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Domain\Repository;
use Centreon\Infrastructure\CentreonLegacyDB\ServiceEntityRepository;
class DowntimeServiceGroupRelationRepository extends ServiceEntityRepository
{
/**
* Export
*
* @param int[] $pollerIds
* @param array $serviceTemplateChain
* @return array
*/
public function export(array $pollerIds, ?array $serviceTemplateChain = null): array
{
// prevent SQL exception
if (! $pollerIds) {
return [];
}
$ids = join(',', $pollerIds);
$serviceList = join(',', $serviceTemplateChain ?? []);
$sqlFilterServiceList = $serviceList ? " OR dsgr.sg_sg_id IN ({$serviceList})" : '';
$sql = <<<SQL
SELECT
t.dt_id
FROM downtime AS t
INNER JOIN downtime_servicegroup_relation AS dsgr ON dsgr.dt_id = t.dt_id
AND dsgr.sg_sg_id IN (SELECT t1a.host_host_id
FROM
ns_host_relation AS t1a
WHERE
t1a.nagios_server_id IN ({$ids})
GROUP BY t1a.host_host_id){$sqlFilterServiceList}
GROUP BY t.dt_id
SQL;
$stmt = $this->db->prepare($sql);
$stmt->execute();
$result = [];
while ($row = $stmt->fetch()) {
$result[] = $row;
}
return $result;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Repository/TrapServiceRelationRepository.php | centreon/src/Centreon/Domain/Repository/TrapServiceRelationRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Domain\Repository;
use Centreon\Infrastructure\CentreonLegacyDB\ServiceEntityRepository;
class TrapServiceRelationRepository extends ServiceEntityRepository
{
/**
* Export
*
* @param int[] $pollerIds
* @param array $templateChainList
* @return array
*/
public function export(array $pollerIds, ?array $templateChainList = null): array
{
// prevent SQL exception
if (! $pollerIds) {
return [];
}
$ids = join(',', $pollerIds);
$list = join(',', $templateChainList ?? []);
$sqlFilterList = $list ? " OR t.service_id IN ({$list})" : '';
$sqlFilter = TrapRepository::exportFilterSql($pollerIds);
$sql = <<<SQL
SELECT
t.*
FROM traps_service_relation AS t
WHERE t.service_id IN ({$sqlFilter}){$sqlFilterList}
SQL;
$stmt = $this->db->prepare($sql);
$stmt->execute();
$result = [];
while ($row = $stmt->fetch()) {
$result[] = $row;
}
return $result;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Repository/TrapGroupRepository.php | centreon/src/Centreon/Domain/Repository/TrapGroupRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Domain\Repository;
use Centreon\Infrastructure\CentreonLegacyDB\ServiceEntityRepository;
class TrapGroupRepository extends ServiceEntityRepository
{
/**
* Export
*
* @param int[] $pollerIds
* @param array $templateChainList
* @return array
*/
public function export(array $pollerIds, ?array $templateChainList = null): array
{
// prevent SQL exception
if (! $pollerIds) {
return [];
}
$ids = join(',', $pollerIds);
$list = join(',', $templateChainList ?? []);
$sqlFilterList = $list ? " OR tsr.service_id IN ({$list})" : '';
$sqlFilter = TrapRepository::exportFilterSql($pollerIds);
$sql = <<<SQL
SELECT
t.*
FROM traps_group AS t
INNER JOIN traps_group_relation AS tgr ON tgr.traps_group_id = t.traps_group_id
INNER JOIN traps_service_relation AS tsr ON
tsr.traps_id = tgr.traps_id AND
(tsr.service_id IN ({$sqlFilter}){$sqlFilterList})
GROUP BY t.traps_group_id
SQL;
$stmt = $this->db->prepare($sql);
$stmt->execute();
$result = [];
while ($row = $stmt->fetch()) {
$result[] = $row;
}
return $result;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Repository/TimezoneRepository.php | centreon/src/Centreon/Domain/Repository/TimezoneRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Domain\Repository;
use Centreon\Infrastructure\CentreonLegacyDB\ServiceEntityRepository;
use PDO;
class TimezoneRepository extends ServiceEntityRepository
{
/**
* Get by ID
*
* @param int $id
* @return array
*/
public function get(int $id): ?array
{
$sql = <<<'SQL'
SELECT
t.*
FROM timezone AS t
WHERE t.timezone_id = :id
LIMIT 0, 1
SQL;
$stmt = $this->db->prepare($sql);
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();
if ($stmt->rowCount() === 0) {
return null;
}
return $stmt->fetch();
}
/**
* Export
*
* @param int[] $pollerIds
* @return array
*/
public function export(array $pollerIds): array
{
// prevent SQL exception
if (! $pollerIds) {
return [];
}
$ids = join(',', $pollerIds);
$sql = <<<SQL
SELECT
tz.*,
t.nagios_id AS `_nagios_id`
FROM cfg_nagios AS t
INNER JOIN timezone AS tz ON tz.timezone_id = t.use_timezone
WHERE t.nagios_id IN ({$ids})
GROUP BY tz.timezone_id
SQL;
$stmt = $this->db->prepare($sql);
$stmt->execute();
$result = [];
while ($row = $stmt->fetch()) {
$result[] = $row;
}
return $result;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Repository/CfgNagiosBrokerModuleRepository.php | centreon/src/Centreon/Domain/Repository/CfgNagiosBrokerModuleRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Domain\Repository;
use Centreon\Infrastructure\CentreonLegacyDB\ServiceEntityRepository;
class CfgNagiosBrokerModuleRepository extends ServiceEntityRepository
{
/**
* Export
*
* @param int[] $pollerIds
* @return array
*/
public function export(array $pollerIds): array
{
// prevent SQL exception
if (! $pollerIds) {
return [];
}
$ids = join(',', $pollerIds);
$sql = <<<SQL
SELECT t.*
FROM cfg_nagios_broker_module AS t
INNER JOIN cfg_nagios AS cn ON cn.nagios_id = t.cfg_nagios_id
WHERE cn.nagios_server_id IN ({$ids})
GROUP BY t.bk_mod_id
SQL;
$stmt = $this->db->prepare($sql);
$stmt->execute();
$result = [];
while ($row = $stmt->fetch()) {
$result[] = $row;
}
return $result;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Repository/HostGroupRepository.php | centreon/src/Centreon/Domain/Repository/HostGroupRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Domain\Repository;
use Centreon\Infrastructure\CentreonLegacyDB\ServiceEntityRepository;
class HostGroupRepository extends ServiceEntityRepository
{
/**
* Export host's groups
*
* @param int[] $pollerIds
* @param array $templateChainList
* @return array
*/
public function export(array $pollerIds, ?array $templateChainList = null): array
{
// prevent SQL exception
if (! $pollerIds) {
return [];
}
$ids = join(',', $pollerIds);
$sql = <<<SQL
SELECT l.* FROM(
SELECT
t.*
FROM hostgroup AS t
INNER JOIN hostgroup_relation AS hg ON hg.hostgroup_hg_id = t.hg_id
INNER JOIN ns_host_relation AS hr ON hr.host_host_id = hg.host_host_id
WHERE hr.nagios_server_id IN ({$ids})
GROUP BY t.hg_id
SQL;
if ($templateChainList) {
$list = join(',', $templateChainList);
$sql .= <<<SQL
UNION
SELECT
tt.*
FROM hostgroup AS tt
INNER JOIN hostgroup_relation AS hg ON hg.hostgroup_hg_id = tt.hg_id AND hg.host_host_id IN ({$list})
GROUP BY tt.hg_id
SQL;
}
$sql .= <<<'SQL'
) AS l
GROUP BY l.hg_id
SQL;
$stmt = $this->db->prepare($sql);
$stmt->execute();
$result = [];
while ($row = $stmt->fetch()) {
$result[] = $row;
}
return $result;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Repository/TimePeriodIncludeRelationRepository.php | centreon/src/Centreon/Domain/Repository/TimePeriodIncludeRelationRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Domain\Repository;
use Centreon\Infrastructure\CentreonLegacyDB\ServiceEntityRepository;
class TimePeriodIncludeRelationRepository extends ServiceEntityRepository
{
/**
* Export
*
* @param array $timeperiodList
* @return array
*/
public function export(?array $timeperiodList = null): array
{
if (! $timeperiodList) {
return [];
}
$list = join(',', $timeperiodList);
$sql = <<<SQL
SELECT
t.*
FROM timeperiod_include_relations AS t
WHERE t.timeperiod_id IN ({$list})
GROUP BY t.include_id
SQL;
$stmt = $this->db->prepare($sql);
$stmt->execute();
$result = [];
while ($row = $stmt->fetch()) {
$result[] = $row;
}
return $result;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Repository/RepositoryException.php | centreon/src/Centreon/Domain/Repository/RepositoryException.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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);
namespace Centreon\Domain\Repository;
/**
* Class
*
* @class RepositoryException
* @package Centreon\Domain\Repository
*
* @deprecated instead use {@see \Core\Common\Domain\Exception\RepositoryException}
*/
class RepositoryException extends \Exception
{
public static function notYetImplemented(): self
{
return new self(_('Not yet implemented'));
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Repository/AclResourcesSgRelationsRepository.php | centreon/src/Centreon/Domain/Repository/AclResourcesSgRelationsRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Domain\Repository;
use Centreon\Domain\Repository\Interfaces\AclResourceRefreshInterface;
use Centreon\Infrastructure\CentreonLegacyDB\ServiceEntityRepository;
class AclResourcesSgRelationsRepository extends ServiceEntityRepository implements AclResourceRefreshInterface
{
/**
* Refresh
*/
public function refresh(): void
{
$sql = 'DELETE FROM acl_resources_sg_relations '
. 'WHERE sg_id NOT IN (SELECT t2.sg_id FROM servicegroup AS t2)';
$stmt = $this->db->prepare($sql);
$stmt->execute();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Repository/OnDemandMacroServiceRepository.php | centreon/src/Centreon/Domain/Repository/OnDemandMacroServiceRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Domain\Repository;
use Centreon\Infrastructure\CentreonLegacyDB\ServiceEntityRepository;
class OnDemandMacroServiceRepository extends ServiceEntityRepository
{
/**
* Export
*
* @todo restriction by poller
*
* @param int[] $pollerIds
* @param array $templateChainList
* @return array
*/
public function export(array $pollerIds, ?array $templateChainList = null): array
{
// prevent SQL exception
if (! $pollerIds) {
return [];
}
$ids = join(',', $pollerIds);
$sql = <<<SQL
SELECT l.* FROM(
SELECT
t.*
FROM on_demand_macro_service AS t
INNER JOIN host_service_relation AS hsr ON hsr.service_service_id = t.svc_svc_id
LEFT JOIN hostgroup AS hg ON hg.hg_id = hsr.hostgroup_hg_id
LEFT JOIN hostgroup_relation AS hgr ON hgr.hostgroup_hg_id = hg.hg_id
INNER JOIN ns_host_relation AS hr ON hr.host_host_id = hsr.host_host_id OR hr.host_host_id = hgr.host_host_id
WHERE hr.nagios_server_id IN ({$ids})
GROUP BY t.svc_macro_id
SQL;
if ($templateChainList) {
$list = join(',', $templateChainList);
$sql .= <<<SQL
UNION
SELECT
tt.*
FROM on_demand_macro_service AS tt
WHERE tt.svc_svc_id IN ({$list})
GROUP BY tt.svc_macro_id
SQL;
}
$sql .= <<<'SQL'
) AS l
GROUP BY l.svc_macro_id
SQL;
$stmt = $this->db->prepare($sql);
$stmt->execute();
$result = [];
while ($row = $stmt->fetch()) {
$result[] = $row;
}
return $result;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Repository/CfgCentreonBrokerRepository.php | centreon/src/Centreon/Domain/Repository/CfgCentreonBrokerRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Domain\Repository;
use Centreon\Domain\Repository\Interfaces\CfgCentreonBrokerInterface;
use Centreon\Infrastructure\CentreonLegacyDB\ServiceEntityRepository;
use Centreon\Infrastructure\Service\Exception\NotFoundException;
/**
* Repository to manage main centreon broker configuration
* @todo move management of cfg_centreonbroker_info in another repository
*/
class CfgCentreonBrokerRepository extends ServiceEntityRepository implements CfgCentreonBrokerInterface
{
/**
* {@inheritDoc}
* @throws NotFoundException
*/
public function findCentralBrokerConfigId(): int
{
// to find central broker configuration,
// we search a configuration with an input which is listing on port 5669
$sql = 'SELECT cb.config_id '
. 'FROM cfg_centreonbroker cb, cfg_centreonbroker_info cbi, nagios_server ns '
. 'WHERE cb.ns_nagios_server = ns.id '
. 'AND cb.config_id = cbi.config_id '
. 'AND ns.localhost = "1" ' // central poller should be on localhost
. 'AND cb.daemon = 1 ' // central broker should be linked to cbd daemon
. 'AND cb.config_activate = "1" '
. 'AND cbi.config_group = "input" '
. 'AND cbi.config_value = "5669"';
$stmt = $this->db->prepare($sql);
$stmt->execute();
if ($row = $stmt->fetch()) {
$configId = $row['config_id'];
} else {
throw new NotFoundException(_('Central broker config id not found'));
}
return $configId;
}
/**
* {@inheritDoc}
* @throws NotFoundException
*/
public function findBrokerConfigIdByPollerId(int $pollerId): int
{
// to find poller broker configuration,
// we search a configuration with an input which is listing on port 5669
$sql = 'SELECT cb.config_id '
. 'FROM cfg_centreonbroker cb, cfg_centreonbroker_info cbi, nagios_server ns '
. 'WHERE cb.ns_nagios_server = ns.id '
. 'AND cb.config_id = cbi.config_id '
. 'AND cb.ns_nagios_server = :poller_id '
. 'AND cb.daemon = 1 ' // central broker should be linked to cbd daemon
. 'AND cb.config_activate = "1" '
. 'AND cbi.config_group = "input" '
. 'AND cbi.config_value = "5669"';
$stmt = $this->db->prepare($sql);
$stmt->bindParam(':poller_id', $pollerId, \PDO::PARAM_INT);
$stmt->execute();
if ($row = $stmt->fetch()) {
$configId = $row['config_id'];
} else {
throw new NotFoundException(_('Poller broker config id not found'));
}
return $configId;
}
/**
* Export poller's broker configurations
*
* @param int[] $pollerIds
* @return array
*/
public function export(array $pollerIds): array
{
// prevent SQL exception
if (! $pollerIds) {
return [];
}
$ids = join(',', $pollerIds);
$sql = <<<SQL
SELECT * FROM cfg_centreonbroker WHERE ns_nagios_server IN ({$ids})
SQL;
$stmt = $this->db->prepare($sql);
$stmt->execute();
$result = [];
while ($row = $stmt->fetch()) {
$result[] = $row;
}
return $result;
}
/**
* Truncate centreon broker configuration in database (cfg_centreonbroker, cfg_centreonbroker_info)
*/
public function truncate(): void
{
$sql = <<<'SQL'
TRUNCATE TABLE `cfg_centreonbroker`;
TRUNCATE TABLE `cfg_centreonbroker_info`
SQL;
$stmt = $this->db->prepare($sql);
$stmt->execute();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Repository/TimePeriodExcludeRelationRepository.php | centreon/src/Centreon/Domain/Repository/TimePeriodExcludeRelationRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Domain\Repository;
use Centreon\Infrastructure\CentreonLegacyDB\ServiceEntityRepository;
class TimePeriodExcludeRelationRepository extends ServiceEntityRepository
{
/**
* Export
*
* @param array $timeperiodList
* @return array
*/
public function export(?array $timeperiodList = null): array
{
if (! $timeperiodList) {
return [];
}
$list = join(',', $timeperiodList);
$sql = <<<SQL
SELECT
t.*
FROM timeperiod_exclude_relations AS t
WHERE t.timeperiod_id IN ({$list})
GROUP BY t.exclude_id
SQL;
$stmt = $this->db->prepare($sql);
$stmt->execute();
$result = [];
while ($row = $stmt->fetch()) {
$result[] = $row;
}
return $result;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Repository/HostCategoryRepository.php | centreon/src/Centreon/Domain/Repository/HostCategoryRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Domain\Repository;
use Centreon\Infrastructure\CentreonLegacyDB\ServiceEntityRepository;
class HostCategoryRepository extends ServiceEntityRepository
{
/**
* Export
*
* @param int[] $pollerIds
* @param array $templateChainList
* @return array
*/
public function export(array $pollerIds, ?array $templateChainList = null): array
{
// prevent SQL exception
if (! $pollerIds) {
return [];
}
$ids = join(',', $pollerIds);
$sql = <<<SQL
SELECT l.* FROM(
SELECT
t.*
FROM hostcategories AS t
INNER JOIN hostcategories_relation AS hc ON hc.hostcategories_hc_id = t.hc_id
INNER JOIN host AS h ON h.host_id = hc.host_host_id
INNER JOIN ns_host_relation AS hr ON hr.host_host_id = h.host_id
WHERE hr.nagios_server_id IN ({$ids})
GROUP BY t.hc_id
SQL;
if ($templateChainList) {
$list = join(',', $templateChainList);
$sql .= <<<SQL
UNION
SELECT
tt.*
FROM hostcategories AS tt
INNER JOIN hostcategories_relation AS hc ON hc.hostcategories_hc_id = tt.hc_id AND hc.host_host_id IN ({$list})
GROUP BY tt.hc_id
SQL;
}
$sql .= <<<'SQL'
) AS l
GROUP BY l.hc_id
SQL;
$stmt = $this->db->prepare($sql);
$stmt->execute();
$result = [];
while ($row = $stmt->fetch()) {
$result[] = $row;
}
return $result;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Repository/TaskRepository.php | centreon/src/Centreon/Domain/Repository/TaskRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Domain\Repository;
use Centreon\Domain\Entity\Task;
use Centreon\Infrastructure\CentreonLegacyDB\ServiceEntityRepository;
use PDO;
class TaskRepository extends ServiceEntityRepository
{
/**
* Find one by id
* @param int $id
* @return Task|null
*/
public function findOneById($id)
{
$sql = 'SELECT * FROM task WHERE `id` = :id LIMIT 1';
$stmt = $this->db->prepare($sql);
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_CLASS, Task::class);
$result = $stmt->fetch();
return $result ?: null;
}
/**
* Find one by parent id
* @param int $id
* @return Task|null
*/
public function findOneByParentId($id)
{
$sql = 'SELECT * FROM task WHERE `parent_id` = :id LIMIT 1';
$stmt = $this->db->prepare($sql);
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_CLASS, Task::class);
$result = $stmt->fetch();
return $result ?: null;
}
/**
* find all pending export tasks
*/
public function findExportTasks()
{
$sql = 'SELECT * FROM task WHERE `type` = "export" AND `status` = "pending"';
$stmt = $this->db->prepare($sql);
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_CLASS, Task::class);
$result = $stmt->fetchAll();
return $result ?: null;
}
/**
* find all pending import tasks
*/
public function findImportTasks()
{
$sql = 'SELECT * FROM task WHERE `type` = "import" AND `status` = "pending"';
$stmt = $this->db->prepare($sql);
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_CLASS, Task::class);
$result = $stmt->fetchAll();
return $result ?: null;
}
/**
* update task status
* @param mixed $status
* @param mixed $taskId
*/
public function updateStatus($status, $taskId)
{
$sql = "UPDATE task SET status = '{$status}' WHERE id = {$taskId}";
$stmt = $this->db->prepare($sql);
return $stmt->execute();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Repository/ContactGroupRepository.php | centreon/src/Centreon/Domain/Repository/ContactGroupRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Domain\Repository;
use Centreon\Domain\Entity\ContactGroup;
use Centreon\Domain\Repository\Traits\CheckListOfIdsTrait;
use Centreon\Infrastructure\CentreonLegacyDB\Interfaces\PaginationRepositoryInterface;
use Centreon\Infrastructure\CentreonLegacyDB\StatementCollector;
use Centreon\Infrastructure\DatabaseConnection;
use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB;
class ContactGroupRepository extends AbstractRepositoryRDB implements PaginationRepositoryInterface
{
use CheckListOfIdsTrait;
/** @var int */
private int $resultCountForPagination = 0;
/**
* @param DatabaseConnection $db
*/
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* Check list of IDs
*
* @return bool
*/
public function checkListOfIds(array $ids): bool
{
return $this->checkListOfIdsTrait($ids, ContactGroup::TABLE, ContactGroup::ENTITY_IDENTIFICATOR_COLUMN);
}
/**
* {@inheritDoc}
*/
public function getPaginationList($filters = null, ?int $limit = null, ?int $offset = null, $ordering = []): array
{
$collector = new StatementCollector();
$sql = 'SELECT SQL_CALC_FOUND_ROWS * FROM `:db`.contactgroup';
$isWhere = false;
if ($filters !== null) {
if ($filters['search'] ?? false) {
$sql .= ' WHERE `cg_name` LIKE :search';
$collector->addValue(':search', "%{$filters['search']}%");
$isWhere = true;
}
if (
array_key_exists('ids', $filters)
&& is_array($filters['ids'])
&& $filters['ids'] !== []
) {
$idsListKey = [];
foreach ($filters['ids'] as $x => $id) {
$key = ":id{$x}";
$idsListKey[] = $key;
$collector->addValue($key, $id, \PDO::PARAM_INT);
unset($x, $id);
}
$sql .= $isWhere ? ' AND' : ' WHERE';
$sql .= ' `cg_id` IN (' . implode(',', $idsListKey) . ')';
}
}
if ($ordering['field'] ?? false) {
$sql .= ' ORDER BY `' . $ordering['field'] . '` ' . $ordering['order'];
}
if ($limit !== null) {
$sql .= ' LIMIT :limit';
$collector->addValue(':limit', $limit, \PDO::PARAM_INT);
}
if ($offset !== null) {
$sql .= ' OFFSET :offset';
$collector->addValue(':offset', $offset, \PDO::PARAM_INT);
}
$statement = $this->db->prepare($this->translateDbName($sql));
$collector->bind($statement);
$statement->execute();
$foundRecords = $this->db->query('SELECT FOUND_ROWS()');
if ($foundRecords !== false && ($total = $foundRecords->fetchColumn()) !== false) {
$this->resultCountForPagination = $total;
}
$statement->setFetchMode(\PDO::FETCH_CLASS, ContactGroup::class);
return $statement->fetchAll();
}
/**
* {@inheritDoc}
*/
public function getPaginationListTotal(): int
{
return $this->resultCountForPagination;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Repository/OptionsRepository.php | centreon/src/Centreon/Domain/Repository/OptionsRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Domain\Repository;
use Centreon\Domain\Entity\Options;
use Centreon\Infrastructure\CentreonLegacyDB\ServiceEntityRepository;
use PDO;
class OptionsRepository extends ServiceEntityRepository
{
/**
* Export options
*
* @return Options[]
*/
public function export(): array
{
$sql = 'SELECT * FROM options';
$stmt = $this->db->prepare($sql);
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_CLASS, Options::class);
$result = [];
while ($row = $stmt->fetch()) {
$result[] = $row;
}
return $result;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Repository/ServiceRepository.php | centreon/src/Centreon/Domain/Repository/ServiceRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Domain\Repository;
use Centreon\Infrastructure\CentreonLegacyDB\StatementCollector;
use Centreon\Infrastructure\DatabaseConnection;
use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB;
use PDO;
class ServiceRepository extends AbstractRepositoryRDB
{
/**
* @param DatabaseConnection $db
*/
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* Export
*
* @todo restriction by poller
*
* @param int[] $pollerIds
* @param array $templateChainList
* @return array
*/
public function export(array $pollerIds, ?array $templateChainList = null): array
{
// prevent SQL exception
if (! $pollerIds) {
return [];
}
$ids = implode(',', $pollerIds);
$sql = <<<SQL
SELECT l.* FROM(
SELECT
t.*
FROM service AS t
INNER JOIN host_service_relation AS hsr ON hsr.service_service_id = t.service_id
LEFT JOIN hostgroup AS hg ON hg.hg_id = hsr.hostgroup_hg_id
LEFT JOIN hostgroup_relation AS hgr ON hgr.hostgroup_hg_id = hg.hg_id
INNER JOIN ns_host_relation AS hr ON hr.host_host_id = hsr.host_host_id OR hr.host_host_id = hgr.host_host_id
WHERE hr.nagios_server_id IN ({$ids})
GROUP BY t.service_id
SQL;
if ($templateChainList) {
$list = implode(',', $templateChainList);
$sql .= <<<SQL
UNION
SELECT
tt.*
FROM service AS tt
WHERE tt.service_id IN ({$list})
GROUP BY tt.service_id
SQL;
}
$sql .= <<<'SQL'
) AS l
GROUP BY l.service_id
SQL;
$stmt = $this->db->prepare($sql);
$stmt->execute();
$result = [];
while ($row = $stmt->fetch()) {
$result[] = $row;
}
return $result;
}
public function truncate(): void
{
$sql = <<<'SQL'
TRUNCATE TABLE `host_service_relation`;
TRUNCATE TABLE `servicegroup_relation`;
TRUNCATE TABLE `servicegroup`;
TRUNCATE TABLE `service_categories`;
TRUNCATE TABLE `service_categories_relation`;
TRUNCATE TABLE `on_demand_macro_service`;
TRUNCATE TABLE `extended_service_information`;
TRUNCATE TABLE `service`;
SQL;
$stmt = $this->db->prepare($sql);
$stmt->execute();
}
/**
* Get a chain of the related objects
*
* @param int[] $pollerIds
* @param int[] $ba
* @return array
*/
public function getChainByPoller(array $pollerIds, ?array $ba = null): array
{
// prevent SQL exception
if (! $pollerIds) {
return [];
}
$ids = implode(',', $pollerIds);
$sql = <<<SQL
SELECT l.* FROM (
SELECT
t.service_template_model_stm_id AS `id`
FROM service AS t
INNER JOIN host_service_relation AS hsr ON hsr.service_service_id = t.service_id
LEFT JOIN hostgroup AS hg ON hg.hg_id = hsr.hostgroup_hg_id
LEFT JOIN hostgroup_relation AS hgr ON hgr.hostgroup_hg_id = hg.hg_id
INNER JOIN ns_host_relation AS hr ON hr.host_host_id = hsr.host_host_id OR hr.host_host_id = hgr.host_host_id
WHERE t.service_template_model_stm_id IS NOT NULL AND hr.nagios_server_id IN ({$ids})
GROUP BY t.service_template_model_stm_id
SQL;
// Extract BA services
if ($ba) {
foreach ($ba as $key => $val) {
$ba[$key] = "'ba_{$val}'";
}
$ba = implode(',', $ba);
$sql .= " UNION SELECT t2.service_id AS `id` FROM service AS t2 WHERE t2.service_description IN({$ba})";
}
$sql .= ') AS l GROUP BY l.id';
$stmt = $this->db->prepare($sql);
$stmt->execute();
$result = [];
while ($row = $stmt->fetch()) {
$result[$row['id']] = $row['id'];
$this->getChainByParant($row['id'], $result);
}
return $result;
}
public function getChainByParant($id, &$result)
{
$sql = <<<'SQL'
SELECT
t.service_template_model_stm_id AS `id`
FROM service AS t
WHERE t.service_template_model_stm_id IS NOT NULL AND t.service_id = :id
GROUP BY t.service_template_model_stm_id
SQL;
$stmt = $this->db->prepare($sql);
$stmt->bindValue(':id', $id, PDO::PARAM_INT);
$stmt->execute();
while ($row = $stmt->fetch()) {
$isExisting = array_key_exists($row['id'], $result);
$result[$row['id']] = $row['id'];
if (! $isExisting) {
$this->getChainByParant($row['id'], $result);
}
}
return $result;
}
/**
* Remove service entity by ID
*
* @param int $id
* @return void
*/
public function removeById(int $id): void
{
$sql = 'DELETE FROM `service`'
. ' WHERE `service_id` = :id';
$collector = new StatementCollector();
$collector->addValue(':id', $id);
$stmt = $this->db->prepare($sql);
$collector->bind($stmt);
$stmt->execute();
}
/**
* Remove relation between Service and Host
*
* @param int $id
* @return void
*/
public function removeHostRelationByServiceId(int $id): void
{
$sql = 'DELETE FROM `host_service_relation`'
. ' WHERE `service_service_id` = :id';
$collector = new StatementCollector();
$collector->addValue(':id', $id);
$stmt = $this->db->prepare($sql);
$collector->bind($stmt);
$stmt->execute();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Repository/AclResourcesHgRelationsRepository.php | centreon/src/Centreon/Domain/Repository/AclResourcesHgRelationsRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Domain\Repository;
use Centreon\Domain\Repository\Interfaces\AclResourceRefreshInterface;
use Centreon\Infrastructure\CentreonLegacyDB\ServiceEntityRepository;
class AclResourcesHgRelationsRepository extends ServiceEntityRepository implements AclResourceRefreshInterface
{
/**
* Refresh
*/
public function refresh(): void
{
$sql = 'DELETE FROM acl_resources_hg_relations '
. 'WHERE hg_hg_id NOT IN (SELECT t2.hg_id FROM hostgroup AS t2)';
$stmt = $this->db->prepare($sql);
$stmt->execute();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Repository/ImagesRepository.php | centreon/src/Centreon/Domain/Repository/ImagesRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Domain\Repository;
use Centreon\Domain\Entity\Image;
use Centreon\Domain\Entity\ImageDir;
use Centreon\Domain\Repository\Traits\CheckListOfIdsTrait;
use Centreon\Infrastructure\CentreonLegacyDB\Interfaces\PaginationRepositoryInterface;
use Centreon\Infrastructure\CentreonLegacyDB\StatementCollector;
use Centreon\Infrastructure\DatabaseConnection;
use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB;
use PDO;
class ImagesRepository extends AbstractRepositoryRDB implements PaginationRepositoryInterface
{
use CheckListOfIdsTrait;
/** @var int */
private int $resultCountForPagination = 0;
/**
* @param DatabaseConnection $db
*/
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* {@inheritDoc}
*/
public function checkListOfIds(array $ids): bool
{
return $this->checkListOfIdsTrait($ids, Image::TABLE, 'img_id');
}
/**
* {@inheritDoc}
*/
public function getPaginationList($filters = null, ?int $limit = null, ?int $offset = null, $ordering = []): array
{
$collector = new StatementCollector();
$sql = 'SELECT SQL_CALC_FOUND_ROWS * FROM `' . ImageDir::TABLE . '`,`' . ImageDir::JOIN_TABLE . '` vidr,`' . Image::TABLE . '` '
. 'WHERE `img_id` = `vidr`.`img_img_id` AND `dir_id` = `vidr`.`dir_dir_parent_id`';
if ($filters !== null) {
if (array_key_exists('search', $filters) && $filters['search']) {
$sql .= ' AND `img_name` LIKE :search';
$collector->addValue(':search', "%{$filters['search']}%");
}
if (array_key_exists('ids', $filters) && is_array($filters['ids'])) {
$idsListKey = [];
foreach ($filters['ids'] as $x => $id) {
$key = ":id{$x}";
$idsListKey[] = $key;
$collector->addValue($key, $id, PDO::PARAM_INT);
unset($x, $id);
}
$sql .= ' AND `img_id` IN (' . implode(',', $idsListKey) . ')';
}
}
if ($limit !== null) {
$sql .= ' LIMIT :limit';
$collector->addValue(':limit', $limit, PDO::PARAM_INT);
}
if ($limit !== null) {
$sql .= ' OFFSET :offset';
$collector->addValue(':offset', $offset, PDO::PARAM_INT);
}
$sql .= ' ORDER BY `dir_name`, `img_name`';
$stmt = $this->db->prepare($sql);
$collector->bind($stmt);
$stmt->execute();
$foundRecords = $this->db->query('SELECT FOUND_ROWS()');
if ($foundRecords !== false && ($total = $foundRecords->fetchColumn()) !== false) {
$this->resultCountForPagination = $total;
}
$stmt->setFetchMode(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, Image::class);
return $stmt->fetchAll();
}
/**
* @param int $id
* @throws \Exception
* @return mixed
*/
public function getOnebyId(int $id)
{
if (empty($id)) {
throw new \Exception('Id required to get Icon by ID, none provided');
}
$sql = 'SELECT * FROM `' . ImageDir::TABLE . '`,`' . ImageDir::JOIN_TABLE . '` vidr,`' . Image::TABLE
. '` WHERE `img_id` = `vidr`.`img_img_id` AND `dir_id` = `vidr`.`dir_dir_parent_id` AND `img_id` =' . $id;
$stmt = $this->db->prepare($sql);
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, Image::class);
return $stmt->fetch();
}
/**
* {@inheritDoc}
*/
public function getPaginationListTotal(): int
{
return $this->resultCountForPagination;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Repository/ServiceGroupRepository.php | centreon/src/Centreon/Domain/Repository/ServiceGroupRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Domain\Repository;
use Centreon\Infrastructure\CentreonLegacyDB\ServiceEntityRepository;
class ServiceGroupRepository extends ServiceEntityRepository
{
/**
* Export
*
* @todo restriction by poller
*
* @param int[] $pollerIds
* @param array $templateChainList
* @return array
*/
public function export(array $pollerIds, ?array $templateChainList = null): array
{
// prevent SQL exception
if (! $pollerIds) {
return [];
}
$ids = join(',', $pollerIds);
$sql = <<<SQL
SELECT l.* FROM(
SELECT
t.*
FROM servicegroup AS t
INNER JOIN servicegroup_relation AS sgr ON sgr.servicegroup_sg_id = t.sg_id
LEFT JOIN hostgroup AS hg ON hg.hg_id = sgr.hostgroup_hg_id
LEFT JOIN hostgroup_relation AS hgr ON hgr.hostgroup_hg_id = hg.hg_id
INNER JOIN ns_host_relation AS hr ON hr.host_host_id = sgr.host_host_id OR hr.host_host_id = hgr.host_host_id
WHERE hr.nagios_server_id IN ({$ids})
GROUP BY t.sg_id
SQL;
if ($templateChainList) {
$list = join(',', $templateChainList);
$sql .= <<<SQL
UNION
SELECT
tt.*
FROM servicegroup AS tt
INNER JOIN servicegroup_relation AS _sgr ON _sgr.servicegroup_sg_id = tt.sg_id AND _sgr.service_service_id IN ({$list})
GROUP BY tt.sg_id
SQL;
}
$sql .= <<<'SQL'
) AS l
GROUP BY l.sg_id
SQL;
$stmt = $this->db->prepare($sql);
$stmt->execute();
$result = [];
while ($row = $stmt->fetch()) {
$result[] = $row;
}
return $result;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Repository/PollerCommandRelationsRepository.php | centreon/src/Centreon/Domain/Repository/PollerCommandRelationsRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Domain\Repository;
use Centreon\Infrastructure\CentreonLegacyDB\ServiceEntityRepository;
class PollerCommandRelationsRepository extends ServiceEntityRepository
{
/**
* Export
*
* @param int[] $pollerIds
* @return array
*/
public function export(array $pollerIds): array
{
// prevent SQL exception
if (! $pollerIds) {
return [];
}
$ids = join(',', $pollerIds);
$sql = <<<SQL
SELECT
t.*
FROM poller_command_relations AS t
WHERE t.poller_id IN ({$ids})
SQL;
$stmt = $this->db->prepare($sql);
$stmt->execute();
$result = [];
while ($row = $stmt->fetch()) {
$result[] = $row;
}
return $result;
}
public function truncate(): void
{
$sql = <<<'SQL'
TRUNCATE TABLE `poller_command_relations`
SQL;
$stmt = $this->db->prepare($sql);
$stmt->execute();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Repository/OnDemandMacroCommandRepository.php | centreon/src/Centreon/Domain/Repository/OnDemandMacroCommandRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Domain\Repository;
use Centreon\Infrastructure\CentreonLegacyDB\ServiceEntityRepository;
class OnDemandMacroCommandRepository extends ServiceEntityRepository
{
/**
* Export
*
* @param int[] $pollerIds
* @return array
*/
public function export(array $pollerIds): array
{
// prevent SQL exception
if (! $pollerIds) {
return [];
}
$ids = join(',', $pollerIds);
$sql = <<<SQL
SELECT
odmc1.*
FROM command AS t1
INNER JOIN on_demand_macro_command AS odmc1 ON odmc1.command_command_id = t1.command_id
INNER JOIN cfg_nagios AS cn1 ON
cn1.global_service_event_handler = t1.command_id OR
cn1.global_host_event_handler = t1.command_id
WHERE
cn1.nagios_id IN ({$ids})
GROUP BY odmc1.command_command_id
UNION
SELECT
odmc2.*
FROM command AS t2
INNER JOIN on_demand_macro_command AS odmc2 ON odmc2.command_command_id = t2.connector_id
INNER JOIN poller_command_relations AS pcr2 ON pcr2.command_id = t2.command_id
WHERE
pcr2.poller_id IN ({$ids})
GROUP BY odmc2.command_command_id
UNION
SELECT
odmc3.*
FROM command AS t3
INNER JOIN on_demand_macro_command AS odmc3 ON odmc3.command_command_id = t3.connector_id
INNER JOIN host AS h3 ON
h3.command_command_id = t3.command_id OR
h3.command_command_id2 = t3.command_id
INNER JOIN ns_host_relation AS nhr3 ON nhr3.host_host_id = h3.host_id
WHERE
nhr3.nagios_server_id IN ({$ids})
GROUP BY odmc3.command_command_id
UNION
SELECT
odmc4.*
FROM command AS t4
INNER JOIN on_demand_macro_command AS odmc4 ON odmc4.command_command_id = t4.connector_id
INNER JOIN host AS h4 ON
h4.command_command_id = t4.command_id OR
h4.command_command_id2 = t4.command_id
INNER JOIN ns_host_relation AS nhr4 ON nhr4.host_host_id = h4.host_id
WHERE
nhr4.nagios_server_id IN ({$ids})
GROUP BY odmc4.command_command_id
UNION
SELECT
odmc.*
FROM command AS t
INNER JOIN on_demand_macro_command AS odmc ON odmc.command_command_id = t.connector_id
INNER JOIN service AS s ON
s.command_command_id = t.command_id OR
s.command_command_id2 = t.command_id
INNER JOIN host_service_relation AS hsr ON
hsr.service_service_id = s.service_id
LEFT JOIN hostgroup_relation AS hgr ON hgr.hostgroup_hg_id = hsr.hostgroup_hg_id
LEFT JOIN ns_host_relation AS nhr ON
nhr.host_host_id = hsr.host_host_id OR
nhr.host_host_id = hgr.host_host_id
WHERE
nhr.nagios_server_id IN ({$ids})
GROUP BY odmc.command_command_id
SQL;
$stmt = $this->db->prepare($sql);
$stmt->execute();
$result = [];
while ($row = $stmt->fetch()) {
$result[] = $row;
}
return $result;
}
/**
* Export
*
* @param int[] $list
* @return array
*/
public function exportList(array $list): array
{
// prevent SQL exception
if (! $list) {
return [];
}
$ids = join(',', $list);
$sql = <<<SQL
SELECT
t.*
FROM on_demand_macro_command AS t
WHERE t.command_command_id IN ({$ids})
GROUP BY t.command_macro_id
SQL;
$stmt = $this->db->prepare($sql);
$stmt->execute();
$result = [];
while ($row = $stmt->fetch()) {
$result[] = $row;
}
return $result;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Repository/HostRepository.php | centreon/src/Centreon/Domain/Repository/HostRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Domain\Repository;
use Centreon\Infrastructure\DatabaseConnection;
use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB;
class HostRepository extends AbstractRepositoryRDB
{
/**
* @param DatabaseConnection $db
*/
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* Export hosts
*
* @param int[] $pollerIds
* @param array $templateChainList
* @return array
*/
public function export(array $pollerIds, ?array $templateChainList = null): array
{
// prevent SQL exception
if (! $pollerIds) {
return [];
}
$ids = join(',', $pollerIds);
$sql = <<<SQL
SELECT l.* FROM(
SELECT
t.*,
hr.nagios_server_id AS `_nagios_id`
FROM host AS t
INNER JOIN ns_host_relation AS hr ON hr.host_host_id = t.host_id
WHERE hr.nagios_server_id IN ({$ids})
GROUP BY t.host_id
SQL;
if ($templateChainList) {
$list = join(',', $templateChainList);
$sql .= <<<SQL
UNION
SELECT
tt.*,
NULL AS `_nagios_id`
FROM host AS tt
WHERE tt.host_id IN ({$list})
GROUP BY tt.host_id
SQL;
}
$sql .= <<<'SQL'
) AS l
GROUP BY l.host_id
SQL;
$stmt = $this->db->prepare($sql);
$stmt->execute();
$result = [];
while ($row = $stmt->fetch()) {
$result[] = $row;
}
return $result;
}
public function truncate(): void
{
$sql = <<<'SQL'
TRUNCATE TABLE `ns_host_relation`;
TRUNCATE TABLE `hostgroup_relation`;
TRUNCATE TABLE `hostgroup`;
TRUNCATE TABLE `hostcategories_relation`;
TRUNCATE TABLE `hostcategories`;
TRUNCATE TABLE `host_hostparent_relation`;
TRUNCATE TABLE `on_demand_macro_host`;
TRUNCATE TABLE `hostgroup_hg_relation`;
TRUNCATE TABLE `extended_host_information`;
TRUNCATE TABLE `host`;
TRUNCATE TABLE `host_template_relation`;
SQL;
$stmt = $this->db->prepare($sql);
$stmt->execute();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Repository/GivGraphTemplateRepository.php | centreon/src/Centreon/Domain/Repository/GivGraphTemplateRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Domain\Repository;
use Centreon\Infrastructure\CentreonLegacyDB\ServiceEntityRepository;
class GivGraphTemplateRepository extends ServiceEntityRepository
{
/**
* Export
*
* @param int[] $pollerIds
* @param array $hostTemplateChain
* @param array $serviceTemplateChain
* @return array
*/
public function export(array $pollerIds, ?array $hostTemplateChain = null, ?array $serviceTemplateChain = null): array
{
// prevent SQL exception
if (! $pollerIds) {
return [];
}
$ids = join(',', $pollerIds);
$hostList = join(',', $hostTemplateChain ?? []);
$sqlFilterHostList = $hostList ? " OR msr.host_id IN ({$hostList})" : '';
$serviceList = join(',', $serviceTemplateChain ?? []);
$sqlFilterServiceList = $serviceList ? " OR esi2.service_service_id IN ({$serviceList})" : '';
$sql = <<<SQL
SELECT l.* FROM (
SELECT
t.*
FROM giv_graphs_template AS t
INNER JOIN meta_service AS ms ON ms.graph_id = t.graph_id
INNER JOIN meta_service_relation AS msr ON msr.meta_id = ms.meta_id
WHERE msr.host_id IN (SELECT t1a.host_host_id
FROM
ns_host_relation AS t1a
WHERE
t1a.nagios_server_id IN ({$ids})
GROUP BY t1a.host_host_id){$sqlFilterHostList}
GROUP BY t.graph_id
UNION
SELECT
t2.*
FROM giv_graphs_template AS t2
INNER JOIN extended_service_information AS esi2 ON esi2.graph_id = t2.graph_id
WHERE esi2.service_service_id IN (SELECT t2a.service_service_id
FROM
host_service_relation AS t2a
LEFT JOIN
hostgroup AS hg2a ON hg2a.hg_id = t2a.hostgroup_hg_id
LEFT JOIN
hostgroup_relation AS hgr2a ON hgr2a.hostgroup_hg_id = hg2a.hg_id
INNER JOIN
ns_host_relation AS hr2a ON hr2a.host_host_id = t2a.host_host_id
OR hr2a.host_host_id = hgr2a.host_host_id
WHERE
hr2a.nagios_server_id IN ({$ids})
GROUP BY t2a.service_service_id){$sqlFilterServiceList}
GROUP BY t2.graph_id
) AS l
GROUP BY l.graph_id
SQL;
$stmt = $this->db->prepare($sql);
$stmt->execute();
$result = [];
while ($row = $stmt->fetch()) {
$result[] = $row;
}
return $result;
}
/**
* Export list
*
* @param int[] $list
* @return array
*/
public function exportList(array $list): array
{
// prevent SQL exception
if (! $list) {
return [];
}
$ids = join(',', $list);
$sql = <<<SQL
SELECT
t.*
FROM giv_graphs_template AS t
WHERE t.graph_id IN ({$ids})
GROUP BY t.graph_id
SQL;
$stmt = $this->db->prepare($sql);
$stmt->execute();
$result = [];
while ($row = $stmt->fetch()) {
$result[] = $row;
}
return $result;
}
public function truncate(): void
{
$sql = <<<'SQL'
TRUNCATE TABLE `giv_graphs_template`;
SQL;
$stmt = $this->db->prepare($sql);
$stmt->execute();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Repository/TrapMatchingPropsRepository.php | centreon/src/Centreon/Domain/Repository/TrapMatchingPropsRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Domain\Repository;
use Centreon\Infrastructure\CentreonLegacyDB\ServiceEntityRepository;
class TrapMatchingPropsRepository extends ServiceEntityRepository
{
/**
* Export
*
* @param int[] $pollerIds
* @param array $templateChainList
* @return array
*/
public function export(array $pollerIds, ?array $templateChainList = null): array
{
// prevent SQL exception
if (! $pollerIds) {
return [];
}
$ids = join(',', $pollerIds);
$list = join(',', $templateChainList ?? []);
$sqlFilterList = $list ? " OR tsr.service_id IN ({$list})" : '';
$sqlFilter = TrapRepository::exportFilterSql($pollerIds);
$sql = <<<SQL
SELECT
t.*
FROM traps_matching_properties AS t
INNER JOIN traps_service_relation AS tsr ON
tsr.traps_id = t.trap_id AND
(tsr.service_id IN ({$sqlFilter}){$sqlFilterList})
GROUP BY t.tmo_id
SQL;
$stmt = $this->db->prepare($sql);
$stmt->execute();
$result = [];
while ($row = $stmt->fetch()) {
$result[] = $row;
}
return $result;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Repository/CfgResourceRepository.php | centreon/src/Centreon/Domain/Repository/CfgResourceRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Domain\Repository;
use Centreon\Infrastructure\CentreonLegacyDB\ServiceEntityRepository;
class CfgResourceRepository extends ServiceEntityRepository
{
/**
* Export cfg resources
*
* @param int[] $pollerIds
* @return array
*/
public function export(array $pollerIds): array
{
// prevent SQL exception
if (! $pollerIds) {
return [];
}
$ids = join(',', $pollerIds);
$sql = <<<SQL
SELECT
t.*,
GROUP_CONCAT(crir.instance_id) AS _instance_id
FROM cfg_resource AS t
INNER JOIN cfg_resource_instance_relations AS crir ON crir.resource_id = t.resource_id
WHERE crir.instance_id IN ({$ids})
GROUP BY t.resource_id
SQL;
$stmt = $this->db->prepare($sql);
$stmt->execute();
$result = [];
while ($row = $stmt->fetch()) {
$result[] = $row;
}
return $result;
}
public function truncate(): void
{
$sql = <<<'SQL'
TRUNCATE TABLE `cfg_resource`;
TRUNCATE TABLE `cfg_resource_instance_relations`
SQL;
$stmt = $this->db->prepare($sql);
$stmt->execute();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Repository/CfgNagiosRepository.php | centreon/src/Centreon/Domain/Repository/CfgNagiosRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Domain\Repository;
use Centreon\Infrastructure\CentreonLegacyDB\ServiceEntityRepository;
class CfgNagiosRepository extends ServiceEntityRepository
{
/**
* Export poller's Nagios configurations
*
* @param int[] $pollerIds
* @return array
*/
public function export(array $pollerIds): array
{
// prevent SQL exception
if (! $pollerIds) {
return [];
}
$ids = join(',', $pollerIds);
$sql = <<<SQL
SELECT * FROM cfg_nagios WHERE nagios_server_id IN ({$ids})
SQL;
$stmt = $this->db->prepare($sql);
$stmt->execute();
$result = [];
while ($row = $stmt->fetch()) {
$result[] = $row;
}
return $result;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Repository/TrapVendorRepository.php | centreon/src/Centreon/Domain/Repository/TrapVendorRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Domain\Repository;
use Centreon\Infrastructure\CentreonLegacyDB\ServiceEntityRepository;
class TrapVendorRepository extends ServiceEntityRepository
{
/**
* Export
*
* @param int[] $pollerIds
* @param array $templateChainList
* @return array
*/
public function export(array $pollerIds, ?array $templateChainList = null): array
{
// prevent SQL exception
if (! $pollerIds) {
return [];
}
$ids = join(',', $pollerIds);
$list = join(',', $templateChainList ?? []);
$sqlFilterList = $list ? " OR tsr.service_id IN ({$list})" : '';
$sqlFilter = TrapRepository::exportFilterSql($pollerIds);
$sql = <<<SQL
SELECT
t.*
FROM traps_vendor AS t
INNER JOIN traps AS tr ON tr.manufacturer_id = t.id
INNER JOIN traps_service_relation AS tsr ON
tsr.traps_id = tr.traps_id AND
(tsr.service_id IN ({$sqlFilter}){$sqlFilterList})
GROUP BY t.id
SQL;
$stmt = $this->db->prepare($sql);
$stmt->execute();
$result = [];
while ($row = $stmt->fetch()) {
$result[] = $row;
}
return $result;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Repository/MetaServiceRelationRepository.php | centreon/src/Centreon/Domain/Repository/MetaServiceRelationRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Domain\Repository;
use Centreon\Infrastructure\CentreonLegacyDB\ServiceEntityRepository;
class MetaServiceRelationRepository extends ServiceEntityRepository
{
/**
* Export
*
* @param int[] $pollerIds
* @param array $templateChainList
* @return array
*/
public function export(array $pollerIds, ?array $templateChainList = null): array
{
// prevent SQL exception
if (! $pollerIds) {
return [];
}
$ids = join(',', $pollerIds);
$sql = <<<SQL
SELECT l.* FROM(
SELECT
t.*
FROM meta_service_relation AS t
INNER JOIN ns_host_relation AS hr ON hr.host_host_id = t.host_id
WHERE hr.nagios_server_id IN ({$ids})
GROUP BY t.msr_id
SQL;
if ($templateChainList) {
$list = join(',', $templateChainList);
$sql .= <<<SQL
UNION
SELECT
tt.*
FROM meta_service_relation AS tt
WHERE tt.host_id IN ({$list})
GROUP BY tt.msr_id
SQL;
}
$sql .= <<<'SQL'
) AS l
GROUP BY l.msr_id
SQL;
$stmt = $this->db->prepare($sql);
$stmt->execute();
$result = [];
while ($row = $stmt->fetch()) {
$result[] = $row;
}
return $result;
}
/**
* Export
*
* @param int[] $list
* @return array
*/
public function exportList(array $list): array
{
// prevent SQL exception
if (! $list) {
return [];
}
$ids = join(',', $list);
$sql = <<<SQL
SELECT
t.*
FROM meta_service_relation AS t
WHERE t.meta_id IN ({$ids})
GROUP BY t.msr_id
SQL;
$stmt = $this->db->prepare($sql);
$stmt->execute();
$result = [];
while ($row = $stmt->fetch()) {
$result[] = $row;
}
return $result;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Repository/ServiceCategoryRelationRepository.php | centreon/src/Centreon/Domain/Repository/ServiceCategoryRelationRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Domain\Repository;
use Centreon\Infrastructure\CentreonLegacyDB\ServiceEntityRepository;
class ServiceCategoryRelationRepository extends ServiceEntityRepository
{
/**
* Export
*
* @todo restriction by poller
*
* @param int[] $pollerIds
* @param array $templateChainList
* @return array
*/
public function export(array $pollerIds, ?array $templateChainList = null): array
{
// prevent SQL exception
if (! $pollerIds) {
return [];
}
$ids = join(',', $pollerIds);
$sql = <<<SQL
SELECT l.* FROM(
SELECT
t.*
FROM service_categories_relation AS t
INNER JOIN host_service_relation AS hsr ON hsr.service_service_id = t.service_service_id
LEFT JOIN hostgroup AS hg ON hg.hg_id = hsr.hostgroup_hg_id
LEFT JOIN hostgroup_relation AS hgr ON hgr.hostgroup_hg_id = hg.hg_id
INNER JOIN ns_host_relation AS hr ON hr.host_host_id = hsr.host_host_id OR hr.host_host_id = hgr.host_host_id
WHERE hr.nagios_server_id IN ({$ids})
GROUP BY t.scr_id
SQL;
if ($templateChainList) {
$list = join(',', $templateChainList);
$sql .= <<<SQL
UNION
SELECT
tt.*
FROM service_categories_relation AS tt
WHERE tt.service_service_id IN ({$list})
GROUP BY tt.scr_id
SQL;
}
$sql .= <<<'SQL'
) AS l
GROUP BY l.scr_id
SQL;
$stmt = $this->db->prepare($sql);
$stmt->execute();
$result = [];
while ($row = $stmt->fetch()) {
$result[] = $row;
}
return $result;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Repository/ExtendedServiceInformationRepository.php | centreon/src/Centreon/Domain/Repository/ExtendedServiceInformationRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Domain\Repository;
use Centreon\Infrastructure\CentreonLegacyDB\ServiceEntityRepository;
class ExtendedServiceInformationRepository extends ServiceEntityRepository
{
/**
* Export host's macros
*
* @todo restriction by poller
*
* @param int[] $pollerIds
* @param array $templateChainList
* @return array
*/
public function export(array $pollerIds, ?array $templateChainList = null): array
{
// prevent SQL exception
if (! $pollerIds) {
return [];
}
$ids = join(',', $pollerIds);
$sql = <<<SQL
SELECT l.* FROM(
SELECT
t.*
FROM extended_service_information AS t
INNER JOIN host_service_relation AS hsr ON hsr.service_service_id = t.service_service_id
LEFT JOIN hostgroup AS hg ON hg.hg_id = hsr.hostgroup_hg_id
LEFT JOIN hostgroup_relation AS hgr ON hgr.hostgroup_hg_id = hg.hg_id
INNER JOIN ns_host_relation AS hr ON hr.host_host_id = hsr.host_host_id OR hr.host_host_id = hgr.host_host_id
WHERE hr.nagios_server_id IN ({$ids})
GROUP BY t.esi_id
SQL;
if ($templateChainList) {
$list = join(',', $templateChainList);
$sql .= <<<SQL
UNION
SELECT
tt.*
FROM extended_service_information AS tt
WHERE tt.service_service_id IN ({$list})
GROUP BY tt.esi_id
SQL;
}
$sql .= <<<'SQL'
) AS l
GROUP BY l.esi_id
SQL;
$stmt = $this->db->prepare($sql);
$stmt->execute();
$result = [];
while ($row = $stmt->fetch()) {
$result[] = $row;
}
return $result;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Repository/DowntimeServiceRelationRepository.php | centreon/src/Centreon/Domain/Repository/DowntimeServiceRelationRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Domain\Repository;
use Centreon\Infrastructure\CentreonLegacyDB\ServiceEntityRepository;
class DowntimeServiceRelationRepository extends ServiceEntityRepository
{
/**
* Export
*
* @param int[] $pollerIds
* @param array $hostTemplateChain
* @return array
*/
public function export(array $pollerIds, ?array $hostTemplateChain = null): array
{
// prevent SQL exception
if (! $pollerIds) {
return [];
}
$ids = join(',', $pollerIds);
$hostList = join(',', $hostTemplateChain ?? []);
$sqlFilterHostList = $hostList ? " OR t.host_host_id IN ({$hostList})" : '';
$sql = <<<SQL
SELECT
t.*
FROM downtime_service_relation AS t
WHERE t.host_host_id IN (SELECT t1a.host_host_id
FROM
ns_host_relation AS t1a
WHERE
t1a.nagios_server_id IN ({$ids})
GROUP BY t1a.host_host_id){$sqlFilterHostList}
GROUP BY t.dt_id
SQL;
$stmt = $this->db->prepare($sql);
$stmt->execute();
$result = [];
while ($row = $stmt->fetch()) {
$result[] = $row;
}
return $result;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Repository/Interfaces/DataStorageEngineInterface.php | centreon/src/Centreon/Domain/Repository/Interfaces/DataStorageEngineInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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);
namespace Centreon\Domain\Repository\Interfaces;
use Core\Common\Application\Repository\RepositoryManagerInterface;
/**
* This interface is designed to perform specific operations on the data storage engine.
*
* @deprecated instead use {@see RepositoryManagerInterface}
*/
interface DataStorageEngineInterface
{
/**
* Rollback the operations in the transaction.
*
* @throws \Exception
*
* @return bool
*/
public function rollbackTransaction(): bool;
/**
* Start a transaction.
*
* @throws \Exception
*
* @return bool
*/
public function startTransaction(): bool;
/**
* Commit the operations in the transaction.
*
* @throws \Exception
*
* @return bool
*/
public function commitTransaction(): bool;
/**
* Check if a transaction is already started.
*
* @return bool
*/
public function isAlreadyinTransaction(): bool;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Repository/Interfaces/CfgCentreonBrokerInfoInterface.php | centreon/src/Centreon/Domain/Repository/Interfaces/CfgCentreonBrokerInfoInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Domain\Repository\Interfaces;
use Centreon\Domain\Entity\CfgCentreonBrokerInfo;
interface CfgCentreonBrokerInfoInterface
{
/**
* Get new config group id by config id for a specific flow
* once the config group is got from this method, it is possible to insert a new flow in the broker configuration
*
* @param int $configId the broker configuration id
* @param string $flow the flow type : input, output, log...
* @return int the new config group id
*/
public function getNewConfigGroupId(int $configId, string $flow): int;
/**
* Insert broker configuration in database (table cfg_centreonbroker_info)
*
* @param CfgCentreonBrokerInfo $cfgCentreonBrokerInfo the broker info entity
*/
public function add(CfgCentreonBrokerInfo $cfgCentreonBrokerInfo): void;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Repository/Interfaces/AclResourceRefreshInterface.php | centreon/src/Centreon/Domain/Repository/Interfaces/AclResourceRefreshInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Domain\Repository\Interfaces;
interface AclResourceRefreshInterface
{
public function refresh(): void;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Repository/Interfaces/CfgCentreonBrokerInterface.php | centreon/src/Centreon/Domain/Repository/Interfaces/CfgCentreonBrokerInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Domain\Repository\Interfaces;
interface CfgCentreonBrokerInterface
{
/**
* Get config id of central broker
* It can be useful to add bam broker configuration
* Or add an input to manage one peer retention
*
* @return int the config id of central broker
*/
public function findCentralBrokerConfigId(): int;
/**
* Get config id of poller broker
*
* @param int $pollerId pollerId the poller id
* @return int the config id of poller broker
*/
public function findBrokerConfigIdByPollerId(int $pollerId): int;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Repository/Interfaces/RepositoryExceptionInterface.php | centreon/src/Centreon/Domain/Repository/Interfaces/RepositoryExceptionInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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);
namespace Centreon\Domain\Repository\Interfaces;
interface RepositoryExceptionInterface extends \Throwable
{
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Repository/Traits/CheckListOfIdsTrait.php | centreon/src/Centreon/Domain/Repository/Traits/CheckListOfIdsTrait.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Domain\Repository\Traits;
use Centreon\Infrastructure\CentreonLegacyDB\StatementCollector;
trait CheckListOfIdsTrait
{
/**
* Check a list of IDs
*
* @param array $ids
* @param string $tableName not needed if entity had metadata
* @param string $columnNameOfIdentificator not needed if entity had metadata
* @return bool
*/
protected function checkListOfIdsTrait(
array $ids,
string $tableName,
string $columnNameOfIdentificator,
): bool {
$count = count($ids);
$collector = new StatementCollector();
$sql = "SELECT COUNT(*) AS `total` FROM `{$tableName}` ";
$isWhere = false;
foreach ($ids as $x => $value) {
$key = ":id{$x}";
$sql .= (! $isWhere ? 'WHERE ' : 'OR ') . "`{$columnNameOfIdentificator}` = {$key} ";
$collector->addValue($key, $value);
$isWhere = true;
unset($x, $value);
}
$sql .= 'LIMIT 0, 1';
$stmt = $this->db->prepare($sql);
$collector->bind($stmt);
$stmt->execute();
$result = $stmt->fetch();
return (int) $result['total'] === $count;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Media/Model/Image.php | centreon/src/Centreon/Domain/Media/Model/Image.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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);
namespace Centreon\Domain\Media\Model;
use Centreon\Domain\Common\Assertion\Assertion;
/**
* This class is designed to represent an image or icon
*
* @package Centreon\Domain\Media\Model
*/
class Image
{
public const MAX_NAME_LENGTH = 255;
public const MAX_PATH_LENGTH = 255;
public const MAX_COMMENTS_LENGTH = 65535;
/** @var int|null */
private $id;
/** @var string */
private $name;
/** @var string */
private $path;
/** @var string|null */
private $comment;
/**
* @return int|null
*/
public function getId(): ?int
{
return $this->id;
}
/**
* @param int|null $id
* @return Image
*/
public function setId(?int $id): Image
{
$this->id = $id;
return $this;
}
/**
* @return string
*/
public function getName(): string
{
return $this->name;
}
/**
* @param string $name
* @throws \Assert\AssertionFailedException
* @return Image
*/
public function setName(string $name): Image
{
Assertion::maxLength($name, self::MAX_NAME_LENGTH, 'Image::name');
$this->name = $name;
return $this;
}
/**
* @return string
*/
public function getPath(): string
{
return $this->path;
}
/**
* @param string $path
* @throws \Assert\AssertionFailedException
* @return Image
*/
public function setPath(string $path): Image
{
Assertion::maxLength($path, self::MAX_PATH_LENGTH, 'Image::path');
$this->path = $path;
return $this;
}
/**
* @return string|null
*/
public function getComment(): ?string
{
return $this->comment;
}
/**
* @param string|null $comment
* @throws \Assert\AssertionFailedException
* @return Image
*/
public function setComment(?string $comment): Image
{
if ($comment !== null) {
Assertion::maxLength($comment, self::MAX_COMMENTS_LENGTH, 'Image::comment');
}
$this->comment = $comment;
return $this;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Security/AuthenticationToken.php | centreon/src/Centreon/Domain/Security/AuthenticationToken.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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);
namespace Centreon\Domain\Security;
class AuthenticationToken
{
/** @var string Authentication token */
private $token;
/** @var \DateTime Generation date of the authentication token */
private $generatedDate;
/** @var int Contact ID for which the token belongs */
private $contactId;
/** @var bool Indicates whether the authentication token is valid */
private $isValid;
/**
* AuthenticationToken constructor.
*
* @param string $token Authentication token
* @param int $contactId Contact ID
* @param \DateTime $generatedDate Generation date of the authentication token
* @param bool $isValid Indicates whether the authentication token is valid
*/
public function __construct(
string $token,
int $contactId,
\DateTime $generatedDate,
bool $isValid,
) {
$this->token = $token;
$this->contactId = $contactId;
$this->generatedDate = $generatedDate;
$this->isValid = $isValid;
}
/**
* @return string
*/
public function getToken(): string
{
return $this->token;
}
public function getContactId(): int
{
return $this->contactId;
}
/**
* @return \DateTime
*/
public function getGeneratedDate(): \DateTime
{
return $this->generatedDate;
}
/**
* @return bool
*/
public function isValid(): bool
{
return $this->isValid;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Security/Session.php | centreon/src/Centreon/Domain/Security/Session.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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);
namespace Centreon\Domain\Security;
class Session
{
/** @var int */
private $id;
/** @var string */
private $sessionId;
/** @var int */
private $userId;
/** @var \DateTime */
private $lastReload;
/** @var string */
private $ipAddress;
/** @var bool */
private $isValid;
/**
* @return int
*/
public function getId(): int
{
return $this->id;
}
/**
* @param int $id
* @return Session
*/
public function setId(int $id): Session
{
$this->id = $id;
return $this;
}
/**
* @return string
*/
public function getSessionId(): string
{
return $this->sessionId;
}
/**
* @param string $sessionId
* @return Session
*/
public function setSessionId(string $sessionId): Session
{
$this->sessionId = $sessionId;
return $this;
}
/**
* @return int
*/
public function getUserId(): int
{
return $this->userId;
}
/**
* @param int $userId
* @return Session
*/
public function setUserId(int $userId): Session
{
$this->userId = $userId;
return $this;
}
/**
* @return \DateTime
*/
public function getLastReload(): \DateTime
{
return $this->lastReload;
}
/**
* @param \DateTime $lastReload
* @return Session
*/
public function setLastReload(\DateTime $lastReload): Session
{
$this->lastReload = $lastReload;
return $this;
}
/**
* @return string
*/
public function getIpAddress(): string
{
return $this->ipAddress;
}
/**
* @param string $ipAddress
* @return Session
*/
public function setIpAddress(string $ipAddress): Session
{
$this->ipAddress = $ipAddress;
return $this;
}
/**
* @return bool
*/
public function isValid(): bool
{
return $this->isValid;
}
/**
* @param bool $isValid
* @return Session
*/
public function setIsValid(bool $isValid): Session
{
$this->isValid = $isValid;
return $this;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Platform/PlatformException.php | centreon/src/Centreon/Domain/Platform/PlatformException.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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);
namespace Centreon\Domain\Platform;
class PlatformException extends \Exception
{
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Platform/PlatformService.php | centreon/src/Centreon/Domain/Platform/PlatformService.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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);
namespace Centreon\Domain\Platform;
use Centreon\Domain\Platform\Interfaces\PlatformRepositoryInterface;
use Centreon\Domain\Platform\Interfaces\PlatformServiceInterface;
/**
* This class is designed to retrieve the version of modules, widgets, remote pollers from the Centreon Platform.
*
* @package Centreon\Domain\Platform
*/
class PlatformService implements PlatformServiceInterface
{
/** @var PlatformRepositoryInterface */
private $platformRepository;
/**
* @param PlatformRepositoryInterface $informationRepository
*/
public function __construct(PlatformRepositoryInterface $informationRepository)
{
$this->platformRepository = $informationRepository;
}
/**
* @inheritDoc
*/
public function getWebVersion(): string
{
try {
$webVersion = $this->platformRepository->getWebVersion();
return $webVersion ?? '0.0.0';
} catch (\Exception $ex) {
throw new PlatformException('Error while searching for the web version of the Centreon platform');
}
}
/**
* @inheritDoc
*/
public function getModulesVersion(): array
{
try {
return $this->platformRepository->getModulesVersion();
} catch (\Exception $ex) {
throw new PlatformException('Error while searching for the modules version of the Centreon platform');
}
}
/**
* @inheritDoc
*/
public function getWidgetsVersion(string $webVersion): array
{
try {
return $this->platformRepository->getWidgetsVersion($webVersion);
} catch (\Exception $ex) {
throw new PlatformException('Error while searching for the widgets version of the Centreon platform');
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Platform/Interfaces/PlatformServiceInterface.php | centreon/src/Centreon/Domain/Platform/Interfaces/PlatformServiceInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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);
namespace Centreon\Domain\Platform\Interfaces;
use Centreon\Domain\Platform\PlatformException;
interface PlatformServiceInterface
{
/**
* Retrieves the web version of the Centreon platform.
*
* @throws PlatformException
* @return string Version of the Centreon platform
*/
public function getWebVersion(): string;
/**
* Retrieves the version of each modules installed on the Centreon platform.
*
* @throws PlatformException
* @return array<string, string> Version of the modules on the Centreon platform
*/
public function getModulesVersion(): array;
/**
* Retrieves the version of each widget installed on the Centreon platform.
*
* @param string $webVersion Centreon web version
* @throws PlatformException
* @return array<string, string> Version of the widgets on the Centreon platform
*/
public function getWidgetsVersion(string $webVersion): array;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Platform/Interfaces/PlatformRepositoryInterface.php | centreon/src/Centreon/Domain/Platform/Interfaces/PlatformRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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);
namespace Centreon\Domain\Platform\Interfaces;
interface PlatformRepositoryInterface
{
/**
* Retrieves the web version of the Centreon platform.
*
* @throws \Exception
* @return string|null Version of the Centreon platform
*/
public function getWebVersion(): ?string;
/**
* Retrieves the version of each modules installed on the Centreon platform.
*
* @throws \Exception
* @return array<string, string> Version of the modules on the Centreon platform
*/
public function getModulesVersion(): array;
/**
* Retrieves the version of each widget installed on the Centreon platform.
*
* @param string $webVersion Centreon web version
* @throws \Exception
* @return array<string, string> Version of the widgets on the Centreon platform
*/
public function getWidgetsVersion(string $webVersion): array;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Log/ErrorFileHandler.php | centreon/src/Centreon/Domain/Log/ErrorFileHandler.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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);
namespace Centreon\Domain\Log;
use Monolog\Formatter\FormatterInterface;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
/**
* Specific monolog handler used to take into account an activation status to log or not the messages.
*
* @package Centreon\Domain\Log
*/
class ErrorFileHandler extends StreamHandler
{
/**
* @param FormatterInterface $formatter Monolog formatter
* @param string|resource $stream Resource or Log filename
* @param int|null $filePermission Optional file permissions (default (0644) are only for owner read/write)
* @param mixed $level The minimum logging level at which this handler will be triggered
* @param bool $useLocking Try to lock log file before doing any writes
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not
* @throws \InvalidArgumentException
*/
public function __construct(
FormatterInterface $formatter,
$stream,
?int $filePermission = null,
$level = Logger::EMERGENCY,
bool $useLocking = false,
bool $bubble = true,
) {
parent::__construct($stream, $level, $bubble, $filePermission, $useLocking);
$this->setFormatter($formatter);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Log/ContactForDebug.php | centreon/src/Centreon/Domain/Log/ContactForDebug.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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);
namespace Centreon\Domain\Log;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
/**
* This class is designed to specify the unique contact for which messages will be logged.
*
* @package Centreon\Domain\Log
*/
class ContactForDebug
{
/** @var int */
private $id;
/** @var string */
private $email;
/**
* @param int|string|null $identifier
*/
public function __construct($identifier)
{
if ($identifier !== null) {
if (is_numeric($identifier)) {
$this->id = (int) $identifier;
} elseif (is_string($identifier)) {
$this->email = $identifier;
}
}
}
/**
* @return int
*/
public function getId(): int
{
return $this->id;
}
/**
* @return string
*/
public function getEmail(): string
{
return $this->email;
}
/**
* Indicates whether the logger can log messages for the given contact.
* The comparison is made by comparing the id or email of the contact.
* If no id or email has been defined the method will always return TRUE.
*
* @param ContactInterface $contact
* @return bool
*/
public function isValidForContact(ContactInterface $contact): bool
{
if ($this->id === null && $this->email === null) {
return true;
}
if ($this->id !== null && $contact->getId() === $this->id) {
return true;
}
return (bool) ($this->email !== null && $contact->getEmail() === $this->email);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Log/LoggerTrait.php | centreon/src/Centreon/Domain/Log/LoggerTrait.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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);
namespace Centreon\Domain\Log;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Psr\Log\InvalidArgumentException;
use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;
use Symfony\Contracts\Service\Attribute\Required;
/**
* This class is design to provide all the methods for recording events.
*/
trait LoggerTrait
{
private ?ContactInterface $loggerContact = null;
private ?LoggerInterface $logger = null;
private ?ContactForDebug $loggerContactForDebug = null;
/**
* @param ContactInterface $loggerContact
*/
#[Required]
public function setLoggerContact(ContactInterface $loggerContact): void
{
$this->loggerContact = $loggerContact;
}
/**
* @param ContactForDebug $loggerContactForDebug
*/
#[Required]
public function setLoggerContactForDebug(ContactForDebug $loggerContactForDebug): void
{
$this->loggerContactForDebug = $loggerContactForDebug;
}
/**
* @param LoggerInterface $centreonLogger
*/
#[Required]
public function setLogger(LoggerInterface $centreonLogger): void
{
$this->logger = $centreonLogger;
}
/**
* @param string $message
* @param array<string,mixed> $context
* @param callable|null $callable
*
* @see LoggerInterface::emergency
*/
private function emergency(string $message, array $context = [], ?callable $callable = null): void
{
$this->executeLog(LogLevel::EMERGENCY, $message, $context, $callable);
}
/**
* @param string $message
* @param array<string,mixed> $context
* @param callable|null $callable
*
* @see LoggerInterface::alert
*/
private function alert(string $message, array $context = [], ?callable $callable = null): void
{
$this->executeLog(LogLevel::ALERT, $message, $context, $callable);
}
/**
* @param string $message
* @param array<string,mixed> $context
* @param callable|null $callable
*
* @see LoggerInterface::critical
*/
private function critical(string $message, array $context = [], ?callable $callable = null): void
{
$this->executeLog(LogLevel::CRITICAL, $message, $context, $callable);
}
/**
* @param string $message
* @param array<string,mixed> $context
* @param callable|null $callable
*
* @see LoggerInterface::error
*/
private function error(string $message, array $context = [], ?callable $callable = null): void
{
$this->executeLog(LogLevel::ERROR, $message, $context, $callable);
}
/**
* @param string $message
* @param array<string,mixed> $context
* @param callable|null $callable
*
* @see LoggerInterface::warning
*/
private function warning(string $message, array $context = [], ?callable $callable = null): void
{
$this->executeLog(LogLevel::WARNING, $message, $context, $callable);
}
/**
* @param string $message
* @param array<string,mixed> $context
* @param callable|null $callable
*
* @see LoggerInterface::notice
*/
private function notice(string $message, array $context = [], ?callable $callable = null): void
{
$this->executeLog(LogLevel::NOTICE, $message, $context, $callable);
}
/**
* @param string $message
* @param array<string,mixed> $context
* @param callable|null $callable
*
* @see LoggerInterface::info
*/
private function info(string $message, array $context = [], ?callable $callable = null): void
{
$this->executeLog(LogLevel::INFO, $message, $context, $callable);
}
/**
* @param string $message
* @param array<string,mixed> $context
* @param callable|null $callable
*
* @see LoggerInterface::debug
*/
private function debug(string $message, array $context = [], ?callable $callable = null): void
{
$this->executeLog(LogLevel::DEBUG, $message, $context, $callable);
}
/**
* @param mixed $level
* @param string $message
* @param array<string,mixed> $context
* @param callable|null $callable
*
* @throws InvalidArgumentException
*
* @see LoggerInterface::log
*/
private function log($level, string $message, array $context = [], ?callable $callable = null): void
{
$this->executeLog($level, $message, $context, $callable);
}
/**
* @return bool
*/
private function canBeLogged(): bool
{
return $this->logger !== null
&& $this->loggerContactForDebug !== null
&& $this->loggerContact !== null
&& $this->loggerContactForDebug->isValidForContact($this->loggerContact);
}
/**
* @param string $level
* @param string $message
* @param array<string,mixed> $context
* @param callable|null $callable
*
* @return void
*/
private function executeLog(
string $level,
string $message,
array $context = [],
?callable $callable = null,
): void {
if ($this->canBeLogged()) {
if ($callable !== null) {
$context = array_merge($context, $callable());
}
$normalizedContext = $this->normalizeContext($context);
$this->logger->log($level, $message, $normalizedContext);
}
}
/**
* @param array<string,mixed> $customContext
*
* @return array<string,mixed>
*/
private function normalizeContext(array $customContext): array
{
// Add default context with request infos
$defaultContext = [
'request_infos' => [
'uri' => isset($_SERVER['REQUEST_URI']) ? urldecode($_SERVER['REQUEST_URI']) : null,
'http_method' => $_SERVER['REQUEST_METHOD'] ?? null,
'server' => $_SERVER['SERVER_NAME'] ?? null,
],
];
$exceptionContext = [];
if (isset($customContext['exception'])) {
$exceptionContext = $customContext['exception'];
unset($customContext['exception']);
}
return [
'custom' => $customContext !== [] ? $customContext : null,
'exception' => $exceptionContext !== [] ? $exceptionContext : null,
'default' => $defaultContext,
];
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Log/Logger.php | centreon/src/Centreon/Domain/Log/Logger.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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);
namespace Centreon\Domain\Log;
use Psr\Log\LoggerInterface;
/**
* This class is designed to be used in legacy codebase to use a logger
*
* @package Centreon\Domain\Log
*/
class Logger implements LoggerInterface
{
use LoggerTrait {
emergency as traitEmergency;
alert as traitAlert;
critical as traitCritical;
error as traitError;
warning as traitWarning;
notice as traitNotice;
info as traitInfo;
debug as traitDebug;
log as traitLog;
}
/**
* Factory
*
* @return LoggerInterface
*/
public static function create(): LoggerInterface
{
return new self();
}
/**
* @inheritDoc
*/
public function emergency(string|\Stringable $message, array $context = []): void
{
$this->traitEmergency($message, $context);
}
/**
* @inheritDoc
*/
public function alert(string|\Stringable $message, array $context = []): void
{
$this->traitAlert($message, $context);
}
/**
* @inheritDoc
*/
public function critical(string|\Stringable $message, array $context = []): void
{
$this->traitCritical($message, $context);
}
/**
* @inheritDoc
*/
public function error(string|\Stringable $message, array $context = []): void
{
$this->traitError($message, $context);
}
/**
* @inheritDoc
*/
public function warning(string|\Stringable $message, array $context = []): void
{
$this->traitWarning($message, $context);
}
/**
* @inheritDoc
*/
public function notice(string|\Stringable $message, array $context = []): void
{
$this->traitNotice($message, $context);
}
/**
* @inheritDoc
*/
public function info(string|\Stringable $message, array $context = []): void
{
$this->traitInfo($message, $context);
}
/**
* @inheritDoc
*/
public function debug(string|\Stringable $message, array $context = []): void
{
$this->traitDebug($message, $context);
}
/**
* @inheritDoc
*/
public function log($level, string|\Stringable $message, array $context = []): void
{
$this->traitLog($level, $message, $context);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Service/AbstractCentreonService.php | centreon/src/Centreon/Domain/Service/AbstractCentreonService.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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);
namespace Centreon\Domain\Service;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
class AbstractCentreonService
{
/** @var ContactInterface */
protected $contact;
/**
* Used to filter requests according to a contact.
* If the filter is defined, all requests will use the ACL of the contact
* to fetch data.
*
* @param mixed $contact Contact to use as a ACL filter
* @throws \Exception
* @return self
*/
public function filterByContact($contact)
{
if (! \is_object($contact) || ! ($contact instanceof ContactInterface)) {
throw new \Exception('Contact expected');
}
$this->contact = $contact;
return $this;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Service/FrontendComponentService.php | centreon/src/Centreon/Domain/Service/FrontendComponentService.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Domain\Service;
use CentreonLegacy\ServiceProvider;
use Psr\Container\ContainerInterface;
/**
* Class to manage external frontend components provided by modules and widgets
*/
class FrontendComponentService
{
/**
* FrontendComponentService constructor
*
* @param ContainerInterface $services
*/
public function __construct(private ContainerInterface $services)
{
}
/**
* List of class dependencies
*
* @return array
*/
public static function dependencies(): array
{
return [
ServiceProvider::CENTREON_LEGACY_MODULE_INFORMATION,
];
}
/**
* Get frontend external hooks
*
* @return array The list of hooks (js and css)
*/
public function getHooks(): array
{
$installedModules = $this->getInstalledModules();
// search in each installed modules if there are hooks
$hooks = [];
foreach (array_keys($installedModules) as $installedModule) {
$modulePath = __DIR__ . '/../../../../www/modules/' . $installedModule . '/static/hooks';
$chunks = $this->getChunksByModuleName($installedModule);
$files = [];
$this->getDirContents($modulePath, $files, '/\.(js|css)$/');
foreach ($files as $path => $hookFiles) {
if (preg_match('/\/static\/hooks(\/.+)$/', $path, $hookMatches)) {
// parse hook name by removing beginning of the path
$hookName = $hookMatches[1];
$hookParameters = $this->getBundleStructure($path, $hookFiles, $chunks);
if (! $hookParameters['js']['bundle'] !== null) {
$hooks[$hookName] = $hookParameters;
}
}
}
}
return $hooks;
}
/**
* Get frontend external pages
*
* @return array The list of pages (routes, js and css)
*/
public function getPages(): array
{
$installedModules = $this->getInstalledModules();
// search in each installed modules if there are pages
$pages = [];
foreach (array_keys($installedModules) as $installedModule) {
$modulePath = __DIR__ . '/../../../../www/modules/' . $installedModule . '/static/pages';
$chunks = $this->getChunksByModuleName($installedModule);
$files = [];
$this->getDirContents($modulePath, $files, '/\.(js|css)$/');
foreach ($files as $path => $pageFiles) {
if (preg_match('/\/static\/pages(\/.+)$/', $path, $pageMatches)) {
$pageParameters = $this->getBundleStructure($path, $pageFiles, $chunks);
if ($pageParameters['js']['bundle'] !== null) {
// parse page name by removing beginning of the path
$pageName = str_replace('/_', '/:', $pageMatches[1]);
$pages[$pageName] = $pageParameters;
}
}
}
}
return $pages;
}
/**
* Get directory files grouped by directory matching regex
*
* @param string $dir the directory to explore
* @param array $results the found files
* @param string $regex the regex to match
* @return array
*/
private function getDirContents(
string $dir,
array &$results = [],
string $regex = '/.*/',
bool $recursive = true,
): array {
$files = [];
if (is_dir($dir)) {
$files = scandir($dir);
}
foreach ($files as $key => $value) {
$path = $dir . DIRECTORY_SEPARATOR . $value;
if (! is_dir($path) && preg_match($regex, $path)) {
// group files by directory
$results[dirname($path)][] = basename($path);
} elseif ($recursive && $value != '.' && $value != '..') {
$this->getDirContents($path, $results, $regex);
}
}
return $results;
}
/**
* Get list of installed modules
*
* @return array list of installed modules
*/
private function getInstalledModules(): array
{
return $this->services->get(ServiceProvider::CENTREON_LEGACY_MODULE_INFORMATION)
->getInstalledList();
}
/**
* Get list of chunks found in module directory
* Chunks represent common source code between hooks and pages
*
* @return array the list of chunks
*/
private function getChunksByModuleName(string $moduleName): array
{
$chunks = [];
$modulePath = __DIR__ . '/../../../../www/modules/' . $moduleName . '/static';
$files = [];
$this->getDirContents($modulePath, $files, '/\.js$/', false);
foreach ($files as $path => $chunkFiles) {
$chunkPath = str_replace(__DIR__ . '/../../../../www', '', $path);
foreach ($chunkFiles as $chunkFile) {
$chunks[] = $chunkPath . '/' . $chunkFile;
}
}
return $chunks;
}
/**
* Get structure of files which compose external pages or hooks
*
* @param string $path The absolute base path of the external bundle
* @param array $files The files of the bundle (js and css)
* @param array $commons The common chunks between bundles
* @return array The structure of the files needed to load an external bundle
*/
private function getBundleStructure(string $path, array $files, array $commons): array
{
// set relative path
$relativePath = str_replace(__DIR__ . '/../../../../www', '', $path);
// add page parameters (js and css files)
$structure = [
'js' => [
'commons' => $commons,
'chunks' => [],
'bundle' => null,
],
'css' => [],
];
foreach ($files as $file) {
if (preg_match('/\.js$/', $file)) {
if (preg_match('/^(index|main)/', $file)) {
$structure['js']['bundle'] = $relativePath . '/' . $file;
} else {
$structure['js']['chunks'][] = $relativePath . '/' . $file;
}
} elseif (preg_match('/\.css$/', $file)) {
$structure['css'][] = $relativePath . '/' . $file;
}
}
return $structure;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Service/EntityDescriptorMetadataInterface.php | centreon/src/Centreon/Domain/Service/EntityDescriptorMetadataInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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);
namespace Centreon\Domain\Service;
interface EntityDescriptorMetadataInterface
{
/**
* Entity descriptor used to define the setter method for a specific column.
*
* @return array<string, string>
*/
public static function loadEntityDescriptorMetadata(): array;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Service/I18nService.php | centreon/src/Centreon/Domain/Service/I18nService.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Domain\Service;
use CentreonLegacy\Core\Module\Information;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Finder\Finder;
/**
* Class to manage translation of centreon and its extensions
*/
class I18nService
{
/** @var Information */
private $modulesInformation;
/** @var string */
private $lang;
/** @var Finder */
private $finder;
/** @var Filesystem */
private $filesystem;
/**
* I18nService constructor
*
* @param Information $modulesInformation To get information from centreon modules
*/
public function __construct(Information $modulesInformation, Finder $finder, Filesystem $filesystem)
{
$this->modulesInformation = $modulesInformation;
$this->initLang();
$this->finder = $finder;
$this->filesystem = $filesystem;
}
/**
* Get translation from centreon and its extensions
*
* @return array
*/
public function getTranslation(): array
{
$centreonTranslation = $this->getCentreonTranslation();
$extensionsTranslation = $this->getExtensionsTranslation();
return array_replace_recursive($centreonTranslation, $extensionsTranslation);
}
/**
* Get all translations fron Centreon and its modules
*
* @return array
*/
public function getAllTranslations(): array
{
$centreonTranslation = $this->getAllCentreonTranslation();
$modulesTranslation = $this->getAllModulesTranslation();
return array_replace_recursive($centreonTranslation, $modulesTranslation);
}
/**
* Initialize lang object to bind language
*
* @return void
*/
private function initLang(): void
{
$this->lang = getenv('LANG');
if (! str_contains($this->lang, '.UTF-8')) {
$this->lang .= '.UTF-8';
}
}
/**
* Get all translations from centreon
*
* @return array
*/
private function getCentreonTranslation(): array
{
$data = [];
$translationPath = __DIR__ . "/../../../../www/locale/{$this->lang}/LC_MESSAGES";
$translationFile = 'messages.ser';
if ($this->filesystem->exists($translationPath . '/' . $translationFile)) {
$files = $this->finder
->name($translationFile)
->in($translationPath);
foreach ($files as $file) {
$data = unserialize($file->getContents());
}
}
return $data;
}
/**
* Get translation from centreon
*
* @return array
*/
private function getAllCentreonTranslation(): array
{
$data = [];
$languages = ['fr_FR.UTF-8', 'de_DE.UTF-8', 'es_ES.UTF-8', 'pt-PT.UTF-8', 'pt_BR.UTF-8'];
foreach ($languages as $language) {
$translationPath = __DIR__ . "/../../../../www/locale/{$language}/LC_MESSAGES";
$translationFile = 'messages.ser';
if ($this->filesystem->exists($translationPath . '/' . $translationFile)) {
$files = $this->finder
->name($translationFile)
->in($translationPath);
foreach ($files as $file) {
$data += unserialize($file->getContents());
}
}
}
return $data;
}
/**
* Get translation from each installed module
*
* @return array
*/
private function getExtensionsTranslation(): array
{
$data = [];
// loop over each installed modules to get translation
foreach (array_keys($this->modulesInformation->getInstalledList()) as $module) {
$translationPath = __DIR__ . "/../../../../www/modules/{$module}/locale/{$this->lang}/LC_MESSAGES";
$translationFile = 'messages.ser';
if ($this->filesystem->exists($translationPath . '/' . $translationFile)) {
$files = $this->finder
->name($translationFile)
->in($translationPath);
foreach ($files as $file) {
$data = array_replace_recursive(
$data,
unserialize($file->getContents())
);
}
}
}
return $data;
}
/**
* Get all translation from each installed module
*
* @return array
*/
private function getAllModulesTranslation(): array
{
$data = [];
$languages = ['fr_FR.UTF-8', 'de_DE.UTF-8', 'es_ES.UTF-8', 'pt-PT.UTF-8', 'pt_BR.UTF-8'];
foreach ($languages as $language) {
// loop over each installed modules to get translation
foreach (array_keys($this->modulesInformation->getInstalledList()) as $module) {
$translationPath = __DIR__ . "/../../../../www/modules/{$module}/locale/{$language}/LC_MESSAGES";
$translationFile = 'messages.ser';
if ($this->filesystem->exists($translationPath . '/' . $translationFile)) {
$files = $this->finder
->name($translationFile)
->in($translationPath);
foreach ($files as $file) {
$data = array_replace_recursive(
$data,
unserialize($file->getContents())
);
}
}
}
}
return $data;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Service/BrokerConfigurationService.php | centreon/src/Centreon/Domain/Service/BrokerConfigurationService.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Domain\Service;
use Centreon\Domain\Repository\Interfaces\CfgCentreonBrokerInfoInterface;
/**
* Service to manage broker flows configuration
*/
class BrokerConfigurationService
{
/** @var CfgCentreonBrokerInfoInterface */
private $brokerInfoRepository;
/**
* Set broker infos repository to manage flows (input, output, log...)
*
* @param CfgCentreonBrokerInfoInterface $cfgCentreonBrokerInfo the broker info repository
*/
public function setBrokerInfoRepository(CfgCentreonBrokerInfoInterface $cfgCentreonBrokerInfo): void
{
$this->brokerInfoRepository = $cfgCentreonBrokerInfo;
}
/**
* Add flow (input, output, log...)
*
* @param int $configId the config id to update
* @param string $configGroup the config group to add (input, output...)
* @param \Centreon\Domain\Entity\CfgCentreonBrokerInfo[] $brokerInfoEntities the flow parameters to insert
*/
public function addFlow(int $configId, string $configGroup, array $brokerInfoEntities): void
{
// get new input config group id on central broker configuration
// to add new IPv4 input
$configGroupId = $this->brokerInfoRepository->getNewConfigGroupId($configId, $configGroup);
// insert each line of configuration in database thanks to BrokerInfoEntity
foreach ($brokerInfoEntities as $brokerInfoEntity) {
$brokerInfoEntity->setConfigId($configId);
$brokerInfoEntity->setConfigGroup($configGroup);
$brokerInfoEntity->setConfigGroupId($configGroupId);
$this->brokerInfoRepository->add($brokerInfoEntity);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Service/JsonValidator/ValidatorCache.php | centreon/src/Centreon/Domain/Service/JsonValidator/ValidatorCache.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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);
namespace Centreon\Domain\Service\JsonValidator;
use Centreon\Domain\Service\JsonValidator\Interfaces\ValidatorCacheInterface;
use Symfony\Component\Config\ConfigCache;
class ValidatorCache implements ValidatorCacheInterface
{
/** @var ConfigCache */
private $cache;
/** @var string Name of the cache file used to store data */
private $cacheFile;
/**
* ValidatorCache constructor.
*
* @param string $cacheFile Name of the cache file
* @param bool $isDebug State of the debug mode
*/
public function __construct(string $cacheFile, bool $isDebug)
{
$this->cacheFile = $cacheFile;
$this->cache = new ConfigCache($cacheFile, $isDebug);
}
/**
* @inheritDoc
*/
public function getCacheFile(): string
{
return $this->cacheFile;
}
/**
* @inheritDoc
*/
public function setCache(string $data, array $metadata = []): void
{
$resourceFiles = [];
foreach ($metadata as $yamlFile) {
$resourceFiles[] = $yamlFile;
}
$this->cache->write($data, $metadata);
}
/**
* @inheritDoc
*/
public function getCache(): ?string
{
return (($cache = file_get_contents($this->cacheFile)) !== false)
? (string) $cache
: null;
}
/**
* @inheritDoc
*/
public function isCacheValid(): bool
{
return $this->cache->isFresh();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Service/JsonValidator/Validator.php | centreon/src/Centreon/Domain/Service/JsonValidator/Validator.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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);
namespace Centreon\Domain\Service\JsonValidator;
use Centreon\Domain\Service\JsonValidator\Interfaces\JsonValidatorInterface;
use Centreon\Domain\Service\JsonValidator\Interfaces\ValidatorCacheInterface;
use JsonSchema\Constraints\Constraint;
use JsonSchema\Validator as JsonSchemaValidator;
use Symfony\Component\Config\Resource\FileResource;
use Symfony\Component\Config\Resource\ResourceInterface;
use Symfony\Component\Validator\ConstraintViolation;
use Symfony\Component\Validator\ConstraintViolationList;
use Symfony\Component\Validator\ConstraintViolationListInterface;
use Symfony\Component\Yaml\Yaml;
/**
* Validator used to validate a JSON from a json-schema description.
*
* @package Centreon\Domain\Service\JsonValidator
*/
class Validator implements JsonValidatorInterface
{
public const VERSION_LATEST = 'latest';
public const VERSION_BETA = 'beta';
private const VERSION_DEFAULT = 'default';
private const COMPONENTS_REFERENCE = '$components';
/** @var JsonSchemaValidator */
private $validator;
/** @var array List of definitions that will be used to validate the JSON */
private $definitions = [];
/** @var ResourceInterface[] List of YAML definition files */
private $definitionFiles = [];
/** @var string Version of the definition files to use for the validation process */
private $version = self::VERSION_DEFAULT;
/** @var string Path where the definition files are stored */
private $validationFilePath;
/** @var ValidatorCacheInterface */
private $validatorCache;
/**
* Validator constructor.
*
* @param string $validationFilePath
* @param ValidatorCacheInterface $validatorCache
*/
public function __construct(string $validationFilePath, ValidatorCacheInterface $validatorCache)
{
$this->validationFilePath = $validationFilePath;
$this->validatorCache = $validatorCache;
}
/**
* @inheritDoc
*/
public function forVersion(string $version): JsonValidatorInterface
{
$this->version = $version;
return $this;
}
/**
* @inheritDoc
*/
public function validate(string $json, string $modelName): ConstraintViolationListInterface
{
if ($this->validator === null) {
$this->validator = new JsonSchemaValidator();
}
$dataToValidate = json_decode($json);
if ($dataToValidate === null) {
throw new \Exception(_('The JSON cannot be decoded'));
}
if (empty($this->definitions) && $this->validationFilePath !== null) {
$this->loadDefinitionFile();
}
$definitionsToUseForValidation = [];
/*
* First of all, we look for definitions according to the given version.
* otherwise, we look for the default definitions.
*/
if (
array_key_exists($this->version, $this->definitions)
&& array_key_exists($modelName, $this->definitions[$this->version])
) {
$definitionsToUseForValidation = $this->populateComponentsToDefinitions(
$this->definitions[$this->version][$modelName],
$this->definitions[self::VERSION_DEFAULT]
);
} elseif (
array_key_exists(self::VERSION_DEFAULT, $this->definitions)
&& array_key_exists($modelName, $this->definitions[self::VERSION_DEFAULT])
) {
$definitionsToUseForValidation = $this->populateComponentsToDefinitions(
$this->definitions[self::VERSION_DEFAULT][$modelName],
$this->definitions[self::VERSION_DEFAULT]
);
}
if ($definitionsToUseForValidation === []) {
throw new \Exception(
sprintf(_('The definition model "%s" to validate the JSON does not exist or is empty'), $modelName)
);
}
$this->validator->validate(
$dataToValidate,
$definitionsToUseForValidation,
Constraint::CHECK_MODE_ONLY_REQUIRED_DEFAULTS
);
return (! $this->validator->isValid())
? $this->formatErrors($this->validator->getErrors(), $json)
: new ConstraintViolationList();
}
/**
* Add component references to definitions
*
* @param array $definitionsToPopulate
* @param array $versionedDefinitions
* @return array The definitions with component refs if exist
*/
private function populateComponentsToDefinitions(
array $definitionsToPopulate,
array $versionedDefinitions,
): array {
if (array_key_exists(self::COMPONENTS_REFERENCE, $versionedDefinitions)) {
$definitionsToPopulate[self::COMPONENTS_REFERENCE] = $versionedDefinitions[self::COMPONENTS_REFERENCE];
}
return $definitionsToPopulate;
}
/**
* Load the definition files for the filesystem or cache.
*/
private function loadDefinitionFile(): void
{
$this->definitionFiles = [];
if (! $this->validatorCache->isCacheValid()) {
// We will load the definition files and create the cache
if (is_file($this->validationFilePath)) {
$info = pathinfo($this->validationFilePath);
if (($info['extension'] ?? '') === 'yaml') {
$this->getDefinitionsByFile($this->validationFilePath);
}
} elseif (is_dir($this->validationFilePath)) {
foreach (new \DirectoryIterator($this->validationFilePath) as $fileInfo) {
if ($fileInfo->isDir() && ! in_array($fileInfo->getFilename(), ['.', '..'])) {
$version = $fileInfo->getFilename();
$this->definitions = array_merge_recursive(
$this->definitions,
$this->getDefinitionsByVersion($version)
);
}
}
}
// The definitions are loaded, we put them in the cache
$this->validatorCache->setCache(
serialize($this->definitions),
$this->definitionFiles
);
} elseif (($cache = $this->validatorCache->getCache()) !== null) {
// We retrieve data from cache
$this->definitions = unserialize($cache);
}
}
private function getDefinitionsByVersion(string $version): array
{
$versionPath = $this->validationFilePath . DIRECTORY_SEPARATOR . $version;
$directoryIterator = new \RecursiveDirectoryIterator($versionPath);
$recursiveIterator = new \RecursiveIteratorIterator($directoryIterator);
$yamlFiles = new \RegexIterator($recursiveIterator, '/^.+\.yaml/i', \RecursiveRegexIterator::GET_MATCH);
$definitions = [];
foreach ($yamlFiles as $file) {
$definitions = array_merge_recursive(
$definitions,
$this->getDefinitionsByFile($file[0])
);
}
return [$version => $definitions];
}
/**
* Get the definitions found in the file.
*
* @param string $pathFilename Path name of the definition file
* @return array Returns the definitions found
*/
private function getDefinitionsByFile(string $pathFilename): array
{
$this->definitionFiles[] = new FileResource($pathFilename);
if (($yamlData = file_get_contents($pathFilename)) !== false) {
return Yaml::parse($yamlData);
}
return [];
}
/**
* Format the validation errors.
*
* @param array $errors Errors list
* @param string $json Serialized JSON data to analyse
* @return ConstraintViolationListInterface Returns the formatted error list
*/
private function formatErrors(array $errors, string $json): ConstraintViolationListInterface
{
$jsonData = json_decode($json, true);
$constraints = new ConstraintViolationList();
foreach ($errors as $error) {
$originalValue = $this->getOriginalValue(explode('.', $error['property']), $jsonData);
$constraints->add(
new ConstraintViolation(
$error['message'],
null,
[],
'Downtime',
$error['property'],
$originalValue
)
);
}
return $constraints;
}
/**
* Retrieve the original value corresponding to the property in the JSON data.
*
* @param array $root property path (ex: my_object.date or date)
* @param array $data Data for which we want to find the value of the given key
* @return string|null If found, returns the value otherwise null
*/
private function getOriginalValue(array $root, array $data): ?string
{
$firstKeyToFind = array_shift($root);
if (array_key_exists($firstKeyToFind, $data)) {
if (is_array($data[$firstKeyToFind])) {
return $this->getOriginalValue($root, $data[$firstKeyToFind]);
}
if (\is_bool($data[$firstKeyToFind])) {
return ($data[$firstKeyToFind]) ? 'true' : 'false';
}
return (string) $data[$firstKeyToFind];
}
return null;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Service/JsonValidator/ValidatorException.php | centreon/src/Centreon/Domain/Service/JsonValidator/ValidatorException.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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);
namespace Centreon\Domain\Service\JsonValidator;
class ValidatorException extends \Exception
{
public function __construct($message = '', $code = 0, ?\Throwable $previous = null)
{
parent::__construct($message, $code, $previous);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Service/JsonValidator/Interfaces/JsonValidatorInterface.php | centreon/src/Centreon/Domain/Service/JsonValidator/Interfaces/JsonValidatorInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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);
namespace Centreon\Domain\Service\JsonValidator\Interfaces;
use Symfony\Component\Validator\ConstraintViolationListInterface;
interface JsonValidatorInterface
{
/**
* Validate a JSON string according to a model.
*
* @param string $json String representing the JSON to validate
* @param string $modelName Model name to apply to validate the JSON
* @throws \Exception
* @return ConstraintViolationListInterface
*/
public function validate(string $json, string $modelName): ConstraintViolationListInterface;
/**
* Defines the version of the definition files that will be used for the validation process.
*
* @param string $version Version to use for the definition files
* @return $this
*/
public function forVersion(string $version): JsonValidatorInterface;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Service/JsonValidator/Interfaces/ValidatorCacheInterface.php | centreon/src/Centreon/Domain/Service/JsonValidator/Interfaces/ValidatorCacheInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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);
namespace Centreon\Domain\Service\JsonValidator\Interfaces;
interface ValidatorCacheInterface
{
/**
* Stores data in the cache file.
*
* @param string $data Data to store
* @param array $metadata Metadata list
*/
public function setCache(string $data, array $metadata = []): void;
/**
* Get the pathname of cache file.
*
* @return string
*/
public function getCacheFile(): string;
/**
* Get the cached data.
*
* @return string|null
*/
public function getCache(): ?string;
/**
* Indicates whether cache is valid or not.
* <br\>**Warning**, with Docker the "filemtime" function returns the start date of
* the Container and not the modification date of the file.
* So when debug = TRUE, the Cache will not be able to detect the
* modifications of the YAML definition files stored in metadata.
*
* @return bool Returns TRUE if the cache is valid
*/
public function isCacheValid(): bool;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Proxy/Proxy.php | centreon/src/Centreon/Domain/Proxy/Proxy.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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);
namespace Centreon\Domain\Proxy;
/**
* This class is designed to represent a proxy configuration.
*
* @package Centreon\Domain\Proxy
*/
class Proxy
{
public const PROTOCOL_HTTP = 'http://';
public const PROTOCOL_HTTPS = 'https://';
/**
* @see https://metacpan.org/pod/LWP::Protocol::connect
*/
public const PROTOCOL_CONNECT = 'connect://';
/**
* @var string[]
*/
public const AVAILABLE_PROTOCOLS = [
self::PROTOCOL_HTTP,
self::PROTOCOL_HTTPS,
self::PROTOCOL_CONNECT,
];
/** @var string|null */
private $url;
/** @var int|null */
private $port;
/** @var string|null */
private $user;
/** @var string|null */
private $password;
/** @var string Proxy connection protocol (default: Proxy::PROTOCOL_HTTP) */
private $protocol = self::PROTOCOL_HTTP;
public function __construct()
{
}
/**
* **Available formats:**
*
* <<procotol>>://<<user>>:<<password>>@<<url>>:<<port>>
*
* <<procotol>>://<<user>>:<<password>>@<<url>>
*
* <<procotol>>://<<url>>:<<port>>
*
* <<procotol>>://<<url>>
*
* @return string
*/
public function __toString(): string
{
$uri = '';
if (! empty($this->url)) {
$uri .= $this->protocol;
if (! empty($this->user)) {
$uri .= $this->user . ':' . $this->password . '@';
}
if (! empty($this->port) && $this->port > 0 && $this->port < 65536) {
$uri .= $this->url . ':' . $this->port;
} else {
$uri .= $this->url;
}
}
return $uri;
}
/**
* @return string|null
*/
public function getUrl(): ?string
{
return $this->url;
}
/**
* @param string|null $url an empty url will not be taken into account
* @return Proxy
*/
public function setUrl(?string $url): Proxy
{
if (! empty($url)) {
$this->url = $url;
}
return $this;
}
/**
* @return int|null
*/
public function getPort(): ?int
{
return $this->port;
}
/**
* @param int|null $port Numerical value (0 >= PORT <= 65535)
* @throws \InvalidArgumentException
* @return Proxy
*/
public function setPort(?int $port): Proxy
{
if ($port >= 0 && $port <= 65535) {
$this->port = $port;
} else {
throw new \InvalidArgumentException(
sprintf(_('The port can only be between 0 and 65535 inclusive'))
);
}
return $this;
}
/**
* @return string|null
*/
public function getUser(): ?string
{
return $this->user;
}
/**
* @param string|null $user an empty user will not be taken into account
* @return Proxy
*/
public function setUser(?string $user): Proxy
{
if (! empty($user)) {
$this->user = $user;
}
return $this;
}
/**
* @return string|null
*/
public function getPassword(): ?string
{
return $this->password;
}
/**
* @param string|null $password
* @return Proxy
*/
public function setPassword(?string $password): Proxy
{
$this->password = $password;
return $this;
}
/**
* @return string
*/
public function getProtocol(): string
{
return $this->protocol;
}
/**
* @param string $protocol
* @throws \InvalidArgumentException
* @return Proxy
* @see Proxy::PROTOCOL_HTTP
* @see Proxy::PROTOCOL_HTTPS
* @see Proxy::PROTOCOL_CONNECT
*/
public function setProtocol(string $protocol): Proxy
{
if (! in_array($protocol, static::AVAILABLE_PROTOCOLS)) {
throw new \InvalidArgumentException(
sprintf(_('Protocol %s is not allowed'), $protocol)
);
}
$this->protocol = $protocol;
return $this;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Proxy/ProxyService.php | centreon/src/Centreon/Domain/Proxy/ProxyService.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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);
namespace Centreon\Domain\Proxy;
use Centreon\Domain\Proxy\Interfaces\ProxyRepositoryInterface;
use Centreon\Domain\Proxy\Interfaces\ProxyServiceInterface;
/**
* This class is designed to manage proxy-related actions such as configuration.
*
* @package Centreon\Domain\Proxy
*/
class ProxyService implements ProxyServiceInterface
{
/** @var ProxyRepositoryInterface */
private $proxyRepository;
/**
* ProxyService constructor.
*
* @param ProxyRepositoryInterface $proxyRepository
*/
public function __construct(ProxyRepositoryInterface $proxyRepository)
{
$this->proxyRepository = $proxyRepository;
}
/**
* @inheritDoc
*/
public function getProxy(): Proxy
{
return $this->proxyRepository->getProxy();
}
/**
* @inheritDoc
*/
public function updateProxy(Proxy $proxy): void
{
$this->proxyRepository->updateProxy($proxy);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Proxy/Interfaces/ProxyServiceInterface.php | centreon/src/Centreon/Domain/Proxy/Interfaces/ProxyServiceInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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);
namespace Centreon\Domain\Proxy\Interfaces;
use Centreon\Domain\Proxy\Proxy;
interface ProxyServiceInterface
{
/**
* Update the proxy configuration.
*
* @param Proxy $proxy Proxy details
*/
public function updateProxy(Proxy $proxy): void;
/**
* Get the proxy configuration.
*
* @return Proxy
*/
public function getProxy(): Proxy;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Domain/Proxy/Interfaces/ProxyRepositoryInterface.php | centreon/src/Centreon/Domain/Proxy/Interfaces/ProxyRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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);
namespace Centreon\Domain\Proxy\Interfaces;
use Centreon\Domain\Proxy\Proxy;
interface ProxyRepositoryInterface
{
/**
* Updates the proxy.
*
* @param Proxy $proxy Proxy to add
*/
public function updateProxy(Proxy $proxy): void;
/**
* Retrieve the proxy.
*
* @return Proxy
*/
public function getProxy(): Proxy;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Infrastructure/DatabaseConnection.php | centreon/src/Centreon/Infrastructure/DatabaseConnection.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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);
namespace Centreon\Infrastructure;
use Adaptation\Database\Connection\Adapter\Pdo\Transformer\PdoParameterTypeTransformer;
use Adaptation\Database\Connection\Collection\QueryParameters;
use Adaptation\Database\Connection\ConnectionInterface;
use Adaptation\Database\Connection\Exception\ConnectionException;
use Adaptation\Database\Connection\Model\ConnectionConfig;
use Adaptation\Database\Connection\Trait\ConnectionTrait;
use Adaptation\Database\Connection\ValueObject\QueryParameter;
use Centreon\Domain\Log\Logger;
use Core\Common\Infrastructure\ExceptionLogger\ExceptionLogger;
use Psr\Log\LogLevel;
/**
* This class extend the PDO class and can be used to create a database
* connection.
* This class is used by all database repositories.
*
* @class DatabaseConnection
* @package Centreon\Infrastructure
*/
class DatabaseConnection extends \PDO implements ConnectionInterface
{
use ConnectionTrait;
/**
* By default, the queries are buffered.
*
* @var bool
*/
private bool $isBufferedQueryActive = true;
/**
* DatabaseConnection constructor.
*
* @param ConnectionConfig $connectionConfig
*
* @throws ConnectionException
*/
public function __construct(
private readonly ConnectionConfig $connectionConfig,
) {
try {
parent::__construct(
$this->connectionConfig->getMysqlDsn(),
$this->connectionConfig->getUser(),
$this->connectionConfig->getPassword(),
[
\PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES {$this->connectionConfig->getCharset()}",
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
]
);
} catch (\PDOException $exception) {
$this->writeDbLog(
message: "Unable to connect to database : {$exception->getMessage()}",
customContext: ['dsn_mysql' => $this->connectionConfig->getMysqlDsn()],
previous: $exception,
);
throw ConnectionException::connectionFailed($exception);
}
}
/**
* Factory
*
* @param ConnectionConfig $connectionConfig
*
* @throws ConnectionException
* @return DatabaseConnection
*/
public static function createFromConfig(ConnectionConfig $connectionConfig): self
{
return new self($connectionConfig);
}
/**
* switch connection to another database
*
* @param string $dbName
*
* @throws ConnectionException
*/
public function switchToDb(string $dbName): void
{
$this->executeStatement('use ' . $dbName);
}
/**
* @return ConnectionConfig
*/
public function getConnectionConfig(): ConnectionConfig
{
return $this->connectionConfig;
}
/**
* To get the used native connection by DBAL (PDO, mysqli, ...).
*
* @return \PDO
*/
public function getNativeConnection(): \PDO
{
return $this;
}
/***
* Returns the ID of the last inserted row.
* If the underlying driver does not support identity columns, an exception is thrown.
*
* @throws ConnectionException
* @return string
*/
public function getLastInsertId(): string
{
try {
return (string) $this->lastInsertId();
} catch (\Throwable $exception) {
$this->writeDbLog(
message: 'Unable to get last insert id',
previous: $exception,
);
throw ConnectionException::getLastInsertFailed($exception);
}
}
/**
* Check if a connection with the database exist.
*
* @return bool
*/
public function isConnected(): bool
{
try {
$this->executeSelectQuery('SELECT 1');
return true;
} catch (ConnectionException $exception) {
$this->writeDbLog(
message: 'Unable to establish the connection.',
query: 'SELECT 1',
previous: $exception,
);
return false;
}
}
/**
* The usage of this method is discouraged. Use prepared statements.
*
* @param string $value
*
* @return string
*/
public function quoteString(string $value): string
{
return parent::quote($value);
}
// --------------------------------------- CUD METHODS -----------------------------------------
/**
* To execute all queries except the queries getting results (SELECT).
*
* Executes an SQL statement with the given parameters and returns the number of affected rows.
*
* Could be used for:
* - DML statements: INSERT, UPDATE, DELETE, etc.
* - DDL statements: CREATE, DROP, ALTER, etc.
* - DCL statements: GRANT, REVOKE, etc.
* - Session control statements: ALTER SESSION, SET, DECLARE, etc.
* - Other statements that don't yield a row set.
*
* @param string $query
* @param QueryParameters|null $queryParameters
*
* @throws ConnectionException
* @return int
*
* @example $queryParameters = QueryParameters::create([QueryParameter::int('id', 1), QueryParameter::string('name', 'John')]);
* $nbAffectedRows = $db->executeStatement('UPDATE table SET name = :name WHERE id = :id', $queryParameters);
* // $nbAffectedRows = 1
*/
public function executeStatement(string $query, ?QueryParameters $queryParameters = null): int
{
try {
if (empty($query)) {
throw ConnectionException::notEmptyQuery();
}
if (str_starts_with($query, 'SELECT') || str_starts_with($query, 'select')) {
throw ConnectionException::executeStatementBadFormat(
'Cannot use it with a SELECT query',
$query
);
}
$pdoStatement = $this->prepare($query);
if (! is_null($queryParameters) && ! $queryParameters->isEmpty()) {
/** @var QueryParameter $queryParameter */
foreach ($queryParameters->getIterator() as $queryParameter) {
$pdoStatement->bindValue(
$queryParameter->getName(),
$queryParameter->getValue(),
($queryParameter->getType() !== null)
? PdoParameterTypeTransformer::transformFromQueryParameterType(
$queryParameter->getType()
) : \PDO::PARAM_STR
);
}
}
$pdoStatement->execute();
return $pdoStatement->rowCount();
} catch (\Throwable $exception) {
$this->writeDbLog(
message: 'Unable to execute statement',
customContext: ['query_parameters' => $queryParameters],
query: $query,
previous: $exception,
);
throw ConnectionException::executeStatementFailed($exception, $query, $queryParameters);
}
}
// --------------------------------------- FETCH METHODS -----------------------------------------
/**
* Prepares and executes an SQL query and returns the first row of the result
* as a numerically indexed array.
*
* Could be only used with SELECT.
*
* @param string $query
* @param QueryParameters|null $queryParameters
*
* @throws ConnectionException
* @return array<int, mixed>|false false is returned if no rows are found
*
* @example $queryParameters = QueryParameters::create([QueryParameter::int('id', 1)]);
* $result = $db->fetchNumeric('SELECT * FROM table WHERE id = :id', $queryParameters);
* // $result = [0 => 1, 1 => 'John', 2 => 'Doe']
*/
public function fetchNumeric(string $query, ?QueryParameters $queryParameters = null): false|array
{
try {
$this->validateSelectQuery($query);
$pdoStatement = $this->executeSelectQuery($query, $queryParameters);
return $pdoStatement->fetch(\PDO::FETCH_NUM);
} catch (\Throwable $exception) {
$this->writeDbLog(
message: 'Unable to fetch numeric query',
customContext: ['query_parameters' => $queryParameters],
query: $query,
previous: $exception,
);
throw ConnectionException::fetchNumericQueryFailed($exception, $query, $queryParameters);
}
}
/**
* Prepares and executes an SQL query and returns the first row of the result as an associative array.
*
* Could be only used with SELECT.
*
* @param string $query
* @param QueryParameters|null $queryParameters
*
* @throws ConnectionException
* @return array<string, mixed>|false false is returned if no rows are found
*
* @example $queryParameters = QueryParameters::create([QueryParameter::int('id', 1)]);
* $result = $db->fetchAssociative('SELECT * FROM table WHERE id = :id', $queryParameters);
* // $result = ['id' => 1, 'name' => 'John', 'surname' => 'Doe']
*/
public function fetchAssociative(string $query, ?QueryParameters $queryParameters = null): false|array
{
try {
$this->validateSelectQuery($query);
$pdoStatement = $this->executeSelectQuery($query, $queryParameters);
return $pdoStatement->fetch(\PDO::FETCH_ASSOC);
} catch (\Throwable $exception) {
$this->writeDbLog(
message: 'Unable to fetch associative query',
customContext: ['query_parameters' => $queryParameters],
query: $query,
previous: $exception,
);
throw ConnectionException::fetchAssociativeQueryFailed($exception, $query, $queryParameters);
}
}
/**
* Prepares and executes an SQL query and returns the value of a single column
* of the first row of the result.
*
* Could be only used with SELECT.
*
* @param string $query
* @param QueryParameters|null $queryParameters
*
* @throws ConnectionException
* @return mixed|false false is returned if no rows are found
*
* @example $queryParameters = QueryParameters::create([QueryParameter::string('name', 'John')]);
* $result = $db->fetchOne('SELECT name FROM table WHERE name = :name', $queryParameters);
* // $result = 'John'
*/
public function fetchOne(string $query, ?QueryParameters $queryParameters = null): mixed
{
try {
$this->validateSelectQuery($query);
$pdoStatement = $this->executeSelectQuery($query, $queryParameters);
return $pdoStatement->fetch(\PDO::FETCH_COLUMN);
} catch (\Throwable $exception) {
$this->writeDbLog(
message: 'Unable to fetch one query',
customContext: ['query_parameters' => $queryParameters],
query: $query,
previous: $exception,
);
throw ConnectionException::fetchOneQueryFailed($exception, $query, $queryParameters);
}
}
/**
* Prepares and executes an SQL query and returns the result as an array of the first column values.
*
* Could be only used with SELECT.
*
* @param string $query
* @param QueryParameters|null $queryParameters
*
* @throws ConnectionException
* @return list<mixed>
*
* @example $queryParameters = QueryParameters::create([QueryParameter::bool('active', true)]);
* $result = $db->fetchFirstColumn('SELECT name FROM table WHERE active = :active', $queryParameters);
* // $result = ['John', 'Jean']
*/
public function fetchFirstColumn(string $query, ?QueryParameters $queryParameters = null): array
{
try {
$this->validateSelectQuery($query);
$pdoStatement = $this->executeSelectQuery($query, $queryParameters);
return $pdoStatement->fetchAll(\PDO::FETCH_COLUMN);
} catch (\Throwable $exception) {
$this->writeDbLog(
message: 'Unable to fetch by column query',
customContext: ['query_parameters' => $queryParameters],
query: $query,
previous: $exception,
);
throw ConnectionException::fetchFirstColumnQueryFailed($exception, $query, $queryParameters);
}
}
/**
* Prepares and executes an SQL query and returns the result as an array of numeric arrays.
*
* Could be only used with SELECT.
*
* @param string $query
* @param QueryParameters|null $queryParameters
*
* @throws ConnectionException
* @return array<array<int,mixed>>
*
* @example $queryParameters = QueryParameters::create([QueryParameter::bool('active', true)]);
* $result = $db->fetchAllNumeric('SELECT * FROM table WHERE active = :active', $queryParameters);
* // $result = [[0 => 1, 1 => 'John', 2 => 'Doe'], [0 => 2, 1 => 'Jean', 2 => 'Dupont']]
*/
public function fetchAllNumeric(string $query, ?QueryParameters $queryParameters = null): array
{
try {
$this->validateSelectQuery($query);
$pdoStatement = $this->executeSelectQuery($query, $queryParameters);
return $pdoStatement->fetchAll(\PDO::FETCH_NUM);
} catch (\Throwable $exception) {
$this->writeDbLog(
message: 'Unable to fetch all numeric query',
customContext: ['query_parameters' => $queryParameters],
query: $query,
previous: $exception,
);
throw ConnectionException::fetchAllNumericQueryFailed($exception, $query, $queryParameters);
}
}
/**
* Prepares and executes an SQL query and returns the result as an array of associative arrays.
*
* Could be only used with SELECT.
*
* @param string $query
* @param QueryParameters|null $queryParameters
*
* @throws ConnectionException
* @return array<array<string,mixed>>
*
* @example $queryParameters = QueryParameters::create([QueryParameter::bool('active', true)]);
* $result = $db->fetchAllAssociative('SELECT * FROM table WHERE active = :active', $queryParameters);
* // $result = [['id' => 1, 'name' => 'John', 'surname' => 'Doe'], ['id' => 2, 'name' => 'Jean', 'surname' => 'Dupont']]
*/
public function fetchAllAssociative(string $query, ?QueryParameters $queryParameters = null): array
{
try {
$this->validateSelectQuery($query);
$pdoStatement = $this->executeSelectQuery($query, $queryParameters);
return $pdoStatement->fetchAll(\PDO::FETCH_ASSOC);
} catch (\Throwable $exception) {
$this->writeDbLog(
message: 'Unable to fetch all associative query',
customContext: ['query_parameters' => $queryParameters],
query: $query,
previous: $exception,
);
throw ConnectionException::fetchAllAssociativeQueryFailed($exception, $query, $queryParameters);
}
}
/**
* Prepares and executes an SQL query and returns the result as an associative array with the keys
* mapped to the first column and the values mapped to the second column.
*
* Could be only used with SELECT.
*
* @param string $query
* @param QueryParameters|null $queryParameters
*
* @throws ConnectionException
* @return array<int|string,mixed>
*
* @example $queryParameters = QueryParameters::create([QueryParameter::bool('active', true)]);
* $result = $db->fetchAllKeyValue('SELECT name, surname FROM table WHERE active = :active', $queryParameters);
* // $result = ['John' => 'Doe', 'Jean' => 'Dupont']
*/
public function fetchAllKeyValue(string $query, ?QueryParameters $queryParameters = null): array
{
try {
$this->validateSelectQuery($query);
$pdoStatement = $this->executeSelectQuery($query, $queryParameters);
return $pdoStatement->fetchAll(\PDO::FETCH_KEY_PAIR);
} catch (\Throwable $exception) {
$this->writeDbLog(
message: 'Unable to fetch all key value query',
customContext: ['query_parameters' => $queryParameters],
query: $query,
previous: $exception,
);
throw ConnectionException::fetchAllKeyValueQueryFailed($exception, $query, $queryParameters);
}
}
// --------------------------------------- ITERATE METHODS -----------------------------------------
/**
* Prepares and executes an SQL query and returns the result as an iterator over rows represented as numeric arrays.
*
* Could be only used with SELECT.
*
* @param string $query
* @param QueryParameters|null $queryParameters
*
* @throws ConnectionException
* @return \Traversable<int,list<mixed>>
*
* @example $queryParameters = QueryParameters::create([QueryParameter::bool('active', true)]);
* $result = $db->iterateNumeric('SELECT * FROM table WHERE active = :active', $queryParameters);
* foreach ($result as $row) {
* // $row = [0 => 1, 1 => 'John', 2 => 'Doe']
* // $row = [0 => 2, 1 => 'Jean', 2 => 'Dupont']
* }
*/
public function iterateNumeric(string $query, ?QueryParameters $queryParameters = null): \Traversable
{
try {
$this->validateSelectQuery($query);
$pdoStatement = $this->executeSelectQuery($query, $queryParameters);
while (($row = $pdoStatement->fetch(\PDO::FETCH_NUM)) !== false) {
yield $row;
}
} catch (\Throwable $exception) {
$this->writeDbLog(
message: 'Unable to iterate numeric query',
customContext: ['query_parameters' => $queryParameters],
query: $query,
previous: $exception,
);
throw ConnectionException::iterateNumericQueryFailed($exception, $query, $queryParameters);
}
}
/**
* Prepares and executes an SQL query and returns the result as an iterator over rows represented
* as associative arrays.
*
* Could be only used with SELECT.
*
* @param string $query
* @param QueryParameters|null $queryParameters
*
* @throws ConnectionException
* @return \Traversable<int,array<string,mixed>>
*
* @example $queryParameters = QueryParameters::create([QueryParameter::bool('active', true)]);
* $result = $db->iterateAssociative('SELECT * FROM table WHERE active = :active', $queryParameters);
* foreach ($result as $row) {
* // $row = ['id' => 1, 'name' => 'John', 'surname' => 'Doe']
* // $row = ['id' => 2, 'name' => 'Jean', 'surname' => 'Dupont']
* }
*/
public function iterateAssociative(string $query, ?QueryParameters $queryParameters = null): \Traversable
{
try {
$this->validateSelectQuery($query);
$pdoStatement = $this->executeSelectQuery($query, $queryParameters);
while (($row = $pdoStatement->fetch(\PDO::FETCH_ASSOC)) !== false) {
yield $row;
}
} catch (\Throwable $exception) {
$this->writeDbLog(
message: 'Unable to iterate associative query',
customContext: ['query_parameters' => $queryParameters],
query: $query,
previous: $exception,
);
throw ConnectionException::iterateAssociativeQueryFailed($exception, $query, $queryParameters);
}
}
/**
* Prepares and executes an SQL query and returns the result as an iterator over the column values.
*
* Could be only used with SELECT.
*
* @param string $query
* @param QueryParameters|null $queryParameters
*
* @throws ConnectionException
* @return \Traversable<int,list<mixed>>
*
* @example $queryParameters = QueryParameters::create([QueryParameter::bool('active', true)]);
* $result = $db->iterateColumn('SELECT name FROM table WHERE active = :active', $queryParameters);
* foreach ($result as $value) {
* // $value = 'John'
* // $value = 'Jean'
* }
*/
public function iterateColumn(string $query, ?QueryParameters $queryParameters = null): \Traversable
{
try {
$this->validateSelectQuery($query);
$pdoStatement = $this->executeSelectQuery($query, $queryParameters);
while (($row = $pdoStatement->fetch(\PDO::FETCH_COLUMN)) !== false) {
yield $row;
}
} catch (\Throwable $exception) {
$this->writeDbLog(
message: 'Unable to iterate by column query',
customContext: ['query_parameters' => $queryParameters],
query: $query,
previous: $exception,
);
throw ConnectionException::iterateColumnQueryFailed($exception, $query, $queryParameters);
}
}
// ----------------------------------------- TRANSACTIONS -----------------------------------------
/**
* Checks whether a transaction is currently active.
*
* @return bool TRUE if a transaction is currently active, FALSE otherwise
*/
public function isTransactionActive(): bool
{
return parent::inTransaction();
}
/**
* Opens a new transaction. This must be closed by calling one of the following methods:
* {@see commitTransaction} or {@see rollBackTransaction}
*
* @throws ConnectionException
* @return void
*/
public function startTransaction(): void
{
try {
$this->beginTransaction();
} catch (\Throwable $exception) {
$this->writeDbLog(
message: 'Unable to start transaction',
previous: $exception,
);
throw ConnectionException::startTransactionFailed($exception);
}
}
/**
* To validate a transaction.
*
* @throws ConnectionException
* @return bool
*/
public function commitTransaction(): bool
{
try {
if (! parent::commit()) {
throw ConnectionException::commitTransactionFailed();
}
return true;
} catch (\Throwable $exception) {
$this->writeDbLog(
message: 'Unable to commit transaction',
previous: $exception,
);
throw ConnectionException::commitTransactionFailed($exception);
}
}
/**
* To cancel a transaction.
*
* @throws ConnectionException
* @return bool
*/
public function rollBackTransaction(): bool
{
try {
if (! parent::rollBack()) {
throw ConnectionException::rollbackTransactionFailed();
}
return true;
} catch (\Throwable $exception) {
$this->writeDbLog(
message: 'Unable to rollback transaction',
previous: $exception,
);
throw ConnectionException::rollbackTransactionFailed($exception);
}
}
// ------------------------------------- UNBUFFERED QUERIES -----------------------------------------
/**
* Checks that the connection instance allows the use of unbuffered queries.
*
* @throws ConnectionException
*/
public function allowUnbufferedQuery(): bool
{
$currentDriverName = "pdo_{$this->getAttribute(\PDO::ATTR_DRIVER_NAME)}";
if (! in_array($currentDriverName, self::DRIVER_ALLOWED_UNBUFFERED_QUERY, true)) {
$this->writeDbLog(
message: 'Unbuffered queries are not allowed with this driver',
customContext: ['driver_name' => $currentDriverName]
);
throw ConnectionException::allowUnbufferedQueryFailed(parent::class, $currentDriverName);
}
return true;
}
/**
* Prepares a statement to execute a query without buffering. Only works for SELECT queries.
*
* @throws ConnectionException
* @return void
*/
public function startUnbufferedQuery(): void
{
$this->allowUnbufferedQuery();
if (! $this->setAttribute(\PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false)) {
$this->writeDbLog(message: 'Error while starting an unbuffered query');
throw ConnectionException::startUnbufferedQueryFailed();
}
$this->isBufferedQueryActive = false;
}
/**
* Checks whether an unbuffered query is currently active.
*
* @return bool
*/
public function isUnbufferedQueryActive(): bool
{
return $this->isBufferedQueryActive === false;
}
/**
* To close an unbuffered query.
*
* @throws ConnectionException
* @return void
*/
public function stopUnbufferedQuery(): void
{
if (! $this->isUnbufferedQueryActive()) {
$this->writeDbLog(
message: 'Error while stopping an unbuffered query, no unbuffered query is currently active'
);
throw ConnectionException::stopUnbufferedQueryFailed(
'Error while stopping an unbuffered query, no unbuffered query is currently active'
);
}
if (! $this->setAttribute(\PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true)) {
$this->writeDbLog(message: 'Error while stopping an unbuffered query');
throw ConnectionException::stopUnbufferedQueryFailed('Error while stopping an unbuffered query');
}
$this->isBufferedQueryActive = true;
}
// --------------------------------------- BASE METHODS -----------------------------------------
/**
* @param \PDOStatement $pdoStatement
*
* @throws ConnectionException
* @return bool
*/
public function closeQuery(\PDOStatement $pdoStatement): bool
{
try {
return $pdoStatement->closeCursor();
} catch (\Throwable $exception) {
$this->writeDbLog(
message: "Error while closing the \PDOStatement cursor: {$exception->getMessage()}",
query: $pdoStatement->queryString,
previous: $exception,
);
throw ConnectionException::closeQueryFailed($exception, $pdoStatement->queryString);
}
}
// --------------------------------------- PROTECTED METHODS -----------------------------------------
/**
* Write SQL errors messages
*
* @param string $message
* @param array<string,mixed> $customContext
* @param string $query
* @param \Throwable|null $previous
*/
protected function writeDbLog(
string $message,
array $customContext = [],
string $query = '',
?\Throwable $previous = null,
): void {
// prepare context of the database exception
$context = [
'database_name' => $this->connectionConfig->getDatabaseNameConfiguration(),
'database_connector' => self::class,
'query' => $query,
];
if (! is_null($previous)) {
ExceptionLogger::create()->log($previous, $context, LogLevel::CRITICAL);
} else {
Logger::create()->critical($message, $context);
}
}
// --------------------------------------- PRIVATE METHODS -----------------------------------------
/**
* To execute all queries starting with SELECT.
*
* Only for SELECT queries.
*
* @param string $query
* @param QueryParameters|null $queryParameters
*
* @throws ConnectionException
* @return \PDOStatement
*/
private function executeSelectQuery(
string $query,
?QueryParameters $queryParameters = null,
): \PDOStatement {
try {
$this->validateSelectQuery($query);
$pdoStatement = $this->prepare($query);
if (! is_null($queryParameters) && ! $queryParameters->isEmpty()) {
/** @var QueryParameter $queryParameter */
foreach ($queryParameters->getIterator() as $queryParameter) {
$pdoStatement->bindValue(
$queryParameter->getName(),
$queryParameter->getValue(),
($queryParameter->getType() !== null)
? PdoParameterTypeTransformer::transformFromQueryParameterType(
$queryParameter->getType()
) : \PDO::PARAM_STR
);
}
}
$pdoStatement->execute();
return $pdoStatement;
} catch (\Throwable $exception) {
$this->writeDbLog(
message: 'Error while executing the select query',
customContext: ['query_parameters' => $queryParameters],
query: $query,
previous: $exception,
);
throw ConnectionException::selectQueryFailed(
previous: $exception,
query: $query,
queryParameters: $queryParameters
);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Infrastructure/Event/FileLoader.php | centreon/src/Centreon/Infrastructure/Event/FileLoader.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Infrastructure\Event;
/**
* This class is used to find and include a specific php file in a tree.
*
* @package Centreon\Domain\Entity
*/
class FileLoader implements DispatcherLoaderInterface
{
/** @var string Path where we will try to find php files */
private $pathModules;
/** @var string Name of the php file to find in path */
private $filename;
/**
* FileLoader constructor.
*
* @param string $pathModules Path where we will try to find php files
* @param string $filename Name of the php file to find in path
*/
public function __construct(string $pathModules, string $filename)
{
$this->pathModules = $pathModules;
$this->filename = $filename;
}
/**
* Include all php file found.
*
* @throws \Exception
*/
public function load(): void
{
if (! is_dir($this->pathModules)) {
throw new \Exception(_('The path does not exist'));
}
$modules = scandir($this->pathModules);
foreach ($modules as $module) {
$fileToInclude = $this->pathModules . '/' . $module . '/' . $this->filename;
if (preg_match('/^(?!\.)/', $module)
&& is_dir($this->pathModules . '/' . $module)
&& file_exists($fileToInclude)
) {
require_once $fileToInclude;
}
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Infrastructure/Event/EventHandler.php | centreon/src/Centreon/Infrastructure/Event/EventHandler.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Infrastructure\Event;
/**
* This class is for use with the EventDispatcher class.
*
* @see EventDispatcher
* @package Centreon\Domain\Entity
*/
class EventHandler
{
/**
* @var array List of callable functions ordered by priority. They will be
* loaded before the callable functions defined in the list named 'processing'.
*/
private $preProcessing = [];
/**
* @var array List of callable functions ordered by priority. They will be
* loaded before the callable functions defined in the list named
* 'postProcessing' and after callable functions defined in the list named
* 'preProcessing'.
*/
private $processing = [];
/**
* @var array List of callable functions ordered by priority. They will be
* loaded after the callable functions defined in the list named 'processing'.
*/
private $postProcessing = [];
/**
* @see EventHandler::$preProcessing
* @return array list of callable functions ordered by priority
*/
public function getPreProcessing(): array
{
return $this->preProcessing;
}
/**
* @param callable $preProcessing Callable function
* @param int $priority Execution priority of the callable function
*/
public function setPreProcessing(callable $preProcessing, int $priority = 20): void
{
$this->preProcessing[$priority][] = $preProcessing;
}
/**
* @see EventHandler::$processing
* @return array list of callable functions ordered by priority
*/
public function getProcessing(): array
{
return $this->processing;
}
/**
* @param callable $processing Callable function.
* <code>
* <?php>
* $eventHandler = new EventHandler();
* $eventHandler->setProcessing(
* function(int $eventType, array $arguments, array $executionContext) {...},
* 20
* );
* ?>
* <code>
* @param int $priority Execution priority of the callable function
*/
public function setProcessing(callable $processing, int $priority = 20): void
{
$this->processing[$priority][] = $processing;
}
/**
* @see EventHandler::$postProcessing
* @return array list of callable functions ordered by priority
*/
public function getPostProcessing(): array
{
return $this->postProcessing;
}
/**
* @param callable $postProcessing Callable function
* @param int $priority Execution priority of the callable function
*/
public function setPostProcessing(callable $postProcessing, int $priority = 20): void
{
$this->postProcessing[$priority][] = $postProcessing;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Infrastructure/Event/EventDispatcher.php | centreon/src/Centreon/Infrastructure/Event/EventDispatcher.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Infrastructure\Event;
/**
* Class EventDispatcher
*
* @see EventHandler
* @package Centreon\Domain\Entity
*/
class EventDispatcher
{
/**
* Event types
*/
public const EVENT_ADD = 1;
public const EVENT_UPDATE = 2;
public const EVENT_DELETE = 4;
public const EVENT_READ = 8;
public const EVENT_DISPLAY = 16;
public const EVENT_DUPLICATE = 32;
public const EVENT_SYNCHRONIZE = 64;
/**
* @var array List a values returned by callable function defined in the
* event handler. Their values are partitioned by context name.
*/
private $executionContext = [];
/** @var mixed[] */
private $eventHandlers;
/** @var array sorted list of methods that will be called in the event handler */
private $eventMethods = ['preProcessing', 'processing', 'postProcessing'];
/** @var DispatcherLoaderInterface */
private $dispatcherLoader;
/**
* @return DispatcherLoaderInterface
*/
public function getDispatcherLoader(): ?DispatcherLoaderInterface
{
return $this->dispatcherLoader;
}
/**
* @param DispatcherLoaderInterface $dispatcherLoader loader that will be
* used to include PHP files in which we add event handlers
*/
public function setDispatcherLoader(DispatcherLoaderInterface $dispatcherLoader): void
{
$this->dispatcherLoader = $dispatcherLoader;
}
/**
* Add a new event handler which will be called by the method 'notify'
*
* @see EventDispatcher::notify()
* @param string $context Name of the context in which we add the event handler
* @param int $eventType Event type
* @param EventHandler $eventHandler Event handler to add
*/
public function addEventHandler(string $context, int $eventType, EventHandler $eventHandler): void
{
foreach ($this->eventMethods as $eventMethod) {
$methodName = 'get' . ucfirst($eventMethod);
foreach (call_user_func([$eventHandler, $methodName]) as $priority => $callables) {
$this->eventHandlers[$context][$eventType][$eventMethod][$priority] = array_merge(
$this->eventHandlers[$context][$eventType][$eventMethod][$priority] ?? [],
$callables
);
}
}
}
/**
* Notify all event handlers for a specific context and type of event.
*
* @param string $context name of the context in which we will call all the
* registered event handlers
* @param int $eventType Event type. Only event handlers registered for this event will be called.
* We can add several types of events using the binary operator '|'
* @param array $arguments Array of arguments that will be passed to callable
* functions defined in event handlers
*/
public function notify(string $context, int $eventType, $arguments = []): void
{
$sortedCallables = $this->getSortedCallables($context, $eventType);
/*
* Pay attention,
* The order of this loop is important because we have to call the
* callable functions in this precise order
* "pre-processing", "processing" and "post-processing".
*/
foreach ($this->eventMethods as $eventMethod) {
if (isset($sortedCallables[$eventMethod])) {
/*
* We will call all the callable functions defined in order of priority
* (from the lowest priority to the highest)
* All results returned by the callable functions will be saved
* in the execution context and isolated by the context name.
*/
foreach ($sortedCallables[$eventMethod] as $priority => $callables) {
foreach ($callables as $callable) {
$currentExecutionContext
= $this->executionContext[$context][$eventType] ?? [];
$result = call_user_func_array(
$callable,
[$arguments, $currentExecutionContext, $eventType]
);
if (isset($result)) {
$this->executionContext[$context][$eventType]
= array_merge(
$this->executionContext[$context][$eventType] ?? [],
$result
);
}
}
}
}
}
}
/**
* Retrieve all callable functions sorted by method and priority for a
* specific context and event type.
*
* @param string $context name of the context
* @param int $eventType event type
* @return array List of partitioned event handlers by processing method
* ('preProcessing', 'processing', 'postProcessing') and processing priority
*/
private function getSortedCallables(string $context, int $eventType): array
{
$sortedCallables = [];
if (isset($this->eventHandlers[$context])) {
foreach ($this->eventHandlers[$context] as $contextEventType => $callablesSortedByMethod) {
if ($contextEventType & $eventType) {
foreach ($callablesSortedByMethod as $method => $callablesSortedByPriority) {
foreach ($callablesSortedByPriority as $priority => $callables) {
$sortedCallables[$method][$priority] = array_merge_recursive(
$sortedCallables[$method][$priority] ?? [],
$callables
);
/*
* It is important to sort from the lowest priority
* to the highest because the callable function with
* the lowest priority will be called first.
*/
ksort($sortedCallables[$method]);
}
}
}
}
}
return $sortedCallables;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Infrastructure/Event/DispatcherLoaderInterface.php | centreon/src/Centreon/Infrastructure/Event/DispatcherLoaderInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Centreon\Infrastructure\Event;
interface DispatcherLoaderInterface
{
public function load(): void;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Infrastructure/ActionLog/ActionLogRepositoryRDB.php | centreon/src/Centreon/Infrastructure/ActionLog/ActionLogRepositoryRDB.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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);
namespace Centreon\Infrastructure\ActionLog;
use Centreon\Domain\ActionLog\ActionLog;
use Centreon\Domain\ActionLog\Interfaces\ActionLogRepositoryInterface;
use Centreon\Domain\Repository\RepositoryException;
use Centreon\Domain\RequestParameters\RequestParameters;
use Centreon\Infrastructure\DatabaseConnection;
use Centreon\Infrastructure\Repository\AbstractRepositoryDRB;
use Centreon\Infrastructure\RequestParameters\SqlRequestParametersTranslator;
class ActionLogRepositoryRDB extends AbstractRepositoryDRB implements ActionLogRepositoryInterface
{
/** @var SqlRequestParametersTranslator */
private $sqlRequestTranslator;
/**
* @param DatabaseConnection $db
* @param SqlRequestParametersTranslator $sqlRequestTranslator
*/
public function __construct(DatabaseConnection $db, SqlRequestParametersTranslator $sqlRequestTranslator)
{
$this->db = $db;
$this->sqlRequestTranslator = $sqlRequestTranslator;
$this->sqlRequestTranslator
->getRequestParameters()
->setConcordanceStrictMode(RequestParameters::CONCORDANCE_MODE_STRICT);
}
/**
* @inheritDoc
*/
public function addAction(ActionLog $actionLog): int
{
$request = $this->translateDbName(
'INSERT INTO `:dbstg`.log_action
(action_log_date, object_type, object_id, object_name, action_type, log_contact_id)
VALUES (:creation_date, :object_type, :object_id, :object_name, :action_type, :contact_id)'
);
$creationDate = $actionLog->getCreationDate() !== null
? $actionLog->getCreationDate()->getTimestamp()
: (new \DateTime())->getTimestamp();
$statement = $this->db->prepare($request);
$statement->bindValue(':creation_date', $creationDate, \PDO::PARAM_INT);
$statement->bindValue(':object_type', $actionLog->getObjectType(), \PDO::PARAM_STR);
$statement->bindValue(':object_id', $actionLog->getObjectId(), \PDO::PARAM_INT);
$statement->bindValue(':object_name', $actionLog->getObjectName(), \PDO::PARAM_STR);
$statement->bindValue(':action_type', $actionLog->getActionType(), \PDO::PARAM_STR);
$statement->bindValue(':contact_id', $actionLog->getContactId(), \PDO::PARAM_INT);
$statement->execute();
return (int) $this->db->lastInsertId();
}
/**
* @inheritDoc
*/
public function addDetailsOfAction(ActionLog $actionLog, array $details): void
{
if ($actionLog->getId() === null) {
throw new RepositoryException(_('Action log id can not be null'));
}
if ($details === []) {
return;
}
// We avoid to start again a database transaction
$isAlreadyInTransaction = $this->db->inTransaction();
if (! $isAlreadyInTransaction) {
$this->db->beginTransaction();
}
try {
$statement = $this->db->prepare(
$this->translateDbName(
'INSERT INTO `:dbstg`.log_action_modification (field_name, field_value, action_log_id)
VALUES (:field_name, :field_value, :action_log_id)'
)
);
foreach ($details as $fieldName => $fieldValue) {
$statement->bindValue(':field_name', $fieldName, \PDO::PARAM_STR);
$statement->bindValue(':field_value', $fieldValue, \PDO::PARAM_STR);
$statement->bindValue(':action_log_id', $actionLog->getId(), \PDO::PARAM_INT);
$statement->execute();
}
if (! $isAlreadyInTransaction) {
$this->db->commit();
}
} catch (\Exception $ex) {
if (! $isAlreadyInTransaction) {
$this->db->rollBack();
}
throw $ex;
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Infrastructure/Acknowledgement/AcknowledgementRepositoryRDB.php | centreon/src/Centreon/Infrastructure/Acknowledgement/AcknowledgementRepositoryRDB.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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);
namespace Centreon\Infrastructure\Acknowledgement;
use Centreon\Domain\Acknowledgement\Acknowledgement;
use Centreon\Domain\Acknowledgement\Interfaces\AcknowledgementRepositoryInterface;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Entity\EntityCreator;
use Centreon\Domain\RequestParameters\RequestParameters;
use Centreon\Infrastructure\DatabaseConnection;
use Centreon\Infrastructure\Repository\AbstractRepositoryDRB;
use Centreon\Infrastructure\RequestParameters\RequestParametersTranslatorException;
use Centreon\Infrastructure\RequestParameters\SqlRequestParametersTranslator;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
final class AcknowledgementRepositoryRDB extends AbstractRepositoryDRB implements AcknowledgementRepositoryInterface
{
/** @var SqlRequestParametersTranslator */
private $sqlRequestTranslator;
/** @var AccessGroup[] List of access group used to filter the requests */
private $accessGroups;
/** @var bool Indicates whether the contact is an admin or not */
private $isAdmin = false;
/** @var ContactInterface */
private $contact;
/** @var array<string, string> */
private $hostConcordanceArray = [
'author_id' => 'contact.contact_id',
'comment' => 'ack.comment_data',
'entry_time' => 'ack.entry_time',
'deletion_time' => 'ack.deletion_time',
'host_id' => 'ack.host_id',
'id' => 'ack.acknowledgement_id',
'is_notify_contacts' => 'ack.notify_contacts',
'is_persistent_comment' => 'ack.persistent_comment',
'is_sticky' => 'ack.sticky',
'poller_id' => 'ack.instance_id',
'state' => 'ack.state',
'type' => 'ack.type',
];
/** @var array<string, string> */
private $serviceConcordanceArray;
/**
* AcknowledgementRepositoryRDB constructor.
*
* @param DatabaseConnection $db
* @param SqlRequestParametersTranslator $sqlRequestTranslator
*/
public function __construct(
DatabaseConnection $db,
SqlRequestParametersTranslator $sqlRequestTranslator,
) {
$this->db = $db;
$this->sqlRequestTranslator = $sqlRequestTranslator;
$this->sqlRequestTranslator
->getRequestParameters()
->setConcordanceStrictMode(RequestParameters::CONCORDANCE_MODE_STRICT);
$this->serviceConcordanceArray = array_merge(
$this->hostConcordanceArray,
[
'service_id' => 'ack.service_id',
'service.display_name' => 'srv.display_name',
]
);
}
/**
* @inheritDoc
*/
public function filterByAccessGroups(?array $accessGroups): AcknowledgementRepositoryInterface
{
$this->accessGroups = $accessGroups;
return $this;
}
/**
* @inheritDoc
*/
public function setAdmin(bool $isAdmin): AcknowledgementRepositoryInterface
{
$this->isAdmin = $isAdmin;
return $this;
}
/**
* @inheritDoc
*/
public function getAdmin(): bool
{
return $this->isAdmin;
}
/**
* {@inheritDoc}
* @throws \PDOException
*/
public function findHostsAcknowledgements(): array
{
return $this->findAcknowledgementsOf(Acknowledgement::TYPE_HOST_ACKNOWLEDGEMENT);
}
/**
* {@inheritDoc}
* @throws \PDOException
*/
public function findServicesAcknowledgements(): array
{
return $this->findAcknowledgementsOf(Acknowledgement::TYPE_SERVICE_ACKNOWLEDGEMENT);
}
/**
* @inheritDoc
*/
public function findAcknowledgementsByHost(int $hostId): array
{
$acknowledgements = [];
if ($this->hasNotEnoughRightsToContinue()) {
return $acknowledgements;
}
$accessGroupFilter = $this->isAdmin()
? ' '
: ' INNER JOIN `:dbstg`.`centreon_acl` acl
ON acl.host_id = ack.host_id
INNER JOIN `:db`.`acl_groups` acg
ON acg.acl_group_id = acl.group_id
AND acg.acl_group_activate = \'1\'
AND acg.acl_group_id IN (' . $this->accessGroupIdToString($this->accessGroups) . ') ';
$request
= 'SELECT ack.*, contact.contact_id AS author_id
FROM `:dbstg`.acknowledgements ack
LEFT JOIN `:db`.contact
ON contact.contact_alias = ack.author'
. $accessGroupFilter
. 'WHERE ack.host_id = :host_id
AND ack.service_id = 0';
$this->sqlRequestTranslator->addSearchValue('host_id', [\PDO::PARAM_INT => $hostId]);
return $this->processListingRequest($request);
}
/**
* {@inheritDoc}
* @throws \PDOException
*/
public function findAcknowledgementsByService(int $hostId, int $serviceId): array
{
$acknowledgements = [];
if ($this->hasNotEnoughRightsToContinue()) {
return $acknowledgements;
}
$accessGroupFilter = $this->isAdmin()
? ' '
: ' INNER JOIN `:dbstg`.`centreon_acl` acl
ON acl.host_id = ack.host_id
AND acl.service_id = ack.service_id
INNER JOIN `:db`.`acl_groups` acg
ON acg.acl_group_id = acl.group_id
AND acg.acl_group_activate = \'1\'
AND acg.acl_group_id IN (' . $this->accessGroupIdToString($this->accessGroups) . ') ';
$request
= 'SELECT ack.*, contact.contact_id AS author_id
FROM `:dbstg`.acknowledgements ack
LEFT JOIN `:db`.contact
ON contact.contact_alias = ack.author'
. $accessGroupFilter
. 'WHERE ack.host_id = :host_id
AND ack.service_id = :service_id';
$this->sqlRequestTranslator->addSearchValue('host_id', [\PDO::PARAM_INT => $hostId]);
$this->sqlRequestTranslator->addSearchValue('service_id', [\PDO::PARAM_INT => $serviceId]);
return $this->processListingRequest($request);
}
/**
* {@inheritDoc}
* @throws \PDOException
*/
public function findLatestHostAcknowledgement(int $hostId): ?Acknowledgement
{
if ($this->hasNotEnoughRightsToContinue()) {
return null;
}
$accessGroupFilter = $this->isAdmin()
? ' '
: ' INNER JOIN `:dbstg`.`centreon_acl` acl
ON acl.host_id = ack2.host_id
INNER JOIN `:db`.`acl_groups` acg
ON acg.acl_group_id = acl.group_id
AND acg.acl_group_activate = \'1\'
AND acg.acl_group_id IN (' . $this->accessGroupIdToString($this->accessGroups) . ') ';
$request
= 'SELECT ack.*, contact.contact_id AS author_id
FROM `:dbstg`.acknowledgements ack
LEFT JOIN `:db`.contact
ON contact.contact_alias = ack.author
WHERE ack.acknowledgement_id = (
SELECT MAX(ack2.acknowledgement_id)
FROM `:dbstg`.acknowledgements ack2'
. $accessGroupFilter
. 'WHERE ack2.host_id = :host_id
AND ack2.service_id = 0)';
$request = $this->translateDbName($request);
$statement = $this->db->prepare($request);
$statement->bindValue(':host_id', $hostId, \PDO::PARAM_INT);
$statement->execute();
if ($result = $statement->fetch(\PDO::FETCH_ASSOC)) {
return EntityCreator::createEntityByArray(
Acknowledgement::class,
$result
);
}
return null;
}
/**
* {@inheritDoc}
* @throws \PDOException
*/
public function findLatestServiceAcknowledgement(int $hostId, int $serviceId): ?Acknowledgement
{
if ($this->hasNotEnoughRightsToContinue()) {
return null;
}
$accessGroupFilter = $this->isAdmin()
? ' '
: ' INNER JOIN `:dbstg`.`centreon_acl` acl
ON acl.host_id = ack2.host_id
AND acl.service_id = ack2.service_id
INNER JOIN `:db`.`acl_groups` acg
ON acg.acl_group_id = acl.group_id
AND acg.acl_group_activate = \'1\'
AND acg.acl_group_id IN (' . $this->accessGroupIdToString($this->accessGroups) . ') ';
$request
= 'SELECT ack.*, contact.contact_id AS author_id
FROM `:dbstg`.acknowledgements ack
LEFT JOIN `:db`.contact
ON contact.contact_alias = ack.author
WHERE ack.acknowledgement_id = (
SELECT MAX(ack2.acknowledgement_id)
FROM `:dbstg`.acknowledgements ack2'
. $accessGroupFilter
. 'WHERE ack2.host_id = :host_id
AND ack2.service_id = :service_id)';
$request = $this->translateDbName($request);
$statement = $this->db->prepare($request);
$statement->bindValue(':host_id', $hostId, \PDO::PARAM_INT);
$statement->bindValue(':service_id', $serviceId, \PDO::PARAM_INT);
$statement->execute();
if ($result = $statement->fetch(\PDO::FETCH_ASSOC)) {
return EntityCreator::createEntityByArray(
Acknowledgement::class,
$result
);
}
return null;
}
/**
* @inheritDoc
*/
public function findOneAcknowledgementForAdminUser(int $acknowledgementId): ?Acknowledgement
{
// Internal call for an admin user
return $this->findOneAcknowledgement($acknowledgementId, true);
}
/**
* @inheritDoc
*/
public function findOneAcknowledgementForNonAdminUser(int $acknowledgementId): ?Acknowledgement
{
if ($this->hasNotEnoughRightsToContinue()) {
return null;
}
// Internal call for non admin user
return $this->findOneAcknowledgement($acknowledgementId, false);
}
/**
* @inheritDoc
*/
public function findAcknowledgementsForAdminUser(): array
{
// Internal call for an admin user
return $this->findAcknowledgements(true);
}
/**
* @inheritDoc
*/
public function findAcknowledgementsForNonAdminUser(): array
{
if ($this->hasNotEnoughRightsToContinue()) {
return [];
}
// Internal call for non admin user
return $this->findAcknowledgements(false);
}
/**
* @inheritDoc
*/
public function setContact(ContactInterface $contact): AcknowledgementRepositoryInterface
{
$this->contact = $contact;
return $this;
}
/**
* Generic function to find acknowledgement.
*
* @param int $type Type of acknowledgement
* @throws \Exception
* @throws \PDOException
* @throws RequestParametersTranslatorException
* @return Acknowledgement[]
*/
private function findAcknowledgementsOf(int $type = Acknowledgement::TYPE_HOST_ACKNOWLEDGEMENT): array
{
$acknowledgements = [];
if ($this->hasNotEnoughRightsToContinue()) {
return $acknowledgements;
}
$accessGroupFilter = $this->isAdmin()
? ' '
: ' INNER JOIN `:dbstg`.`centreon_acl` acl
ON acl.host_id = ack.host_id'
. (
($type === Acknowledgement::TYPE_SERVICE_ACKNOWLEDGEMENT)
? ' AND acl.service_id = ack.service_id '
: ''
)
. ' INNER JOIN `:db`.`acl_groups` acg
ON acg.acl_group_id = acl.group_id
AND acg.acl_group_activate = \'1\'
AND acg.acl_group_id IN (' . $this->accessGroupIdToString($this->accessGroups) . ') ';
$this->sqlRequestTranslator->setConcordanceArray(
$type === Acknowledgement::TYPE_SERVICE_ACKNOWLEDGEMENT
? $this->serviceConcordanceArray
: $this->hostConcordanceArray
);
$request = 'SELECT ack.*, contact.contact_id AS author_id
FROM `:dbstg`.acknowledgements ack
LEFT JOIN `:db`.contact
ON contact.contact_alias = ack.author '
. $accessGroupFilter
. 'WHERE ack.service_id ' . (($type === Acknowledgement::TYPE_HOST_ACKNOWLEDGEMENT) ? ' = 0' : ' != 0');
return $this->processListingRequest($request);
}
/**
* Find one acknowledgement taking into account or not the ACLs.
*
* @param int $acknowledgementId Acknowledgement id
* @param bool $isAdmin Indicates whether user is an admin
* @throws \Exception
* @return Acknowledgement|null Return NULL if the acknowledgement has not been found
*/
private function findOneAcknowledgement(int $acknowledgementId, bool $isAdmin = false): ?Acknowledgement
{
$aclRequest = '';
if ($isAdmin === false) {
$aclRequest
= ' INNER JOIN `:dbstg`.`centreon_acl` acl
ON acl.host_id = ack.host_id
AND (acl.service_id = ack.service_id OR acl.service_id IS NULL)
INNER JOIN `:db`.`acl_groups` acg
ON acg.acl_group_id = acl.group_id
AND acg.acl_group_activate = \'1\'
AND acg.acl_group_id IN ('
. $this->accessGroupIdToString($this->accessGroups) . ') ';
}
$request
= 'SELECT SQL_CALC_FOUND_ROWS DISTINCT ack.*, contact.contact_id AS author_id
FROM `:dbstg`.acknowledgements ack
LEFT JOIN `:db`.`contact`
ON contact.contact_alias = ack.author'
. $aclRequest
. ' WHERE ack.acknowledgement_id = :acknowledgement_id';
$request = $this->translateDbName($request);
$prepare = $this->db->prepare($request);
$prepare->bindValue(':acknowledgement_id', $acknowledgementId, \PDO::PARAM_INT);
$prepare->execute();
if (false !== ($row = $prepare->fetch(\PDO::FETCH_ASSOC))) {
return EntityCreator::createEntityByArray(
Acknowledgement::class,
$row
);
}
return null;
}
/**
* Find all acknowledgements.
*
* @param bool $isAdmin Indicates whether user is an admin
* @throws \Exception
* @return Acknowledgement[]
*/
private function findAcknowledgements(bool $isAdmin): array
{
$this->sqlRequestTranslator->setConcordanceArray($this->serviceConcordanceArray);
$aclRequest = '';
if ($isAdmin === false) {
$aclRequest
= ' INNER JOIN `:dbstg`.`centreon_acl` acl
ON acl.host_id = ack.host_id
AND (acl.service_id = ack.service_id OR acl.service_id IS NULL)
INNER JOIN `:db`.`acl_groups` acg
ON acg.acl_group_id = acl.group_id
AND acg.acl_group_activate = \'1\'
AND acg.acl_group_id IN ('
. $this->accessGroupIdToString($this->accessGroups) . ') ';
}
$request
= 'SELECT SQL_CALC_FOUND_ROWS DISTINCT ack.*, contact.contact_id AS author_id
FROM `:dbstg`.acknowledgements ack
LEFT JOIN `:db`.`contact`
ON contact.contact_alias = ack.author
INNER JOIN `:dbstg`.hosts
ON hosts.host_id = ack.host_id
LEFT JOIN `:dbstg`.services srv
ON srv.service_id = ack.service_id
AND srv.host_id = hosts.host_id'
. $aclRequest;
return $this->processListingRequest($request);
}
/**
* Check if the current contact is admin
*
* @return bool
*/
private function isAdmin(): bool
{
return ($this->contact !== null)
? $this->contact->isAdmin()
: false;
}
/**
* @return bool return TRUE if the contact is an admin or has at least one access group
*/
private function hasNotEnoughRightsToContinue(): bool
{
return ($this->contact !== null)
? ! ($this->contact->isAdmin() || count($this->accessGroups) > 0)
: count($this->accessGroups) == 0;
}
/**
* Execute the request and retrieve the acknowledgements list
*
* @param string $request Request to execute
* @throws \Exception
* @return Acknowledgement[]
*/
private function processListingRequest(string $request): array
{
$request = $this->translateDbName($request);
// Search
$searchRequest = $this->sqlRequestTranslator->translateSearchParameterToSql();
$request .= ! is_null($searchRequest) ? $searchRequest : '';
// Sort
$sortRequest = $this->sqlRequestTranslator->translateSortParameterToSql();
$request .= ! is_null($sortRequest)
? $sortRequest
: ' ORDER BY ack.host_id, ack.service_id, ack.entry_time DESC';
// Pagination
$request .= $this->sqlRequestTranslator->translatePaginationToSql();
$statement = $this->db->prepare($request);
foreach ($this->sqlRequestTranslator->getSearchValues() as $key => $data) {
$type = key($data);
$value = $data[$type];
$statement->bindValue($key, $value, $type);
}
$statement->execute();
$result = $this->db->query('SELECT FOUND_ROWS()');
if ($result !== false && ($total = $result->fetchColumn()) !== false) {
$this->sqlRequestTranslator->getRequestParameters()->setTotal((int) $total);
}
$acknowledgements = [];
while (false !== ($result = $statement->fetch(\PDO::FETCH_ASSOC))) {
$acknowledgements[] = EntityCreator::createEntityByArray(
Acknowledgement::class,
$result
);
}
return $acknowledgements;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Infrastructure/PlatformTopology/Repository/PlatformTopologyRegisterRepositoryAPI.php | centreon/src/Centreon/Infrastructure/PlatformTopology/Repository/PlatformTopologyRegisterRepositoryAPI.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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);
namespace Centreon\Infrastructure\PlatformTopology\Repository;
use Centreon\Application\ApiPlatform;
use Centreon\Domain\PlatformInformation\Model\PlatformInformation;
use Centreon\Domain\PlatformTopology\Exception\PlatformTopologyException;
use Centreon\Domain\PlatformTopology\Interfaces\PlatformInterface;
use Centreon\Domain\PlatformTopology\Interfaces\PlatformTopologyRegisterRepositoryInterface;
use Centreon\Domain\Proxy\Proxy;
use Centreon\Infrastructure\PlatformTopology\Repository\Exception\PlatformTopologyRepositoryException;
use Symfony\Component\HttpClient\HttpClient;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\DecodingExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
class PlatformTopologyRegisterRepositoryAPI implements PlatformTopologyRegisterRepositoryInterface
{
/** @var HttpClientInterface */
private $httpClient;
/** @var ApiPlatform */
private $apiPlatform;
/**
* Central's API endpoints base path
*
* @var string
*/
private $baseApiEndpoint;
/**
* PlatformTopologyRegisterRepositoryAPI constructor.
* @param HttpClientInterface $httpClient
* @param ApiPlatform $apiPlatform
*/
public function __construct(HttpClientInterface $httpClient, ApiPlatform $apiPlatform)
{
$this->httpClient = $httpClient;
$this->apiPlatform = $apiPlatform;
}
/**
* @inheritDoc
*/
public function registerPlatformToParent(
PlatformInterface $platform,
PlatformInformation $platformInformation,
?Proxy $proxy = null,
): void {
/**
* Call the API on the n-1 server to register it too
*/
try {
// Get a Token
$token = $this->getToken($platformInformation, $proxy);
// Central's API register platform payload
$registerPayload = [
'json' => [
'name' => $platform->getName(),
'hostname' => $platform->getHostname(),
'type' => $platform->getType(),
'address' => $platform->getAddress(),
'parent_address' => $platform->getParentAddress(),
],
'headers' => [
'X-AUTH-TOKEN' => $token,
],
];
$registerResponse = $this->httpClient->request(
'POST',
$this->baseApiEndpoint . '/platform/topology',
$registerPayload
);
// Get request status code and return the error message
if ($registerResponse->getStatusCode() !== Response::HTTP_CREATED) {
$errorMessage = sprintf(
_("The platform: '%s'@'%s' cannot be added to the Central linked to this Remote"),
$platform->getName(),
$platform->getAddress()
);
$returnedMessage = json_decode($registerResponse->getContent(false), true);
if (! empty($returnedMessage)) {
$errorMessage .= ' / ' . _("Central's response => Code : ")
. implode(', ', $returnedMessage);
}
throw new PlatformTopologyException(
$errorMessage
);
}
} catch (TransportExceptionInterface $e) {
throw PlatformTopologyRepositoryException::apiRequestOnCentralException($e->getMessage());
} catch (ClientExceptionInterface $e) {
throw PlatformTopologyRepositoryException::apiClientException($e->getMessage());
} catch (RedirectionExceptionInterface $e) {
throw PlatformTopologyRepositoryException::apiRedirectionException($e->getMessage());
} catch (ServerExceptionInterface $e) {
$message = _('API calling the Central returned a Server exception');
throw PlatformTopologyRepositoryException::apiServerException($message, $e->getMessage());
} catch (DecodingExceptionInterface $e) {
throw PlatformTopologyRepositoryException::apiDecodingResponseFailure($e->getMessage());
} catch (\Exception $e) {
throw PlatformTopologyRepositoryException::apiUndeterminedError($e->getMessage());
}
}
/**
* @inheritDoc
*/
public function deletePlatformToParent(
PlatformInterface $platform,
PlatformInformation $platformInformation,
?Proxy $proxy = null,
): void {
try {
$token = $this->getToken($platformInformation, $proxy);
$getPayload = [
'headers' => [
'X-AUTH-TOKEN' => $token,
],
];
$getResponse = $this->httpClient->request(
'GET',
$this->baseApiEndpoint . '/platform/topology',
$getPayload
);
// Get request status code and return the error message
if ($getResponse->getStatusCode() !== Response::HTTP_OK) {
$errorMessage = sprintf(
_("The platform: '%s'@'%s' cannot be found on the Central"),
$platform->getName(),
$platform->getAddress()
);
$returnedMessage = json_decode($getResponse->getContent(false), true);
if (! empty($returnedMessage)) {
$errorMessage .= ' / ' . _("Central's response => Code : ")
. implode(', ', $returnedMessage);
}
throw new PlatformTopologyException(
$errorMessage
);
}
// Parse the response body to found the platform we want to delete
$responseBody = json_decode($getResponse->getContent(false), true);
$platformsOnParent = $responseBody['graph']['nodes'];
$platformToDeleteId = null;
foreach ($platformsOnParent as $topologyId => $platformOnParent) {
if ($platformOnParent['metadata']['address'] === $platform->getAddress()) {
$platformToDeleteId = $topologyId;
}
}
if ($platformToDeleteId === null) {
throw PlatformTopologyException::notFoundOnCentral(
$platform->getName(),
$platform->getAddress()
);
}
$deletePayload = [
'headers' => [
'X-AUTH-TOKEN' => $token,
],
];
$deleteResponse = $this->httpClient->request(
'DELETE',
$this->baseApiEndpoint . '/platform/topology/' . $platformToDeleteId,
$deletePayload
);
// Get request status code and return the error message
if ($deleteResponse->getStatusCode() !== Response::HTTP_NO_CONTENT) {
$errorMessage = sprintf(
_("The platform: '%s'@'%s' cannot be delete from the Central"),
$platform->getName(),
$platform->getAddress()
);
$returnedMessage = json_decode($deleteResponse->getContent(false), true);
if (! empty($returnedMessage)) {
$errorMessage .= ' / ' . _("Central's response => Code : ")
. implode(', ', $returnedMessage);
}
throw new PlatformTopologyException($errorMessage);
}
} catch (TransportExceptionInterface $e) {
throw PlatformTopologyRepositoryException::apiRequestOnCentralException($e->getMessage());
} catch (ClientExceptionInterface $e) {
throw PlatformTopologyRepositoryException::apiClientException($e->getMessage());
} catch (RedirectionExceptionInterface $e) {
throw PlatformTopologyRepositoryException::apiRedirectionException($e->getMessage());
} catch (ServerExceptionInterface $e) {
$message = _('API calling the Central returned a Server exception');
throw PlatformTopologyRepositoryException::apiServerException($message, $e->getMessage());
} catch (DecodingExceptionInterface $e) {
throw PlatformTopologyRepositoryException::apiDecodingResponseFailure($e->getMessage());
} catch (\Exception $e) {
throw PlatformTopologyRepositoryException::apiUndeterminedError($e->getMessage());
}
}
/**
* Get a valid token to request the API.
* @param PlatformInformation $platformInformation
* @param Proxy|null $proxy
* @throws ClientExceptionInterface
* @throws DecodingExceptionInterface
* @throws RedirectionExceptionInterface
* @throws PlatformTopologyRepositoryException
* @throws ServerExceptionInterface
* @throws TransportExceptionInterface
* @return string
*/
private function getToken(
PlatformInformation $platformInformation,
?Proxy $proxy = null,
): string {
// Central's API endpoints base path building
$this->baseApiEndpoint = $platformInformation->getApiScheme() . '://'
. $platformInformation->getCentralServerAddress() . ':'
. $platformInformation->getApiPort() . DIRECTORY_SEPARATOR
. $platformInformation->getApiPath() . '/api/v'
. ((string) $this->apiPlatform->getVersion());
// Enable specific options
$optionPayload = [];
// Enable proxy
if ($proxy !== null && ! empty((string) $proxy)) {
$optionPayload['proxy'] = (string) $proxy;
}
// On https scheme, the SSL verify_peer needs to be specified
if ($platformInformation->getApiScheme() === 'https') {
$optionPayload['verify_peer'] = $platformInformation->hasApiPeerValidation();
$optionPayload['verify_host'] = $platformInformation->hasApiPeerValidation();
}
// Set the options for next http_client calls
if ($optionPayload !== []) {
$this->httpClient = HttpClient::create($optionPayload);
}
// Central's API login payload
$loginPayload = [
'json' => [
'security' => [
'credentials' => [
'login' => $platformInformation->getApiUsername(),
'password' => $platformInformation->getApiCredentials(),
],
],
],
];
// Login on the Central to get a valid token
$loginResponse = $this->httpClient->request(
'POST',
$this->baseApiEndpoint . '/login',
$loginPayload
);
$token = $loginResponse->toArray()['security']['token'] ?? false;
if ($token === false) {
throw PlatformTopologyRepositoryException::failToGetToken($platformInformation->getCentralServerAddress());
}
return $token;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Infrastructure/PlatformTopology/Repository/PlatformTopologyRepositoryRDB.php | centreon/src/Centreon/Infrastructure/PlatformTopology/Repository/PlatformTopologyRepositoryRDB.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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);
namespace Centreon\Infrastructure\PlatformTopology\Repository;
use Centreon\Domain\PlatformTopology\Interfaces\PlatformInterface;
use Centreon\Domain\PlatformTopology\Interfaces\PlatformTopologyRepositoryInterface;
use Centreon\Infrastructure\DatabaseConnection;
use Centreon\Infrastructure\PlatformTopology\Repository\Model\PlatformTopologyFactoryRDB;
use Centreon\Infrastructure\Repository\AbstractRepositoryDRB;
use Core\Common\Infrastructure\Repository\SqlMultipleBindTrait;
/**
* This class is designed to manage the repository of the platform topology requests
*
* @package Centreon\Infrastructure\PlatformTopology
*
* @phpstan-type _platformTopology array{
* id: int,
* address:string,
* hostname: string|null,
* name: string,
* type: string,
* parent_id: int|null,
* pending: string|null,
* server_id: int|null
* }
*/
class PlatformTopologyRepositoryRDB extends AbstractRepositoryDRB implements PlatformTopologyRepositoryInterface
{
use SqlMultipleBindTrait;
/**
* PlatformTopologyRepositoryRDB constructor.
* @param DatabaseConnection $db
*/
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* @inheritDoc
*/
public function addPlatformToTopology(PlatformInterface $platform): void
{
$statement = $this->db->prepare(
$this->translateDbName('
INSERT INTO `:db`.platform_topology
(`address`, `name`, `type`, `parent_id`, `server_id`, `hostname`, `pending`)
VALUES (:address, :name, :type, :parentId, :serverId, :hostname, :pendingStatus)
')
);
$statement->bindValue(':address', $platform->getAddress(), \PDO::PARAM_STR);
$statement->bindValue(':name', $platform->getName(), \PDO::PARAM_STR);
$statement->bindValue(':type', $platform->getType(), \PDO::PARAM_STR);
$statement->bindValue(':parentId', $platform->getParentId(), \PDO::PARAM_INT);
$statement->bindValue(':serverId', $platform->getServerId(), \PDO::PARAM_INT);
$statement->bindValue(':hostname', $platform->getHostname(), \PDO::PARAM_STR);
$statement->bindValue(':pendingStatus', ($platform->isPending() ? '1' : '0'), \PDO::PARAM_STR);
$statement->execute();
}
/**
* @inheritDoc
*/
public function findPlatformByName(string $serverName): ?PlatformInterface
{
$statement = $this->db->prepare(
$this->translateDbName('
SELECT * FROM `:db`.platform_topology
WHERE `name` = :name
')
);
$statement->bindValue(':name', $serverName, \PDO::PARAM_STR);
$statement->execute();
$platform = null;
if ($result = $statement->fetch(\PDO::FETCH_ASSOC)) {
/** @var _platformTopology $result */
$platform = PlatformTopologyFactoryRDB::create($result);
}
return $platform;
}
/**
* @inheritDoc
*/
public function findPlatformByAddress(string $serverAddress): ?PlatformInterface
{
$statement = $this->db->prepare(
$this->translateDbName('
SELECT * FROM `:db`.platform_topology
WHERE `address` = :address
')
);
$statement->bindValue(':address', $serverAddress, \PDO::PARAM_STR);
$statement->execute();
$platform = null;
if ($result = $statement->fetch(\PDO::FETCH_ASSOC)) {
/** @var _platformTopology $result */
$platform = PlatformTopologyFactoryRDB::create($result);
}
return $platform;
}
/**
* @inheritDoc
*/
public function findTopLevelPlatformByType(string $serverType): ?PlatformInterface
{
$statement = $this->db->prepare(
$this->translateDbName('
SELECT * FROM `:db`.platform_topology
WHERE `type` = :type AND `parent_id` IS NULL
')
);
$statement->bindValue(':type', $serverType, \PDO::PARAM_STR);
$statement->execute();
$platform = null;
if ($result = $statement->fetch(\PDO::FETCH_ASSOC)) {
/** @var _platformTopology $result */
$platform = PlatformTopologyFactoryRDB::create($result);
}
return $platform;
}
/**
* @inheritDoc
*/
public function findLocalMonitoringIdFromName(string $serverName): ?PlatformInterface
{
$statement = $this->db->prepare(
$this->translateDbName('
SELECT `id` FROM `:db`.nagios_server
WHERE `localhost` = \'1\' AND ns_activate = \'1\' AND `name` = :name collate utf8_bin
')
);
$statement->bindValue(':name', $serverName, \PDO::PARAM_STR);
$statement->execute();
$platform = null;
if ($result = $statement->fetch(\PDO::FETCH_ASSOC)) {
/** @var int[] $result */
$platform = PlatformTopologyFactoryRDB::create($result);
}
return $platform;
}
/**
* @inheritDoc
*/
public function getPlatformTopology(): array
{
$statement = $this->db->query('SELECT * FROM `platform_topology`');
$platformTopology = [];
if ($statement !== false) {
foreach ($statement as $topology) {
/** @var _platformTopology $topology */
$platform = PlatformTopologyFactoryRDB::create($topology);
$platformTopology[] = $platform;
}
}
return $platformTopology;
}
/**
* @inheritDoc
*/
public function getPlatformTopologyByAccessGroupIds(array $accessGroupIds): array
{
if ($accessGroupIds === []) {
return [];
}
if (! $this->hasRestrictedAccessToPlatforms($accessGroupIds)) {
return $this->getPlatformTopology();
}
[$bindValues, $bindQuery] = $this->createMultipleBindQuery($accessGroupIds, ':access_group_id');
$statement = $this->db->prepare($this->translateDbName(
<<<SQL
SELECT *
FROM `platform_topology` pt
JOIN `:db`.`acl_resources_poller_relations` arpr
ON pt.server_id = arpr.poller_id
JOIN `:db`.`acl_res_group_relations` argr
ON arpr.acl_res_id = argr.acl_res_id
WHERE argr.acl_group_id IN ({$bindQuery})
SQL
));
foreach ($bindValues as $key => $value) {
$statement->bindValue($key, $value, \PDO::PARAM_INT);
}
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$statement->execute();
$platformTopology = [];
foreach ($statement as $topology) {
/** @var _platformTopology $topology */
$platform = PlatformTopologyFactoryRDB::create($topology);
$platformTopology[] = $platform;
}
return $platformTopology;
}
/**
* @inheritDoc
*/
public function findPlatform(int $platformId): ?PlatformInterface
{
$statement = $this->db->prepare('SELECT * FROM `platform_topology` WHERE id = :platformId');
$statement->bindValue(':platformId', $platformId, \PDO::PARAM_INT);
$statement->execute();
$platform = null;
if ($result = $statement->fetch(\PDO::FETCH_ASSOC)) {
/** @var _platformTopology $result */
$platform = PlatformTopologyFactoryRDB::create($result);
}
return $platform;
}
/**
* @inheritDoc
*/
public function deletePlatform(int $serverId): void
{
$statement = $this->db->prepare(
$this->translateDbName('DELETE FROM `:db`.`platform_topology` WHERE id = :serverId')
);
$statement->bindValue(':serverId', $serverId, \PDO::PARAM_INT);
$statement->execute();
}
/**
* @inheritDoc
*/
public function findTopLevelPlatform(): ?PlatformInterface
{
$statement = $this->db->prepare(
$this->translateDbName('
SELECT * FROM `:db`.platform_topology
WHERE `parent_id` IS NULL
')
);
$statement->execute();
$platform = null;
if ($result = $statement->fetch(\PDO::FETCH_ASSOC)) {
/** @var _platformTopology $result */
$platform = PlatformTopologyFactoryRDB::create($result);
}
return $platform;
}
/**
* @inheritDoc
*/
public function findChildrenPlatformsByParentId(int $parentId): array
{
$statement = $this->db->prepare(
$this->translateDbName('SELECT * FROM `:db`.`platform_topology` WHERE parent_id = :parentId')
);
$statement->bindValue(':parentId', $parentId, \PDO::PARAM_INT);
$statement->execute();
$childrenPlatforms = [];
if ($result = $statement->fetchAll(\PDO::FETCH_ASSOC)) {
foreach ($result as $platform) {
/** @var _platformTopology $platform */
$childrenPlatforms[] = PlatformTopologyFactoryRDB::create($platform);
}
}
return $childrenPlatforms;
}
/**
* @inheritDoc
*/
public function updatePlatformParameters(PlatformInterface $platform): void
{
$statement = $this->db->prepare(
$this->translateDbName(
'UPDATE `:db`.`platform_topology` SET
`address` = :address,
`hostname` = :hostname,
`name` = :name,
`type` = :type,
`parent_id` = :parentId,
`server_id` = :serverId,
`pending` = :pendingStatus
WHERE id = :id'
)
);
$statement->bindValue(':address', $platform->getAddress(), \PDO::PARAM_STR);
$statement->bindValue(':hostname', $platform->getHostname(), \PDO::PARAM_STR);
$statement->bindValue(':name', $platform->getName(), \PDO::PARAM_STR);
$statement->bindValue(':type', $platform->getType(), \PDO::PARAM_STR);
$statement->bindValue(':parentId', $platform->getParentId(), \PDO::PARAM_INT);
$statement->bindValue(':serverId', $platform->getServerId(), \PDO::PARAM_INT);
$statement->bindValue(':id', $platform->getId(), \PDO::PARAM_INT);
$statement->bindValue(':pendingStatus', ($platform->isPending() ? '1' : '0'), \PDO::PARAM_STR);
$statement->execute();
}
/**
* @inheritDoc
*/
public function findCentralRemoteChildren(): array
{
$central = $this->findTopLevelPlatformByType('central');
$remoteChildren = [];
if ($central !== null) {
$statement = $this->db->prepare(
$this->translateDbName(
"SELECT * FROM `:db`.platform_topology WHERE `type` = 'remote' AND `parent_id` = :parentId"
)
);
$statement->bindValue(':parentId', $central->getId(), \PDO::PARAM_INT);
$statement->execute();
if ($result = $statement->fetchAll(\PDO::FETCH_ASSOC)) {
foreach ($result as $platform) {
/** @var _platformTopology $platform */
$remoteChildren[] = PlatformTopologyFactoryRDB::create($platform);
}
}
}
return $remoteChildren;
}
/**
* @inheritDoc
*/
public function hasRestrictedAccessToPlatforms(array $accessGroupIds): bool
{
if ($accessGroupIds === []) {
return false;
}
[$bindValues, $bindQuery] = $this->createMultipleBindQuery($accessGroupIds, ':access_group_id');
$statement = $this->db->prepare($this->translateDbName(
<<<SQL
SELECT 1
FROM `:db`.`acl_res_group_relations` argr
JOIN `:db`.`acl_resources_poller_relations` arpr
ON arpr.acl_res_id = argr.acl_res_id
WHERE argr.acl_group_id IN ({$bindQuery})
SQL
));
foreach ($bindValues as $key => $value) {
$statement->bindValue($key, $value, \PDO::PARAM_INT);
}
$statement->execute();
return (bool) $statement->fetchColumn();
}
/**
* @inheritDoc
*/
public function hasAccessToPlatform(array $accessGroupIds, int $platformId): bool
{
if ($accessGroupIds === []) {
return false;
}
if (! $this->hasRestrictedAccessToPlatforms($accessGroupIds)) {
return true;
}
[$bindValues, $bindQuery] = $this->createMultipleBindQuery($accessGroupIds, ':access_group_id');
$statement = $this->db->prepare($this->translateDbName(
<<<SQL
SELECT 1
FROM `:db`.`acl_resources_poller_relations` arpr
JOIN `:db`.`acl_res_group_relations` argr
ON arpr.acl_res_id = argr.acl_res_id
WHERE argr.acl_group_id IN ({$bindQuery})
AND arpr.poller_id = :platformId
SQL
));
$statement->bindValue(':platformId', $platformId, \PDO::PARAM_INT);
foreach ($bindValues as $key => $value) {
$statement->bindValue($key, $value, \PDO::PARAM_INT);
}
$statement->execute();
return (bool) $statement->fetchColumn();
}
}
| 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.