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/Infrastructure/PlatformTopology/Repository/Model/PlatformJsonGraph.php | centreon/src/Centreon/Infrastructure/PlatformTopology/Repository/Model/PlatformJsonGraph.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Model;
use Centreon\Domain\PlatformTopology\Interfaces\PlatformInterface;
use Centreon\Domain\PlatformTopology\Model\PlatformRelation;
/**
* Format Platform to fit the JSON Graph Schema specification
* @see https://github.com/jsongraph/json-graph-specification
*/
class PlatformJsonGraph
{
/** @var string|null Stringified Platform Id */
private $id;
/** @var string|null Platform type */
private $type;
/** @var string|null Platform Name */
private $label;
/** @var array<string,string> Custom properties of a Json Graph Object */
private $metadata = [];
/** @var array<string,string> relation details between a platform and its parent */
private $relation = [];
public function __construct(PlatformInterface $platform)
{
$this->setId((string) $platform->getId());
$this->setType($platform->getType());
$this->setLabel($platform->getName());
if ($platform->getRelation() !== null) {
$this->setRelation($platform->getRelation());
}
$metadata = [];
$metadata['pending'] = ($platform->isPending() ? 'true' : 'false');
if ($platform->getServerId() !== null) {
$metadata['centreon-id'] = (string) $platform->getServerId();
}
if ($platform->getHostname() !== null) {
$metadata['hostname'] = $platform->getHostname();
}
if ($platform->getAddress() !== null) {
$metadata['address'] = $platform->getAddress();
}
$this->setMetadata($metadata);
}
/**
* @return string|null
*/
public function getId(): ?string
{
return $this->id;
}
/**
* @param string|null $id
* @return self
*/
public function setId(?string $id): self
{
$this->id = $id;
return $this;
}
/**
* @return string|null
*/
public function getType(): ?string
{
return $this->type;
}
/**
* @param string|null $type
* @return self
*/
public function setType(?string $type): self
{
$this->type = $type;
return $this;
}
/**
* @return string|null
*/
public function getLabel(): ?string
{
return $this->label;
}
/**
* @param string|null $label
* @return self
*/
public function setLabel(?string $label): self
{
$this->label = $label;
return $this;
}
/**
* @return array<string,string>
*/
public function getMetadata(): array
{
return $this->metadata;
}
/**
* @param array<string,string> $metadata
* @return self
*/
public function setMetadata(array $metadata): self
{
$this->metadata = $metadata;
return $this;
}
/**
* @return array<string,string>
*/
public function getRelation(): array
{
return $this->relation;
}
/**
* @param PlatformRelation $platformRelation
* @return self
*/
public function setRelation(PlatformRelation $platformRelation): self
{
$this->relation = [
'source' => (string) $platformRelation->getSource(),
'relation' => $platformRelation->getRelation(),
'target' => (string) $platformRelation->getTarget(),
];
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/Infrastructure/PlatformTopology/Repository/Model/PlatformTopologyFactoryRDB.php | centreon/src/Centreon/Infrastructure/PlatformTopology/Repository/Model/PlatformTopologyFactoryRDB.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Model;
use Centreon\Domain\PlatformTopology\Interfaces\PlatformInterface;
use Centreon\Domain\PlatformTopology\Model\PlatformPending;
use Centreon\Domain\PlatformTopology\Model\PlatformRegistered;
class PlatformTopologyFactoryRDB
{
/**
* Create a platform entity depending on the pending status.
*
* @param array<null|int|string> $platformData
*
* @return PlatformInterface
*/
public static function create(array $platformData): PlatformInterface
{
if ($platformData['pending'] === '1') {
return self::createPlatformPending($platformData);
}
return self::createPlatformRegistered($platformData);
}
/**
* Return a Registered platform entity.
*
* @param array<null|int|string> $platformData
*
* @return PlatformRegistered
*/
private static function createPlatformRegistered(array $platformData): PlatformRegistered
{
$platformReturned = new PlatformRegistered();
foreach ($platformData as $key => $value) {
switch ($key) {
case 'id':
$value = (int) $value;
if ($value > 0) {
$platformReturned->setId($value);
}
break;
case 'name':
if (is_string($value)) {
$platformReturned->setName($value);
}
break;
case 'hostname':
if (is_string($value)) {
$platformReturned->setHostname($value);
}
break;
case 'type':
if (is_string($value)) {
$platformReturned->setType($value);
}
break;
case 'address':
if (is_string($value)) {
$platformReturned->setAddress($value);
}
break;
case 'parent_id':
$value = (int) $value;
if ($value > 0) {
$platformReturned->setParentId($value);
}
break;
case 'server_id':
$value = (int) $value;
if ($value > 0) {
$platformReturned->setServerId($value);
}
break;
}
}
return $platformReturned;
}
/**
* Return a pending platform pending.
*
* @param array<int|string> $platformData
*
* @return PlatformPending
*/
private static function createPlatformPending(array $platformData): PlatformPending
{
$platformReturned = new PlatformPending();
foreach ($platformData as $key => $value) {
switch ($key) {
case 'id':
$value = (int) $value;
if ($value > 0) {
$platformReturned->setId($value);
}
break;
case 'name':
if (is_string($value)) {
$platformReturned->setName($value);
}
break;
case 'hostname':
if (is_string($value)) {
$platformReturned->setHostname($value);
}
break;
case 'type':
if (is_string($value)) {
$platformReturned->setType($value);
}
break;
case 'address':
if (is_string($value)) {
$platformReturned->setAddress($value);
}
break;
case 'parent_id':
$value = (int) $value;
if ($value > 0) {
$platformReturned->setParentId($value);
}
break;
case 'server_id':
$value = (int) $value;
if ($value > 0) {
$platformReturned->setServerId($value);
}
break;
}
}
return $platformReturned;
}
}
| 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/Exception/PlatformTopologyRepositoryException.php | centreon/src/Centreon/Infrastructure/PlatformTopology/Repository/Exception/PlatformTopologyRepositoryException.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Exception;
use Centreon\Domain\PlatformTopology\Interfaces\PlatformTopologyRepositoryExceptionInterface;
use Centreon\Domain\Repository\RepositoryException;
class PlatformTopologyRepositoryException extends RepositoryException implements
PlatformTopologyRepositoryExceptionInterface
{
/**
* Failure on authentication token retrieval
* @param string $centralServerAddress
* @return PlatformTopologyRepositoryException
*/
public static function failToGetToken(string $centralServerAddress): self
{
return new self(
sprintf(
_("Failed to get the auth token from Central : '%s''"),
$centralServerAddress
)
);
}
/**
* Failure returned from the API calling the Central
* @param string $details
* @return PlatformTopologyRepositoryException
*/
public static function apiRequestOnCentralException(string $details): self
{
return new self(_("Request to the Central's API failed") . ' : ' . $details);
}
/**
* Transport exception related to the client
* @param string $details
* @return PlatformTopologyRepositoryException
*/
public static function apiClientException(string $details): self
{
return new self(_('API calling the Central returned a Client exception') . ' : ' . $details);
}
/**
* Transport exception related to the redirection
* @param string $details
* @return PlatformTopologyRepositoryException
*/
public static function apiRedirectionException(string $details): self
{
return new self(_('API calling the Central returned a Redirection exception') . ' : ' . $details);
}
/**
* Transport exception related to the server
* @param string $message concatenated message with the central response
* @param string $details
* @return PlatformTopologyRepositoryException
*/
public static function apiServerException(string $message, string $details): self
{
return new self($message . ' : ' . $details);
}
/**
* Central response decoding failure
* @param string $details
* @return PlatformTopologyRepositoryException
*/
public static function apiDecodingResponseFailure(string $details): self
{
return new self(_("Unable to decode Central's API response") . ' : ' . $details);
}
/**
* Undetermined error when calling the central's API
* @param string $details
* @return PlatformTopologyRepositoryException
*/
public static function apiUndeterminedError(string $details): self
{
return new self(_("Error from Central's register API") . ' : ' . $details);
}
}
| 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/Filter/FilterRepositoryRDB.php | centreon/src/Centreon/Infrastructure/Filter/FilterRepositoryRDB.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Filter;
use Centreon\Domain\Entity\EntityCreator;
use Centreon\Domain\Filter\Filter;
use Centreon\Domain\Filter\FilterCriteria;
use Centreon\Domain\Filter\Interfaces\FilterRepositoryInterface;
use Centreon\Domain\RequestParameters\RequestParameters;
use Centreon\Infrastructure\DatabaseConnection;
use Centreon\Infrastructure\Repository\AbstractRepositoryDRB;
use Centreon\Infrastructure\RequestParameters\SqlRequestParametersTranslator;
/**
* This class is designed to manage the repository of the monitoring servers
*
* @package Centreon\Infrastructure\Filter
*/
class FilterRepositoryRDB extends AbstractRepositoryDRB implements FilterRepositoryInterface
{
/** @var SqlRequestParametersTranslator */
private $sqlRequestTranslator;
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* Initialized by the dependency injector.
*
* @param SqlRequestParametersTranslator $sqlRequestTranslator
*/
public function setSqlRequestTranslator(SqlRequestParametersTranslator $sqlRequestTranslator): void
{
$this->sqlRequestTranslator = $sqlRequestTranslator;
$this->sqlRequestTranslator
->getRequestParameters()
->setConcordanceStrictMode(
RequestParameters::CONCORDANCE_MODE_STRICT
);
}
/**
* @inheritDoc
*/
public function addFilter(Filter $filter): int
{
$maxOrder = $this->findMaxOrderByUserId($filter->getUserId(), $filter->getPageName());
$request = $this->translateDbName(
'INSERT INTO `:db`.user_filter
(name, user_id, page_name, criterias, `order`)
VALUES (:name, :user_id, :page_name, :criterias, :order)'
);
$statement = $this->db->prepare($request);
$statement->bindValue(':name', $filter->getName(), \PDO::PARAM_STR);
$statement->bindValue(':user_id', $filter->getUserId(), \PDO::PARAM_INT);
$statement->bindValue(':page_name', $filter->getPageName(), \PDO::PARAM_STR);
$statement->bindValue(':criterias', json_encode($this->buildCriteriasFromFilter($filter)), \PDO::PARAM_STR);
$statement->bindValue(':order', $maxOrder + 1, \PDO::PARAM_INT);
$statement->execute();
return (int) $this->db->lastInsertId();
}
/**
* @inheritDoc
*/
public function updateFilter(Filter $filter): void
{
$previousFilter = $this->findFilterByUserIdAndId(
$filter->getUserId(),
$filter->getPageName(),
$filter->getId()
);
if ($previousFilter === null) {
return;
}
$previousOrder = $previousFilter->getOrder();
$order = $filter->getOrder();
if ($order > $previousOrder) {
$this->decrementOrderBetweenIntervalByUserId(
$filter->getUserId(),
$filter->getPageName(),
$previousOrder,
$order
);
} elseif ($order < $previousOrder) {
$this->incrementOrderBetweenIntervalByUserId(
$filter->getUserId(),
$filter->getPageName(),
$order,
$previousOrder
);
}
$request = $this->translateDbName('
UPDATE `:db`.user_filter
SET name = :name, criterias = :criterias, `order` = :order
WHERE user_id = :user_id
AND page_name = :page_name
AND id = :filter_id
');
$statement = $this->db->prepare($request);
$statement->bindValue(':name', $filter->getName(), \PDO::PARAM_STR);
$statement->bindValue(':criterias', json_encode($this->buildCriteriasFromFilter($filter)), \PDO::PARAM_STR);
$statement->bindValue(':order', $filter->getOrder(), \PDO::PARAM_INT);
$statement->bindValue(':user_id', $filter->getUserId(), \PDO::PARAM_INT);
$statement->bindValue(':page_name', $filter->getPageName(), \PDO::PARAM_STR);
$statement->bindValue(':filter_id', $filter->getId(), \PDO::PARAM_INT);
$statement->execute();
$this->removeOrderGapByUserId($filter->getUserId(), $filter->getPageName());
}
/**
* @inheritDoc
*/
public function deleteFilter(Filter $filter): void
{
$request = $this->translateDbName('
DELETE FROM `:db`.user_filter
WHERE user_id = :user_id
AND page_name = :page_name
AND id = :filter_id
');
$statement = $this->db->prepare($request);
$statement->bindValue(':user_id', $filter->getUserId(), \PDO::PARAM_INT);
$statement->bindValue(':page_name', $filter->getPageName(), \PDO::PARAM_STR);
$statement->bindValue(':filter_id', $filter->getId(), \PDO::PARAM_STR);
$statement->execute();
$this->removeOrderGapByUserId($filter->getUserId(), $filter->getPageName());
}
/**
* @inheritDoc
*/
public function findFiltersByUserIdWithRequestParameters(int $userId, string $pageName): array
{
$this->sqlRequestTranslator->setConcordanceArray([
'id' => 'id',
'name' => 'name',
]);
// Search
$searchRequest = $this->sqlRequestTranslator->translateSearchParameterToSql();
// Sort
$sortRequest = $this->sqlRequestTranslator->translateSortParameterToSql();
// Pagination
$paginationRequest = $this->sqlRequestTranslator->translatePaginationToSql();
return $this->findFiltersByUserId($userId, $pageName, $searchRequest, $sortRequest, $paginationRequest);
}
/**
* @inheritDoc
*/
public function findFiltersByUserIdWithoutRequestParameters(int $userId, string $pageName): array
{
return $this->findFiltersByUserId($userId, $pageName, null, null, null);
}
/**
* {@inheritDoc}
* @throws \Exception
*/
public function findFilterByUserIdAndName(int $userId, string $pageName, string $name): ?Filter
{
$request = $this->translateDbName('
SELECT id, name, user_id, page_name, criterias, `order`
FROM `:db`.user_filter
WHERE user_id = :user_id
AND page_name = :page_name
AND name = :name
');
$statement = $this->db->prepare($request);
$statement->bindValue(':user_id', $userId, \PDO::PARAM_INT);
$statement->bindValue(':page_name', $pageName, \PDO::PARAM_STR);
$statement->bindValue(':name', $name, \PDO::PARAM_STR);
$statement->execute();
if (false !== ($filter = $statement->fetch(\PDO::FETCH_ASSOC))) {
/**
* @var FilterCriteria[] $filterCriterias
*/
$filterCriterias = [];
foreach (json_decode($filter['criterias'], true) as $filterCriteria) {
$filterCriterias[] = EntityCreator::createEntityByArray(
FilterCriteria::class,
$filterCriteria
);
}
$filter['criterias'] = $filterCriterias;
/**
* @var Filter $filterEntity
*/
return EntityCreator::createEntityByArray(
Filter::class,
$filter
);
}
return null;
}
/**
* {@inheritDoc}
* @throws \Exception
*/
public function findFilterByUserIdAndId(int $userId, string $pageName, int $filterId): ?Filter
{
$request = $this->translateDbName('
SELECT id, name, user_id, page_name, criterias, `order`
FROM `:db`.user_filter
WHERE user_id = :user_id
AND id = :filter_id
AND page_name = :page_name
');
$statement = $this->db->prepare($request);
$statement->bindValue(':user_id', $userId, \PDO::PARAM_INT);
$statement->bindValue(':filter_id', $filterId, \PDO::PARAM_INT);
$statement->bindValue(':page_name', $pageName, \PDO::PARAM_STR);
$statement->execute();
if (false !== ($filter = $statement->fetch(\PDO::FETCH_ASSOC))) {
/**
* @var FilterCriteria[] $filterCriterias
*/
$filterCriterias = [];
foreach (json_decode($filter['criterias'], true) as $filterCriteria) {
$filterCriterias[] = EntityCreator::createEntityByArray(
FilterCriteria::class,
$filterCriteria
);
}
$filter['criterias'] = $filterCriterias;
/**
* @var Filter $filterEntity
*/
return EntityCreator::createEntityByArray(
Filter::class,
$filter
);
}
return null;
}
/**
* @param Filter $filter
* @return array<string, mixed>
*/
private function buildCriteriasFromFilter(Filter $filter): array
{
$criterias = $filter->getCriterias();
return array_map(
static fn (FilterCriteria $criteria): array => [
'name' => $criteria->getName(),
'type' => $criteria->getType(),
'object_type' => $criteria->getObjectType(),
'value' => $criteria->getValue(),
'search_data' => $criteria->getSearchData(),
],
$criterias
);
}
/**
* Retrieve all filters linked to a user id
*
* @param int $userId user id for which we want to find filters
* @param string $pageName page name
* @param string|null $searchRequest search request
* @param string|null $sortRequest sort request
* @param string|null $paginationRequest pagination request
* @throws \Exception
* @return Filter[]
*/
private function findFiltersByUserId(
int $userId,
string $pageName,
?string $searchRequest = null,
?string $sortRequest = null,
?string $paginationRequest = null,
): array {
$request = $this->translateDbName('
SELECT SQL_CALC_FOUND_ROWS id, name, user_id, page_name, criterias, `order`
FROM `:db`.user_filter
');
// Search
$request .= ! is_null($searchRequest) ? $searchRequest . ' AND ' : ' WHERE ';
$request .= 'user_id = :user_id AND page_name = :page_name';
$this->sqlRequestTranslator->addSearchValue(':user_id', [\PDO::PARAM_INT => $userId]);
$this->sqlRequestTranslator->addSearchValue(':page_name', [\PDO::PARAM_STR => $pageName]);
// Sort
$request .= ! is_null($sortRequest) ? $sortRequest : ' ORDER BY `order` ASC';
// Pagination
$request .= ! is_null($paginationRequest) ? $paginationRequest : '';
$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);
}
$filters = [];
while (false !== ($filter = $statement->fetch(\PDO::FETCH_ASSOC))) {
/**
* @var FilterCriteria[] $filterCriterias
*/
$filterCriterias = [];
foreach (json_decode($filter['criterias'], true) as $filterCriteria) {
$filterCriterias[] = EntityCreator::createEntityByArray(
FilterCriteria::class,
$filterCriteria
);
}
$filter['criterias'] = $filterCriterias;
/**
* @var Filter $filterEntity
*/
$filterEntity = EntityCreator::createEntityByArray(
Filter::class,
$filter
);
$filters[] = $filterEntity;
}
return $filters;
}
/**
* Find max order value by user id and page name
*
* @param int $userId The user id
* @param string $pageName The page name
* @return int The max order value
*/
private function findMaxOrderByUserId(int $userId, string $pageName): int
{
$maxOrder = 0;
$request = $this->translateDbName('
SELECT max(`order`) as max_order
FROM `:db`.user_filter
WHERE user_id = :user_id
AND page_name = :page_name
');
$statement = $this->db->prepare($request);
$statement->bindValue(':user_id', $userId, \PDO::PARAM_INT);
$statement->bindValue(':page_name', $pageName, \PDO::PARAM_STR);
$statement->execute();
if (false !== ($order = $statement->fetch(\PDO::FETCH_ASSOC))) {
$maxOrder = $order['max_order'] === null ? 0 : (int) $order['max_order'];
}
return $maxOrder;
}
/**
* Remove order gap which happen after filter deletion
*
* @param int $userId The user id
* @param string $pageName The page name
* @return void
*/
private function removeOrderGapByUserId(int $userId, string $pageName): void
{
$filters = $this->findFiltersByUserId($userId, $pageName, null, null, null);
$currentOrder = 1;
foreach ($filters as $filter) {
if ($filter->getOrder() !== $currentOrder) {
$filter->setOrder($currentOrder);
$this->updateFilterOrder($filter);
}
$currentOrder++;
}
}
/**
* Decrement order of filters which have order between given interval
*
* @param int $userId The user id
* @param string $pageName The page name
* @param int $lowOrder The low order interval
* @param int $highOrder The high order interval
* @return void
*/
private function decrementOrderBetweenIntervalByUserId(
int $userId,
string $pageName,
int $lowOrder,
int $highOrder,
): void {
$filters = $this->findFiltersByUserId($userId, $pageName, null, null, null);
foreach ($filters as $filter) {
if ($filter->getOrder() >= $lowOrder && $filter->getOrder() <= $highOrder) {
$filter->setOrder($filter->getOrder() - 1);
$this->updateFilterOrder($filter);
}
}
}
/**
* Increment order of filters which have order between given interval
*
* @param int $userId The user id
* @param string $pageName The page name
* @param int $lowOrder The low order interval
* @param int $highOrder The high order interval
* @return void
*/
private function incrementOrderBetweenIntervalByUserId(
int $userId,
string $pageName,
int $lowOrder,
int $highOrder,
): void {
$filters = $this->findFiltersByUserId($userId, $pageName, null, null, null);
foreach ($filters as $filter) {
if ($filter->getOrder() >= $lowOrder && $filter->getOrder() <= $highOrder) {
$filter->setOrder($filter->getOrder() + 1);
$this->updateFilterOrder($filter);
}
}
}
/**
* Update filter order
*
* @param Filter $filter
* @return void
*/
private function updateFilterOrder(Filter $filter): void
{
$request = $this->translateDbName('
UPDATE `:db`.user_filter
SET `order` = :order
WHERE user_id = :user_id
AND page_name = :page_name
AND id = :filter_id
');
$statement = $this->db->prepare($request);
$statement->bindValue(':order', $filter->getOrder(), \PDO::PARAM_INT);
$statement->bindValue(':user_id', $filter->getUserId(), \PDO::PARAM_INT);
$statement->bindValue(':page_name', $filter->getPageName(), \PDO::PARAM_STR);
$statement->bindValue(':filter_id', $filter->getId(), \PDO::PARAM_INT);
$statement->execute();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Infrastructure/MetaServiceConfiguration/Repository/MetaServiceConfigurationRepositoryRDB.php | centreon/src/Centreon/Infrastructure/MetaServiceConfiguration/Repository/MetaServiceConfigurationRepositoryRDB.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\MetaServiceConfiguration\Repository;
use Assert\AssertionFailedException;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\MetaServiceConfiguration\Interfaces\MetaServiceConfigurationReadRepositoryInterface;
use Centreon\Domain\MetaServiceConfiguration\Model\MetaServiceConfiguration;
use Centreon\Domain\RequestParameters\RequestParameters;
use Centreon\Infrastructure\DatabaseConnection;
use Centreon\Infrastructure\MetaServiceConfiguration\Repository\Model\MetaServiceConfigurationFactoryRdb;
use Centreon\Infrastructure\Repository\AbstractRepositoryDRB;
use Centreon\Infrastructure\RequestParameters\Interfaces\NormalizerInterface;
use Centreon\Infrastructure\RequestParameters\SqlRequestParametersTranslator;
/**
* This class is designed to represent the MariaDb repository to manage meta service configuration.
*
* @package Centreon\Infrastructure\MetaServiceConfiguration\Repository
*/
class MetaServiceConfigurationRepositoryRDB extends AbstractRepositoryDRB implements
MetaServiceConfigurationReadRepositoryInterface
{
/** @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 findAll(): array
{
return $this->findAllRequest(null);
}
/**
* @inheritDoc
*/
public function findAllByContact(ContactInterface $contact): array
{
return $this->findAllRequest($contact->getId());
}
/**
* @inheritDoc
* @throws AssertionFailedException
*/
public function findById(int $metaId): ?MetaServiceConfiguration
{
return $this->findByIdRequest($metaId, null);
}
/**
* @inheritDoc
* @throws AssertionFailedException
*/
public function findByIdAndContact(int $metaId, ContactInterface $contact): ?MetaServiceConfiguration
{
return $this->findByIdRequest($metaId, $contact->getId());
}
/**
* Find all meta services configurations filtered by contact id.
*
* @param int|null $contactId Contact id related to host categories
* @throws AssertionFailedException
* @throws \InvalidArgumentException
* @return MetaServiceConfiguration[]
*/
private function findAllRequest(?int $contactId): array
{
$this->sqlRequestTranslator->setConcordanceArray([
'id' => 'ms.meta_id',
'name' => 'ms.meta_name',
'is_activated' => 'ms.meta_activate',
]);
$this->sqlRequestTranslator->addNormalizer(
'is_activated',
new class () implements NormalizerInterface {
/**
* @inheritDoc
*/
public function normalize($valueToNormalize): string
{
if (is_bool($valueToNormalize)) {
return ($valueToNormalize === true) ? '1' : '0';
}
return $valueToNormalize;
}
}
);
$request = "SELECT SQL_CALC_FOUND_ROWS
ms.meta_id,
ms.meta_name,
ms.meta_display,
ms.data_source_type,
CASE
WHEN ms.data_source_type = 0 THEN 'gauge'
WHEN ms.data_source_type = 1 THEN 'counter'
WHEN ms.data_source_type = 2 THEN 'derive'
WHEN ms.data_source_type = 3 THEN 'absolute'
END AS `data_source_type`,
ms.meta_select_mode,
ms.regexp_str,
ms.metric,
ms.warning,
ms.critical,
ms.meta_activate,
ms.calcul_type,
CASE
WHEN ms.calcul_type = 'AVE' THEN 'average'
WHEN ms.calcul_type = 'SOM' THEN 'sum'
WHEN ms.calcul_type = 'MIN' THEN 'minimum'
WHEN ms.calcul_type = 'MAX' THEN 'maximum'
END AS `calculation_type`
FROM `:db`.meta_service ms";
if ($contactId !== null) {
$request .= ' INNER JOIN `:db`.acl_resources_meta_relations armr
ON ms.meta_id = armr.meta_id
INNER JOIN `:db`.acl_resources res
ON armr.acl_res_id = res.acl_res_id
INNER JOIN `:db`.acl_res_group_relations argr
ON res.acl_res_id = argr.acl_res_id
INNER JOIN `:db`.acl_groups ag
ON argr.acl_group_id = ag.acl_group_id
LEFT JOIN `:db`.acl_group_contacts_relations agcr
ON ag.acl_group_id = agcr.acl_group_id
LEFT JOIN `:db`.acl_group_contactgroups_relations agcgr
ON ag.acl_group_id = agcgr.acl_group_id
LEFT JOIN `:db`.contactgroup_contact_relation cgcr
ON cgcr.contactgroup_cg_id = agcgr.cg_cg_id
AND cgcr.contact_contact_id = :contact_id';
}
// Search
$searchRequest = $this->sqlRequestTranslator->translateSearchParameterToSql();
$request .= ! is_null($searchRequest) ? $searchRequest : '';
// Sort
$sortRequest = $this->sqlRequestTranslator->translateSortParameterToSql();
$request .= ! is_null($sortRequest)
? $sortRequest
: ' ORDER BY ms.meta_name ASC';
// Pagination
$request .= $this->sqlRequestTranslator->translatePaginationToSql();
$statement = $this->db->prepare($this->translateDbName($request));
foreach ($this->sqlRequestTranslator->getSearchValues() as $key => $data) {
$type = key($data);
$value = $data[$type];
$statement->bindValue($key, $value, $type);
}
if ($contactId !== null) {
$statement->bindValue(':contact_id', $contactId, \PDO::PARAM_INT);
}
$statement->execute();
$result = $this->db->query('SELECT FOUND_ROWS()');
if ($result !== false && ($total = $result->fetchColumn()) !== false) {
$this->sqlRequestTranslator->getRequestParameters()->setTotal((int) $total);
}
$metaServicesConfigurations = [];
while (($record = $statement->fetch(\PDO::FETCH_ASSOC)) !== false) {
$metaServicesConfigurations[] = MetaServiceConfigurationFactoryRdb::create($record);
}
return $metaServicesConfigurations;
}
/**
* Find a category by id and contact id.
*
* @param int $metaId Id of the meta service configuration to be found
* @param int|null $contactId Contact id related to host categories
* @throws AssertionFailedException
* @return MetaServiceConfiguration|null
*/
private function findByIdRequest(int $metaId, ?int $contactId): ?MetaServiceConfiguration
{
$request = "SELECT ms.meta_id,
ms.meta_name,
ms.meta_display,
ms.data_source_type,
CASE
WHEN ms.data_source_type = 0 THEN 'gauge'
WHEN ms.data_source_type = 1 THEN 'counter'
WHEN ms.data_source_type = 2 THEN 'derive'
WHEN ms.data_source_type = 3 THEN 'absolute'
END AS `data_source_type`,
ms.meta_select_mode,
ms.regexp_str,
ms.metric,
ms.warning,
ms.critical,
ms.meta_activate,
ms.calcul_type,
CASE
WHEN ms.calcul_type = 'AVE' THEN 'average'
WHEN ms.calcul_type = 'SOM' THEN 'sum'
WHEN ms.calcul_type = 'MIN' THEN 'minimum'
WHEN ms.calcul_type = 'MAX' THEN 'maximum'
END AS `calculation_type`
FROM `:db`.meta_service ms";
if ($contactId !== null) {
$request .= ' INNER JOIN `:db`.acl_resources_meta_relations armr
ON ms.meta_id = armr.meta_id
INNER JOIN `:db`.acl_resources res
ON armr.acl_res_id = res.acl_res_id
INNER JOIN `:db`.acl_res_group_relations argr
ON res.acl_res_id = argr.acl_res_id
INNER JOIN `:db`.acl_groups ag
ON argr.acl_group_id = ag.acl_group_id
LEFT JOIN `:db`.acl_group_contacts_relations agcr
ON ag.acl_group_id = agcr.acl_group_id
LEFT JOIN `:db`.acl_group_contactgroups_relations agcgr
ON ag.acl_group_id = agcgr.acl_group_id
LEFT JOIN `:db`.contactgroup_contact_relation cgcr
ON cgcr.contactgroup_cg_id = agcgr.cg_cg_id';
}
$request .= ' WHERE ms.meta_id = :id';
if ($contactId !== null) {
$request .= ' AND (agcr.contact_contact_id = :contact_id OR cgcr.contact_contact_id = :contact_id)';
}
$statement = $this->db->prepare($this->translateDbName($request));
$statement->bindValue(':id', $metaId, \PDO::PARAM_INT);
if ($contactId !== null) {
$statement->bindValue(':contact_id', $contactId, \PDO::PARAM_INT);
}
$statement->execute();
if (($result = $statement->fetch(\PDO::FETCH_ASSOC)) !== false) {
return MetaServiceConfigurationFactoryRdb::create($result);
}
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/Infrastructure/MetaServiceConfiguration/Repository/Model/MetaServiceConfigurationFactoryRdb.php | centreon/src/Centreon/Infrastructure/MetaServiceConfiguration/Repository/Model/MetaServiceConfigurationFactoryRdb.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\MetaServiceConfiguration\Repository\Model;
use Centreon\Domain\MetaServiceConfiguration\Model\MetaServiceConfiguration;
/**
* This class is designed to provide a way to create the MetaServiceConfiguration entity from the database.
*
* @package Centreon\Infrastructure\MetaServiceConfiguration\Repository\Model
*/
class MetaServiceConfigurationFactoryRdb
{
/**
* Create a MetaServiceConfiguration entity from database data.
*
* @param array<string, mixed> $data
* @throws \Assert\AssertionFailedException
* @return MetaServiceConfiguration
*/
public static function create(array $data): MetaServiceConfiguration
{
return (new MetaServiceConfiguration(
$data['meta_name'],
$data['calculation_type'],
(int) $data['meta_select_mode']
))
->setId((int) $data['meta_id'])
->setActivated($data['meta_activate'] === '1')
->setOutput($data['meta_display'])
->setDataSourceType($data['data_source_type'])
->setRegexpString($data['regexp_str'])
->setMetric($data['metric'])
->setWarning($data['warning'])
->setCritical($data['critical']);
}
}
| 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/MetaServiceConfiguration/API/Model/MetaServiceConfigurationV2110Factory.php | centreon/src/Centreon/Infrastructure/MetaServiceConfiguration/API/Model/MetaServiceConfigurationV2110Factory.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\MetaServiceConfiguration\API\Model;
use Centreon\Domain\MetaServiceConfiguration\UseCase\V2110\FindMetaServicesConfigurationsResponse;
use Centreon\Domain\MetaServiceConfiguration\UseCase\V2110\FindOneMetaServiceConfigurationResponse;
/**
* This class is designed to create the MetaServiceConfigurationV21 entity
*
* @package Centreon\Infrastructure\Monitoring\MetaService\API\Model
*/
class MetaServiceConfigurationV2110Factory
{
/**
* @param FindOneMetaServiceConfigurationResponse $response
* @return \stdClass
*/
public static function createOneFromResponse(
FindOneMetaServiceConfigurationResponse $response,
): \stdClass {
$newMetaServiceConfiguration = self::createEmptyClass();
$metaServiceConfiguration = $response->getMetaServiceConfiguration();
$newMetaServiceConfiguration->id = $metaServiceConfiguration['id'];
$newMetaServiceConfiguration->name = $metaServiceConfiguration['name'];
$newMetaServiceConfiguration->isActivated = $metaServiceConfiguration['is_activated'];
$newMetaServiceConfiguration->output = $metaServiceConfiguration['meta_display'];
$newMetaServiceConfiguration->calculationType = $metaServiceConfiguration['calcul_type'];
$newMetaServiceConfiguration->dataSourceType = $metaServiceConfiguration['data_source_type'];
$newMetaServiceConfiguration->metaSelectMode = $metaServiceConfiguration['meta_select_mode'];
$newMetaServiceConfiguration->regexpString = $metaServiceConfiguration['regexp_str'];
$newMetaServiceConfiguration->metric = $metaServiceConfiguration['metric'];
$newMetaServiceConfiguration->warning = $metaServiceConfiguration['warning'];
$newMetaServiceConfiguration->critical = $metaServiceConfiguration['critical'];
return $newMetaServiceConfiguration;
}
/**
* @param FindMetaServicesConfigurationsResponse $response
* @return \stdClass[]
*/
public static function createAllFromResponse(
FindMetaServicesConfigurationsResponse $response,
): array {
$metaServicesConfigurations = [];
foreach ($response->getMetaServicesConfigurations() as $metaServiceConfiguration) {
$newMetaServiceConfiguration = self::createEmptyClass();
$newMetaServiceConfiguration->id = $metaServiceConfiguration['id'];
$newMetaServiceConfiguration->name = $metaServiceConfiguration['name'];
$newMetaServiceConfiguration->isActivated = $metaServiceConfiguration['is_activated'];
$newMetaServiceConfiguration->output = $metaServiceConfiguration['meta_display'];
$newMetaServiceConfiguration->calculationType = $metaServiceConfiguration['calcul_type'];
$newMetaServiceConfiguration->dataSourceType = $metaServiceConfiguration['data_source_type'];
$newMetaServiceConfiguration->metaSelectMode = $metaServiceConfiguration['meta_select_mode'];
$newMetaServiceConfiguration->regexpString = $metaServiceConfiguration['regexp_str'];
$newMetaServiceConfiguration->metric = $metaServiceConfiguration['metric'];
$newMetaServiceConfiguration->warning = $metaServiceConfiguration['warning'];
$newMetaServiceConfiguration->critical = $metaServiceConfiguration['critical'];
$metaServicesConfigurations[] = $newMetaServiceConfiguration;
}
return $metaServicesConfigurations;
}
/**
* @return \stdClass
*/
private static function createEmptyClass(): \stdClass
{
return new class () extends \stdClass {
public $id;
public $name;
public $isActivated;
public $output;
public $calculationType;
public $dataSourceType;
public $metaSelectMode;
public $regexpString;
public $metric;
public $warning;
public $critical;
};
}
}
| 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/Webservice/WebserviceAutorizePublicInterface.php | centreon/src/Centreon/Infrastructure/Webservice/WebserviceAutorizePublicInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Webservice;
interface WebserviceAutorizePublicInterface
{
}
| 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/Webservice/WebserviceAutorizeRestApiInterface.php | centreon/src/Centreon/Infrastructure/Webservice/WebserviceAutorizeRestApiInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Webservice;
interface WebserviceAutorizeRestApiInterface
{
/**
* Authorize to access to the action
*
* @param string $action The action name
* @param \CentreonUser $user The current user
* @param bool $isInternal If the api is call in internal
* @return bool If the user has access to the action
*/
public function authorize($action, $user, $isInternal = false);
}
| 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/Webservice/WebServiceAbstract.php | centreon/src/Centreon/Infrastructure/Webservice/WebServiceAbstract.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Webservice;
use Centreon\Application\DataRepresenter;
use Centreon\ServiceProvider;
use JsonSerializable;
use Pimple\Container;
use Symfony\Component\Serializer;
/**
* @OA\Server(
* url="{protocol}://{host}/centreon/api",
* variables={
* "protocol": {"enum": {"http", "https"}, "default": "http"},
* "host": {"default": "centreon-dev"}
* }
* )
*/
/**
* @OA\Info(
* title="Centreon Server API",
* version="0.1"
* )
*/
/**
* @OA\ExternalDocumentation(
* url="https://documentation.centreon.com/docs/centreon/en/18.10/api/api_rest/index.html",
* description="Official Centreon documentation about REST API"
* )
*/
/**
* @OA\Components(
* securitySchemes={
* "Session": {
* "type": "apiKey",
* "in": "cookie",
* "name": "centreon",
* "description": "This type of authorization is mostly used for needs of Centreon Web UI"
* },
* "AuthToken": {
* "type": "apiKey",
* "in": "header",
* "name": "HTTP_CENTREON_AUTH_TOKEN",
* "description": "For external access to the resources that require authorization"
* }
* }
* )
*/
abstract class WebServiceAbstract extends \CentreonWebService
{
/** @var Container */
protected $di;
/**
* Name of the webservice (the value that will be in the object parameter)
*
* @return string
*/
abstract public static function getName(): string;
/**
* Getter for DI container
*
* @return Container
*/
public function getDi(): Container
{
return $this->di;
}
/**
* Setter for DI container
*
* @param Container $di
*/
public function setDi(Container $di): void
{
$this->di = $di;
}
/**
* Get URL parameters
*
* @return array<mixed>
*/
public function query(): array
{
$request = $_GET;
return $request;
}
/**
* Get body of request as string
*
* @return string
*/
public function payloadRaw(): string
{
$content = file_get_contents('php://input');
return $content ? (string) $content : '';
}
/**
* Get body of request as decoded JSON
*
* @return array
*/
public function payload(): array
{
$request = [];
$content = $this->payloadRaw();
if ($content) {
$request = json_decode($content, true);
if (json_last_error() !== JSON_ERROR_NONE) {
$request = [];
}
}
return $request;
}
/**
* Get the Serializer service
*
* @return Serializer\Serializer
*/
public function getSerializer(): Serializer\Serializer
{
return $this->di[ServiceProvider::SERIALIZER];
}
/**
* Return success response
*
* @param mixed $data
* @param array $context the context for Serializer
* @return JsonSerializable
*/
public function success($data, array $context = []): JsonSerializable
{
return new DataRepresenter\Response(
$this->getSerializer()->normalize($data, null, $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/Infrastructure/Webservice/DependenciesTrait.php | centreon/src/Centreon/Infrastructure/Webservice/DependenciesTrait.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Webservice;
use Centreon\ServiceProvider;
use Pimple\Container;
use Pimple\Psr11\ServiceLocator;
use Symfony\Component\Serializer;
trait DependenciesTrait
{
/** @var ServiceLocator */
protected $services;
/**
* List of dependencies
*
* @return array
*/
public static function dependencies(): array
{
return [
ServiceProvider::SERIALIZER,
];
}
/**
* Extract services that are in use only
*
* @param Container $di
*/
public function setDi(Container $di): void
{
$this->services = new ServiceLocator($di, static::dependencies());
}
/**
* Get the Serializer service
*
* @return Serializer\Serializer
*/
public function getSerializer(): Serializer\Serializer
{
return $this->services->get(ServiceProvider::SERIALIZER);
}
}
| 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/CentreonLegacyDB/EntityPersister.php | centreon/src/Centreon/Infrastructure/CentreonLegacyDB/EntityPersister.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\CentreonLegacyDB;
use Centreon\Infrastructure\CentreonLegacyDB\Mapping\ClassMetadata;
class EntityPersister
{
/** @var string */
protected $entityClassName;
/** @var ClassMetadata */
protected $classMetadata;
/**
* Construct
*
* @param class-string $entityClassName
* @param ClassMetadata $classMetadata
*/
public function __construct($entityClassName, ClassMetadata $classMetadata)
{
$this->entityClassName = $entityClassName;
$this->classMetadata = $classMetadata;
}
/**
* Get table name of entity
*
* @return object of Entity
*/
public function load(array $data): object
{
$entity = new $this->entityClassName();
// load entity with data
foreach ($data as $column => $value) {
$property = $this->classMetadata->getProperty($column);
if ($property === null) {
continue;
}
$action = 'set' . ucfirst($property);
if (! is_callable([$entity, $action])) {
continue;
}
$formatter = $this->classMetadata->getFormatter($property);
if ($formatter === null) {
$entity->{$action}($value);
} else {
$entity->{$action}($formatter($value));
}
}
return $entity;
}
}
| 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/CentreonLegacyDB/StatementCollector.php | centreon/src/Centreon/Infrastructure/CentreonLegacyDB/StatementCollector.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\CentreonLegacyDB;
use PDO;
use PDOStatement;
/**
* The purpose of the collector is to have the ability to bind a value data (parameters
* and column too) to statement before the statement object to be initialized
*/
class StatementCollector
{
/**
* Collection of columns
*
* @var array
*/
protected $columns = [];
/**
* Collection of values
*
* @var array
*/
protected $values = [];
/**
* Collection of parameters
*
* @var array
*/
protected $params = [];
/**
* Add a column
*
* @param string $parameter
* @param mixed $value
* @param int $data_type
*/
public function addColumn($parameter, $value, int $data_type = PDO::PARAM_STR): void
{
$this->columns[$parameter] = [
'value' => $value,
'data_type' => $data_type,
];
}
/**
* Add a value
*
* @param string $parameter
* @param mixed $value
* @param int $data_type
*/
public function addValue($parameter, $value, int $data_type = PDO::PARAM_STR): void
{
$this->values[$parameter] = [
'value' => $value,
'data_type' => $data_type,
];
}
/**
* Add a parameter
*
* @param string $parameter
* @param mixed $value
* @param int $data_type
*/
public function addParam($parameter, $value, int $data_type = PDO::PARAM_STR): void
{
$this->params[$parameter] = [
'value' => $value,
'data_type' => $data_type,
];
}
/**
* Bind collected data to statement
*
* @param PDOStatement $stmt
*/
public function bind(PDOStatement $stmt): void
{
// bind columns to statment
foreach ($this->values as $parameter => $data) {
$stmt->bindColumn($parameter, $data['value'], $data['data_type']);
}
// bind values to statment
foreach ($this->values as $parameter => $data) {
$stmt->bindValue($parameter, $data['value'], $data['data_type']);
}
// bind parameters to statment
foreach ($this->values as $parameter => $data) {
$stmt->bindParam($parameter, $data['value'], $data['data_type']);
}
}
}
| 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/CentreonLegacyDB/CentreonDBAdapter.php | centreon/src/Centreon/Infrastructure/CentreonLegacyDB/CentreonDBAdapter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\CentreonLegacyDB;
use Centreon\Infrastructure\Service\CentreonDBManagerService;
use Centreon\Infrastructure\Service\Exception\NotFoundException;
use CentreonDB;
use ReflectionClass;
/**
* Executes commands against Centreon database backend.
*/
class CentreonDBAdapter
{
/** @var CentreonDBManagerService */
protected $manager;
/** @var CentreonDB */
private $db;
private $count = 0;
private $error = false;
private $errorInfo = '';
private $query;
private $result;
/**
* Construct
*
* @param CentreonDB $db
* @param CentreonDBManagerService $manager
*/
public function __construct(CentreonDB $db, ?CentreonDBManagerService $manager = null)
{
$this->db = $db;
$this->manager = $manager;
}
public function getRepository($repository): ServiceEntityRepository
{
$interface = ServiceEntityRepository::class;
$ref = new ReflectionClass($repository);
$hasInterface = $ref->isSubclassOf($interface);
if ($hasInterface === false) {
throw new NotFoundException(sprintf('Repository %s must implement %s', $repository, $interface));
}
return new $repository($this->db, $this->manager);
}
public function getCentreonDBInstance(): CentreonDB
{
return $this->db;
}
/**
* @param string $query
* @param array $params
*
* @throws \Exception
* @return $this
*/
public function query($query, $params = [])
{
$this->error = false;
$this->errorInfo = '';
$this->query = $this->db->prepare($query);
if (! $this->query) {
throw new \Exception('Error at preparing the query.');
}
if (is_array($params) && $params !== []) {
$x = 1;
foreach ($params as $param) {
$this->query->bindValue($x, $param);
$x++;
}
}
try {
$result = $this->query->execute();
$isSelect = str_contains(strtolower($query), 'select');
if ($result && $isSelect) {
$this->result = $this->query->fetchAll(\PDO::FETCH_OBJ);
$this->count = $this->query->rowCount();
} elseif (! $result) {
$this->error = true;
$this->errorInfo = $this->query->errorInfo();
}
} catch (\Exception $e) {
throw new \Exception('Query failed. ' . $e->getMessage());
}
return $this;
}
/**
* @param string $table
* @param array $fields
*
* @throws \Exception
* @return int Last inserted ID
*/
public function insert($table, array $fields)
{
if (! $fields) {
throw new \Exception("The argument `fields` can't be empty");
}
$keys = [];
$keyVars = [];
foreach ($fields as $key => $value) {
$keys[] = "`{$key}`";
$keyVars[] = ":{$key}";
}
$columns = join(',', $keys);
$values = join(',', $keyVars);
$sql = "INSERT INTO {$table} ({$columns}) VALUES ({$values})";
$stmt = $this->db->prepare($sql);
foreach ($fields as $key => $value) {
$stmt->bindValue(':' . $key, $value);
}
try {
$stmt->execute();
} catch (\Exception $e) {
throw new \Exception('Query failed. ' . $e->getMessage());
}
return (int) $this->db->lastInsertId();
}
/**
* Insert data using load data infile
*
* @param string $file Path and name of file to load
* @param string $table Table name
* @param array $fieldsClause Values of subclauses of FIELDS clause
* @param array $linesClause Values of subclauses of LINES clause
* @param array $columns Columns name
*
* @throws \Exception
* @return void
*/
public function loadDataInfile(string $file, string $table, array $fieldsClause, array $linesClause, array $columns): void
{
// SQL statement format:
// LOAD DATA
// INFILE 'file_name'
// INTO TABLE tbl_name
// FIELDS TERMINATED BY ',' ENCLOSED BY '\'' ESCAPED BY '\\'
// LINES TERMINATED BY '\n' STARTING BY ''
// (`col_name`, `col_name`,...)
// Construct SQL statement
$sql = "LOAD DATA LOCAL INFILE '{$file}'";
$sql .= " INTO TABLE {$table}";
$sql .= " FIELDS TERMINATED BY '" . $fieldsClause['terminated_by'] . "' ENCLOSED BY '"
. $fieldsClause['enclosed_by'] . "' ESCAPED BY '" . $fieldsClause['escaped_by'] . "'";
$sql .= " LINES TERMINATED BY '" . $linesClause['terminated_by'] . "' STARTING BY '"
. $linesClause['starting_by'] . "'";
$sql .= ' (`' . implode('`, `', $columns) . '`)';
// Prepare PDO statement.
$stmt = $this->db->prepare($sql);
// Execute
try {
$stmt->execute();
} catch (\Exception $e) {
throw new \Exception('Query failed. ' . $e->getMessage());
}
}
/**
* @param string $table
* @param array $fields
* @param int $id
*
* @throws \Exception
* @return bool|int Updated ID
*/
public function update($table, array $fields, int $id)
{
$keys = [];
$keyValues = [];
foreach ($fields as $key => $value) {
array_push($keys, $key . '= :' . $key);
array_push($keyValues, [$key, $value]);
}
$sql = "UPDATE {$table} SET " . implode(', ', $keys) . ' WHERE id = :id';
$qq = $this->db->prepare($sql);
$qq->bindParam(':id', $id);
foreach ($keyValues as $key => $value) {
$qq->bindParam(':' . $key, $value);
}
try {
$result = $qq->execute();
} catch (\Exception $e) {
throw new \Exception('Query failed. ' . $e->getMessage());
}
return $result;
}
public function results()
{
return $this->result;
}
public function count()
{
return $this->count;
}
public function fails()
{
return $this->error;
}
public function passes()
{
return ! $this->error;
}
public function errorInfo()
{
return $this->errorInfo;
}
public function beginTransaction(): void
{
$this->db->beginTransaction();
}
public function commit(): void
{
$this->db->commit();
}
public function rollBack(): void
{
$this->db->rollBack();
}
}
| 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/CentreonLegacyDB/ServiceEntityRepository.php | centreon/src/Centreon/Infrastructure/CentreonLegacyDB/ServiceEntityRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\CentreonLegacyDB;
use Centreon\Infrastructure\Service\CentreonDBManagerService;
use CentreonDB;
/**
* Compatibility with Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository
*/
abstract class ServiceEntityRepository
{
/** @var CentreonDB */
protected $db;
/** @var CentreonDBManagerService */
protected $manager;
/** @var Mapping\ClassMetadata */
protected $classMetadata;
/** @var EntityPersister */
protected $entityPersister;
/**
* Construct
*
* @param CentreonDB $db
* @param CentreonDBManagerService $manager
*/
public function __construct(CentreonDB $db, ?CentreonDBManagerService $manager = null)
{
$this->db = $db;
$this->manager = $manager;
$this->classMetadata = new Mapping\ClassMetadata();
// load metadata for Entity implemented MetadataInterface
$this->loadMetadata();
}
/**
* Get class name and namespace of the Entity
*
* <example>
* public static function entityClass(): string
* {
* return MyEntity::class;
* }
* </example>
*
* @return string
*/
public static function entityClass(): string
{
return str_replace(
'\\Domain\\Repository\\',
'\\Domain\\Entity\\', // change namespace
substr(static::class, 0, -10) // remove class name suffix "Repository"
);
}
public function getEntityPersister(): ?EntityPersister
{
return $this->entityPersister;
}
/**
* Get ClassMetadata
*
* @return Mapping\ClassMetadata
*/
public function getClassMetadata(): Mapping\ClassMetadata
{
return $this->classMetadata;
}
/**
* Load ClassMetadata with data from the Entity
*
* @return void
*/
protected function loadMetadata(): void
{
if (is_subclass_of(static::entityClass(), Mapping\MetadataInterface::class)) {
(static::entityClass())::loadMetadata($this->classMetadata);
// prepare the Entity persister
$this->entityPersister = new EntityPersister(static::entityClass(), $this->classMetadata);
}
}
/**
* This method will update the relation table to clean up old data and add the missing
*
* @param array $list
* @param int $id
* @param string $tableName
* @param string $columnA
* @param string $columnB
*/
protected function updateRelationData(array $list, int $id, string $tableName, string $columnA, string $columnB)
{
$listExists = [];
$listAdd = [];
$listRemove = [];
$rows = (function () use ($id, $tableName, $columnA, $columnB) {
$sql = "SELECT `{$columnB}` FROM `{$tableName}` WHERE `{$columnA}` = :{$columnA} LIMIT 0, 5000";
$stmt = $this->db->prepare($sql);
$stmt->bindValue(":{$columnA}", $id, \PDO::PARAM_INT);
$stmt->execute();
return $stmt->fetchAll();
})();
// to remove
foreach ($rows as $row) {
$pollerId = $row[$columnB];
if (! in_array($pollerId, $list)) {
$listRemove[] = $pollerId;
}
$listExists[] = $pollerId;
unset($row, $pollerId);
}
// to add
foreach ($list as $pollerId) {
if (! in_array($pollerId, $listExists)) {
$listAdd[] = $pollerId;
}
unset($pollerId);
}
// removing
foreach ($listRemove as $pollerId) {
(function () use ($id, $pollerId, $tableName, $columnA, $columnB): void {
$sql = "DELETE FROM `{$tableName}` WHERE `{$columnA}` = :{$columnA} AND `{$columnB}` = :{$columnB}";
$stmt = $this->db->prepare($sql);
$stmt->bindValue(":{$columnA}", $id, \PDO::PARAM_INT);
$stmt->bindValue(":{$columnB}", $pollerId, \PDO::PARAM_INT);
$stmt->execute();
})();
unset($pollerId);
}
// adding
foreach ($listAdd as $pollerId) {
(function () use ($id, $pollerId, $tableName, $columnA, $columnB): void {
$sql = "INSERT INTO `{$tableName}` (`{$columnA}`, `{$columnB}`) VALUES (:{$columnA}, :{$columnB})";
$stmt = $this->db->prepare($sql);
$stmt->bindValue(":{$columnA}", $id, \PDO::PARAM_INT);
$stmt->bindValue(":{$columnB}", $pollerId, \PDO::PARAM_INT);
$stmt->execute();
})();
unset($pollerId);
}
}
}
| 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/CentreonLegacyDB/Interfaces/PaginationRepositoryInterface.php | centreon/src/Centreon/Infrastructure/CentreonLegacyDB/Interfaces/PaginationRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\CentreonLegacyDB\Interfaces;
interface PaginationRepositoryInterface
{
/**
* Get a list of elements by criteria
*
* @param mixed $filters
* @param int $limit
* @param int $offset
* @param array<string,string> $ordering
* @return array<int,mixed>
*/
public function getPaginationList($filters = null, ?int $limit = null, ?int $offset = null, $ordering = []): array;
/**
* Get total count of elements in the list
*
* @return int
*/
public function getPaginationListTotal(): 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/Infrastructure/CentreonLegacyDB/Mapping/MetadataInterface.php | centreon/src/Centreon/Infrastructure/CentreonLegacyDB/Mapping/MetadataInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\CentreonLegacyDB\Mapping;
interface MetadataInterface
{
/**
* Describe the relationship between properties and DB columns as names and data types
*
* @param ClassMetadata $metadata
* @return void
*/
public static function loadMetadata(ClassMetadata $metadata): 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/CentreonLegacyDB/Mapping/ClassMetadata.php | centreon/src/Centreon/Infrastructure/CentreonLegacyDB/Mapping/ClassMetadata.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\CentreonLegacyDB\Mapping;
use PDO;
class ClassMetadata
{
public const COLUMN = 'column';
public const TYPE = 'type';
public const FORMATTER = 'formatter';
/**
* Table name of entity
*
* @var string
*/
protected $tableName;
/**
* List of properties of entity vs columns in DB table
*
* @var array
*/
protected $columns;
/**
* Name of property that is the primary key
*
* @var string
*/
protected $primaryKey;
/**
* Set table name
*
* @param string $name
* @return self
*/
public function setTableName($name): self
{
$this->tableName = $name;
return $this;
}
/**
* Get table name of entity
*
* @return string
*/
public function getTableName(): ?string
{
return $this->tableName;
}
/**
* Add information about the property
*
* @param string $property name of the property in the Entity class
* @param string $columnName name of the column in DB
* @param int $dataType type of data use PDO::PARAM_*
* @param callable $dataFormatter
* @param bool $primaryKey is it PK
* @return self
*/
public function add(
string $property,
string $columnName,
int $dataType = PDO::PARAM_STR,
?callable $dataFormatter = null,
$primaryKey = false,
): self {
$this->columns[$property] = [
static::COLUMN => $columnName,
static::TYPE => $dataType,
static::FORMATTER => $dataFormatter,
];
// mark property as primary kay
if ($primaryKey === true) {
$this->primaryKey = $property;
}
return $this;
}
/**
* Has PK
*
* @return bool
*/
public function hasPrimaryKey(): bool
{
return $this->primaryKey !== null;
}
/**
* Get PK property
*
* @return string
*/
public function getPrimaryKey(): ?string
{
return $this->primaryKey;
}
/**
* Get PK column
*
* @return string
*/
public function getPrimaryKeyColumn(): ?string
{
return $this->hasPrimaryKey() ? $this->getColumn($this->getPrimaryKey()) : null;
}
/**
* Check is property exists in metadata
*
* @param string $property
* @return bool
*/
public function has(string $property): bool
{
return array_key_exists($property, $this->columns);
}
/**
* Get metadata of the property
*
* @param string $property
* @return array|null
*/
public function get(string $property): ?array
{
return $this->has($property) ? $this->columns[$property] : null;
}
/**
* Get column name of the property
*
* @param string $property
* @return string|null
*/
public function getColumn(string $property): ?string
{
return $this->has($property) ? $this->columns[$property][static::COLUMN] : null;
}
/**
* Get data for columns
*
* @return array|null
*/
public function getColumns(): ?array
{
return $this->columns;
}
/**
* Get data type of the property
*
* @param string $property
* @return int
*/
public function getType(string $property): int
{
return $this->has($property) ? $this->columns[$property][static::TYPE] : PDO::PARAM_INT;
}
/**
* Get data formatter function
*
* @param string $property
* @return callable|null
*/
public function getFormatter(string $property): ?callable
{
return $this->has($property) ? $this->columns[$property][static::FORMATTER] : null;
}
/**
* Get the property by the column name
*
* @param string $column
* @return string|null
*/
public function getProperty(string $column): ?string
{
foreach ($this->columns as $property => $data) {
if (strtolower($data[self::COLUMN]) === strtolower($column)) {
return $property;
}
}
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/Infrastructure/Broker/BrokerRepositoryRDB.php | centreon/src/Centreon/Infrastructure/Broker/BrokerRepositoryRDB.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Broker;
use Centreon\Domain\Broker\BrokerConfiguration;
use Centreon\Domain\Broker\Interfaces\BrokerRepositoryInterface;
use Centreon\Infrastructure\DatabaseConnection;
class BrokerRepositoryRDB implements BrokerRepositoryInterface
{
/** @var DatabaseConnection */
private $db;
/**
* BrokerRepositoryRDB constructor.
* @param DatabaseConnection $db
*/
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* Get Broker Configurations based on the configuration Key
*
* @param int $monitoringServerId
* @param string $configKey
* @return BrokerConfiguration[]
*/
public function findByMonitoringServerAndParameterName(int $monitoringServerId, string $configKey): array
{
$statement = $this->db->prepare('
SELECT config_value, cfgbi.config_id AS id
FROM cfg_centreonbroker_info cfgbi
INNER JOIN cfg_centreonbroker AS cfgb
ON cfgbi.config_id = cfgb.config_id
INNER JOIN nagios_server AS ns
ON cfgb.ns_nagios_server = ns.id
AND ns.id = :monitoringServerId
WHERE config_key = :configKey
');
$statement->bindValue(':monitoringServerId', $monitoringServerId, \PDO::PARAM_INT);
$statement->bindValue(':configKey', $configKey, \PDO::PARAM_STR);
$statement->execute();
$brokerConfigurations = [];
while (($result = $statement->fetch(\PDO::FETCH_ASSOC)) !== false) {
$brokerConfigurations[] = (new BrokerConfiguration())
->setId((int) $result['id'])
->setConfigurationKey($configKey)
->setConfigurationValue($result['config_value']);
}
return $brokerConfigurations;
}
}
| 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/FileManager/File.php | centreon/src/Centreon/Infrastructure/FileManager/File.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\FileManager;
class File
{
protected $name;
protected $type;
protected $extension;
protected $tmp_name;
protected $error;
protected $size;
public function __construct(array $data)
{
$this->name = $data['name'] ?? '';
$this->type = $data['type'] ?? '';
$this->tmp_name = $data['tmp_name'] ?? '';
$this->error = $data['error'] ?? 0;
$this->size = $data['size'] ?? 0;
$this->extension = $this->name ? pathinfo($this->name, PATHINFO_EXTENSION) : '';
}
public function getName(): string
{
return $this->name;
}
public function getType(): string
{
return $this->type;
}
public function getExtension(): string
{
return $this->extension;
}
public function getTmpName(): string
{
return $this->tmp_name;
}
public function getError(): int
{
return $this->error;
}
public function getSize(): int
{
return $this->size;
}
}
| 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/Contact/ContactRepositoryRDB.php | centreon/src/Centreon/Infrastructure/Contact/ContactRepositoryRDB.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Contact;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactRepositoryInterface;
use Centreon\Domain\Menu\Model\Page;
use Centreon\Infrastructure\DatabaseConnection;
use Core\Common\Infrastructure\Repository\SqlMultipleBindTrait;
/**
* Database repository for the contacts.
*
* @package Centreon\Infrastructure\Contact
*/
final class ContactRepositoryRDB implements ContactRepositoryInterface
{
use SqlMultipleBindTrait;
private const MENU_ACCESS_NO_ACCESS = 0;
private const MENU_ACCESS_READ_WRITE_ACCESS = 1;
/** @var DatabaseConnection */
private $db;
/**
* ContactRepositoryRDB constructor.
* @param DatabaseConnection $pdo
*/
public function __construct(DatabaseConnection $pdo)
{
$this->db = $pdo;
}
/**
* @inheritDoc
*/
public function findById(int $contactId): ?Contact
{
$request = $this->translateDbName(
'SELECT contact.*, cp.password AS contact_passwd, t.topology_url,
t.topology_url_opt, t.is_react, t.topology_id, tz.timezone_name, t.topology_page as default_page
FROM `:db`.contact
LEFT JOIN `:db`.contact as template
ON contact.contact_template_id = template.contact_id
LEFT JOIN `:db`.contact_password cp
ON cp.contact_id = contact.contact_id
LEFT JOIN `:db`.timezone tz
ON tz.timezone_id = contact.contact_location
LEFT JOIN `:db`.topology t
ON t.topology_page = COALESCE(contact.default_page, template.default_page)
WHERE contact.contact_id = :contact_id
ORDER BY cp.creation_date DESC LIMIT 1'
);
$statement = $this->db->prepare($request);
$statement->bindValue(':contact_id', $contactId, \PDO::PARAM_INT);
$contact = null;
$statement->execute();
if (($result = $statement->fetch(\PDO::FETCH_ASSOC)) !== false) {
$contact = $this->createContact($result);
}
return $contact;
}
/**
* @inheritDoc
*/
public function findByName(string $name): ?Contact
{
$request = $this->translateDbName(
'SELECT contact.*, cp.password AS contact_passwd, t.topology_url,
t.topology_url_opt, t.is_react, t.topology_id, tz.timezone_name, t.topology_page as default_page
FROM `:db`.contact
LEFT JOIN `:db`.contact as template
ON contact.contact_template_id = template.contact_id
LEFT JOIN `:db`.contact_password cp
ON cp.contact_id = contact.contact_id
LEFT JOIN `:db`.timezone tz
ON tz.timezone_id = contact.contact_location
LEFT JOIN `:db`.topology t
ON t.topology_page = COALESCE(contact.default_page, template.default_page)
WHERE contact.contact_alias = :username
ORDER BY cp.creation_date DESC LIMIT 1'
);
$statement = $this->db->prepare($request);
$statement->bindValue(':username', $name, \PDO::PARAM_STR);
$statement->execute();
$contact = null;
if (($result = $statement->fetch(\PDO::FETCH_ASSOC)) !== false) {
$contact = $this->createContact($result);
}
return $contact;
}
/**
* @inheritDoc
*/
public function findByEmail(string $email): ?Contact
{
$request = $this->translateDbName(
'SELECT contact.*, cp.password AS contact_passwd, t.topology_url,
t.topology_url_opt, t.is_react, t.topology_id, tz.timezone_name, t.topology_page as default_page
FROM `:db`.contact
LEFT JOIN `:db`.contact as template
ON contact.contact_template_id = template.contact_id
LEFT JOIN `:db`.contact_password cp
ON cp.contact_id = contact.contact_id
LEFT JOIN `:db`.timezone tz
ON tz.timezone_id = contact.contact_location
LEFT JOIN `:db`.topology t
ON t.topology_page = COALESCE(contact.default_page, template.default_page)
WHERE contact.contact_email = :email
ORDER BY cp.creation_date DESC LIMIT 1'
);
$statement = $this->db->prepare($request);
$statement->bindValue(':email', $email, \PDO::PARAM_STR);
$statement->execute();
$contact = null;
if (($result = $statement->fetch(\PDO::FETCH_ASSOC)) !== false) {
$contact = $this->createContact($result);
}
return $contact;
}
/**
* @inheritDoc
*/
public function findBySession(string $sessionId): ?Contact
{
$request = $this->translateDbName(
'SELECT contact.*, cp.password AS contact_passwd, t.topology_url,
t.topology_url_opt, t.is_react, t.topology_id, tz.timezone_name, t.topology_page as default_page
FROM `:db`.contact
LEFT JOIN `:db`.contact as template
ON contact.contact_template_id = template.contact_id
LEFT JOIN `:db`.contact_password cp
ON cp.contact_id = contact.contact_id
LEFT JOIN `:db`.timezone tz
ON tz.timezone_id = contact.contact_location
LEFT JOIN `:db`.topology t
ON t.topology_page = COALESCE(contact.default_page, template.default_page)
INNER JOIN `:db`.session
on session.user_id = contact.contact_id
WHERE session.session_id = :session_id
ORDER BY cp.creation_date DESC LIMIT 1'
);
$statement = $this->db->prepare($request);
$statement->bindValue(':session_id', $sessionId, \PDO::PARAM_STR);
$statement->execute();
$contact = null;
if (($result = $statement->fetch(\PDO::FETCH_ASSOC)) !== false) {
$contact = $this->createContact($result);
}
return $contact;
}
/**
* @inheritDoc
*
* Check if token is present in security_authentication_tokens (session token)
* and on top of that in security_token (JWT, OAuth access token...)
*/
public function findByAuthenticationToken(string $token): ?Contact
{
$statement = $this->db->prepare(
$this->translateDbName(
<<<'SQL'
SELECT contact.*, cp.password AS contact_passwd, t.topology_url,
t.topology_url_opt, t.is_react, t.topology_id, tz.timezone_name, t.topology_page as default_page
FROM `:db`.contact
LEFT JOIN `:db`.contact as template
ON contact.contact_template_id = template.contact_id
LEFT JOIN `:db`.contact_password cp
ON cp.contact_id = contact.contact_id
LEFT JOIN `:db`.timezone tz
ON tz.timezone_id = contact.contact_location
LEFT JOIN `:db`.topology t
ON t.topology_page = COALESCE(contact.default_page, template.default_page)
INNER JOIN `:db`.security_authentication_tokens sat
ON sat.user_id = contact.contact_id
INNER JOIN `:db`.security_token st
ON st.id = sat.provider_token_id
WHERE (sat.token = :token OR st.token = :token)
AND sat.is_revoked = 0
ORDER BY cp.creation_date DESC LIMIT 1
SQL
)
);
$statement->bindValue(':token', $token, \PDO::PARAM_STR);
$statement->execute();
$contact = null;
if ($result = $statement->fetch(\PDO::FETCH_ASSOC)) {
$contact = $this->createContact($result);
}
return $contact;
}
/**
* Replace all instances of :dbstg and :db by the real db names.
* The table names of the database are defined in the services.yaml
* configuration file.
*
* @param string $request Request to translate
* @return string Request translated
*/
protected function translateDbName(string $request): string
{
return str_replace(
[':dbstg', ':db'],
[$this->db->getConnectionConfig()->getDatabaseNameRealTime(), $this->db->getConnectionConfig()->getDatabaseNameConfiguration()],
$request
);
}
/**
* Find and add all topology rules defined by all menus access defined for this contact.
* The purpose is to limit access to the API based on menus access.
*
* @param Contact $contact Contact for which we want to add the topology rules
*/
private function addTopologyRules(Contact $contact): void
{
$topologySubquery
= $contact->isAdmin()
? 'SELECT topology.topology_id, 1 AS access_right
FROM `:db`.topology'
: 'SELECT topology.topology_id, acltr.access_right
FROM `:db`.contact contact
LEFT JOIN `:db`.contactgroup_contact_relation cgcr
ON cgcr.contact_contact_id = contact.contact_id
LEFT JOIN `:db`.acl_group_contactgroups_relations gcgr
ON gcgr.cg_cg_id = cgcr.contactgroup_cg_id
LEFT JOIN `:db`.acl_group_contacts_relations gcr
ON gcr.contact_contact_id = contact.contact_id
LEFT JOIN `:db`.acl_group_topology_relations agtr
ON agtr.acl_group_id = gcr.acl_group_id
OR agtr.acl_group_id = gcgr.acl_group_id
LEFT JOIN `:db`.acl_topology_relations acltr
ON acltr.acl_topo_id = agtr.acl_topology_id
INNER JOIN `:db`.topology
ON topology.topology_id = acltr.topology_topology_id
WHERE contact.contact_id = :contact_id';
$request
= 'SELECT topology.topology_name, topology.topology_page,
topology.topology_parent, access.access_right
FROM `:db`.topology
LEFT JOIN (' . $topologySubquery . ') AS access
ON access.topology_id = topology.topology_id
WHERE topology.topology_page IS NOT NULL
ORDER BY topology.topology_page';
$prepare = $this->db->prepare(
$this->translateDbName($request)
);
if ($contact->isAdmin() === false) {
$prepare->bindValue(':contact_id', $contact->getId(), \PDO::PARAM_INT);
}
$prepare->execute();
$topologies = [];
$rightsCounter = 0;
while ($row = $prepare->fetch(\PDO::FETCH_ASSOC)) {
$topologyAccess = (int) $row['access_right'];
$topologyPage = $row['topology_page'];
$topologyName = $row['topology_name'];
// No point in adding topology if no access.
if ($topologyAccess > self::MENU_ACCESS_NO_ACCESS) {
// If topology_page already registered only update the rights when needed (ie: giving more access though menu access)
if (isset($topologies[$topologyPage])) {
if (
$topologyAccess === self::MENU_ACCESS_READ_WRITE_ACCESS
&& $topologies[$topologyPage]['right'] !== self::MENU_ACCESS_READ_WRITE_ACCESS
) {
$topologies[$topologyPage]['right'] = self::MENU_ACCESS_READ_WRITE_ACCESS;
}
} else {
$topologies[$topologyPage] = [
'name' => $topologyName,
'right' => $topologyAccess,
];
$rightsCounter++; // increment when a new topology is added
}
}
}
$nameOfTopologiesRules = [];
if ($rightsCounter > 0) {
foreach ($topologies as $topologyPage => $details) {
$originalTopologyPage = $topologyPage;
$ruleName = null;
$lvl2Name = null;
$lvl3Name = null;
$lvl4Name = null;
if (strlen((string) $topologyPage) === 7) {
$lvl4Name = $topologies[$topologyPage]['name'];
$topologyPage = (int) substr((string) $topologyPage, 0, 5);
// To avoid create entry for the parent menu
$nameOfTopologiesRules[$topologyPage] = null;
}
if (strlen((string) $topologyPage) === 5) {
if ($lvl4Name === null && array_key_exists($topologyPage, $nameOfTopologiesRules)) {
continue;
}
$lvl3Name = $topologies[$topologyPage]['name'];
$topologyPage = (int) substr((string) $topologyPage, 0, 3);
}
if (strlen((string) $topologyPage) === 3) {
$lvl2Name = $topologies[$topologyPage]['name'];
$topologyPage = (int) substr((string) $topologyPage, 0, 1);
}
if (strlen((string) $topologyPage) === 1) {
$ruleName = 'ROLE_' . $topologies[$topologyPage]['name'];
}
if ($lvl2Name !== null) {
$ruleName .= '_' . $lvl2Name;
}
if ($lvl3Name !== null) {
$ruleName .= '_' . $lvl3Name;
}
if ($lvl4Name !== null) {
$ruleName .= '_' . $lvl4Name;
}
$ruleName .= ($details['right'] === 2) ? '_R' : '_RW';
$nameOfTopologiesRules[$originalTopologyPage] = $ruleName;
}
foreach ($nameOfTopologiesRules as $page => $name) {
if ($name !== null) {
$name = preg_replace(['/\s/', '/\W/'], ['_', ''], $name);
$name = strtoupper($name);
$contact->addTopologyRule($name);
}
}
}
}
/**
* Find and add all rules for a contact.
*
* @param Contact $contact Contact for which we want to find and add all rules
*/
private function addActionRules(Contact $contact): void
{
$request
= 'SELECT DISTINCT rules.acl_action_name
FROM `:db`.contact contact
LEFT JOIN `:db`.contactgroup_contact_relation cgcr
ON cgcr.contact_contact_id = contact.contact_id
LEFT JOIN `:db`.acl_group_contactgroups_relations gcgr
ON gcgr.cg_cg_id = cgcr.contactgroup_cg_id
LEFT JOIN `:db`.acl_group_contacts_relations gcr
ON gcr.contact_contact_id = contact.contact_id
LEFT JOIN `:db`.acl_group_actions_relations agar
ON agar.acl_group_id = gcr.acl_group_id
OR agar.acl_group_id = gcgr.acl_group_id
LEFT JOIN `:db`.acl_actions actions
ON actions.acl_action_id = agar.acl_action_id
LEFT JOIN `:db`.acl_actions_rules rules
ON rules.acl_action_rule_id = actions.acl_action_id
WHERE contact.contact_id = :contact_id
AND rules.acl_action_name IS NOT NULL
ORDER BY rules.acl_action_name';
$request = $this->translateDbName($request);
$statement = $this->db->prepare($request);
$statement->bindValue(':contact_id', $contact->getId(), \PDO::PARAM_INT);
$statement->execute();
while ($result = $statement->fetch(\PDO::FETCH_ASSOC)) {
$this->addActionRule($contact, $result['acl_action_name']);
}
}
/**
* Remove charset part of contact lang
*
* @param string $lang
* @return string The contact locale
*/
private function parseLocaleFromContactLang(string $lang): string
{
$locale = Contact::DEFAULT_LOCALE;
if (preg_match('/^(\w{2}_\w{2})/', $lang, $matches)) {
$locale = $matches[1];
}
return $locale;
}
/**
* Get the default timezone.
*
* @return string The timezone name
*/
private function getDefaultTimezone(): string
{
$query = <<<'SQL'
SELECT timezone.timezone_name
FROM `:db`.timezone
JOIN `:db`.options ON timezone.timezone_id = options.value
WHERE options.key = 'gmt'
SQL;
$query = $this->translateDbName($query);
$statement = $this->db->prepare($query);
$statement->execute();
$result = $statement->fetch(\PDO::FETCH_ASSOC);
return $result['timezone_name'] ?? date_default_timezone_get();
}
/**
* Create a contact based on the data.
*
* @param mixed[] $contact Array of values representing the contact information
*
* @throws \Exception
* @return Contact Returns a new instance of contact
*/
private function createContact(array $contact): Contact
{
$contactTimezoneName = ! empty($contact['timezone_name'])
? $contact['timezone_name']
: $this->getDefaultTimezone();
$contactLocale = ! empty($contact['contact_lang'])
? $this->parseLocaleFromContactLang($contact['contact_lang'])
: null;
$page = null;
if ($contact['default_page'] !== null) {
$page = new Page(
(int) $contact['topology_id'],
$contact['topology_url'],
(int) $contact['default_page'],
(bool) $contact['is_react']
);
if (! empty($contact['topology_url_opt'])) {
$page->setUrlOptions($contact['topology_url_opt']);
}
}
$contactObj = (new Contact())
->setId((int) $contact['contact_id'])
->setName($contact['contact_name'])
->setAlias($contact['contact_alias'])
->setEmail($contact['contact_email'])
->setLang($contact['contact_lang'])
->setTemplateId((int) $contact['contact_template_id'])
->setIsActive($contact['contact_activate'] === '1')
->setAllowedToReachWeb($contact['contact_oreon'] === '1')
->setAdmin($contact['contact_admin'] === '1')
->setToken($contact['contact_autologin_key'])
->setEncodedPassword($contact['contact_passwd'])
->setAccessToApiRealTime($contact['reach_api_rt'] === 1)
->setAccessToApiConfiguration($contact['reach_api'] === 1)
->setTimezone(new \DateTimeZone($contactTimezoneName))
->setTimezoneId((int) $contact['contact_location'])
->setLocale($contactLocale)
->setDefaultPage($page)
->setUseDeprecatedPages($contact['show_deprecated_pages'] === '1')
->setUseDeprecatedCustomViews($contact['show_deprecated_custom_views'] === '1')
->setTheme($contact['contact_theme'])
->setUserInterfaceDensity($contact['user_interface_density']);
if ($contactObj->isAdmin()) {
$contactObj
->setAccessToApiConfiguration(true)
->setAccessToApiRealTime(true);
}
$this->addActionRules($contactObj);
$this->addTopologyRules($contactObj);
return $contactObj;
}
/**
* Add an action rule to contact.
*
* @param Contact $contact Contact for which we want to add rule
* @param string $ruleName Rule to add
*/
private function addActionRule(Contact $contact, string $ruleName): void
{
switch ($ruleName) {
case 'host_schedule_check':
$contact->addRole(Contact::ROLE_HOST_CHECK);
break;
case 'host_schedule_forced_check':
$contact->addRole(Contact::ROLE_HOST_CHECK);
$contact->addRole(Contact::ROLE_HOST_FORCED_CHECK);
break;
case 'service_schedule_check':
$contact->addRole(Contact::ROLE_SERVICE_CHECK);
break;
case 'service_schedule_forced_check':
$contact->addRole(Contact::ROLE_SERVICE_CHECK);
$contact->addRole(Contact::ROLE_SERVICE_FORCED_CHECK);
break;
case 'host_acknowledgement':
$contact->addRole(Contact::ROLE_HOST_ACKNOWLEDGEMENT);
break;
case 'host_disacknowledgement':
$contact->addRole(Contact::ROLE_HOST_DISACKNOWLEDGEMENT);
break;
case 'service_acknowledgement':
$contact->addRole(Contact::ROLE_SERVICE_ACKNOWLEDGEMENT);
break;
case 'service_disacknowledgement':
$contact->addRole(Contact::ROLE_SERVICE_DISACKNOWLEDGEMENT);
break;
case 'service_schedule_downtime':
$contact->addRole(Contact::ROLE_ADD_SERVICE_DOWNTIME);
$contact->addRole(Contact::ROLE_CANCEL_SERVICE_DOWNTIME);
break;
case 'host_schedule_downtime':
$contact->addRole(Contact::ROLE_ADD_HOST_DOWNTIME);
$contact->addRole(Contact::ROLE_CANCEL_HOST_DOWNTIME);
break;
case 'service_submit_result':
$contact->addRole(Contact::ROLE_SERVICE_SUBMIT_RESULT);
break;
case 'host_submit_result':
$contact->addRole(Contact::ROLE_HOST_SUBMIT_RESULT);
break;
case 'host_comment':
$contact->addRole(Contact::ROLE_HOST_ADD_COMMENT);
break;
case 'service_comment':
$contact->addRole(Contact::ROLE_SERVICE_ADD_COMMENT);
break;
case 'service_display_command':
$contact->addRole(Contact::ROLE_DISPLAY_COMMAND);
break;
case 'generate_cfg':
$contact->addRole(Contact::ROLE_GENERATE_CONFIGURATION);
break;
case 'manage_tokens':
$contact->addRole(Contact::ROLE_MANAGE_TOKENS);
// no break
case 'create_edit_poller_cfg':
$contact->addRole(Contact::ROLE_CREATE_EDIT_POLLER_CFG);
break;
case 'delete_poller_cfg':
$contact->addRole(Contact::ROLE_DELETE_POLLER_CFG);
break;
case 'top_counter':
$contact->addRole(Contact::ROLE_DISPLAY_TOP_COUNTER);
break;
case 'poller_stats':
$contact->addRole(Contact::ROLE_DISPLAY_TOP_COUNTER_POLLERS_STATISTICS);
break;
}
}
}
| 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/Icon/IconRepositoryRDB.php | centreon/src/Centreon/Infrastructure/Icon/IconRepositoryRDB.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Icon;
use Centreon\Domain\Configuration\Icon\Icon;
use Centreon\Domain\Configuration\Icon\Interfaces\IconRepositoryInterface;
use Centreon\Domain\RequestParameters\RequestParameters;
use Centreon\Infrastructure\DatabaseConnection;
use Centreon\Infrastructure\Repository\AbstractRepositoryDRB;
use Centreon\Infrastructure\RequestParameters\SqlRequestParametersTranslator;
class IconRepositoryRDB extends AbstractRepositoryDRB implements IconRepositoryInterface
{
/** @var SqlRequestParametersTranslator */
private $sqlRequestTranslator;
/**
* IconRepositoryRDB constructor.
*
* @param DatabaseConnection $db
*/
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* Initialized by the dependency injector.
*
* @param SqlRequestParametersTranslator $sqlRequestTranslator
*/
public function setSqlRequestTranslator(SqlRequestParametersTranslator $sqlRequestTranslator): void
{
$this->sqlRequestTranslator = $sqlRequestTranslator;
$this->sqlRequestTranslator
->getRequestParameters()
->setConcordanceStrictMode(RequestParameters::CONCORDANCE_MODE_STRICT);
}
/**
* @inheritDoc
*/
public function getIconsWithRequestParameters(): array
{
$this->sqlRequestTranslator->setConcordanceArray([
'id' => 'vi.img_id',
'name' => 'vi.img_name',
]);
// Search
$searchRequest = $this->sqlRequestTranslator->translateSearchParameterToSql();
// Sort
$sortRequest = $this->sqlRequestTranslator->translateSortParameterToSql();
// Pagination
$paginationRequest = $this->sqlRequestTranslator->translatePaginationToSql();
return $this->getIcons($searchRequest, $sortRequest, $paginationRequest);
}
/**
* @inheritDoc
*/
public function getIconsWithoutRequestParameters(): array
{
return $this->getIcons(null, null, null);
}
/**
* @inheritDoc
*/
public function getIcon(int $id): ?Icon
{
$statement = $this->db->prepare(
$this->translateDbName(
<<<'SQL'
SELECT vi.*, vid.dir_name AS `img_dir`
FROM `:db`.`view_img` AS `vi`
LEFT JOIN `:db`.`view_img_dir_relation` AS `vidr`
ON vi.img_id = vidr.img_img_id
LEFT JOIN `:db`.`view_img_dir` AS `vid`
ON vid.dir_id = vidr.dir_dir_parent_id
WHERE vi.img_id = :id
SQL
)
);
$statement->bindValue(':id', $id, \PDO::PARAM_INT);
$statement->execute();
$icon = null;
if (($row = $statement->fetch(\PDO::FETCH_ASSOC)) !== false) {
$icon = new Icon();
$icon
->setId((int) $row['img_id'])
->setDirectory($row['img_dir'])
->setName($row['img_name'])
->setUrl($row['img_dir'] . '/' . $row['img_path']);
}
return $icon;
}
/**
* Retrieve all icons according to ACL of contact
*
* @param string|null $searchRequest search request
* @param string|null $sortRequest sort request
* @param string|null $paginationRequest pagination request
* @return Icon[]
*/
private function getIcons(
?string $searchRequest = null,
?string $sortRequest = null,
?string $paginationRequest = null,
): array {
$request = $this->translateDbName('
SELECT SQL_CALC_FOUND_ROWS vi.*, vid.dir_name AS `img_dir`
FROM `view_img` AS `vi`
LEFT JOIN `:db`.`view_img_dir_relation` AS `vidr` ON vi.img_id = vidr.img_img_id
LEFT JOIN `:db`.`view_img_dir` AS `vid` ON vid.dir_id = vidr.dir_dir_parent_id
');
// Search
$request .= ! is_null($searchRequest) ? $searchRequest : '';
// Sort
$request .= ! is_null($sortRequest) ? $sortRequest : ' ORDER BY vi.img_id ASC';
// Pagination
$request .= ! is_null($paginationRequest) ? $paginationRequest : '';
$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);
}
$icons = [];
while ($row = $statement->fetch(\PDO::FETCH_ASSOC)) {
$icon = new Icon();
$icon
->setId((int) $row['img_id'])
->setDirectory($row['img_dir'])
->setName($row['img_name'])
->setUrl($row['img_dir'] . '/' . $row['img_path']);
$icons[] = $icon;
}
return $icons;
}
}
| 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/RemoteServer/RemoteServerRepositoryFile.php | centreon/src/Centreon/Infrastructure/RemoteServer/RemoteServerRepositoryFile.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\RemoteServer;
use Centreon\Domain\RemoteServer\Interfaces\RemoteServerLocalConfigurationRepositoryInterface;
class RemoteServerRepositoryFile implements RemoteServerLocalConfigurationRepositoryInterface
{
/** @var string */
private $centreonConfFilePath;
/**
* @param string $centreonConfFilePath
*/
public function setCentreonConfFilePath(string $centreonConfFilePath): void
{
$this->centreonConfFilePath = DIRECTORY_SEPARATOR . ltrim($centreonConfFilePath, DIRECTORY_SEPARATOR);
}
/**
* @inheritDoc
*/
public function updateInstanceModeCentral(): void
{
system(
"sed -i -r 's/(\\\$instance_mode?\s+=?\s+\")([a-z]+)(\";)/\\1central\\3/' "
. $this->centreonConfFilePath
);
}
/**
* @inheritDoc
*/
public function updateInstanceModeRemote(): void
{
system(
"sed -i -r 's/(\\\$instance_mode?\s+=?\s+\")([a-z]+)(\";)/\\1remote\\3/' "
. $this->centreonConfFilePath
);
}
}
| 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/RemoteServer/RemoteServerRepositoryRDB.php | centreon/src/Centreon/Infrastructure/RemoteServer/RemoteServerRepositoryRDB.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\RemoteServer;
use Centreon\Domain\RemoteServer\Interfaces\RemoteServerRepositoryInterface;
use Centreon\Infrastructure\DatabaseConnection;
use Centreon\Infrastructure\Repository\AbstractRepositoryDRB;
class RemoteServerRepositoryRDB extends AbstractRepositoryDRB implements RemoteServerRepositoryInterface
{
/**
* RemoteServerRepositoryRDB constructor.
* @param DatabaseConnection $db
*/
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* @inheritDoc
*/
public function deleteRemoteServerByServerId(int $serverId): void
{
$statement = $this->db->prepare(
$this->translateDbName('DELETE FROM remote_servers WHERE server_id = :server_id')
);
$statement->bindValue(':server_id', $serverId, \PDO::PARAM_INT);
$statement->execute();
}
/**
* @inheritDoc
*/
public function deleteAdditionalRemoteServer(int $monitoringServerId): void
{
$statement = $this->db->prepare(
$this->translateDbName('DELETE FROM rs_poller_relation WHERE remote_server_id = :id')
);
$statement->bindValue(':id', $monitoringServerId, \PDO::PARAM_INT);
$statement->execute();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Infrastructure/Serializer/ObjectConstructor.php | centreon/src/Centreon/Infrastructure/Serializer/ObjectConstructor.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Serializer;
use Centreon\Infrastructure\Serializer\Exception\SerializerException;
use JMS\Serializer\Construction\ObjectConstructorInterface;
use JMS\Serializer\DeserializationContext;
use JMS\Serializer\Metadata\ClassMetadata;
use JMS\Serializer\Visitor\DeserializationVisitorInterface;
/**
* This class is designed to allow the use of class constructors during deserialization phases.
*
* @package Centreon\Infrastructure\Serializer
*/
class ObjectConstructor implements ObjectConstructorInterface
{
/**
* {@inheritDoc}
* @param array<string, mixed> $type
* @throws SerializerException
* @throws \ReflectionException
* @throws \Throwable
*/
public function construct(
DeserializationVisitorInterface $visitor,
ClassMetadata $metadata,
$data,
array $type,
DeserializationContext $context,
): ?object {
$className = $metadata->name;
if (! class_exists($className)) {
throw SerializerException::classNotFound($className);
}
$reflection = new \ReflectionClass($className);
$constructor = $reflection->getConstructor();
if ($constructor !== null && $constructor->getNumberOfParameters() > 0) {
$parameters = $constructor->getParameters();
$constructorParameters = [];
foreach ($parameters as $parameter) {
if (array_key_exists($parameter->getName(), $data)) {
$constructorParameters[$parameter->getPosition()] = $data[$parameter->getName()];
} elseif ($parameter->isOptional() === true) {
$constructorParameters[$parameter->getPosition()] = $parameter->getDefaultValue();
}
}
try {
return $reflection->newInstanceArgs($constructorParameters);
} catch (\Throwable $ex) {
if ($ex instanceof \ArgumentCountError) {
throw SerializerException::notEnoughConstructorArguments($className, $ex);
}
throw $ex;
}
} else {
return new $className();
}
}
}
| 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/Serializer/Exception/SerializerException.php | centreon/src/Centreon/Infrastructure/Serializer/Exception/SerializerException.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Serializer\Exception;
/**
* This class is designed to contain all exceptions concerning deserialization.
*
* @package Centreon\Infrastructure\Serializer\Exception
*/
class SerializerException extends \Exception
{
/**
* @param string $classname
* @param \Throwable $ex
* @return self
*/
public static function notEnoughConstructorArguments(string $classname, \Throwable $ex): self
{
return new self(sprintf(_('There are not enough arguments to build the object %s'), $classname), 0, $ex);
}
/**
* @param string $className
* @return self
*/
public static function classNotFound(string $className): self
{
return new self(sprintf(_('Class %s not found'), $className));
}
}
| 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/Downtime/DowntimeRepositoryRDB.php | centreon/src/Centreon/Infrastructure/Downtime/DowntimeRepositoryRDB.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Downtime;
use Centreon\Domain\Downtime\Downtime;
use Centreon\Domain\Downtime\Interfaces\DowntimeRepositoryInterface;
use Centreon\Domain\Entity\EntityCreator;
use Centreon\Infrastructure\DatabaseConnection;
use Centreon\Infrastructure\Repository\AbstractRepositoryDRB;
use Centreon\Infrastructure\RequestParameters\SqlRequestParametersTranslator;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
/**
* Downtime repository for MySQL
*
* @package Centreon\Infrastructure\Downtime
*/
class DowntimeRepositoryRDB extends AbstractRepositoryDRB implements DowntimeRepositoryInterface
{
/** @var SqlRequestParametersTranslator */
private $sqlRequestTranslator;
/** @var AccessGroup[] List of access group used to filter the requests */
private $accessGroups;
/** @var array<string, string> */
private $downtimeConcordanceArray = [
// Relation for downtime
'id' => 'dwt.downtime_id',
'entry_time' => 'dwt.entry_time',
'is_cancelled' => 'dwt.cancelled',
'comment' => 'dwt.comment_data',
'deletion_time' => 'dwt.deletion_time',
'duration' => 'dwt.duration',
'end_time' => 'dwt.end_time',
'is_fixed' => 'dwt.fixed',
'start_time' => 'dwt.start_time',
// Relation for host
'host.id' => 'hosts.host_id',
'host.name' => 'hosts.name',
'host.alias' => 'hosts.alias',
'host.address' => 'hosts.address',
'host.display_name' => 'hosts.display_name',
'host.state' => 'h.state',
// Relation for poller
'poller.id' => 'hosts.instance_id',
// Relation for contact
'contact.id' => 'contact.contact_id',
'contact.name' => 'contact.contact_name',
];
public function __construct(
DatabaseConnection $db,
SqlRequestParametersTranslator $sqlRequestTranslator,
) {
$this->db = $db;
$this->sqlRequestTranslator = $sqlRequestTranslator;
}
/**
* @inheritDoc
*/
public function forAccessGroups(array $accessGroups): DowntimeRepositoryInterface
{
$this->accessGroups = $accessGroups;
return $this;
}
/**
* @inheritDoc
* @throws \Exception
*/
public function findHostDowntimesForNonAdminUser(): array
{
if ($this->hasNotEnoughRightsToContinue()) {
return [];
}
// Internal call for non admin user
return $this->findHostDowntimes(false);
}
/**
* @inheritDoc
*/
public function findHostDowntimesForAdminUser(): array
{
// Internal call for an admin user
return $this->findHostDowntimes(true);
}
/**
* @inheritDoc
*/
public function findOneDowntimeForAdminUser(int $downtimeId): ?Downtime
{
// Internal call for an admin user
return $this->findOneDowntime($downtimeId, true);
}
/**
* @inheritDoc
*/
public function findOneDowntimeForNonAdminUser(int $downtimeId): ?Downtime
{
if ($this->hasNotEnoughRightsToContinue()) {
return null;
}
// Internal call for non admin user
return $this->findOneDowntime($downtimeId, false);
}
/**
* @inheritDoc
*/
public function findDowntimesForAdminUser(): array
{
// Internal call for an admin user
return $this->findDowntimes(true);
}
/**
* @inheritDoc
*/
public function findDowntimesForNonAdminUser(): array
{
if ($this->hasNotEnoughRightsToContinue()) {
return [];
}
// Internal call for non admin user
return $this->findDowntimes(false);
}
/**
* @inheritDoc
*/
public function findDowntimesByHostForAdminUser(int $hostId, bool $withServices = false): array
{
// Internal call for an admin user
return $this->findDowntimesByHost($hostId, $withServices, true);
}
/**
* @inheritDoc
*/
public function findDowntimesByHostForNonAdminUser(int $hostId, bool $withServices = false): array
{
if ($this->hasNotEnoughRightsToContinue()) {
return [];
}
// Internal call for non admin user
return $this->findDowntimesByHost($hostId, $withServices, false);
}
/**
* @inheritDoc
*/
public function findServicesDowntimesForNonAdminUser(): array
{
if ($this->hasNotEnoughRightsToContinue()) {
return [];
}
// Internal call for non admin user
return $this->findServicesDowntimes(false);
}
/**
* @inheritDoc
*/
public function findServicesDowntimesForAdminUser(): array
{
// Internal call for an admin user
return $this->findServicesDowntimes(true);
}
/**
* @inheritDoc
*/
public function findDowntimesByServiceForNonAdminUser(int $hostId, int $serviceId): array
{
if ($this->hasNotEnoughRightsToContinue()) {
return [];
}
// Internal call for non admin user
return $this->findDowntimesByService($hostId, $serviceId, false);
}
/**
* @inheritDoc
*/
public function findDowntimesByServiceForAdminUser(int $hostId, int $serviceId): array
{
// Internal call for an admin user
return $this->findDowntimesByService($hostId, $serviceId, true);
}
/**
* @return bool return TRUE if the contact is an admin or has at least one access group
*/
private function hasNotEnoughRightsToContinue(): bool
{
return count($this->accessGroups) == 0;
}
/**
* @param bool $isAdmin Indicates whether user is an admin
* @throws \Exception
* @return Downtime[]
*/
private function findHostDowntimes(bool $isAdmin = false): array
{
$this->sqlRequestTranslator->setConcordanceArray($this->downtimeConcordanceArray);
$aclRequest = '';
if ($isAdmin === false) {
$aclRequest
= ' INNER JOIN `:dbstg`.`centreon_acl` acl
ON acl.host_id = dwt.host_id
AND 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 dwt.*, contact.contact_id AS author_id
FROM `:dbstg`.downtimes dwt
INNER JOIN `:dbstg`.hosts
ON hosts.host_id = dwt.host_id
AND dwt.service_id = 0
LEFT JOIN `:db`.`contact`
ON contact.contact_alias = dwt.author'
. $aclRequest;
return $this->processRequest($request);
}
/**
* Find one downtime linked to a host tacking into account or not the ACLs of host.
*
* @param int $downtimeId Downtime id
* @param bool $isAdmin Indicates whether user is an admin
* @throws \Exception
* @return Downtime|null Return NULL if the downtime has not been found
*/
private function findOneDowntime(int $downtimeId, bool $isAdmin = false): ?Downtime
{
$aclRequest = '';
if ($isAdmin === false) {
$aclRequest
= ' INNER JOIN `:dbstg`.`centreon_acl` acl
ON acl.host_id = dwt.host_id
AND (acl.service_id = dwt.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 dwt.*, contact.contact_id AS author_id
FROM `:dbstg`.downtimes dwt
LEFT JOIN `:db`.`contact`
ON contact.contact_alias = dwt.author'
. $aclRequest
. ' WHERE dwt.downtime_id = :downtime_id';
$request = $this->translateDbName($request);
$prepare = $this->db->prepare($request);
$prepare->bindValue(':downtime_id', $downtimeId, \PDO::PARAM_INT);
$prepare->execute();
if (false !== ($row = $prepare->fetch(\PDO::FETCH_ASSOC))) {
return EntityCreator::createEntityByArray(
Downtime::class,
$row
);
}
return null;
}
/**
* Find all downtimes.
*
* @param bool $isAdmin Indicates whether user is an admin
* @throws \Exception
* @return Downtime[]
*/
private function findDowntimes(bool $isAdmin): array
{
$serviceConcordanceArray = [
// Relation for service
'service.id' => 'srv.service_id',
'service.display_name' => 'srv.display_name',
];
/*
* If the search parameters contain at least one key corresponding to the services, we must:
* 1. taking into account the search for service
* 2. add the join to the services table
*/
$downtimeConcordanceArray = $this->downtimeConcordanceArray;
$searchParameters = $this->sqlRequestTranslator->getRequestParameters()->extractSearchNames();
$shouldJoinService = false;
if (array_intersect($searchParameters, array_keys($serviceConcordanceArray)) !== []) {
$shouldJoinService = true;
$downtimeConcordanceArray = array_merge($downtimeConcordanceArray, $serviceConcordanceArray);
}
$this->sqlRequestTranslator->setConcordanceArray($downtimeConcordanceArray);
$aclRequest = '';
if ($isAdmin === false) {
$aclRequest
= ' INNER JOIN `:dbstg`.`centreon_acl` acl
ON acl.host_id = dwt.host_id
AND (acl.service_id = dwt.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) . ') ';
}
$serviceRequest = ($shouldJoinService)
? ' INNER JOIN `:dbstg`.services srv
ON srv.service_id = dwt.service_id
AND srv.host_id = hosts.host_id '
: '';
$request
= 'SELECT SQL_CALC_FOUND_ROWS DISTINCT dwt.*, contact.contact_id AS author_id
FROM `:dbstg`.downtimes dwt
LEFT JOIN `:db`.`contact`
ON contact.contact_alias = dwt.author
INNER JOIN `:dbstg`.hosts
ON hosts.host_id = dwt.host_id'
. $serviceRequest
. $aclRequest;
return $this->processRequest($request);
}
/**
* Find all downtimes for a host.
*
* @param int $hostId host id for which we want to find downtimes
* @param bool $withServices
* @param bool $isAdmin Indicates whether user is an admin
* @throws \Exception
* @return Downtime[]
*/
private function findDowntimesByHost(int $hostId, bool $withServices, bool $isAdmin = false): array
{
$concordanceArray = [
// Relation for downtime
'id' => 'dwt.downtime_id',
'entry_time' => 'dwt.entry_time',
'is_cancelled' => 'dwt.cancelled',
'comment' => 'dwt.comment_data',
'deletion_time' => 'dwt.deletion_time',
'duration' => 'dwt.duration',
'end_time' => 'dwt.end_time',
'is_fixed' => 'dwt.fixed',
'start_time' => 'dwt.start_time',
// Relation for contact
'contact.id' => 'contact.contact_id',
'contact.name' => 'contact.contact_name',
];
$this->sqlRequestTranslator->setConcordanceArray($concordanceArray);
$aclRequest = '';
if ($isAdmin === false) {
$aclRequest
= ' INNER JOIN `:dbstg`.`centreon_acl` acl
ON acl.host_id = dwt.host_id'
. ($withServices ? '' : ' AND 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 dwt.*, contact.contact_id AS author_id
FROM `:dbstg`.downtimes dwt
LEFT JOIN `:db`.`contact`
ON contact.contact_alias = dwt.author
INNER JOIN `:dbstg`.hosts
ON hosts.host_id = dwt.host_id
AND dwt.host_id = :host_id'
. ($withServices ? '' : ' AND dwt.service_id = 0')
. $aclRequest;
$this->sqlRequestTranslator->addSearchValue(
':host_id',
[\PDO::PARAM_INT => $hostId]
);
return $this->processRequest($request);
}
/**
* Find all downtimes of all services.
*
* @param bool $isAdmin $isAdmin Indicates whether user is an admin
* @throws \Exception
* @return Downtime[]
*/
private function findServicesDowntimes(bool $isAdmin): array
{
$this->sqlRequestTranslator->setConcordanceArray($this->downtimeConcordanceArray);
$aclRequest = '';
if ($isAdmin === false) {
$aclRequest
= ' INNER JOIN `:dbstg`.`centreon_acl` acl
ON acl.host_id = dwt.host_id
AND acl.service_id = dwt.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 SQL_CALC_FOUND_ROWS DISTINCT dwt.*, contact.contact_id AS author_id
FROM `:dbstg`.downtimes dwt
INNER JOIN `:dbstg`.hosts
ON hosts.host_id = dwt.host_id
INNER JOIN `:dbstg`.services srv
ON srv.service_id = dwt.service_id
AND srv.host_id = hosts.host_id
LEFT JOIN `:db`.`contact`
ON contact.contact_alias = dwt.author'
. $aclRequest;
return $this->processRequest($request);
}
/**
* Find all downtimes for a service (linked to a host).
*
* @param int $hostId Host id linked to this service
* @param int $serviceId Service id for which we want to find downtimes
* @param bool $isAdmin Indicates whether user is an admin
* @throws \Exception
* @return Downtime[]
*/
private function findDowntimesByService(int $hostId, int $serviceId, bool $isAdmin): array
{
$concordanceArray = [
// Relation for downtime
'id' => 'dwt.downtime_id',
'entry_time' => 'dwt.entry_time',
'is_cancelled' => 'dwt.cancelled',
'comment' => 'dwt.comment_data',
'deletion_time' => 'dwt.deletion_time',
'duration' => 'dwt.duration',
'end_time' => 'dwt.end_time',
'is_fixed' => 'dwt.fixed',
'start_time' => 'dwt.start_time',
];
$this->sqlRequestTranslator->setConcordanceArray($concordanceArray);
$aclRequest = '';
if ($isAdmin === false) {
$aclRequest
= ' INNER JOIN `:dbstg`.`centreon_acl` acl
ON acl.host_id = dwt.host_id
AND acl.service_id = dwt.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 SQL_CALC_FOUND_ROWS DISTINCT dwt.*, contact.contact_id AS author_id
FROM `:dbstg`.downtimes dwt
INNER JOIN `:dbstg`.hosts
ON hosts.host_id = dwt.host_id
INNER JOIN `:dbstg`.services srv
ON srv.service_id = dwt.service_id
AND srv.host_id = hosts.host_id
AND dwt.host_id = :host_id
AND srv.service_id = :service_id
LEFT JOIN `:db`.`contact`
ON contact.contact_alias = dwt.author'
. $aclRequest;
$this->sqlRequestTranslator->addSearchValue(':host_id', [\PDO::PARAM_INT => $hostId]);
$this->sqlRequestTranslator->addSearchValue(':service_id', [\PDO::PARAM_INT => $serviceId]);
return $this->processRequest($request);
}
/**
* Execute the request and retrieve the downtimes list
*
* @param string $request Request to execute
* @throws \Exception
* @return Downtime[]
*/
private function processRequest(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 dwt.downtime_id 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);
}
$hostDowntimes = [];
while (false !== ($result = $statement->fetch(\PDO::FETCH_ASSOC))) {
$hostDowntimes[] = EntityCreator::createEntityByArray(
Downtime::class,
$result
);
}
return $hostDowntimes;
}
}
| 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/HostConfiguration/Repository/HostGroupRepositoryRDB.php | centreon/src/Centreon/Infrastructure/HostConfiguration/Repository/HostGroupRepositoryRDB.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\HostConfiguration\Repository;
use Assert\AssertionFailedException;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\HostConfiguration\Host;
use Centreon\Domain\HostConfiguration\Interfaces\HostGroup\HostGroupReadRepositoryInterface;
use Centreon\Domain\HostConfiguration\Interfaces\HostGroup\HostGroupWriteRepositoryInterface;
use Centreon\Domain\HostConfiguration\Model\HostGroup;
use Centreon\Domain\Repository\RepositoryException;
use Centreon\Domain\RequestParameters\RequestParameters;
use Centreon\Infrastructure\DatabaseConnection;
use Centreon\Infrastructure\HostConfiguration\Repository\Model\HostGroupFactoryRdb;
use Centreon\Infrastructure\Repository\AbstractRepositoryDRB;
use Centreon\Infrastructure\RequestParameters\Interfaces\NormalizerInterface;
use Centreon\Infrastructure\RequestParameters\SqlRequestParametersTranslator;
/**
* This class is designed to represent the MariaDb repository to manage host groups
*
* @package Centreon\Infrastructure\HostConfiguration\Repository
*/
class HostGroupRepositoryRDB extends AbstractRepositoryDRB implements
HostGroupReadRepositoryInterface,
HostGroupWriteRepositoryInterface
{
/** @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 addGroup(HostGroup $group): void
{
$statement = $this->db->prepare(
$this->translateDbName('
INSERT INTO `:db`.hostgroup
(hg_name, hg_alias, hg_icon_image, geo_coords, hg_comment, hg_activate)
VALUES (:group_name, :group_alias, :group_icon_id, :group_geo, :group_comment, :is_activate)
')
);
$statement->bindValue(':group_name', $group->getName(), \PDO::PARAM_STR);
$statement->bindValue(':group_alias', $group->getAlias(), \PDO::PARAM_STR);
$statement->bindValue(
':group_icon_id',
($group->getIcon() !== null) ? $group->getIcon()->getId() : null,
\PDO::PARAM_INT
);
$statement->bindValue(':group_geo', $group->getGeoCoords(), \PDO::PARAM_STR);
$statement->bindValue(':group_comment', $group->getComment(), \PDO::PARAM_STR);
$statement->bindValue(':is_activate', $group->isActivated() ? '1' : '0', \PDO::PARAM_STR);
$statement->execute();
$group->setId((int) $this->db->lastInsertId());
}
/**
* @inheritDoc
*/
public function findAllByHost(Host $host): array
{
if ($host->getId() === null) {
return [];
}
$statement = $this->db->prepare(
$this->translateDbName(
'SELECT hg.*, icon.img_id AS icon_id, icon.img_name AS icon_name,
CONCAT(iconD.dir_name,\'/\',icon.img_path) AS icon_path,
icon.img_comment AS icon_comment
FROM `:db`.hostgroup hg
INNER JOIN `:db`.hostgroup_relation hgr
ON hgr.hostgroup_hg_id = hg.hg_id
LEFT JOIN `:db`.view_img icon
ON icon.img_id = hg.hg_icon_image
LEFT JOIN `:db`.view_img_dir_relation iconR
ON iconR.img_img_id = icon.img_id
LEFT JOIN `:db`.view_img_dir iconD
ON iconD.dir_id = iconR.dir_dir_parent_id
WHERE hgr.host_host_id = :host_id'
)
);
$statement->bindValue(':host_id', $host->getId(), \PDO::PARAM_INT);
$statement->execute();
$hostGroups = [];
while (($result = $statement->fetch(\PDO::FETCH_ASSOC)) !== false) {
$hostGroups[] = HostGroupFactoryRdb::create($result);
}
return $hostGroups;
}
/**
* @inheritDoc
*/
public function findById(int $hostGroupId): ?HostGroup
{
try {
return $this->findByIdRequest($hostGroupId, null);
} catch (AssertionFailedException $ex) {
throw new RepositoryException($ex->getMessage(), 0, $ex);
}
}
/**
* @inheritDoc
*/
public function findByIdAndContact(int $hostGroupId, ContactInterface $contact): ?HostGroup
{
try {
return $this->findByIdRequest($hostGroupId, $contact->getId());
} catch (AssertionFailedException $ex) {
throw new RepositoryException($ex->getMessage(), 0, $ex);
}
}
/**
* @inheritDoc
* @throws AssertionFailedException
*/
public function findByNames(array $groupsName): array
{
$hostGroups = [];
if ($groupsName === []) {
return $hostGroups;
}
$statement = $this->db->prepare(
$this->translateDbName(
'SELECT hg.*, icon.img_id AS icon_id, icon.img_name AS icon_name,
CONCAT(iconD.dir_name,\'/\',icon.img_path) AS icon_path,
icon.img_comment AS icon_comment
FROM `:db`.hostgroup hg
LEFT JOIN `:db`.view_img icon
ON icon.img_id = hg.hg_icon_image
LEFT JOIN `:db`.view_img_dir_relation iconR
ON iconR.img_img_id = icon.img_id
LEFT JOIN `:db`.view_img_dir iconD
ON iconD.dir_id = iconR.dir_dir_parent_id
WHERE hg.hg_name IN (?' . str_repeat(',?', count($groupsName) - 1) . ')'
)
);
$statement->execute($groupsName);
while (($result = $statement->fetch(\PDO::FETCH_ASSOC)) !== false) {
$hostGroups[] = HostGroupFactoryRdb::create($result);
}
return $hostGroups;
}
/**
* @inheritDoc
* @throws AssertionFailedException
* @throws \InvalidArgumentException
*/
public function findHostGroups(): array
{
$this->sqlRequestTranslator->setConcordanceArray([
'id' => 'hg_id',
'name' => 'hg_name',
'alias' => 'hg_alias',
'is_activated' => 'hg_activate',
]);
$this->sqlRequestTranslator->addNormalizer(
'is_activated',
new class () implements NormalizerInterface {
/**
* @inheritDoc
*/
public function normalize($valueToNormalize): string
{
if (is_bool($valueToNormalize)) {
return $valueToNormalize === true ? '1' : '0';
}
return $valueToNormalize;
}
}
);
$request = $this->translateDbName(
'SELECT SQL_CALC_FOUND_ROWS hg.*, icon.img_id AS icon_id, icon.img_name AS icon_name,
CONCAT(iconD.dir_name,\'/\',icon.img_path) AS icon_path,
icon.img_comment AS icon_comment
FROM `:db`.hostgroup hg
LEFT JOIN `:db`.view_img icon
ON icon.img_id = hg.hg_icon_image
LEFT JOIN `:db`.view_img_dir_relation iconR
ON iconR.img_img_id = icon.img_id
LEFT JOIN `:db`.view_img_dir iconD
ON iconD.dir_id = iconR.dir_dir_parent_id'
);
// Search
$searchRequest = $this->sqlRequestTranslator->translateSearchParameterToSql();
$request .= ! is_null($searchRequest) ? $searchRequest : '';
// Sort
$sortRequest = $this->sqlRequestTranslator->translateSortParameterToSql();
$request .= ! is_null($sortRequest)
? $sortRequest
: ' ORDER BY hg.hg_id ASC';
// 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);
}
$hostGroups = [];
if ($statement !== false) {
while (($result = $statement->fetch(\PDO::FETCH_ASSOC)) !== false) {
$hostGroups[] = HostGroupFactoryRdb::create($result);
}
}
return $hostGroups;
}
/**
* Find a group by id and contact id.
*
* @param int $hostGroupId Id of the host group to be found
* @param int|null $contactId Contact id related to host groups
* @throws AssertionFailedException
* @return HostGroup|null
*/
private function findByIdRequest(int $hostGroupId, ?int $contactId): ?HostGroup
{
if ($contactId === null) {
$statement = $this->db->prepare(
$this->translateDbName(
'SELECT hg.*, icon.img_id AS icon_id, icon.img_name AS icon_name,
CONCAT(iconD.dir_name,\'/\',icon.img_path) AS icon_path,
icon.img_comment AS icon_comment
FROM `:db`.hostgroup hg
LEFT JOIN `:db`.view_img icon
ON icon.img_id = hg.hg_icon_image
LEFT JOIN `:db`.view_img_dir_relation iconR
ON iconR.img_img_id = icon.img_id
LEFT JOIN `:db`.view_img_dir iconD
ON iconD.dir_id = iconR.dir_dir_parent_id
WHERE hg.hg_id = :id'
)
);
} else {
$statement = $this->db->prepare(
$this->translateDbName(
'SELECT hg.*, icon.img_id AS icon_id, icon.img_name AS icon_name,
CONCAT(iconD.dir_name,\'/\',icon.img_path) AS icon_path,
icon.img_comment AS icon_comment
FROM `:db`.hostgroup hg
LEFT JOIN `:db`.view_img icon
ON icon.img_id = hg.hg_icon_image
LEFT JOIN `:db`.view_img_dir_relation iconR
ON iconR.img_img_id = icon.img_id
LEFT JOIN `:db`.view_img_dir iconD
ON iconD.dir_id = iconR.dir_dir_parent_id
INNER JOIN `:db`.acl_resources_hg_relations arhr
ON hg.hg_id = arhr.hg_hg_id
INNER JOIN `:db`.acl_resources res
ON arhr.acl_res_id = res.acl_res_id
INNER JOIN `:db`.acl_res_group_relations argr
ON res.acl_res_id = argr.acl_res_id
INNER JOIN `:db`.acl_groups ag
ON argr.acl_group_id = ag.acl_group_id
LEFT JOIN `:db`.acl_group_contacts_relations agcr
ON ag.acl_group_id = agcr.acl_group_id
LEFT JOIN `:db`.acl_group_contactgroups_relations agcgr
ON ag.acl_group_id = agcgr.acl_group_id
LEFT JOIn `:db`.contactgroup_contact_relation cgcr
ON cgcr.contactgroup_cg_id = agcgr.cg_cg_id
WHERE hg.hg_id = :id
AND (agcr.contact_contact_id = :contact_id OR cgcr.contact_contact_id = :contact_id)'
)
);
$statement->bindValue(':contact_id', $contactId, \PDO::PARAM_INT);
}
$statement->bindValue(':id', $hostGroupId, \PDO::PARAM_INT);
$statement->execute();
if (($result = $statement->fetch(\PDO::FETCH_ASSOC)) !== false) {
return HostGroupFactoryRdb::create($result);
}
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/Infrastructure/HostConfiguration/Repository/HostMacroRepositoryRDB.php | centreon/src/Centreon/Infrastructure/HostConfiguration/Repository/HostMacroRepositoryRDB.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\HostConfiguration\Repository;
use Centreon\Domain\Common\Assertion\Assertion;
use Centreon\Domain\HostConfiguration\Host;
use Centreon\Domain\HostConfiguration\HostMacro;
use Centreon\Domain\HostConfiguration\Interfaces\HostMacro\HostMacroReadRepositoryInterface;
use Centreon\Domain\HostConfiguration\Interfaces\HostMacro\HostMacroWriteRepositoryInterface;
use Centreon\Domain\RequestParameters\RequestParameters;
use Centreon\Infrastructure\DatabaseConnection;
use Centreon\Infrastructure\HostConfiguration\Repository\Model\HostMacroFactoryRdb;
use Centreon\Infrastructure\Repository\AbstractRepositoryDRB;
use Centreon\Infrastructure\RequestParameters\SqlRequestParametersTranslator;
/**
* This class is designed to represent the MariaDb repository to manage host macro,
*
* @package Centreon\Infrastructure\HostConfiguration\Repository
*/
class HostMacroRepositoryRDB extends AbstractRepositoryDRB implements
HostMacroReadRepositoryInterface,
HostMacroWriteRepositoryInterface
{
/** @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 addMacroToHost(Host $host, HostMacro $hostMacro): void
{
Assertion::notNull($host->getId(), 'Host::id');
$request = $this->translateDbName(
'INSERT INTO `:db`.on_demand_macro_host
(host_host_id, host_macro_name, host_macro_value, is_password, description, macro_order)
VALUES (:host_id, :name, :value, :is_password, :description, :order)'
);
$statement = $this->db->prepare($request);
$statement->bindValue(':host_id', $host->getId(), \PDO::PARAM_INT);
$statement->bindValue(':name', $hostMacro->getName(), \PDO::PARAM_STR);
$statement->bindValue(':value', $hostMacro->getValue(), \PDO::PARAM_STR);
$statement->bindValue(':is_password', $hostMacro->isPassword(), \PDO::PARAM_INT);
$statement->bindValue(':description', $hostMacro->getDescription(), \PDO::PARAM_STR);
$statement->bindValue(':order', $hostMacro->getOrder(), \PDO::PARAM_INT);
$statement->execute();
$hostMacroId = (int) $this->db->lastInsertId();
$hostMacro->setId($hostMacroId);
}
/**
* @inheritDoc
*/
public function findAllByHost(Host $host): array
{
Assertion::notNull($host->getId(), 'Host::id');
$statement = $this->db->prepare(
$this->translateDbName('SELECT * FROM `:db`.on_demand_macro_host WHERE host_host_id = :host_id')
);
$statement->bindValue(':host_id', $host->getId(), \PDO::PARAM_INT);
$statement->execute();
$hostMacros = [];
while ($result = $statement->fetch(\PDO::FETCH_ASSOC)) {
$hostMacros[] = HostMacroFactoryRdb::create($result);
}
return $hostMacros;
}
/**
* @inheritDoc
*/
public function updateMacro(HostMacro $hostMacro): void
{
Assertion::notNull($hostMacro->getId(), 'HostMacro::id');
Assertion::notNull($hostMacro->getHostId(), 'HostMacro::host_id');
$statement = $this->db->prepare(
$this->translateDbName(
'UPDATE `:db`.on_demand_macro_host
SET host_macro_name = :new_name,
host_macro_value = :new_value,
is_password = :is_password,
description = :new_description,
macro_order = :new_order
WHERE host_macro_id = :id'
)
);
$statement->bindValue(':new_name', $hostMacro->getName());
$statement->bindValue(':new_value', $hostMacro->getValue());
$statement->bindValue(':is_password', $hostMacro->isPassword(), \PDO::PARAM_INT);
$statement->bindValue(':new_description', $hostMacro->getDescription());
$statement->bindValue(':new_order', $hostMacro->getOrder(), \PDO::PARAM_INT);
$statement->bindValue(':id', $hostMacro->getId(), \PDO::PARAM_INT);
$statement->execute();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Infrastructure/HostConfiguration/Repository/HostCategoryRepositoryRDB.php | centreon/src/Centreon/Infrastructure/HostConfiguration/Repository/HostCategoryRepositoryRDB.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\HostConfiguration\Repository;
use Assert\AssertionFailedException;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\HostConfiguration\Host;
use Centreon\Domain\HostConfiguration\Interfaces\HostCategory\HostCategoryReadRepositoryInterface;
use Centreon\Domain\HostConfiguration\Interfaces\HostCategory\HostCategoryWriteRepositoryInterface;
use Centreon\Domain\HostConfiguration\Model\HostCategory;
use Centreon\Domain\RequestParameters\RequestParameters;
use Centreon\Infrastructure\DatabaseConnection;
use Centreon\Infrastructure\HostConfiguration\Repository\Model\HostCategoryFactoryRdb;
use Centreon\Infrastructure\Repository\AbstractRepositoryDRB;
use Centreon\Infrastructure\RequestParameters\SqlRequestParametersTranslator;
/**
* This class is designed to represent the MariaDb repository to manage host category.
*
* @package Centreon\Infrastructure\HostConfiguration\Repository
*/
class HostCategoryRepositoryRDB extends AbstractRepositoryDRB implements
HostCategoryReadRepositoryInterface,
HostCategoryWriteRepositoryInterface
{
/** @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 addCategory(HostCategory $category): void
{
$statement = $this->db->prepare(
$this->translateDbName('
INSERT INTO `:db`.hostcategories (hc_name, hc_alias, level, icon_id, hc_comment, hc_activate)
VALUES (:name, :alias, :level, :icon_id, :comment, :is_activated)
')
);
$statement->bindValue(':name', $category->getName(), \PDO::PARAM_STR);
$statement->bindValue(':alias', $category->getAlias(), \PDO::PARAM_STR);
$statement->bindValue(':comment', $category->getComments(), \PDO::PARAM_STR);
$statement->bindValue(':level', null, \PDO::PARAM_INT);
$statement->bindValue(':icon_id', null, \PDO::PARAM_INT);
$statement->bindValue(':is_activated', $category->isActivated() ? '1' : '0', \PDO::PARAM_STR);
$statement->execute();
$category->setId((int) $this->db->lastInsertId());
}
/**
* @inheritDoc
* @throws AssertionFailedException
*/
public function findById(int $categoryId): ?HostCategory
{
return $this->findByIdRequest($categoryId, null);
}
/**
* @inheritDoc
* @throws AssertionFailedException
*/
public function findByIdAndContact(int $categoryId, ContactInterface $contact): ?HostCategory
{
return $this->findByIdRequest($categoryId, $contact->getId());
}
/**
* @inheritDoc
* @throws AssertionFailedException
*/
public function findByNames(array $categoriesName): array
{
$hostCategories = [];
if (($categoriesName === [])) {
return $hostCategories;
}
$statement = $this->db->prepare(
$this->translateDbName('
SELECT * FROM `:db`.hostcategories
WHERE `hc_name` IN (?' . str_repeat(',?', count($categoriesName) - 1) . ')
')
);
$statement->execute($categoriesName);
while (($result = $statement->fetch(\PDO::FETCH_ASSOC)) !== false) {
$hostCategories[] = HostCategoryFactoryRdb::create($result);
}
return $hostCategories;
}
/**
* Find HostCategories by host id
*
* @param Host $host
* @return HostCategory[]
*/
public function findAllByHost(Host $host): array
{
$request = $this->translateDbName(
'SELECT * FROM `:db`.hostcategories hc
JOIN `:db`.hostcategories_relation hc_rel ON hc.hc_id = hc_rel.hostcategories_hc_id
WHERE hc_rel.host_host_id = :host_id
AND hc.level IS NULL'
);
$statement = $this->db->prepare($request);
$statement->bindValue(':host_id', $host->getId(), \PDO::PARAM_INT);
$statement->execute();
$hostCategories = [];
while (($record = $statement->fetch(\PDO::FETCH_ASSOC)) !== false) {
$hostCategories[] = HostCategoryFactoryRdb::create($record);
}
return $hostCategories;
}
/**
* Find a category by id and contact id.
*
* @param int $categoryId Id of the host category to be found
* @param int|null $contactId Contact id related to host categories
* @throws AssertionFailedException
* @return HostCategory|null
*/
private function findByIdRequest(int $categoryId, ?int $contactId): ?HostCategory
{
if ($contactId === null) {
$statement = $this->db->prepare(
$this->translateDbName('SELECT * FROM `:db`.hostcategories WHERE level IS NULL AND hc_id = :id')
);
} else {
$statement = $this->db->prepare(
$this->translateDbName(
'SELECT hc.*
FROM `:db`.hostcategories hc
INNER JOIN `:db`.acl_resources_hc_relations arhr
ON hc.hc_id = arhr.hc_id
INNER JOIN `:db`.acl_resources res
ON arhr.acl_res_id = res.acl_res_id
INNER JOIN `:db`.acl_res_group_relations argr
ON res.acl_res_id = argr.acl_res_id
INNER JOIN `:db`.acl_groups ag
ON argr.acl_group_id = ag.acl_group_id
LEFT JOIN `:db`.acl_group_contacts_relations agcr
ON ag.acl_group_id = agcr.acl_group_id
LEFT JOIN `:db`.acl_group_contactgroups_relations agcgr
ON ag.acl_group_id = agcgr.acl_group_id
LEFT JOIn `:db`.contactgroup_contact_relation cgcr
ON cgcr.contactgroup_cg_id = agcgr.cg_cg_id
WHERE hc.level IS NULL
AND hc.hc_id = :id
AND (agcr.contact_contact_id = :contact_id OR cgcr.contact_contact_id = :contact_id)'
)
);
$statement->bindValue(':contact_id', $contactId, \PDO::PARAM_INT);
}
$statement->bindValue(':id', $categoryId, \PDO::PARAM_INT);
$statement->execute();
if (($result = $statement->fetch(\PDO::FETCH_ASSOC)) !== false) {
return HostCategoryFactoryRdb::create($result);
}
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/Infrastructure/HostConfiguration/Repository/HostConfigurationRepositoryRDB.php | centreon/src/Centreon/Infrastructure/HostConfiguration/Repository/HostConfigurationRepositoryRDB.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\HostConfiguration\Repository;
use Centreon\Domain\Common\Assertion\Assertion;
use Centreon\Domain\Entity\EntityCreator;
use Centreon\Domain\HostConfiguration\Exception\HostCategoryException;
use Centreon\Domain\HostConfiguration\Exception\HostGroupException;
use Centreon\Domain\HostConfiguration\Exception\HostSeverityException;
use Centreon\Domain\HostConfiguration\ExtendedHost;
use Centreon\Domain\HostConfiguration\Host;
use Centreon\Domain\HostConfiguration\HostMacro;
use Centreon\Domain\HostConfiguration\Interfaces\HostConfigurationRepositoryInterface;
use Centreon\Domain\MonitoringServer\MonitoringServer;
use Centreon\Domain\Repository\RepositoryException;
use Centreon\Domain\RequestParameters\RequestParameters;
use Centreon\Infrastructure\DatabaseConnection;
use Centreon\Infrastructure\Repository\AbstractRepositoryDRB;
use Centreon\Infrastructure\RequestParameters\SqlRequestParametersTranslator;
/**
* This class is designed to represent the MariaDb repository to manage host and host template
*
* @package Centreon\Infrastructure\HostConfiguration
*/
class HostConfigurationRepositoryRDB extends AbstractRepositoryDRB implements HostConfigurationRepositoryInterface
{
/** @var SqlRequestParametersTranslator */
private $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 addHost(Host $host): void
{
$request = $this->translateDbName(
'INSERT INTO `:db`.host
(host_name, host_alias, display_name, host_address, host_comment, geo_coords, host_activate,
host_register, host_active_checks_enabled, host_passive_checks_enabled, host_checks_enabled,
host_obsess_over_host, host_check_freshness, host_event_handler_enabled, host_flap_detection_enabled,
host_process_perf_data, host_retain_status_information, host_retain_nonstatus_information,
host_notifications_enabled)
VALUES (:name, :alias, :display_name, :ip_address, :comment, :geo_coords, :is_activate, :host_register,
:active_check_status, :passive_check_status, :check_status, :obsess_over_status,
:freshness_check_status, :event_handler_status, :flap_detection_status, :process_perf_status,
:retain_status_information, :retain_nonstatus_information, :notifications_status)'
);
$statement = $this->db->prepare($request);
$statement->bindValue(':name', $host->getName(), \PDO::PARAM_STR);
$statement->bindValue(':alias', $host->getAlias(), \PDO::PARAM_STR);
$statement->bindValue(':display_name', $host->getDisplayName(), \PDO::PARAM_STR);
$statement->bindValue(':ip_address', $host->getIpAddress(), \PDO::PARAM_STR);
$statement->bindValue(':comment', $host->getComment(), \PDO::PARAM_STR);
$statement->bindValue(':geo_coords', $host->getGeoCoords(), \PDO::PARAM_STR);
$statement->bindValue(':is_activate', $host->isActivated(), \PDO::PARAM_STR);
$statement->bindValue(':host_register', $host->getType(), \PDO::PARAM_STR);
// We don't have these properties in the host object yet, so we set these default values
$statement->bindValue(':active_check_status', '2', \PDO::PARAM_STR);
$statement->bindValue(':passive_check_status', '2', \PDO::PARAM_STR);
$statement->bindValue(':check_status', '2', \PDO::PARAM_STR);
$statement->bindValue(':obsess_over_status', '2', \PDO::PARAM_STR);
$statement->bindValue(':freshness_check_status', '2', \PDO::PARAM_STR);
$statement->bindValue(':event_handler_status', '2', \PDO::PARAM_STR);
$statement->bindValue(':flap_detection_status', '2', \PDO::PARAM_STR);
$statement->bindValue(':process_perf_status', '2', \PDO::PARAM_STR);
$statement->bindValue(':retain_status_information', '2', \PDO::PARAM_STR);
$statement->bindValue(':retain_nonstatus_information', '2', \PDO::PARAM_STR);
$statement->bindValue(':notifications_status', '2', \PDO::PARAM_STR);
$statement->execute();
$hostId = (int) $this->db->lastInsertId();
$host->setId($hostId);
if ($host->getMonitoringServer() !== null) {
$this->linkMonitoringServerToHost($host, $host->getMonitoringServer());
}
if ($host->getExtendedHost() !== null) {
$this->addExtendedHost($hostId, $host->getExtendedHost());
}
$this->linkHostTemplatesToHost($hostId, $host->getTemplates());
$this->linkHostCategoriesToHost($host);
$this->linkSeverityToHost($host);
$this->linkHostGroupsToHost($host);
}
/**
* Link a monitoring server to a host.
*
* @param Host $host Host for which this monitoring server host will be associated
* @param MonitoringServer $monitoringServer Monitoring server to be added
* @throws RepositoryException
* @throws \Throwable
*/
public function linkMonitoringServerToHost(Host $host, MonitoringServer $monitoringServer): void
{
Assertion::notNull($host->getId());
if ($monitoringServer->getId() !== null) {
$request = $this->translateDbName(
'INSERT INTO `:db`.ns_host_relation
(nagios_server_id, host_host_id)
VALUES (:monitoring_server_id, :host_id)'
);
$statement = $this->db->prepare($request);
$statement->bindValue(':monitoring_server_id', $monitoringServer->getId(), \PDO::PARAM_INT);
$statement->bindValue(':host_id', $host->getId(), \PDO::PARAM_INT);
$statement->execute();
if ($statement->rowCount() === 0) {
throw new RepositoryException(
sprintf(_('Monitoring server with id %d not found'), $monitoringServer->getId())
);
}
} elseif (! empty($monitoringServer->getName())) {
$request = $this->translateDbName(
'INSERT INTO `:db`.ns_host_relation
(nagios_server_id, host_host_id)
SELECT nagios_server.id, :host_id
FROM `:db`.nagios_server
WHERE nagios_server.name = :monitoring_server_name'
);
$statement = $this->db->prepare($request);
$statement->bindValue(':monitoring_server_name', $monitoringServer->getName(), \PDO::PARAM_STR);
$statement->bindValue(':host_id', $host->getId(), \PDO::PARAM_INT);
$statement->execute();
if ($statement->rowCount() === 0) {
throw new RepositoryException(
sprintf(_('Monitoring server %s not found'), $monitoringServer->getName())
);
}
}
}
/**
* @inheritDoc
*/
public function findHostByAccessGroupIds(int $hostId, array $accessGroupIds): ?Host
{
if ($accessGroupIds === []) {
return null;
}
$accessGroupRequest = ' INNER JOIN `:db`.acl_resources_host_relations arhr
ON host.host_id = arhr.host_host_id
INNER JOIN `:db`.acl_resources res
ON arhr.acl_res_id = res.acl_res_id
INNER JOIN `:db`.acl_res_group_relations argr
ON res.acl_res_id = argr.acl_res_id
INNER JOIN `:db`.acl_groups ag
ON ag.acl_group_id IN (' . implode(',', $accessGroupIds) . ') ';
return $this->findHostRequest($hostId, $accessGroupRequest);
}
/**
* @inheritDoc
*/
public function findHost(int $hostId): ?Host
{
return $this->findHostRequest($hostId);
}
/**
* @inheritDoc
*/
public function findHostRequest(int $hostId, ?string $accessGroupRequest = null): ?Host
{
$request = $this->translateDbName(
'SELECT host.host_id, host.host_name, host.host_alias, host.display_name AS host_display_name,
host.host_address AS host_ip_address, host.host_comment, host.geo_coords AS host_geo_coords,
host.host_activate AS host_is_activated, host.host_notifications_enabled, nagios.id AS monitoring_server_id,
nagios.name AS monitoring_server_name, ext.*
FROM `:db`.host host
LEFT JOIN `:db`.extended_host_information ext
ON ext.host_host_id = host.host_id
INNER JOIN `:db`.ns_host_relation host_server
ON host_server.host_host_id = host.host_id
INNER JOIN `:db`.nagios_server nagios
ON nagios.id = host_server.nagios_server_id '
. ($accessGroupRequest ?? '')
. 'WHERE host.host_id = :host_id
AND host.host_register = \'1\''
);
$statement = $this->db->prepare($request);
$statement->bindValue(':host_id', $hostId, \PDO::PARAM_INT);
$statement->execute();
if (($record = $statement->fetch(\PDO::FETCH_ASSOC)) !== false) {
return $this->createHost($record);
}
return null;
}
/**
* @inheritDoc
*/
public function findHostTemplatesRecursively(Host $host): array
{
/*
* CTE recurse request next release:
* WITH RECURSIVE template AS (
* SELECT htr.*, 0 AS level
* FROM `:db`.host_template_relation htr
* WHERE htr.host_host_id = :host_id
* UNION
* SELECT htr2.*, template.level + 1
* FROM `:db`.host_template_relation htr2
* INNER JOIN template
* ON template.host_tpl_id = htr2.host_host_id
* INNER JOIN `:db`.host
* ON host.host_id = htr2.host_tpl_id
* AND host.host_register = 1
* )
* SELECT host_host_id AS template_host_id, host_tpl_id AS template_id, `order` AS template_order,
* `level` AS template_level, host.host_id AS id, host.host_name AS name, host.host_alias AS alias,
* host.host_register AS type, host.host_activate AS is_activated
* FROM template
* INNER JOIN `:db`.host
* ON host.host_id = template.host_tpl_id
* ORDER BY `level`, host_host_id, `order`
*/
$request = $this->translateDbName(
'SELECT
host.host_id AS id,
htr.`order` AS template_order,
host.host_name AS name,
host.host_alias AS alias,
host.host_register AS type,
host.host_activate AS is_activated
FROM `:db`.host_template_relation htr, `:db`.host
WHERE
htr.host_host_id = :host_id AND
htr.host_tpl_id = host.host_id AND
host.host_register = 1
ORDER BY htr.`order` ASC'
);
$statement = $this->db->prepare($request);
$hostTemplates = [];
$stack = [[$host->getId(), 0, null, []]];
while (($hostTest = array_shift($stack))) {
if (isset($hostTest[3][$hostTest[0]])) {
continue;
}
$hostTest[3][$hostTest[0]] = 1;
$statement = $this->db->prepare($request);
$statement->bindValue(':host_id', $hostTest[0], \PDO::PARAM_INT);
$statement->execute();
$hostTpl = [];
$currentLevel = $hostTest[1];
while (($record = $statement->fetch(\PDO::FETCH_ASSOC)) !== false) {
$record['template_host_id'] = $hostTest[0];
$record['template_level'] = $currentLevel;
$hostTemplate = EntityCreator::createEntityByArray(
Host::class,
$record
);
if ($currentLevel === 0) {
$hostTemplates[] = $hostTemplate;
} else {
$hostTest[2]->addTemplate($hostTemplate);
}
$hostTpl[] = [$record['id'], $currentLevel + 1, $hostTemplate, $hostTest[3]];
}
$stack = array_merge($hostTpl, $stack);
}
return $hostTemplates;
}
/**
* @inheritDoc
*/
public function getNumberOfHosts(): int
{
$request = $this->translateDbName('SELECT COUNT(*) AS total FROM `:db`.host WHERE host_register = \'1\'');
$statement = $this->db->query($request);
if ($statement !== false && ($result = $statement->fetchColumn()) !== false) {
return (int) $result;
}
return 0;
}
/**
* @inheritDoc
*/
public function hasHostWithSameName(string $hostName): bool
{
$request = $this->translateDbName('SELECT COUNT(*) FROM `:db`.host WHERE host_name = :host_name');
$statement = $this->db->prepare($request);
$statement->bindValue(':host_name', $hostName, \PDO::FETCH_ASSOC);
$statement->execute();
if (($result = $statement->fetchColumn()) !== false) {
return ((int) $result) > 0;
}
return false;
}
/**
* @inheritDoc
*/
public function findCommandLine(int $hostId): ?string
{
/*
* CTE recurse request next release:
* WITH RECURSIVE inherite AS (
* SELECT relation.host_host_id, relation.host_tpl_id, relation.order, host.command_command_id,
* 0 AS level
* FROM `:db`.host
* LEFT JOIN `:db`.host_template_relation relation
* ON relation.host_host_id = host.host_id
* WHERE host.host_id = :host_id
* UNION ALL
* SELECT relation.host_host_id, relation.host_tpl_id, relation.order, host.command_command_id,
* inherite.level + 1
* FROM `:db`.host
* INNER JOIN inherite
* ON inherite.host_tpl_id = host.host_id
* LEFT JOIN `:db`.host_template_relation relation
* ON relation.host_host_id = host.host_id
* )
* SELECT command.command_line
* FROM inherite
* INNER JOIN `:db`.command
* ON command.command_id = inherite.command_command_id
*/
$request = $this->translateDbName(
'SELECT
command.command_line, relation.templates
FROM `:db`.host
LEFT JOIN `:db`.command ON command.command_id = host.command_command_id,
(SELECT GROUP_CONCAT(host_tpl_id) as templates
FROM `:db`.host_template_relation htr
WHERE htr.host_host_id = :host_id ORDER BY `order` ASC) as relation
WHERE host.host_id = :host_id LIMIT 1'
);
$statement = $this->db->prepare($request);
$loop = [];
$stack = [$hostId];
while (($hostTest = array_shift($stack))) {
if (isset($loop[$hostTest])) {
continue;
}
$loop[$hostTest] = 1;
$statement = $this->db->prepare($request);
$statement->bindValue(':host_id', $hostTest, \PDO::PARAM_INT);
$statement->execute();
$hostTpl = null;
$record = $statement->fetch(\PDO::FETCH_ASSOC);
if (! is_null($record['templates']) && is_null($hostTpl)) {
$hostTpl = explode(',', $record['templates']);
}
if (! is_null($record['command_line'])) {
return (string) $record['command_line'];
}
if (! is_null($hostTpl)) {
$stack = array_merge($hostTpl, $stack);
}
}
return null;
}
/**
* @inheritDoc
*/
public function findOnDemandHostMacros(int $hostId, bool $isUsingInheritance = false): array
{
/*
* CTE recurse request next release:
* WITH RECURSIVE inherite AS (
* SELECT relation.host_host_id, relation.host_tpl_id, relation.order, demand.host_macro_id,
* demand.host_macro_name, 0 AS level
* FROM `:db`.host
* LEFT JOIN `:db`.host_template_relation relation
* ON relation.host_host_id = host.host_id
* LEFT JOIN on_demand_macro_host demand
* ON demand.host_host_id = host.host_id
* WHERE host.host_id = :host_id
* UNION ALL
* SELECT relation.host_host_id, relation.host_tpl_id, relation.order, demand.host_macro_id,
* demand.host_macro_name, inherite.level + 1
* FROM `:db`.host
* INNER JOIN inherite
* ON inherite.host_tpl_id = host.host_id
* LEFT JOIN `:db`.host_template_relation relation
* ON relation.host_host_id = host.host_id
* LEFT JOIN on_demand_macro_host demand
* ON demand.host_host_id = host.host_id
* )
* SELECT macro.host_macro_id AS id, macro.host_macro_name AS name,
* macro.host_macro_value AS `value`, macro.macro_order AS `order`, macro.host_host_id AS host_id,
* CASE
* WHEN is_password IS NULL THEN \'0\'
* ELSE is_password
* END is_password, description
* FROM (
* SELECT * FROM inherite
* WHERE host_macro_id IS NOT NULL
* GROUP BY inherite.level, inherite.order, host_macro_name
* ) AS tpl
* INNER JOIN `:db`.on_demand_macro_host macro
* ON macro.host_macro_id = tpl.host_macro_id
* GROUP BY tpl.host_macro_name
*/
$request = $this->translateDbName(
<<<'SQL'
SELECT
host.host_id,
macro.host_macro_id AS id,
macro.host_macro_name AS name,
macro.host_macro_value AS `value`,
macro.macro_order AS `order`,
macro.is_password,
macro.description,
relation.templates
FROM `:db`.host
LEFT JOIN `:db`.on_demand_macro_host macro
ON macro.host_host_id = host.host_id
JOIN ( SELECT GROUP_CONCAT(host_tpl_id ORDER BY `order` ASC) as templates
FROM `:db`.host_template_relation htr
WHERE htr.host_host_id = :host_id
) as relation
WHERE host.host_id = :host_id
SQL
);
/** @var array<HostMacro> $hostMacros The returned array of {@see HostMacro} */
$hostMacros = [];
/** @var array<string, int> $alreadyAdded Used to avoid returning the same macro from different templates */
$alreadyAdded = [];
/** @var array<int, int> $done Used to avoid inheritance loop hell */
$done = [];
/** @var list<int> $stackOfHostIds The algo is using a FIFO stack for inheritance when needed */
$stackOfHostIds = [$hostId];
while ($currentHostId = array_shift($stackOfHostIds)) {
// We want to avoid redoing the same host/host templates (risky inheritance loops).
if (isset($done[$currentHostId])) {
continue;
}
$done[$currentHostId] = 1;
$statement = $this->db->prepare($request);
$statement->bindValue(':host_id', $currentHostId, \PDO::PARAM_INT);
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$statement->execute();
$hostTemplateIds = null;
foreach ($statement as $record) {
/** @var array{
* host_id: int,
* id: ?int,
* name: ?string,
* value: ?string,
* order: ?int,
* is_password: ?int,
* description: ?string,
* templates: ?string
* } $record
*/
// We need to populate the inherited template IDs only once (same value for all rows, cf. SQL query).
$hostTemplateIds ??= empty($record['templates']) ? null : explode(',', $record['templates']);
// Skip already added macro (check by their name).
if ($record['name'] === null || isset($alreadyAdded[$record['name']])) {
continue;
}
$alreadyAdded[$record['name']] = 1;
// Create and append the object.
$record['is_password'] ??= 0;
$hostMacros[] = EntityCreator::createEntityByArray(HostMacro::class, $record);
}
// Filling the stack is done only for inherited templates when we need it.
if ($isUsingInheritance && \is_array($hostTemplateIds)) {
$stackOfHostIds = array_merge($stackOfHostIds, $hostTemplateIds);
}
}
return $hostMacros;
}
/**
* @inheritDoc
*/
public function changeActivationStatus(int $hostId, bool $shouldBeActivated): void
{
$statement = $this->db->prepare(
$this->translateDbName('UPDATE `:db`.host SET host_activate = :activation_status WHERE host_id = :host_id')
);
$statement->bindValue(':host_id', $hostId, \PDO::PARAM_INT);
$statement->bindValue(':activation_status', $shouldBeActivated ? '1' : '0', \PDO::PARAM_STR);
$statement->execute();
}
/**
* @inheritDoc
*/
public function findHostNamesAlreadyUsed(array $namesToCheck): array
{
if ($namesToCheck === []) {
return [];
}
$names = [];
foreach ($namesToCheck as $name) {
$names[] = (string) $name;
}
$statement = $this->db->prepare(
$this->translateDbName(
sprintf(
'SELECT host_name FROM `:db`.host WHERE host_name IN (%s?)',
str_repeat('?,', count($names) - 1)
)
)
);
$statement->execute($names);
$namesFound = [];
while (($result = $statement->fetch(\PDO::FETCH_ASSOC)) !== false) {
$namesFound[] = $result['host_name'];
}
return $namesFound;
}
/**
* @inheritDoc
*/
public function updateHost(Host $host): void
{
$isAlreadyInTransaction = $this->db->inTransaction();
if (! $isAlreadyInTransaction) {
$this->db->beginTransaction();
}
try {
$request = $this->translateDbName(
'UPDATE `:db`.host SET
host_name = :name, host_alias = :alias, host_address = :ip_address, host_comment = :comment,
geo_coords = :geo_coords, host_activate = :is_activate, host_register = :host_register,
host_active_checks_enabled = :active_check_status,
host_passive_checks_enabled = :passive_check_status, host_checks_enabled = :check_status,
host_obsess_over_host = :obsess_over_status, host_check_freshness = :freshness_check_status,
host_event_handler_enabled = :event_handler_status,
host_flap_detection_enabled = :flap_detection_status, host_process_perf_data = :process_perf_status,
host_retain_status_information = :retain_status_information,
host_retain_nonstatus_information = :retain_nonstatus_information,
host_notifications_enabled = :notifications_status
WHERE host_id = :id'
);
$statement = $this->db->prepare($request);
$statement->bindValue(':id', $host->getId(), \PDO::PARAM_INT);
$statement->bindValue(':name', $host->getName(), \PDO::PARAM_STR);
$statement->bindValue(':alias', $host->getAlias(), \PDO::PARAM_STR);
$statement->bindValue(':ip_address', $host->getIpAddress(), \PDO::PARAM_STR);
$statement->bindValue(':comment', $host->getComment(), \PDO::PARAM_STR);
$statement->bindValue(':geo_coords', $host->getGeoCoords(), \PDO::PARAM_STR);
$statement->bindValue(':is_activate', $host->isActivated() ? '1' : '0', \PDO::PARAM_STR);
$statement->bindValue(':host_register', '1', \PDO::PARAM_STR);
$statement->bindValue(':active_check_status', Host::OPTION_DEFAULT, \PDO::PARAM_STR);
$statement->bindValue(':passive_check_status', Host::OPTION_DEFAULT, \PDO::PARAM_STR);
$statement->bindValue(':check_status', Host::OPTION_DEFAULT, \PDO::PARAM_STR);
$statement->bindValue(':obsess_over_status', Host::OPTION_DEFAULT, \PDO::PARAM_STR);
$statement->bindValue(':freshness_check_status', Host::OPTION_DEFAULT, \PDO::PARAM_STR);
$statement->bindValue(':event_handler_status', Host::OPTION_DEFAULT, \PDO::PARAM_STR);
$statement->bindValue(':flap_detection_status', Host::OPTION_DEFAULT, \PDO::PARAM_STR);
$statement->bindValue(':process_perf_status', Host::OPTION_DEFAULT, \PDO::PARAM_STR);
$statement->bindValue(':retain_status_information', Host::OPTION_DEFAULT, \PDO::PARAM_STR);
$statement->bindValue(':retain_nonstatus_information', Host::OPTION_DEFAULT, \PDO::PARAM_STR);
$statement->bindValue(':notifications_status', Host::OPTION_DEFAULT, \PDO::PARAM_STR);
$statement->execute();
$this->updateMonitoringServerRelation($host->getId(), $host->getMonitoringServer()->getId());
// Update links between host groups and hosts
$this->removeHostGroupsToHost($host);
$this->linkHostGroupsToHost($host);
// Update host templates
$this->removeHostTemplatesFromHost($host);
$this->linkHostTemplatesToHost($host->getId(), $host->getTemplates());
// Update Host Categories
$this->removeHostCategoriesFromHost($host);
$this->linkHostCategoriesToHost($host);
$this->updateHostSeverity($host);
if (! $isAlreadyInTransaction) {
$this->db->commit();
}
} catch (\Throwable $ex) {
if (! $isAlreadyInTransaction) {
$this->db->rollBack();
}
throw $ex;
}
}
/**
* @inheritDoc
*/
public function findHostTemplatesByHost(Host $host): array
{
$request = $this->translateDbName(
'SELECT
host.host_id AS id,
htr.`order` AS template_order,
host.host_name AS name,
host.host_alias AS alias,
host.host_register AS type,
host.host_activate AS is_activated
FROM `:db`.host_template_relation htr, `:db`.host
WHERE
htr.host_host_id = :host_id AND
htr.host_tpl_id = host.host_id AND
host.host_register = 1
ORDER BY htr.`order` ASC'
);
$statement = $this->db->prepare($request);
$statement->bindValue(':host_id', $host->getId(), \PDO::PARAM_INT);
$statement->execute();
$hostTemplates = [];
if ($statement !== false) {
while (($result = $statement->fetch(\PDO::FETCH_ASSOC)) !== false) {
$hostTemplates[] = EntityCreator::createEntityByArray(
Host::class,
$result
);
}
}
return $hostTemplates;
}
/**
* @inheritDoc
*/
public function findHostByName(string $hostName): ?Host
{
$request = $this->translateDbName(
'SELECT host.host_id, host.host_name, host.host_alias, host.display_name AS host_display_name,
host.host_address AS host_ip_address, host.host_comment, host.geo_coords AS host_geo_coords,
host.host_activate AS host_is_activated, nagios.id AS monitoring_server_id,
nagios.name AS monitoring_server_name, ext.*
FROM `:db`.host host
LEFT JOIN `:db`.extended_host_information ext
ON ext.host_host_id = host.host_id
INNER JOIN `:db`.ns_host_relation host_server
ON host_server.host_host_id = host.host_id
INNER JOIN `:db`.nagios_server nagios
ON nagios.id = host_server.nagios_server_id
WHERE host.host_name = :host_name
AND host.host_register = \'1\''
);
$statement = $this->db->prepare($request);
$statement->bindValue(':host_name', $hostName, \PDO::PARAM_STR);
$statement->execute();
if (($record = $statement->fetch(\PDO::FETCH_ASSOC)) !== false) {
return $this->createHost($record);
}
return null;
}
/**
* {@inheritDoc}
*/
public function findHostTemplate(int $hostTemplateId): ?Host
{
$request = $this->translateDbName(
'SELECT
host.host_id AS id,
host.host_name AS name,
host.host_alias AS alias,
host.host_register AS type,
host.host_activate AS is_activated
FROM `:db`.host
WHERE
host.host_id = :host_id AND
host.host_register = \'0\''
);
$statement = $this->db->prepare($request);
$statement->bindValue(':host_id', $hostTemplateId, \PDO::PARAM_INT);
$statement->execute();
if (($record = $statement->fetch(\PDO::FETCH_ASSOC)) !== false) {
return EntityCreator::createEntityByArray(
Host::class,
$record
);
}
return null;
}
/**
* Add extended host information.
*
* @param int $hostId Host id for which this extended host will be associated
* @param ExtendedHost $extendedHost Extended host to be added
* @throws \Exception
*/
private function addExtendedHost(int $hostId, ExtendedHost $extendedHost): void
{
$request = $this->translateDbName(
'INSERT INTO `:db`.extended_host_information
(host_host_id, ehi_notes, ehi_notes_url, ehi_action_url)
VALUES (:host_id, :notes, :url, :action_url)'
);
$statement = $this->db->prepare($request);
$statement->bindValue(':host_id', $hostId, \PDO::PARAM_INT);
$statement->bindValue(':notes', $extendedHost->getNotes(), \PDO::PARAM_STR);
$statement->bindValue(':url', $extendedHost->getNotesUrl(), \PDO::PARAM_STR);
$statement->bindValue(':action_url', $extendedHost->getActionUrl(), \PDO::PARAM_STR);
$statement->execute();
}
/**
* Link a host to a given list of host templates.
*
* @param int $hostId Host id for which this templates will be associated
* @param Host[] $hostTemplates Host template to be added
* @throws RepositoryException
* @throws \Exception
*/
private function linkHostTemplatesToHost(int $hostId, array $hostTemplates): void
{
if ($hostTemplates === []) {
return;
}
foreach ($hostTemplates as $order => $template) {
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | true |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Infrastructure/HostConfiguration/Repository/HostSeverityRepositoryRDB.php | centreon/src/Centreon/Infrastructure/HostConfiguration/Repository/HostSeverityRepositoryRDB.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\HostConfiguration\Repository;
use Assert\AssertionFailedException;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\HostConfiguration\Host;
use Centreon\Domain\HostConfiguration\Interfaces\HostSeverity\HostSeverityReadRepositoryInterface;
use Centreon\Domain\HostConfiguration\Model\HostSeverity;
use Centreon\Domain\Repository\RepositoryException;
use Centreon\Domain\RequestParameters\RequestParameters;
use Centreon\Infrastructure\DatabaseConnection;
use Centreon\Infrastructure\HostConfiguration\Repository\Model\HostSeverityFactoryRdb;
use Centreon\Infrastructure\Repository\AbstractRepositoryDRB;
use Centreon\Infrastructure\RequestParameters\SqlRequestParametersTranslator;
/**
* This class is designed to represent the MariaDb repository to manage host severity.
*
* @package Centreon\Infrastructure\HostConfiguration\Repository
*/
class HostSeverityRepositoryRDB extends AbstractRepositoryDRB implements HostSeverityReadRepositoryInterface
{
/** @var SqlRequestParametersTranslator */
private $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 findById(int $hostSeverityId): ?HostSeverity
{
try {
return $this->findByIdRequest($hostSeverityId, null);
} catch (AssertionFailedException $ex) {
throw new RepositoryException($ex->getMessage(), 0, $ex);
}
}
/**
* @inheritDoc
*/
public function findByIdAndContact(int $hostSeverityId, ContactInterface $contact): ?HostSeverity
{
try {
return $this->findByIdRequest($hostSeverityId, $contact->getId());
} catch (AssertionFailedException $ex) {
throw new RepositoryException($ex->getMessage(), 0, $ex);
}
}
/**
* @inheritDoc
*/
public function findByHost(Host $host): ?HostSeverity
{
$statement = $this->db->prepare(
$this->translateDbName(
'SELECT hc.*, icon.img_id AS img_id, icon.img_name AS img_name,
CONCAT(iconD.dir_name,\'/\',icon.img_path) AS img_path, icon.img_comment AS img_comment
FROM `:db`.hostcategories hc
LEFT JOIN `:db`.view_img icon
ON icon.img_id = hc.icon_id
LEFT JOIN `:db`.view_img_dir_relation iconR
ON iconR.img_img_id = icon.img_id
LEFT JOIN `:db`.view_img_dir iconD
ON iconD.dir_id = iconR.dir_dir_parent_id
INNER JOIN `:db`.hostcategories_relation hc_rel
ON hc.hc_id = hc_rel.hostcategories_hc_id
WHERE hc.level IS NOT NULL
AND hc_rel.host_host_id = :host_id'
)
);
$statement->bindValue(':host_id', $host->getId(), \PDO::PARAM_INT);
$statement->execute();
if (($result = $statement->fetch(\PDO::FETCH_ASSOC)) !== false) {
return HostSeverityFactoryRdb::create($result);
}
return null;
}
/**
* Find a severity by id and contact id.
*
* @param int $hostSeverityId Id of the host severity to be found
* @param int|null $contactId Contact id related to host severity
* @throws AssertionFailedException
* @return HostSeverity|null
*/
private function findByIdRequest(int $hostSeverityId, ?int $contactId): ?HostSeverity
{
if ($contactId === null) {
$statement = $this->db->prepare(
$this->translateDbName(
'SELECT hc.*, icon.img_id AS img_id, icon.img_name AS img_name,
CONCAT(iconD.dir_name,\'/\',icon.img_path) AS img_path, icon.img_comment AS img_comment
FROM `:db`.hostcategories hc
LEFT JOIN `:db`.view_img icon
ON icon.img_id = hc.icon_id
LEFT JOIN `:db`.view_img_dir_relation iconR
ON iconR.img_img_id = icon.img_id
LEFT JOIN `:db`.view_img_dir iconD
ON iconD.dir_id = iconR.dir_dir_parent_id
WHERE hc_id = :id AND hc.level IS NOT NULL'
)
);
} else {
$statement = $this->db->prepare(
$this->translateDbName(
'SELECT hc.*, icon.img_id AS img_id, icon.img_name AS img_name,
CONCAT(iconD.dir_name,\'/\',icon.img_path) AS img_path, icon.img_comment AS img_comment
FROM `:db`.hostcategories hc
LEFT JOIN `:db`.view_img icon
ON icon.img_id = hc.icon_id
LEFT JOIN `:db`.view_img_dir_relation iconR
ON iconR.img_img_id = icon.img_id
LEFT JOIN `:db`.view_img_dir iconD
ON iconD.dir_id = iconR.dir_dir_parent_id
INNER JOIN `:db`.acl_resources_hc_relations arhr
ON hc.hc_id = arhr.hc_id
INNER JOIN `:db`.acl_resources res
ON arhr.acl_res_id = res.acl_res_id
INNER JOIN `:db`.acl_res_group_relations argr
ON res.acl_res_id = argr.acl_res_id
INNER JOIN `:db`.acl_groups ag
ON argr.acl_group_id = ag.acl_group_id
LEFT JOIN `:db`.acl_group_contacts_relations agcr
ON ag.acl_group_id = agcr.acl_group_id
LEFT JOIN `:db`.acl_group_contactgroups_relations agcgr
ON ag.acl_group_id = agcgr.acl_group_id
LEFT JOIn `:db`.contactgroup_contact_relation cgcr
ON cgcr.contactgroup_cg_id = agcgr.cg_cg_id
WHERE hc.hc_id = :id AND hc.level IS NOT NULL
AND (agcr.contact_contact_id = :contact_id OR cgcr.contact_contact_id = :contact_id)'
)
);
$statement->bindValue(':contact_id', $contactId, \PDO::PARAM_INT);
}
$statement->bindValue(':id', $hostSeverityId, \PDO::PARAM_INT);
$statement->execute();
if (($result = $statement->fetch(\PDO::FETCH_ASSOC)) !== false) {
return HostSeverityFactoryRdb::create($result);
}
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/Infrastructure/HostConfiguration/Repository/Model/HostGroupFactoryRdb.php | centreon/src/Centreon/Infrastructure/HostConfiguration/Repository/Model/HostGroupFactoryRdb.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\HostConfiguration\Repository\Model;
use Centreon\Domain\HostConfiguration\Model\HostGroup;
use Centreon\Domain\Media\Model\Image;
/**
* This class is designed to provide a way to create the HostGroup entity from the database.
*
* @package Centreon\Infrastructure\HostConfiguration\Repository\Model
*/
class HostGroupFactoryRdb
{
/**
* Create a HostGroup entity from database data.
*
* @param array<string, mixed> $data
* @throws \Assert\AssertionFailedException
* @return HostGroup
*/
public static function create(array $data): HostGroup
{
$hostGroup = new HostGroup($data['hg_name']);
if (isset($data['hg_icon_image'])) {
$hostGroup->setIcon(
(new Image())
->setId((int) $data['icon_id'])
->setName($data['icon_name'])
->setComment($data['icon_comment'])
->setPath(str_replace('//', '/', ($data['icon_path'])))
);
}
$hostGroup
->setId((int) $data['hg_id'])
->setAlias($data['hg_alias'])
->setGeoCoords($data['geo_coords'])
->setComment($data['hg_comment'])
->setActivated((bool) $data['hg_activate']);
return $hostGroup;
}
}
| 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/HostConfiguration/Repository/Model/HostCategoryFactoryRdb.php | centreon/src/Centreon/Infrastructure/HostConfiguration/Repository/Model/HostCategoryFactoryRdb.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\HostConfiguration\Repository\Model;
use Centreon\Domain\HostConfiguration\Model\HostCategory;
/**
* This class is designed to provide a way to create the HostCategory entity from the database.
*
* @package Centreon\Infrastructure\HostConfiguration\Repository\Model
*/
class HostCategoryFactoryRdb
{
/**
* Create a HostCategory entity from database data.
*
* @param array<string, mixed> $data
* @throws \Assert\AssertionFailedException
* @return HostCategory
*/
public static function create(array $data): HostCategory
{
$hostCategory = (new HostCategory($data['hc_name'], $data['hc_alias']))
->setId((int) $data['hc_id'])
->setActivated($data['hc_activate'] === '1');
if ($data['hc_comment'] !== null) {
$hostCategory->setComments($data['hc_comment']);
}
return $hostCategory;
}
}
| 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/HostConfiguration/Repository/Model/HostMacroFactoryRdb.php | centreon/src/Centreon/Infrastructure/HostConfiguration/Repository/Model/HostMacroFactoryRdb.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\HostConfiguration\Repository\Model;
use Centreon\Domain\HostConfiguration\HostMacro;
/**
* This class is designed to provide a way to create the HostMacro entity from the database.
*/
class HostMacroFactoryRdb
{
/**
* Create a HostMacro entity from database data.
*
* @param array<string, mixed> $data
* @return HostMacro
*/
public static function create(array $data): HostMacro
{
return (new HostMacro())
->setId((int) $data['host_macro_id'])
->setName($data['host_macro_name'])
->setValue($data['host_macro_value'])
->setDescription($data['description'])
->setOrder((int) $data['macro_order'])
->setHostId((int) $data['host_host_id'])
->setPassword($data['is_password'] === 1);
}
}
| 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/HostConfiguration/Repository/Model/HostTemplateFactoryRdb.php | centreon/src/Centreon/Infrastructure/HostConfiguration/Repository/Model/HostTemplateFactoryRdb.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\HostConfiguration\Repository\Model;
use Centreon\Domain\HostConfiguration\Exception\HostTemplateFactoryException;
use Centreon\Domain\HostConfiguration\Model\HostTemplate;
use Centreon\Domain\Media\Model\Image;
/**
* This class is designed to provide a way to create the HostTemplate entity from the database.
*
* @package Centreon\Infrastructure\HostConfiguration\Model
*/
class HostTemplateFactoryRdb
{
/**
* Create a HostTemplate entity from database data.
*
* @param array<string, mixed> $data
* @throws HostTemplateFactoryException|\Assert\AssertionFailedException
* @return HostTemplate
* @throw \InvalidArgumentException
*/
public static function create(array $data): HostTemplate
{
$hostTemplate = new HostTemplate();
if (isset($data['icon_id'])) {
$hostTemplate->setIcon(
(new Image())
->setId((int) $data['icon_id'])
->setName($data['icon_name'])
->setComment($data['icon_comment'])
->setPath(str_replace('//', '/', ($data['icon_path'])))
);
}
if (isset($data['smi_id'])) {
$hostTemplate->setStatusMapImage(
(new Image())
->setId((int) $data['smi_id'])
->setName($data['smi_name'])
->setComment($data['smi_comment'])
->setPath(str_replace('//', '/', $data['smi_path']))
);
}
$hostTemplate
->setId((int) $data['host_id'])
->setName($data['host_name'])
->setAlias($data['host_alias'])
->setDisplayName($data['display_name'])
->setAddress($data['host_address'])
->setLocked((bool) $data['host_locked'])
->setActivated((bool) $data['host_activate'])
->setComment($data['host_comment'])
->setActionUrl($data['ehi_action_url'])
->setNotes($data['ehi_notes'])
->setUrlNotes($data['ehi_notes_url'])
->setActionUrl($data['ehi_action_url'])
->setActiveChecksStatus((int) $data['host_active_checks_enabled'])
->setPassiveChecksStatus((int) $data['host_passive_checks_enabled'])
->setFirstNotificationDelay(self::getIntOrNull($data['host_first_notification_delay']))
->setRecoveryNotificationDelay(self::getIntOrNull($data['host_recovery_notification_delay']))
->setMaxCheckAttempts(self::getIntOrNull($data['host_max_check_attempts']))
->setCheckInterval(self::getIntOrNull($data['host_check_interval']))
->setRetryCheckInterval(self::getIntOrNull($data['host_retry_check_interval']))
->setNotificationOptions(self::convertNotificationOptions($data['host_notification_options']))
->setNotificationInterval(self::getIntOrNull($data['host_notification_interval']))
->setStalkingOptions(self::convertStalkingOptions($data['host_stalking_options']))
->setSnmpCommunity($data['host_snmp_community'])
->setSnmpVersion($data['host_snmp_version'])
->setComment($data['host_comment']);
if (! empty($data['parents'])) {
$hostTemplate->setParentIds(explode(',', $data['parents']));
}
return $hostTemplate;
}
/**
* @param int|string|null $property
* @return int|null
*/
private static function getIntOrNull($property): ?int
{
return ($property !== null) ? (int) $property : null;
}
/**
* Convert the notification options from string to integer.
*
* HostTemplate::NOTIFICATION_OPTION_DOWN => d<br>
* HostTemplate::NOTIFICATION_OPTION_UNREACHABLE => u<br>
* HostTemplate::NOTIFICATION_OPTION_RECOVERY => r<br>
* HostTemplate::NOTIFICATION_OPTION_FLAPPING => f<br>
* HostTemplate::NOTIFICATION_OPTION_DOWNTIME_SCHEDULED => s<br>
* HostTemplate::NOTIFICATION_OPTION_NONE => n
*
* @param string|null $options
* @throws HostTemplateFactoryException
* @return int
*/
private static function convertNotificationOptions(?string $options): int
{
if (empty($options)) {
// The null value corresponds to all options
return HostTemplate::NOTIFICATION_OPTION_DOWN
| HostTemplate::NOTIFICATION_OPTION_UNREACHABLE
| HostTemplate::NOTIFICATION_OPTION_RECOVERY
| HostTemplate::NOTIFICATION_OPTION_FLAPPING
| HostTemplate::NOTIFICATION_OPTION_DOWNTIME_SCHEDULED;
}
$optionToDefine = 0;
$optionsTags = explode(',', $options);
$optionsNotAllowed = array_diff($optionsTags, ['d', 'u', 'r', 'f', 's', 'n']);
if ($optionsNotAllowed !== []) {
throw HostTemplateFactoryException::notificationOptionsNotAllowed(implode(',', $optionsNotAllowed));
}
if (in_array('n', $optionsTags)) {
$optionToDefine = 0;
} else {
if (in_array('d', $optionsTags)) {
$optionToDefine |= HostTemplate::NOTIFICATION_OPTION_DOWN;
}
if (in_array('u', $optionsTags)) {
$optionToDefine |= HostTemplate::NOTIFICATION_OPTION_UNREACHABLE;
}
if (in_array('r', $optionsTags)) {
$optionToDefine |= HostTemplate::NOTIFICATION_OPTION_RECOVERY;
}
if (in_array('f', $optionsTags)) {
$optionToDefine |= HostTemplate::NOTIFICATION_OPTION_FLAPPING;
}
if (in_array('s', $optionsTags)) {
$optionToDefine |= HostTemplate::NOTIFICATION_OPTION_DOWNTIME_SCHEDULED;
}
}
return $optionToDefine;
}
/**
* Converts the stalking options from string to integer.
*
* HostTemplate::STALKING_OPTION_UP => o<br>
* HostTemplate::STALKING_OPTION_DOWN => d<br>
* HostTemplate::STALKING_OPTION_UNREACHABLE => u
*
* @param string|null $options
* @throws HostTemplateFactoryException
* @return int
*/
private static function convertStalkingOptions(?string $options): int
{
if (empty($options)) {
return 0;
}
$optionToDefine = 0;
$optionsTags = explode(',', $options);
$optionsNotAllowed = array_diff($optionsTags, ['o', 'd', 'u']);
if ($optionsNotAllowed !== []) {
throw HostTemplateFactoryException::stalkingOptionsNotAllowed(implode(',', $optionsNotAllowed));
}
if (in_array('o', $optionsTags)) {
$optionToDefine |= HostTemplate::STALKING_OPTION_UP;
}
if (in_array('d', $optionsTags)) {
$optionToDefine |= HostTemplate::STALKING_OPTION_DOWN;
}
if (in_array('u', $optionsTags)) {
$optionToDefine |= HostTemplate::STALKING_OPTION_UNREACHABLE;
}
return $optionToDefine;
}
}
| 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/HostConfiguration/Repository/Model/HostSeverityFactoryRdb.php | centreon/src/Centreon/Infrastructure/HostConfiguration/Repository/Model/HostSeverityFactoryRdb.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\HostConfiguration\Repository\Model;
use Centreon\Domain\HostConfiguration\Model\HostSeverity;
use Centreon\Domain\Media\Model\Image;
/**
* This class is designed to provide a way to create the HostSeverity entity from the database.
*
* @package Centreon\Infrastructure\HostConfiguration\Repository\Model
*/
class HostSeverityFactoryRdb
{
/**
* Create a HostSeverity entity from database data.
*
* @param array<string, mixed> $data
* @throws \Assert\AssertionFailedException
* @return HostSeverity
*/
public static function create(array $data): HostSeverity
{
$icon = (new Image())
->setId((int) $data['img_id'])
->setName($data['img_name'])
->setComment($data['img_comment'])
->setPath(str_replace('//', '/', ($data['img_path'])));
$hostSeverity = (new HostSeverity($data['hc_name'], $data['hc_alias'], (int) $data['level'], $icon))
->setId((int) $data['hc_id'])
->setActivated($data['hc_activate'] === '1');
if ($data['hc_comment'] !== null) {
$hostSeverity->setComments($data['hc_comment']);
}
return $hostSeverity;
}
}
| 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/MonitoringServer/MonitoringServerRepositoryRDB.php | centreon/src/Centreon/Infrastructure/MonitoringServer/MonitoringServerRepositoryRDB.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\MonitoringServer;
use Centreon\Domain\Entity\EntityCreator;
use Centreon\Domain\MonitoringServer\Interfaces\MonitoringServerRepositoryInterface;
use Centreon\Domain\MonitoringServer\MonitoringServer;
use Centreon\Domain\MonitoringServer\MonitoringServerResource;
use Centreon\Domain\RequestParameters\RequestParameters;
use Centreon\Infrastructure\DatabaseConnection;
use Centreon\Infrastructure\Repository\AbstractRepositoryDRB;
use Centreon\Infrastructure\RequestParameters\SqlRequestParametersTranslator;
use Core\Common\Infrastructure\Repository\SqlMultipleBindTrait;
use Core\MonitoringServer\Infrastructure\Repository\MonitoringServerRepositoryTrait;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
/**
* This class is designed to manage the repository of the monitoring servers
*
* @package Centreon\Infrastructure\MonitoringServer
*/
class MonitoringServerRepositoryRDB extends AbstractRepositoryDRB implements MonitoringServerRepositoryInterface
{
use MonitoringServerRepositoryTrait;
use SqlMultipleBindTrait;
/** @var SqlRequestParametersTranslator */
private $sqlRequestTranslator;
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* Initialized by the dependency injector.
*
* @param SqlRequestParametersTranslator $sqlRequestTranslator
*/
public function setSqlRequestTranslator(SqlRequestParametersTranslator $sqlRequestTranslator): void
{
$this->sqlRequestTranslator = $sqlRequestTranslator;
$this->sqlRequestTranslator
->getRequestParameters()
->setConcordanceStrictMode(
RequestParameters::CONCORDANCE_MODE_STRICT
);
}
/**
* @inheritDoc
*/
public function findLocalServer(): ?MonitoringServer
{
$request = $this->translateDbName(
'SELECT * FROM `:db`.nagios_server WHERE localhost = \'1\' AND ns_activate = \'1\''
);
$statement = $this->db->query($request);
if ($statement !== false && ($result = $statement->fetch(\PDO::FETCH_ASSOC)) !== false) {
/**
* @var MonitoringServer $server
*/
$server = EntityCreator::createEntityByArray(
MonitoringServer::class,
$result
);
if ((int) $result['last_restart'] === 0) {
$server->setLastRestart(null);
}
return $server;
}
return null;
}
/**
* @inheritDoc
*/
public function findServersWithRequestParameters(): array
{
$this->sqlRequestTranslator->setConcordanceArray([
'id' => 'id',
'name' => 'name',
'is_localhost' => 'localhost',
'address' => 'ns_ip_address',
'is_activate' => 'ns_activate',
]);
// Search
$searchRequest = $this->sqlRequestTranslator->translateSearchParameterToSql();
// Sort
$sortRequest = $this->sqlRequestTranslator->translateSortParameterToSql();
// Pagination
$paginationRequest = $this->sqlRequestTranslator->translatePaginationToSql();
return $this->findServers($searchRequest, $sortRequest, $paginationRequest);
}
/**
* @inheritDoc
*/
public function findServersWithRequestParametersAndAccessGroups(array $accessGroups): array
{
$this->sqlRequestTranslator->setConcordanceArray([
'id' => 'id',
'name' => 'name',
'is_localhost' => 'localhost',
'address' => 'ns_ip_address',
'is_activate' => 'ns_activate',
]);
// Search
$searchRequest = $this->sqlRequestTranslator->translateSearchParameterToSql();
// Sort
$sortRequest = $this->sqlRequestTranslator->translateSortParameterToSql();
// Pagination
$paginationRequest = $this->sqlRequestTranslator->translatePaginationToSql();
return $this->findServers($searchRequest, $sortRequest, $paginationRequest, $accessGroups);
}
/**
* @inheritDoc
*/
public function findAllServersWithAccessGroups(array $accessGroups): array
{
return $this->findServers(searchRequest: null, sortRequest: null, paginationRequest: null, accessGroups: $accessGroups);
}
/**
* @inheritDoc
*/
public function findServersWithoutRequestParameters(): array
{
return $this->findServers(null, null, null);
}
/**
* @inheritDoc
*/
public function findServer(int $monitoringServerId): ?MonitoringServer
{
$request = $this->translateDbName('SELECT * FROM `:db`.nagios_server WHERE id = :server_id');
$statement = $this->db->prepare($request);
$statement->bindValue(':server_id', $monitoringServerId, \PDO::PARAM_INT);
$statement->execute();
if (($record = $statement->fetch(\PDO::FETCH_ASSOC)) !== false) {
/**
* @var MonitoringServer $server
*/
$server = EntityCreator::createEntityByArray(
MonitoringServer::class,
$record
);
if ((int) $record['last_restart'] === 0) {
$server->setLastRestart(null);
}
return $server;
}
return null;
}
/**
* @inheritDoc
*/
public function findByIdAndAccessGroups(int $monitoringServerId, array $accessGroups): ?MonitoringServer
{
if ($accessGroups === []) {
return null;
}
$accessGroupIds = array_map(
fn ($accessGroup) => $accessGroup->getId(),
$accessGroups
);
if (! $this->hasRestrictedAccessToMonitoringServers($accessGroupIds)) {
return $this->findServer($monitoringServerId);
}
[$bindValues, $bindQuery] = $this->createMultipleBindQuery($accessGroupIds, ':acl_group_id_');
$request = $this->translateDbName(
<<<SQL
SELECT * FROM `:db`.nagios_server
INNER JOIN `:db`.acl_resources_poller_relations arpr
ON arpr.poller_id = id
INNER JOIN `:db`.acl_resources res
ON res.acl_res_id = arpr.acl_res_id
INNER JOIN `:db`.acl_res_group_relations argr
ON argr.acl_res_id = res.acl_res_id
WHERE argr.acl_group_id IN ({$bindQuery})
AND id = :server_id
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':server_id', $monitoringServerId, \PDO::PARAM_INT);
foreach ($bindValues as $bindParam => $bindValue) {
$statement->bindValue($bindParam, $bindValue, \PDO::PARAM_INT);
}
$statement->execute();
if (($record = $statement->fetch(\PDO::FETCH_ASSOC)) !== false) {
/** @var MonitoringServer $server */
$server = EntityCreator::createEntityByArray(
MonitoringServer::class,
$record
);
if ((int) $record['last_restart'] === 0) {
$server->setLastRestart(null);
}
return $server;
}
return null;
}
/**
* @inheritDoc
*/
public function findServerByName(string $monitoringServerName): ?MonitoringServer
{
$request = $this->translateDbName('SELECT * FROM `:db`.nagios_server WHERE name = :server_name');
$statement = $this->db->prepare($request);
$statement->bindValue(':server_name', $monitoringServerName, \PDO::PARAM_STR);
$statement->execute();
if (($record = $statement->fetch(\PDO::FETCH_ASSOC)) !== false) {
/**
* @var MonitoringServer $server
*/
$server = EntityCreator::createEntityByArray(
MonitoringServer::class,
$record
);
if ((int) $record['last_restart'] === 0) {
$server->setLastRestart(null);
}
return $server;
}
return null;
}
/**
* @inheritDoc
*/
public function findResource(int $monitoringServerId, string $resourceName): ?MonitoringServerResource
{
$request = $this->translateDbName(
'SELECT resource.* FROM `:db`.cfg_resource resource
INNER JOIN `:db`.cfg_resource_instance_relations rel
ON rel.resource_id = resource.resource_id
WHERE rel.instance_id = :monitoring_server_id
AND resource.resource_name = :resource_name'
);
$statement = $this->db->prepare($request);
$statement->bindValue(':monitoring_server_id', $monitoringServerId, \PDO::PARAM_INT);
$statement->bindValue(':resource_name', $resourceName, \PDO::PARAM_STR);
$statement->execute();
if (($record = $statement->fetch(\PDO::FETCH_ASSOC)) !== false) {
return (new MonitoringServerResource())
->setId((int) $record['resource_id'])
->setName($record['resource_name'])
->setComment($record['resource_comment'])
->setIsActivate($record['resource_activate'] === '1')
->setPath($record['resource_line']);
}
return null;
}
/**
* @inheritDoc
*/
public function notifyConfigurationChanged(MonitoringServer $monitoringServer): void
{
if ($monitoringServer->getId() !== null) {
$request = $this->translateDbName(
'UPDATE `:db`.nagios_server SET updated = "1" WHERE id = :server_id'
);
$statement = $this->db->prepare($request);
$statement->bindValue(':server_id', $monitoringServer->getId(), \PDO::PARAM_INT);
$statement->execute();
} elseif ($monitoringServer->getName() !== null) {
$request = $this->translateDbName(
'UPDATE `:db`.nagios_server SET updated = "1" WHERE name = :server_name'
);
$statement = $this->db->prepare($request);
$statement->bindValue(':server_name', $monitoringServer->getName(), \PDO::PARAM_STR);
$statement->execute();
}
}
/**
* @inheritDoc
*/
public function deleteServer(int $monitoringServerId): void
{
$statement = $this->db->prepare($this->translateDbName('DELETE FROM `:db`.nagios_server WHERE id = :id'));
$statement->bindValue(':id', $monitoringServerId, \PDO::PARAM_INT);
$statement->execute();
}
/**
* @inheritDoc
*/
public function findRemoteServersIps(): array
{
$request = $this->translateDbName('SELECT ip FROM remote_servers');
$statement = $this->db->query($request);
$statement->execute();
if ($statement !== false) {
return $statement->fetchAll(\PDO::FETCH_COLUMN);
}
return [];
}
/**
* Find servers.
*
* @param string|null $searchRequest Search request
* @param string|null $sortRequest Sort request
* @param string|null $paginationRequest Pagination request
* @param AccessGroup[] $accessGroups
*
* @throws \Exception
*
* @return MonitoringServer[]
*/
private function findServers(
?string $searchRequest,
?string $sortRequest,
?string $paginationRequest,
array $accessGroups = [],
): array {
$aclMonitoringServersRequest = '';
$searchRequest ??= '';
$sortRequest ??= ' ORDER BY id DESC';
$paginationRequest ??= '';
$bindValues = [];
if ($accessGroups !== []) {
$accessGroupIds = array_map(
fn ($accessGroup) => $accessGroup->getId(),
$accessGroups
);
if ($this->hasRestrictedAccessToMonitoringServers($accessGroupIds)) {
[$bindValues, $bindQuery] = $this->createMultipleBindQuery($accessGroupIds, ':acl_group_id_');
$aclMonitoringServersRequest = <<<SQL
INNER JOIN `:db`.acl_resources_poller_relations arpr
ON arpr.poller_id = id
INNER JOIN `:db`.acl_resources res
ON res.acl_res_id = arpr.acl_res_id
INNER JOIN `:db`.acl_res_group_relations argr
ON argr.acl_res_id = res.acl_res_id
WHERE argr.acl_group_id IN ({$bindQuery})
SQL;
$searchRequest = str_replace('WHERE', 'AND', $searchRequest);
}
}
$request = $this->translateDbName(
<<<SQL
SELECT SQL_CALC_FOUND_ROWS * FROM `:db`.nagios_server
{$aclMonitoringServersRequest}
{$searchRequest}
{$sortRequest}
{$paginationRequest}
SQL
);
$statement = $this->db->prepare($request);
foreach ($this->sqlRequestTranslator->getSearchValues() as $key => $data) {
$type = key($data);
$value = $data[$type];
$statement->bindValue($key, $value, $type);
}
foreach ($bindValues as $bindParam => $bindValue) {
$statement->bindValue($bindParam, $bindValue, \PDO::PARAM_INT);
}
$statement->execute();
$result = $this->db->query('SELECT FOUND_ROWS()');
if ($result !== false && ($total = $result->fetchColumn()) !== false) {
$this->sqlRequestTranslator->getRequestParameters()->setTotal((int) $total);
}
$servers = [];
while (false !== ($result = $statement->fetch(\PDO::FETCH_ASSOC))) {
/**
* @var MonitoringServer $server
*/
$server = EntityCreator::createEntityByArray(
MonitoringServer::class,
$result
);
if ((int) $result['last_restart'] === 0) {
$server->setLastRestart(null);
}
$servers[] = $server;
}
return $servers;
}
}
| 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/MonitoringServer/Repository/MonitoringServerConfigurationRepositoryApi.php | centreon/src/Centreon/Infrastructure/MonitoringServer/Repository/MonitoringServerConfigurationRepositoryApi.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\MonitoringServer\Repository;
use Centreon\Domain\Authentication\Exception\AuthenticationException;
use Centreon\Domain\Common\Assertion\Assertion;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Exception\TimeoutException;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\MonitoringServer\Interfaces\MonitoringServerConfigurationRepositoryInterface;
use Centreon\Domain\Repository\RepositoryException;
use Centreon\Infrastructure\MonitoringServer\Repository\Exception\MonitoringServerConfigurationRepositoryException;
use DateTime;
use Security\Domain\Authentication\Interfaces\AuthenticationTokenServiceInterface;
use Symfony\Component\HttpClient\Exception\TransportException;
use Symfony\Contracts\HttpClient\HttpClientInterface;
/**
* This class is designed to represent the API repository to manage the generation/move/reload of the monitoring
* server configuration.
*/
class MonitoringServerConfigurationRepositoryApi implements MonitoringServerConfigurationRepositoryInterface
{
use LoggerTrait;
/** @var ContactInterface */
private $contact;
/** @var AuthenticationTokenServiceInterface */
private $authenticationTokenService;
/** @var HttpClientInterface */
private $httpClient;
/** @var string */
private $serverUri;
/** @var int */
private $timeout = 60;
/**
* @param AuthenticationTokenServiceInterface $authenticationTokenService
* @param ContactInterface $contact
* @param HttpClientInterface $httpClient
*/
public function __construct(
AuthenticationTokenServiceInterface $authenticationTokenService,
ContactInterface $contact,
HttpClientInterface $httpClient,
) {
$this->contact = $contact;
$this->authenticationTokenService = $authenticationTokenService;
$this->httpClient = $httpClient;
}
/**
* To be used by the dependency injector to increase the timeout limit.
*
* @param int $timeout
*
* @return MonitoringServerConfigurationRepositoryApi
*/
public function setTimeout(int $timeout): self
{
$this->timeout = $timeout;
return $this;
}
/**
* @inheritDoc
*/
public function generateConfiguration(int $monitoringServerId): void
{
$this->callHttp('generateFiles.php', 'generate=true&debug=true&poller=' . $monitoringServerId);
}
/**
* @inheritDoc
*/
public function moveExportFiles(int $monitoringServerId): void
{
$this->callHttp('moveFiles.php', 'poller=' . $monitoringServerId);
}
/**
* @inheritDoc
*/
public function reloadConfiguration(int $monitoringServerId): void
{
$this->callHttp('restartPollers.php', 'mode=1&poller=' . $monitoringServerId);
}
/**
* @throws \Assert\AssertionFailedException
*/
private function initUri(): void
{
if ($this->serverUri === null) {
$serverScheme = $_SERVER['REQUEST_SCHEME'] ?: 'http';
Assertion::notEmpty($_SERVER['SERVER_NAME']);
Assertion::notEmpty($_SERVER['REQUEST_URI']);
$prefixUri = explode('/', $_SERVER['REQUEST_URI'])[1];
// ex: http://localhost:80/centreon
$this->serverUri = $serverScheme . '://' . $_SERVER['SERVER_NAME'] . '/' . $prefixUri;
}
}
/**
* @param string $filePath
* @param string $payloadBody
*
* @throws RepositoryException
* @throws TimeoutException
* @throws AuthenticationException
*/
private function callHttp(string $filePath, string $payloadBody): void
{
try {
$this->initUri();
$fullUriPath = $this->serverUri . '/include/configuration/configGenerate/xml/' . $filePath;
$authenticationTokens = $this->authenticationTokenService->findByContact($this->contact);
if ($authenticationTokens === null) {
throw AuthenticationException::authenticationTokenNotFound();
}
$providerToken = $authenticationTokens->getProviderToken();
if (
$providerToken->getExpirationDate() !== null
&& $providerToken->getExpirationDate()->getTimestamp() < (new DateTime())->getTimestamp()
) {
throw AuthenticationException::authenticationTokenExpired();
}
$optionPayload = [
'proxy' => null,
'no_proxy' => '*',
'verify_peer' => false,
'headers' => ['X-AUTH-TOKEN' => $providerToken->getToken()],
'body' => $payloadBody,
'timeout' => $this->timeout,
];
$optionPayload['verify_host'] = $optionPayload['verify_peer'];
$response = $this->httpClient->request('POST', $fullUriPath, $optionPayload);
if ($response->getStatusCode() !== 200) {
throw MonitoringServerConfigurationRepositoryException::apiRequestFailed($response->getStatusCode());
}
$xml = $response->getContent();
if (! empty($xml)) {
if (($element = simplexml_load_string($xml)) !== false) {
if ((string) $element->statuscode !== '0') {
throw new RepositoryException((string) $element->error);
}
}
} else {
throw MonitoringServerConfigurationRepositoryException::responseEmpty();
}
} catch (RepositoryException|AuthenticationException $ex) {
throw $ex;
} catch (\Assert\AssertionFailedException $ex) {
throw MonitoringServerConfigurationRepositoryException::errorWhenInitializingApiUri();
} catch (\Throwable $ex) {
if ($ex instanceof TransportException && mb_strpos($ex->getMessage(), 'timeout') > 0) {
throw MonitoringServerConfigurationRepositoryException::timeout($ex);
}
throw MonitoringServerConfigurationRepositoryException::unexpectedError($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/MonitoringServer/Repository/RealTimeMonitoringServerRepositoryRDB.php | centreon/src/Centreon/Infrastructure/MonitoringServer/Repository/RealTimeMonitoringServerRepositoryRDB.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\MonitoringServer\Repository;
use Assert\AssertionFailedException;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Entity\EntityCreator;
use Centreon\Domain\MonitoringServer\Interfaces\RealTimeMonitoringServerRepositoryInterface;
use Centreon\Domain\MonitoringServer\Model\RealTimeMonitoringServer;
use Centreon\Domain\MonitoringServer\MonitoringServer;
use Centreon\Domain\RequestParameters\RequestParameters;
use Centreon\Infrastructure\CentreonLegacyDB\StatementCollector;
use Centreon\Infrastructure\DatabaseConnection;
use Centreon\Infrastructure\MonitoringServer\Repository\Model\RealTimeMonitoringServerFactoryRdb;
use Centreon\Infrastructure\Repository\AbstractRepositoryDRB;
use Centreon\Infrastructure\RequestParameters\Interfaces\NormalizerInterface;
use Centreon\Infrastructure\RequestParameters\SqlRequestParametersTranslator;
/**
* This class is designed to represent the MariaDb repository to manage host category.
*/
class RealTimeMonitoringServerRepositoryRDB extends AbstractRepositoryDRB implements RealTimeMonitoringServerRepositoryInterface
{
/** @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 findAll(): array
{
return $this->findAllRequest([]);
}
/**
* @inheritDoc
*/
public function findByIds(array $ids): array
{
return $this->findAllRequest($ids);
}
/**
* @inheritDoc
*/
public function findAllowedMonitoringServers(ContactInterface $contact): array
{
$request = $this->translateDbName(
'SELECT SQL_CALC_FOUND_ROWS *
FROM `:db`.nagios_server as ns
INNER JOIN `:db`.acl_resources_poller_relations arpr
ON ns.id = arpr.poller_id
INNER JOIN `:db`.acl_resources res
ON arpr.acl_res_id = res.acl_res_id
INNER JOIN `:db`.acl_res_group_relations argr
ON res.acl_res_id = argr.acl_res_id
INNER JOIN `:db`.acl_groups ag
ON argr.acl_group_id = ag.acl_group_id
LEFT JOIN `:db`.acl_group_contacts_relations agcr
ON ag.acl_group_id = agcr.acl_group_id
LEFT JOIN `:db`.acl_group_contactgroups_relations agcgr
ON ag.acl_group_id = agcgr.acl_group_id
LEFT JOIN `:db`.contactgroup_contact_relation cgcr
ON cgcr.contactgroup_cg_id = agcgr.cg_cg_id
WHERE (agcr.contact_contact_id = :contact_id OR cgcr.contact_contact_id = :contact_id)'
);
$statement = $this->db->prepare($request);
$statement->bindValue(':contact_id', $contact->getId(), \PDO::PARAM_INT);
$statement->execute();
$result = $this->db->query('SELECT FOUND_ROWS()');
/**
* @var MonitoringServer[] $allowedMonitoringServers
*/
$allowedMonitoringServers = [];
if ($result !== false && ($total = $result->fetchColumn()) !== false) {
// it means here that there is poller relations with this user
if ((int) $total > 0) {
while (($record = $statement->fetch(\PDO::FETCH_ASSOC)) !== false) {
$allowedMonitoringServers[] = EntityCreator::createEntityByArray(
MonitoringServer::class,
$record
);
}
} else {
// if no relations found for this user it means that he can see all
$statement = $this->db->prepare('SELECT * FROM nagios_server');
$statement->execute();
while (($record = $statement->fetch(\PDO::FETCH_ASSOC)) !== false) {
$allowedMonitoringServers[] = EntityCreator::createEntityByArray(
MonitoringServer::class,
$record
);
}
}
}
return $allowedMonitoringServers;
}
/**
* Find all RealTime Monitoring Servers filtered by contact id.
*
* @param int[] $ids Monitoring Server ids
*
* @throws AssertionFailedException
* @throws \InvalidArgumentException
*
* @return RealTimeMonitoringServer[]
*/
private function findAllRequest(array $ids): array
{
$collector = new StatementCollector();
$this->sqlRequestTranslator->setConcordanceArray([
'id' => 'instances.instance_id',
'name' => 'instances.name',
'running' => 'instances.running',
]);
$this->sqlRequestTranslator->addNormalizer(
'running',
new class () implements NormalizerInterface {
/**
* @inheritDoc
*/
public function normalize($valueToNormalize)
{
if (is_bool($valueToNormalize)) {
return ($valueToNormalize === true) ? '1' : '0';
}
return $valueToNormalize;
}
}
);
$request = $this->translateDbName('SELECT SQL_CALC_FOUND_ROWS * FROM `:dbstg`.instances JOIN `:db`.nagios_server ON instances.instance_id = nagios_server.id');
$whereCondition = false;
// Search
$searchRequest = $this->sqlRequestTranslator->translateSearchParameterToSql();
if ($searchRequest !== null) {
$request .= $searchRequest;
$whereCondition = true;
}
if ($ids !== []) {
$instanceIds = [];
$request .= $whereCondition ? ' AND ' : ' WHERE ';
$whereCondition = true;
foreach ($ids as $index => $instanceId) {
$key = ":instanceId_{$index}";
$instanceIds[] = $key;
$collector->addValue($key, $instanceId, \PDO::PARAM_INT);
}
$request .= 'instances.instance_id IN (' . implode(', ', $instanceIds) . ')';
}
$request .= ($whereCondition ? ' AND ' : ' WHERE ') . 'instances.deleted = 0 AND nagios_server.ns_activate = 1';
// Sort
$sortRequest = $this->sqlRequestTranslator->translateSortParameterToSql();
$request .= ! is_null($sortRequest)
? $sortRequest
: ' ORDER BY instances.name ASC';
// Pagination
$request .= $this->sqlRequestTranslator->translatePaginationToSql();
$statement = $this->db->prepare($request);
foreach ($this->sqlRequestTranslator->getSearchValues() as $key => $data) {
$type = key($data);
$value = $data[$type];
$collector->addValue($key, $value, $type);
}
$collector->bind($statement);
$statement->execute();
$result = $this->db->query('SELECT FOUND_ROWS()');
if ($result !== false && ($total = $result->fetchColumn()) !== false) {
$this->sqlRequestTranslator->getRequestParameters()->setTotal((int) $total);
}
$realTimeMonitoringServers = [];
while (($record = $statement->fetch(\PDO::FETCH_ASSOC)) !== false) {
$realTimeMonitoringServers[] = RealTimeMonitoringServerFactoryRdb::create($record);
}
return $realTimeMonitoringServers;
}
}
| 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/MonitoringServer/Repository/MonitoringServerConfigurationRepositoryFile.php | centreon/src/Centreon/Infrastructure/MonitoringServer/Repository/MonitoringServerConfigurationRepositoryFile.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\MonitoringServer\Repository;
use Centreon\Domain\MonitoringServer\Interfaces\MonitoringServerConfigurationRepositoryInterface;
use Centreon\Domain\Repository\RepositoryException;
use Centreon\Infrastructure\MonitoringServer\Repository\Exception\MonitoringServerConfigurationRepositoryException;
/**
* This class is designed to represent the API repository to manage the generation/move/reload of the monitoring
* server configuration.
*
* @package Centreon\Infrastructure\MonitoringServer\Repository
*/
class MonitoringServerConfigurationRepositoryFile implements MonitoringServerConfigurationRepositoryInterface
{
/**
* @inheritDoc
*/
public function generateConfiguration(int $monitoringServerId): void
{
$_POST['generate'] = true;
$_POST['debug'] = true;
$_POST['poller'] = $monitoringServerId;
$this->includeFile('www/include/configuration/configGenerate/xml/generateFiles.php');
}
/**
* @inheritDoc
*/
public function moveExportFiles(int $monitoringServerId): void
{
$_POST['poller'] = $monitoringServerId;
$this->includeFile('www/include/configuration/configGenerate/xml/moveFiles.php');
}
/**
* @inheritDoc
*/
public function reloadConfiguration(int $monitoringServerId): void
{
$_POST['poller'] = $monitoringServerId;
$_POST['mode'] = 1;
$this->includeFile('www/include/configuration/configGenerate/xml/restartPollers.php');
}
private function includeFile(string $filePath): void
{
try {
ob_start();
require _CENTREON_PATH_ . $filePath;
$xml = ob_get_contents();
ob_end_clean();
if (! empty($xml)) {
if (($element = simplexml_load_string($xml)) !== false) {
if ((string) $element->statuscode !== '0') {
throw new RepositoryException((string) $element->error);
}
}
} else {
throw MonitoringServerConfigurationRepositoryException::responseEmpty();
}
} catch (RepositoryException $ex) {
throw $ex;
} catch (\Throwable $ex) {
throw MonitoringServerConfigurationRepositoryException::unexpectedError($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/MonitoringServer/Repository/Model/RealTimeMonitoringServerFactoryRdb.php | centreon/src/Centreon/Infrastructure/MonitoringServer/Repository/Model/RealTimeMonitoringServerFactoryRdb.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\MonitoringServer\Repository\Model;
use Centreon\Domain\MonitoringServer\Model\RealTimeMonitoringServer;
/**
* This class is designed to provide a way to create the HostCategory entity from the database.
*
* @package Centreon\Infrastructure\HostConfiguration\Repository\Model
*/
class RealTimeMonitoringServerFactoryRdb
{
/**
* Create a RealTimeMonitoringServer entity from database data.
*
* @param array<string, mixed> $data
* @throws \Assert\AssertionFailedException
* @return RealTimeMonitoringServer
*/
public static function create(array $data): RealTimeMonitoringServer
{
return (new RealTimeMonitoringServer((int) $data['instance_id'], $data['name']))
->setRunning((bool) $data['running'])
->setLastAlive((int) $data['last_alive'])
->setVersion($data['version'])
->setDescription($data['description'])
->setAddress($data['address']);
}
}
| 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/MonitoringServer/Repository/Exception/MonitoringServerConfigurationRepositoryException.php | centreon/src/Centreon/Infrastructure/MonitoringServer/Repository/Exception/MonitoringServerConfigurationRepositoryException.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\MonitoringServer\Repository\Exception;
use Centreon\Domain\Exception\TimeoutException;
use Centreon\Domain\Repository\RepositoryException;
/**
* This class is designed to contain all the exceptions concerning the repository for generating and reloading the
* monitoring server configurations.
*
* @package Centreon\Infrastructure\MonitoringServer\Repository\Exception
*/
class MonitoringServerConfigurationRepositoryException extends RepositoryException
{
/**
* @param int|null $errorCode
* @return self
*/
public static function apiRequestFailed(?int $errorCode): self
{
return new self(sprintf(_('Request failed (%d)'), $errorCode));
}
/**
* @return self
*/
public static function errorWhenInitializingApiUri(): self
{
return new self(_('Error when initializing the api uri'));
}
/**
* @return self
*/
public static function responseEmpty(): self
{
return new self(_('Response empty'));
}
/**
* @param \Throwable $ex
* @return TimeoutException
*/
public static function timeout(\Throwable $ex): TimeoutException
{
return new TimeoutException(_('Execution was too long and reached timeout'), 0, $ex);
}
/**
* @param \Throwable $ex
* @return self
*/
public static function unexpectedError(\Throwable $ex): self
{
return new self($ex->getMessage(), $ex->getCode(), $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/MonitoringServer/API/Model/RealTimeMonitoringServer.php | centreon/src/Centreon/Infrastructure/MonitoringServer/API/Model/RealTimeMonitoringServer.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\MonitoringServer\API\Model;
/**
* This class is designed to represent the formatted response of the API request.
*
* @package Centreon\Infrastructure\MonitoringServer\API\Model
*/
class RealTimeMonitoringServer
{
/** @var int */
public $id;
/** @var string */
public $name;
/** @var string|null */
public $address;
/** @var bool */
public $isRunning;
/** @var int|null */
public $lastAlive;
/** @var string|null */
public $version;
/** @var string|null */
public $description;
}
| 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/MonitoringServer/API/Model/RealTimeMonitoringServerFactory.php | centreon/src/Centreon/Infrastructure/MonitoringServer/API/Model/RealTimeMonitoringServerFactory.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\MonitoringServer\API\Model;
use Centreon\Domain\MonitoringServer\UseCase\RealTimeMonitoringServer\FindRealTimeMonitoringServersResponse;
/**
* This class is designed to create the hostCategoryV21 entity
*
* @package Centreon\Infrastructure\HostConfiguration\API\Model\HostCategory
*/
class RealTimeMonitoringServerFactory
{
/**
* @param FindRealTimeMonitoringServersResponse $response
* @return RealTimeMonitoringServer[]
*/
public static function createFromResponse(FindRealTimeMonitoringServersResponse $response): array
{
$realTimeMonitoringServers = [];
foreach ($response->getRealTimeMonitoringServers() as $realTimeMonitoringServer) {
$newRealTimeMonitoringServer = new RealTimeMonitoringServer();
$newRealTimeMonitoringServer->id = $realTimeMonitoringServer['id'];
$newRealTimeMonitoringServer->name = $realTimeMonitoringServer['name'];
$newRealTimeMonitoringServer->address = $realTimeMonitoringServer['address'];
$newRealTimeMonitoringServer->description = $realTimeMonitoringServer['description'];
$newRealTimeMonitoringServer->version = $realTimeMonitoringServer['version'];
$newRealTimeMonitoringServer->isRunning = $realTimeMonitoringServer['is_running'];
$newRealTimeMonitoringServer->lastAlive = $realTimeMonitoringServer['last_alive'];
$realTimeMonitoringServers[] = $newRealTimeMonitoringServer;
}
return $realTimeMonitoringServers;
}
}
| 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/ServiceConfiguration/ServiceConfigurationRepositoryRDB.php | centreon/src/Centreon/Infrastructure/ServiceConfiguration/ServiceConfigurationRepositoryRDB.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\ServiceConfiguration;
use Centreon\Domain\Entity\EntityCreator;
use Centreon\Domain\HostConfiguration\Host;
use Centreon\Domain\RequestParameters\RequestParameters;
use Centreon\Domain\ServiceConfiguration\HostTemplateService;
use Centreon\Domain\ServiceConfiguration\Interfaces\ServiceConfigurationRepositoryInterface;
use Centreon\Domain\ServiceConfiguration\Service;
use Centreon\Domain\ServiceConfiguration\ServiceMacro;
use Centreon\Infrastructure\AccessControlList\AccessControlListRepositoryTrait;
use Centreon\Infrastructure\DatabaseConnection;
use Centreon\Infrastructure\Repository\AbstractRepositoryDRB;
use Centreon\Infrastructure\RequestParameters\SqlRequestParametersTranslator;
/**
* @todo Add ACL control
*
* @package Centreon\Infrastructure\ServiceConfiguration
*/
class ServiceConfigurationRepositoryRDB extends AbstractRepositoryDRB implements ServiceConfigurationRepositoryInterface
{
use AccessControlListRepositoryTrait;
/** @var SqlRequestParametersTranslator */
private $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 addServicesToHost(Host $host, array $servicesToBeCreated): void
{
// We avoid to start again a database transaction
$isAlreadyInTransaction = $this->db->inTransaction();
if (! $isAlreadyInTransaction) {
$this->db->beginTransaction();
}
$addServiceStatement = $this->db->prepare(
$this->translateDbName(
'INSERT INTO `:db`.service
(service_template_model_stm_id, command_command_id, service_description, service_alias, service_locked,
service_activate, service_register)
VALUES (:template_id, :command_id, :description, :alias, :is_locked, :is_activated, :service_type)'
)
);
$addServiceExtensionStatement = $this->db->prepare(
$this->translateDbName(
'INSERT INTO `:db`.extended_service_information
(service_service_id, esi_notes, esi_notes_url, esi_action_url,
esi_icon_image, esi_icon_image_alt, graph_id)
VALUES (:service_id, :notes, :notes_url, :action_url, :icon_image, :icon_image_alt, :graph_id)'
)
);
$addRelationStatement = $this->db->prepare(
$this->translateDbName(
'INSERT INTO `:db`.host_service_relation
(host_host_id, service_service_id)
VALUES (:host_id, :service_id)'
)
);
try {
foreach ($servicesToBeCreated as $serviceTobeCreated) {
/**
* Create service
*/
$addServiceStatement->bindValue(':template_id', $serviceTobeCreated->getTemplateId(), \PDO::PARAM_INT);
$addServiceStatement->bindValue(':command_id', $serviceTobeCreated->getCommandId(), \PDO::PARAM_INT);
$addServiceStatement->bindValue(':description', $serviceTobeCreated->getDescription(), \PDO::PARAM_STR);
$addServiceStatement->bindValue(':alias', $serviceTobeCreated->getTemplateId(), \PDO::PARAM_STR);
$addServiceStatement->bindValue(':is_locked', $serviceTobeCreated->isLocked(), \PDO::PARAM_BOOL);
$addServiceStatement->bindValue(':is_activated', $serviceTobeCreated->isActivated(), \PDO::PARAM_STR);
$addServiceStatement->bindValue(
':service_type',
$serviceTobeCreated->getServiceType(),
\PDO::PARAM_STR
);
$addServiceStatement->execute();
$serviceId = (int) $this->db->lastInsertId();
/**
* Create service extension
*/
$eService = $serviceTobeCreated->getExtendedService();
$addServiceExtensionStatement->bindValue(':service_id', $serviceId, \PDO::PARAM_INT);
$addServiceExtensionStatement->bindValue(':notes', $eService->getNotes(), \PDO::PARAM_STR);
$addServiceExtensionStatement->bindValue(':notes_url', $eService->getNotesUrl(), \PDO::PARAM_STR);
$addServiceExtensionStatement->bindValue(':action_url', $eService->getActionUrl(), \PDO::PARAM_STR);
$addServiceExtensionStatement->bindValue(':icon_image', $eService->getIconId(), \PDO::PARAM_INT);
$addServiceExtensionStatement->bindValue(
':icon_image_alt',
$eService->getIconAlternativeText(),
\PDO::PARAM_STR
);
$addServiceExtensionStatement->bindValue(':graph_id', $eService->getGraphId(), \PDO::PARAM_INT);
$addServiceExtensionStatement->execute();
/**
* Add relation between service and host
*/
$addRelationStatement->bindValue(':host_id', $host->getId(), \PDO::PARAM_INT);
$addRelationStatement->bindValue(':service_id', $serviceId, \PDO::PARAM_INT);
$addRelationStatement->execute();
}
} catch (\Throwable $ex) {
if (! $isAlreadyInTransaction) {
$this->db->rollBack();
}
throw $ex;
}
if (! $isAlreadyInTransaction) {
$this->db->commit();
}
}
/**
* @inheritDoc
*/
public function findService(int $serviceId): ?Service
{
$request = $this->translateDbName(
'SELECT service_id AS id, service_template_model_stm_id AS template_id, display_name AS name,
service_description AS description, service_locked AS is_locked, service_register AS service_type,
service_activate AS is_activated, service_notifications_enabled
FROM `:db`.service
WHERE service_id = :service_id'
);
$statement = $this->db->prepare($request);
$statement->bindValue(':service_id', $serviceId, \PDO::PARAM_INT);
$statement->execute();
if (($record = $statement->fetch(\PDO::FETCH_ASSOC)) !== false) {
return EntityCreator::createEntityByArray(
Service::class,
$record
);
}
return null;
}
/**
* @inheritDoc
*/
public function findOnDemandServiceMacros(int $serviceId, bool $isUsingInheritance = false): array
{
/* CTE recurse request next release:
* WITH RECURSIVE inherite AS (
* SELECT srv.service_id, srv.service_template_model_stm_id AS template_id,
* demand.svc_macro_id AS macro_id, demand.svc_macro_name AS name, 0 AS level
* FROM `:db`.service srv
* LEFT JOIN `:db`.on_demand_macro_service demand
* ON srv.service_id = demand.svc_svc_id
* WHERE service_id = :service_id
* UNION
* SELECT srv.service_id, srv.service_template_model_stm_id AS template_id,
* demand.svc_macro_id AS macro_id, demand.svc_macro_name AS name, inherite.level + 1
* FROM `:db`.service srv
* INNER JOIN inherite
* ON inherite.template_id = srv.service_id
* LEFT JOIN `:db`.on_demand_macro_service demand
* ON srv.service_id = demand.svc_svc_id
* )
* SELECT demand.svc_macro_id AS id, demand.svc_macro_name AS name,
* demand.svc_macro_value AS `value`,
* demand.macro_order AS `order`, demand.description, demand.svc_svc_id AS service_id
* CASE
* WHEN demand.is_password IS NULL THEN \'0\'
* ELSE demand.is_password
* END is_password
* FROM inherite
* INNER JOIN `:db`.on_demand_macro_service demand
* ON demand.svc_macro_id = inherite.macro_id
* WHERE inherite.name IS NOT NULL
*/
$request = $this->translateDbName(
'SELECT
srv.service_id AS service_id, demand.svc_macro_id AS id,
svc_macro_name AS name, svc_macro_value AS `value`,
macro_order AS `order`, is_password, description, service_template_model_stm_id
FROM `:db`.service srv
LEFT JOIN `:db`.on_demand_macro_service demand ON srv.service_id = demand.svc_svc_id
WHERE srv.service_id = :service_id'
);
$statement = $this->db->prepare($request);
$serviceMacros = [];
$loop = [];
$macrosAdded = [];
while (! is_null($serviceId)) {
if (isset($loop[$serviceId])) {
break;
}
$loop[$serviceId] = 1;
$statement->bindValue(':service_id', $serviceId, \PDO::PARAM_INT);
$statement->execute();
while (($record = $statement->fetch(\PDO::FETCH_ASSOC)) !== false) {
$serviceId = $record['service_template_model_stm_id'];
if (is_null($record['name']) || isset($macrosAdded[$record['name']])) {
continue;
}
$macrosAdded[$record['name']] = 1;
$record['is_password'] = is_null($record['is_password']) ? 0 : $record['is_password'];
$serviceMacros[] = EntityCreator::createEntityByArray(
ServiceMacro::class,
$record
);
}
if (! $isUsingInheritance) {
break;
}
}
return $serviceMacros;
}
/**
* @inheritDoc
*/
public function findCommandLine(int $serviceId): ?string
{
/*
* CTE recurse request next release:
* WITH RECURSIVE inherite AS (
* SELECT service_id, service_template_model_stm_id, command_command_id
* FROM `:db`.service
* WHERE service_id = :service_id
* UNION
* SELECT service.command_command_id, service.service_template_model_stm_id, service.command_command_id
* FROM `:db`.service
* INNER JOIN inherite
* ON inherite.service_template_model_stm_id = service.service_id
* AND inherite.command_command_id IS NULL
* )
* SELECT command.command_line
* FROM inherite
* INNER JOIN `:db`.command
* ON command.command_id = inherite.command_command_id
*/
$request = $this->translateDbName(
'SELECT
srv.service_id AS service_id, service_template_model_stm_id,
command.command_line
FROM `:db`.service srv
LEFT JOIN `:db`.command ON srv.command_command_id = command.command_id
WHERE srv.service_id = :service_id LIMIT 1'
);
$statement = $this->db->prepare($request);
$serviceMacros = [];
$loop = [];
while (! is_null($serviceId)) {
if (isset($loop[$serviceId])) {
break;
}
$loop[$serviceId] = 1;
$statement->bindValue(':service_id', $serviceId, \PDO::PARAM_INT);
$statement->execute();
$record = $statement->fetch(\PDO::FETCH_ASSOC);
if (! is_null($record['command_line'])) {
return (string) $record['command_line'];
}
$serviceId = $record['service_template_model_stm_id'];
}
return null;
}
/**
* @inheritDoc
*/
public function findHostTemplateServices(array $hostTemplateIds): array
{
if ($hostTemplateIds === []) {
return [];
}
$request = $this->translateDbName(
'SELECT host.host_id, host.host_name, host.host_alias, host.host_register AS host_type,
host.host_activate AS host_is_activated,
service.service_id, service.service_description, service.service_alias,
service.service_register AS service_service_type, service.service_activate AS service_is_activated
FROM `:db`.host_service_relation hsr
INNER JOIN `:db`.host
ON host.host_id = hsr.host_host_id
AND host.host_register = \'0\'
INNER JOIN `:db`.service
ON service.service_id = hsr.service_service_id
AND service.service_register = \'0\'
WHERE hsr.host_host_id IN (' . str_repeat('?,', count($hostTemplateIds) - 1) . '?)'
);
$statement = $this->db->prepare($request);
$statement->execute($hostTemplateIds);
$hostTemplateServices = [];
while (($record = $statement->fetch(\PDO::FETCH_ASSOC)) !== false) {
$hostTemplate = EntityCreator::createEntityByArray(
Host::class,
$record,
'host_'
);
$serviceTemplate = EntityCreator::createEntityByArray(
Service::class,
$record,
'service_'
);
$hostTemplateServices[] = (new HostTemplateService())
->setHostTemplate($hostTemplate)
->setServiceTemplate($serviceTemplate);
}
return $hostTemplateServices;
}
/**
* @inheritDoc
*/
public function findServicesByHost(Host $host): array
{
$request = $this->translateDbName(
'SELECT service.service_id, service.service_description, service.service_alias,
service.service_register AS service_service_type, service.service_activate AS service_activated,
service.service_activate AS service_is_activated
FROM `:db`.service
INNER JOIN `:db`.host_service_relation hsr
ON hsr.service_service_id = service.service_id
AND service.service_register = \'1\'
WHERE hsr.host_host_id = :host_id'
);
$statement = $this->db->prepare($request);
$statement->bindValue(':host_id', $host->getId(), \PDO::PARAM_INT);
$statement->execute();
$services = [];
while (($record = $statement->fetch(\PDO::FETCH_ASSOC)) !== false) {
$services[] = EntityCreator::createEntityByArray(
Service::class,
$record,
'service_'
);
}
return $services;
}
/**
* @inheritDoc
*/
public function removeServicesOnHost(int $hostId): void
{
$request = $this->translateDbName(
'DELETE service FROM `:db`.service
INNER JOIN `:db`.host_service_relation hsr
ON hsr.service_service_id = service.service_id
WHERE hsr.host_host_id = :host_id'
);
$statement = $this->db->prepare($request);
$statement->bindValue(':host_id', $hostId, \PDO::PARAM_INT);
$statement->execute();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Infrastructure/Menu/MenuRepositoryRDB.php | centreon/src/Centreon/Infrastructure/Menu/MenuRepositoryRDB.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Menu;
use Centreon\Domain\Menu\Interfaces\MenuRepositoryInterface;
use Centreon\Domain\Menu\Model\Page;
use Centreon\Infrastructure\DatabaseConnection;
use Centreon\Infrastructure\Repository\AbstractRepositoryDRB;
class MenuRepositoryRDB extends AbstractRepositoryDRB implements MenuRepositoryInterface
{
/**
* PlatformTopologyRepositoryRDB constructor.
* @param DatabaseConnection $db
*/
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* @inheritDoc
*/
public function disableCentralMenus(): void
{
$this->db->query(
"UPDATE topology SET topology_show = '0'
WHERE topology_page IN ('21003', '601', '602', '60304', '608', '604', '617', '650', '609', '610', '50111',
'50102', '50707', '50120', '618', '60905')
OR topology_parent IN ('601', '602', '608', '604', '617', '650', '609', '610')"
);
}
/**
* @inheritDoc
*/
public function enableCentralMenus(): void
{
$this->db->query(
"UPDATE topology SET topology_show = '1'
WHERE topology_page IN ('21003', '601', '602', '60304', '608', '604', '617', '650', '609', '610', '50111',
'50102', '50707', '50120', '618', '60905')
OR topology_parent IN ('601', '602', '608', '604', '617', '650', '609', '610')"
);
}
/**
* @inheritDoc
*/
public function findPageByTopologyPageNumber(int $pageNumber): ?Page
{
$statement = $this->db->prepare(
$this->translateDbName(
'SELECT topology_id, topology_url, is_react, topology_url_opt FROM `:db`.topology '
. 'WHERE topology_page = :topologyPage'
)
);
$statement->bindValue(':topologyPage', $pageNumber, \PDO::PARAM_INT);
$statement->execute();
$result = $statement->fetch(\PDO::FETCH_ASSOC);
if ($result === false) {
return null;
}
return (
new Page((int) $result['topology_id'], $result['topology_url'], $pageNumber, $result['is_react'] === '1')
)
->setUrlOptions($result['topology_url_opt']);
}
}
| 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/Monitoring/MonitoringRepositoryRDB.php | centreon/src/Centreon/Infrastructure/Monitoring/MonitoringRepositoryRDB.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Monitoring;
use Centreon\Domain\Acknowledgement\Acknowledgement;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Downtime\Downtime;
use Centreon\Domain\Entity\EntityCreator;
use Centreon\Domain\Monitoring\Host;
use Centreon\Domain\Monitoring\HostGroup;
use Centreon\Domain\Monitoring\Interfaces\MonitoringRepositoryInterface;
use Centreon\Domain\Monitoring\ResourceStatus;
use Centreon\Domain\Monitoring\Service;
use Centreon\Domain\Monitoring\ServiceGroup;
use Centreon\Domain\RequestParameters\RequestParameters;
use Centreon\Infrastructure\CentreonLegacyDB\StatementCollector;
use Centreon\Infrastructure\DatabaseConnection;
use Centreon\Infrastructure\Repository\AbstractRepositoryDRB;
use Centreon\Infrastructure\RequestParameters\SqlRequestParametersTranslator;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
/**
* Database repository for the real time monitoring of services and host.
*
* @package Centreon\Infrastructure\Monitoring
*/
final class MonitoringRepositoryRDB extends AbstractRepositoryDRB implements MonitoringRepositoryInterface
{
/** @var AccessGroup[] List of access group used to filter the requests */
private $accessGroups = [];
/** @var SqlRequestParametersTranslator */
private $sqlRequestTranslator;
/** @var ContactInterface */
private $contact;
/**
* MonitoringRepositoryRDB constructor.
*
* @param DatabaseConnection $pdo
*/
public function __construct(DatabaseConnection $pdo)
{
$this->db = $pdo;
}
/**
* @inheritDoc
*/
public function filterByAccessGroups(?array $accessGroups): MonitoringRepositoryInterface
{
$this->accessGroups = $accessGroups;
return $this;
}
/**
* Initialized by the dependency injector.
*
* @param SqlRequestParametersTranslator $sqlRequestTranslator
*/
public function setSqlRequestTranslator(SqlRequestParametersTranslator $sqlRequestTranslator): void
{
$this->sqlRequestTranslator = $sqlRequestTranslator;
$this->sqlRequestTranslator
->getRequestParameters()
->setConcordanceStrictMode(
RequestParameters::CONCORDANCE_MODE_STRICT
);
}
/**
* @inheritDoc
*/
public function findHosts(): array
{
$hosts = [];
if ($this->hasNotEnoughRightsToContinue()) {
return $hosts;
}
$this->sqlRequestTranslator->setConcordanceArray([
'host.id' => 'h.host_id',
'host.name' => 'h.name',
'host.alias' => 'h.alias',
'host.address' => 'h.address',
'host.last_state_change' => 'h.last_state_change',
'host.state' => 'h.state',
'poller.id' => 'h.instance_id',
'service.display_name' => 'srv.display_name',
'host_group.id' => 'hg.hostgroup_id',
'host.is_acknowledged' => 'h.acknowledged',
'host.downtime' => 'h.scheduled_downtime_depth',
'host.criticality' => 'cv.value',
]);
$accessGroupFilter = '';
if ($this->isAdmin() === false) {
$accessGroupIds = array_map(
function ($accessGroup) {
return $accessGroup->getId();
},
$this->accessGroups
);
$accessGroupFilter = ' INNER JOIN `:dbstg`.`centreon_acl` acl
ON acl.host_id = h.host_id
AND acl.service_id IS NULL
AND acl.group_id IN (' . implode(',', $accessGroupIds) . ') ';
}
$request = <<<SQL
SELECT SQL_CALC_FOUND_ROWS DISTINCT
1 AS REALTIME,
h.host_id,
h.name,
h.instance_id,
h.acknowledged,
h.acknowledgement_type,
h.action_url,
h.active_checks,
h.address,
h.alias,
h.check_attempt,
h.check_command,
h.check_freshness,
h.check_interval,
h.check_period,
h.check_type,
h.checked,
h.command_line,
h.default_active_checks,
h.default_event_handler_enabled,
h.default_failure_prediction,
h.default_flap_detection,
h.default_notify,
h.default_passive_checks,
h.default_process_perfdata,
h.display_name,
h.enabled,
h.event_handler,
h.event_handler_enabled,
h.execution_time,
h.failure_prediction,
h.first_notification_delay,
h.flap_detection,
h.flap_detection_on_down,
h.flap_detection_on_unreachable,
h.flap_detection_on_up,
h.flapping,
h.freshness_threshold,
h.high_flap_threshold,
h.icon_image,
h.icon_image_alt,
h.last_check,
h.last_hard_state,
h.last_hard_state_change,
h.last_notification,
h.last_state_change,
h.last_time_down,
h.last_time_unreachable,
h.last_time_up,
h.last_update,
h.latency,
h.low_flap_threshold,
h.max_check_attempts,
h.modified_attributes,
h.next_check,
h.next_host_notification,
h.no_more_notifications,
h.notes,
h.notes_url,
h.notification_interval,
h.notification_number,
h.notification_period,
h.notify,
h.notify_on_down,
h.notify_on_downtime,
h.notify_on_flapping,
h.notify_on_recovery,
h.notify_on_unreachable,
h.obsess_over_host,
h.output,
h.passive_checks,
h.percent_state_change,
h.perfdata,
h.process_perfdata,
h.retain_nonstatus_information,
h.retain_status_information,
h.retry_interval,
h.scheduled_downtime_depth,
h.should_be_scheduled,
h.stalk_on_down,
h.stalk_on_unreachable,
h.stalk_on_up,
h.state,
h.state_type,
h.statusmap_image,
h.timezone,
h.real_state,
cv.value AS criticality,
i.name AS poller_name,
IF (h.display_name LIKE '_Module_Meta%', 'Meta', h.display_name) AS display_name,
IF (h.display_name LIKE '_Module_Meta%', '0', h.state) AS state
FROM `:dbstg`.`instances` i
INNER JOIN `:dbstg`.`hosts` h
ON h.instance_id = i.instance_id
AND h.enabled = '1'
AND h.name NOT LIKE '_Module_BAM%'
{$accessGroupFilter}
LEFT JOIN `:dbstg`.`services` srv
ON srv.host_id = h.host_id
AND srv.enabled = '1'
LEFT JOIN `:dbstg`.`hosts_hostgroups` hg
ON hg.host_id = h.host_id
LEFT JOIN `:dbstg`.`customvariables` cv
ON cv.host_id = h.host_id
AND (cv.service_id = 0 OR cv.service_id IS NULL)
AND cv.name = 'CRITICALITY_LEVEL'
SQL;
$request = $this->translateDbName($request);
// Search
$searchRequest = $this->sqlRequestTranslator->translateSearchParameterToSql();
$request .= ! is_null($searchRequest) ? $searchRequest : '';
// Group
$request .= ' GROUP BY h.host_id, cv.value';
// Sort
$sortRequest = $this->sqlRequestTranslator->translateSortParameterToSql();
$request .= ! is_null($sortRequest) ? $sortRequest : ' ORDER BY h.name ASC';
// 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);
}
if ($statement->execute() === false) {
throw new \Exception(_('Bad SQL request'));
}
$result = $this->db->query('SELECT FOUND_ROWS() AS REALTIME');
if ($result !== false) {
$this->sqlRequestTranslator->getRequestParameters()->setTotal(
(int) $result->fetchColumn()
);
}
$hostIds = [];
while (false !== ($result = $statement->fetch(\PDO::FETCH_ASSOC))) {
$hostIds[] = (int) $result['host_id'];
$hosts[] = EntityCreator::createEntityByArray(
Host::class,
$result
);
}
return $hosts;
}
/**
* @inheritDoc
*/
public function findHostsByHostsGroups(array $hostsGroupsIds): array
{
if ($this->hasNotEnoughRightsToContinue() || $hostsGroupsIds === []) {
return [];
}
$accessGroupFilter = '';
if ($this->isAdmin() === false) {
$accessGroupIds = array_map(
function ($accessGroup) {
return $accessGroup->getId();
},
$this->accessGroups
);
$accessGroupFilter = ' INNER JOIN `:dbstg`.`centreon_acl` acl
ON acl.host_id = h.host_id
AND acl.service_id IS NULL
AND acl.group_id IN (' . implode(',', $accessGroupIds) . ') ';
}
$request
= 'SELECT DISTINCT
1 AS REALTIME,
hg.hostgroup_id, h.*, i.name AS poller_name,
IF (h.display_name LIKE \'_Module_Meta%\', \'Meta\', h.display_name) AS display_name,
IF (h.display_name LIKE \'_Module_Meta%\', \'0\', h.state) AS state
FROM `:dbstg`.`instances` i
INNER JOIN `:dbstg`.`hosts` h
ON h.instance_id = i.instance_id
AND h.enabled = \'1\'
AND h.name NOT LIKE \'_Module_BAM%\''
. $accessGroupFilter
. ' LEFT JOIN `:dbstg`.`services` srv
ON srv.host_id = h.host_id
AND srv.enabled = \'1\'
LEFT JOIN `:dbstg`.`hosts_hostgroups` hg
ON hg.host_id = h.host_id
AND hg.hostgroup_id IN (' . str_repeat('?,', count($hostsGroupsIds) - 1)
. '?) ORDER BY h.name ASC';
$request = $this->translateDbName($request);
$statement = $this->db->prepare($request);
$statement->execute($hostsGroupsIds);
$hostsByHostsGroupsId = [];
while (false !== ($result = $statement->fetch(\PDO::FETCH_ASSOC))) {
$hostsByHostsGroupsId[(int) $result['hostgroup_id']][]
= EntityCreator::createEntityByArray(
Host::class,
$result
);
}
return $hostsByHostsGroupsId;
}
/**
* @inheritDoc
*/
public function findHostsByServiceGroups(array $servicesGroupsIds): array
{
if ($this->hasNotEnoughRightsToContinue() || $servicesGroupsIds === []) {
return [];
}
$accessGroupFilter = '';
if ($this->isAdmin() === false) {
$accessGroupIds = array_map(
function ($accessGroup) {
return $accessGroup->getId();
},
$this->accessGroups
);
$accessGroupFilter = ' INNER JOIN `:dbstg`.`centreon_acl` acl
ON acl.host_id = h.host_id
AND acl.service_id = srv.service_id
AND acl.group_id IN (' . implode(',', $accessGroupIds) . ') ';
}
$request
= 'SELECT DISTINCT
1 AS REALTIME,
ssg.servicegroup_id, h.*, i.name AS poller_name,
IF (h.display_name LIKE \'_Module_Meta%\', \'Meta\', h.display_name) AS display_name,
IF (h.display_name LIKE \'_Module_Meta%\', \'0\', h.state) AS state
FROM `:dbstg`.`instances` i
INNER JOIN `:dbstg`.`hosts` h
ON h.instance_id = i.instance_id
AND h.enabled = \'1\'
AND h.name NOT LIKE \'_Module_BAM%\'
INNER JOIN `:dbstg`.`services` srv
ON srv.host_id = h.host_id
AND srv.enabled = \'1\''
. $accessGroupFilter
. ' LEFT JOIN `:dbstg`.`services_servicegroups` ssg
ON ssg.host_id = h.host_id
AND ssg.servicegroup_id IN (' . str_repeat('?,', count($servicesGroupsIds) - 1)
. '?) ORDER BY h.name ASC';
$request = $this->translateDbName($request);
$statement = $this->db->prepare($request);
$statement->execute($servicesGroupsIds);
$hostsByServicesGroupsId = [];
while (false !== ($result = $statement->fetch(\PDO::FETCH_ASSOC))) {
$hostsByServicesGroupsId[(int) $result['servicegroup_id']][]
= EntityCreator::createEntityByArray(
Host::class,
$result
);
}
return $hostsByServicesGroupsId;
}
/**
* @inheritDoc
*/
public function findHostGroups(?int $hostId): array
{
$hostGroups = [];
if ($this->hasNotEnoughRightsToContinue()) {
return $hostGroups;
}
$hostGroupConcordanceArray = [
'id' => 'hg.hostgroup_id',
'name' => 'hg.name',
];
$hostCategoryConcordanceArray = [
'host_category.id' => 'host_categories.id',
'host_category.name' => 'host_categories.name',
];
// To allow to find host groups relating to host information
$hostConcordanceArray = [
'host.id' => 'h.host_id',
'host.name' => 'h.name',
'host.alias' => 'h.alias',
'host.address' => 'h.address',
'host.display_name' => 'h.display_name',
'host.state' => 'h.state',
'poller.id' => 'h.instance_id',
];
// To allow to find host groups relating to Service information
$serviceConcordanceArray = [
'service.display_name' => 'srv.display_name',
];
$searchParameters = $this->sqlRequestTranslator->getRequestParameters()->extractSearchNames();
$shouldJoinHost = false;
if (array_intersect($searchParameters, array_keys($hostConcordanceArray)) !== []) {
$shouldJoinHost = true;
$hostGroupConcordanceArray = array_merge($hostGroupConcordanceArray, $hostConcordanceArray);
}
$shouldJoinService = false;
if (array_intersect($searchParameters, array_keys($serviceConcordanceArray)) !== []) {
$shouldJoinService = true;
$hostGroupConcordanceArray = array_merge($hostGroupConcordanceArray, $serviceConcordanceArray);
}
$shouldJoinHostCategory = false;
if (array_intersect($searchParameters, array_keys($hostCategoryConcordanceArray)) !== []) {
$shouldJoinHostCategory = true;
$hostGroupConcordanceArray = array_merge($hostGroupConcordanceArray, $hostCategoryConcordanceArray);
}
// if the filter is for specific host id, remove it from search parameters
if ($hostId !== null) {
$shouldJoinHost = true;
unset($hostConcordanceArray['host.id']);
}
$this->sqlRequestTranslator->setConcordanceArray($hostGroupConcordanceArray);
$sqlExtraParameters = [];
$subRequest = '';
if (! $this->isAdmin()) {
$sqlExtraParameters = [':contact_id' => [\PDO::PARAM_INT => $this->contact->getId()]];
// Not an admin, we must to filter on contact
$subRequest
.= ' INNER JOIN `:db`.acl_resources_hg_relations hgr
ON hgr.hg_hg_id = hg.hostgroup_id
INNER JOIN `:db`.acl_resources res
ON res.acl_res_id = hgr.acl_res_id
AND res.acl_res_activate = \'1\'
INNER JOIN `:db`.acl_res_group_relations rgr
ON rgr.acl_res_id = res.acl_res_id
INNER JOIN `:db`.acl_groups grp
ON grp.acl_group_id IN ('
. $this->accessGroupIdToString($this->accessGroups)
. ') AND grp.acl_group_activate = \'1\'
AND grp.acl_group_id = rgr.acl_group_id
LEFT JOIN `:db`.acl_group_contacts_relations gcr
ON gcr.acl_group_id = grp.acl_group_id
LEFT JOIN `:db`.acl_group_contactgroups_relations gcgr
ON gcgr.acl_group_id = grp.acl_group_id
LEFT JOIN `:db`.contactgroup_contact_relation cgcr
ON cgcr.contactgroup_cg_id = gcgr.cg_cg_id
AND (cgcr.contact_contact_id = :contact_id OR gcr.contact_contact_id = :contact_id)';
}
// This join will only be added if a search parameter corresponding to one of the host or Service parameter
if ($shouldJoinHost || $shouldJoinService || $shouldJoinHostCategory) {
$subRequest
.= ' INNER JOIN `:dbstg`.hosts_hostgroups hhg
ON hhg.hostgroup_id = hg.hostgroup_id
INNER JOIN `:dbstg`.hosts h
ON h.host_id = hhg.host_id
AND h.enabled = \'1\'
AND h.name NOT LIKE \'_Module_BAM%\'';
if ($shouldJoinService) {
$subRequest
.= ' LEFT JOIN `:dbstg`.`services` srv
ON srv.host_id = h.host_id
AND srv.enabled = \'1\'';
}
if ($shouldJoinHostCategory) {
// tags table because everything is resolved (templates and so on...)
$subRequest
.= ' INNER JOIN `:dbstg`.resources
ON resources.id = h.host_id
INNER JOIN `:dbstg`.resources_tags
ON resources_tags.resource_id = resources.resource_id
INNER JOIN `:dbstg`.tags host_categories
ON host_categories.tag_id = resources_tags.tag_id
AND host_categories.`type` = 3';
}
if (! $this->isAdmin()) {
$subRequest
.= ' INNER JOIN `:dbstg`.`centreon_acl` acl
ON acl.host_id = h.host_id
AND acl.service_id IS NULL
AND acl.group_id = grp.acl_group_id';
}
}
$request = <<<'SQL'
SELECT SQL_CALC_FOUND_ROWS DISTINCT 1 AS REALTIME, hg.*
FROM `:dbstg`.`hostgroups` hg
INNER JOIN `:db` . `hostgroup` chg ON chg.hg_id = hg.hostgroup_id
SQL;
$request .= $subRequest;
$request = $this->translateDbName($request);
// Search
$searchRequest = $this->sqlRequestTranslator->translateSearchParameterToSql();
// if host id is provided, filter results by it
if ($hostId !== null) {
$searchByHostIdQuery = ! is_null($searchRequest) ? ' AND h.host_id = :hostId' : ' WHERE h.host_id = :hostId';
} else {
$searchByHostIdQuery = '';
}
$request .= ! is_null($searchRequest) ? $searchRequest : '';
$request .= $searchByHostIdQuery;
// Sort
$sortRequest = $this->sqlRequestTranslator->translateSortParameterToSql();
$request .= ! is_null($sortRequest) ? $sortRequest : ' ORDER BY hg.name ASC';
// 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);
}
// We bind extra parameters according to access rights
foreach ($sqlExtraParameters as $key => $data) {
$type = key($data);
$value = $data[$type];
$statement->bindValue($key, $value, $type);
}
if ($hostId !== null) {
// bind the host id to search for it if provided
$statement->bindValue(':hostId', $hostId, \PDO::PARAM_INT);
}
$statement->execute();
$result = $this->db->query('SELECT FOUND_ROWS() AS REALTIME');
if ($result !== false) {
$this->sqlRequestTranslator->getRequestParameters()->setTotal(
(int) $result->fetchColumn()
);
}
while (false !== ($result = $statement->fetch(\PDO::FETCH_ASSOC))) {
$hostGroups[] = EntityCreator::createEntityByArray(
HostGroup::class,
$result
);
}
return $hostGroups;
}
/**
* @inheritDoc
*/
public function findOneHost(int $hostId): ?Host
{
if ($this->hasNotEnoughRightsToContinue()) {
return null;
}
$accessGroupFilter = '';
if ($this->isAdmin() === false) {
$accessGroupIds = array_map(
function ($accessGroup) {
return $accessGroup->getId();
},
$this->accessGroups
);
$accessGroupFilter = ' INNER JOIN `:dbstg`.`centreon_acl` acl
ON acl.host_id = h.host_id
AND acl.service_id IS NULL
AND acl.group_id IN (' . implode(',', $accessGroupIds) . ') ';
}
$request
= 'SELECT 1 AS REALTIME, h.*,
i.name AS poller_name,
IF (h.display_name LIKE \'_Module_Meta%\', \'Meta\', h.display_name) AS display_name,
IF (h.display_name LIKE \'_Module_Meta%\', \'0\', h.state) AS state,
host_cvl.value AS `criticality`
FROM `:dbstg`.`instances` i
INNER JOIN `:dbstg`.`hosts` h
ON h.instance_id = i.instance_id
AND h.enabled = \'1\'
AND h.name NOT LIKE \'_Module_BAM%\'
LEFT JOIN `:dbstg`.`customvariables` AS host_cvl ON host_cvl.host_id = h.host_id
AND host_cvl.service_id = 0 AND host_cvl.name = "CRITICALITY_LEVEL"'
. $accessGroupFilter
. ' WHERE h.host_id = :host_id';
$request = $this->translateDbName($request);
$statement = $this->db->prepare($request);
$statement->bindValue(':host_id', $hostId, \PDO::PARAM_INT);
if ($statement->execute()) {
if (false !== ($row = $statement->fetch(\PDO::FETCH_ASSOC))) {
$host = EntityCreator::createEntityByArray(
Host::class,
$row
);
// get services for host
$servicesByHost = $this->findServicesByHosts([$hostId]);
$host->setServices(! empty($servicesByHost[$hostId]) ? $servicesByHost[$hostId] : []);
// get downtimes for host
$downtimes = $this->findDowntimes($hostId, 0);
$host->setDowntimes($downtimes);
// get active acknowledgment for host
if ($host->getAcknowledged()) {
$acknowledgements = $this->findAcknowledgements($hostId, 0);
if ($acknowledgements !== []) {
$host->setAcknowledgement($acknowledgements[0]);
}
}
return $host;
}
return null;
}
throw new \Exception(_('Bad SQL request'));
}
/**
* @inheritDoc
*/
public function findServicesByIdsForAdminUser(array $serviceIds): array
{
$services = [];
$collector = new StatementCollector();
if ($serviceIds === []) {
return $services;
}
$request
= 'SELECT DISTINCT 1 AS REALTIME, srv.*,
h.host_id AS `host_host_id`, h.name AS `host_name`, h.alias AS `host_alias`,
h.instance_id AS `host_poller_id`, srv.state AS `status_code`,
CASE
WHEN srv.state = 0 THEN "' . ResourceStatus::STATUS_NAME_OK . '"
WHEN srv.state = 1 THEN "' . ResourceStatus::STATUS_NAME_WARNING . '"
WHEN srv.state = 2 THEN "' . ResourceStatus::STATUS_NAME_CRITICAL . '"
WHEN srv.state = 3 THEN "' . ResourceStatus::STATUS_NAME_UNKNOWN . '"
WHEN srv.state = 4 THEN "' . ResourceStatus::STATUS_NAME_PENDING . '"
END AS `status_name`,
CASE
WHEN srv.state = 0 THEN ' . ResourceStatus::SEVERITY_OK . '
WHEN srv.state = 1 THEN ' . ResourceStatus::SEVERITY_MEDIUM . '
WHEN srv.state = 2 THEN ' . ResourceStatus::SEVERITY_HIGH . '
WHEN srv.state = 3 THEN ' . ResourceStatus::SEVERITY_LOW . '
WHEN srv.state = 4 THEN ' . ResourceStatus::SEVERITY_PENDING . '
END AS `status_severity_code`
FROM `:dbstg`.services srv
LEFT JOIN `:dbstg`.hosts h
ON h.host_id = srv.host_id
WHERE srv.enabled = \'1\'
AND h.enabled = \'1\'';
$idsListKey = [];
foreach ($serviceIds as $index => $hostServiceIds) {
$hostKey = ":host_id{$index}";
$hostIdsListKey[] = $hostKey;
$serviceKey = ":service_id{$index}";
$serviceIdsListKey[] = $serviceKey;
$collector->addValue($serviceKey, $hostServiceIds['service_id'], \PDO::PARAM_INT);
$collector->addValue($hostKey, $hostServiceIds['host_id'], \PDO::PARAM_INT);
}
$request .= ' AND srv.service_id IN (' . implode(',', $serviceIdsListKey) . ')';
$request .= ' AND srv.host_id IN (' . implode(',', $hostIdsListKey) . ')';
$request .= ' GROUP BY srv.service_id';
$request = $this->translateDbName($request);
$statement = $this->db->prepare($request);
$collector->bind($statement);
$statement->execute();
while (false !== ($row = $statement->fetch(\PDO::FETCH_ASSOC))) {
$service = EntityCreator::createEntityByArray(
Service::class,
$row
);
$service->setHost(
EntityCreator::createEntityByArray(Host::class, $row, 'host_')
);
$services[] = $service;
}
return $services;
}
/**
* @inheritDoc
*/
public function findHostsByIdsForAdminUser(array $hostIds): array
{
$hosts = [];
if ($hostIds === []) {
return $hosts;
}
$collector = new StatementCollector();
$request
= 'SELECT DISTINCT 1 AS REALTIME, h.*,
i.name AS poller_name,
IF (h.display_name LIKE \'_Module_Meta%\', \'Meta\', h.display_name) AS display_name,
IF (h.display_name LIKE \'_Module_Meta%\', \'0\', h.state) AS state
FROM `:dbstg`.`instances` i
INNER JOIN `:dbstg`.`hosts` h
ON h.instance_id = i.instance_id
AND h.enabled = \'1\'
AND h.name NOT LIKE \'_Module_BAM%\'';
$idsListKey = [];
foreach ($hostIds as $index => $id) {
$key = ":id{$index}";
$idsListKey[] = $key;
$collector->addValue($key, $id, \PDO::PARAM_INT);
}
$request .= ' WHERE h.host_id IN (' . implode(',', $idsListKey) . ')';
$request = $this->translateDbName($request);
$statement = $this->db->prepare($request);
$collector->bind($statement);
$statement->execute();
while (false !== ($row = $statement->fetch(\PDO::FETCH_ASSOC))) {
$hosts[] = EntityCreator::createEntityByArray(
Host::class,
$row
);
}
return $hosts;
}
/**
* @inheritDoc
*/
public function findHostsByIdsForNonAdminUser(array $hostIds): array
{
$hosts = [];
if ($hostIds === []) {
return $hosts;
}
$collector = new StatementCollector();
$accessGroupFilter
= ' INNER JOIN `:dbstg`.`centreon_acl` acl
ON acl.host_id = h.host_id
AND 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 DISTINCT 1 AS REALTIME, h.*,
i.name AS poller_name,
IF (h.display_name LIKE \'_Module_Meta%\', \'Meta\', h.display_name) AS display_name,
IF (h.display_name LIKE \'_Module_Meta%\', \'0\', h.state) AS state
FROM `:dbstg`.`instances` i
INNER JOIN `:dbstg`.`hosts` h
ON h.instance_id = i.instance_id
AND h.enabled = \'1\'
AND h.name NOT LIKE \'_Module_BAM%\''
. $accessGroupFilter;
$idsListKey = [];
foreach ($hostIds as $index => $id) {
$key = ":id{$index}";
$idsListKey[] = $key;
$collector->addValue($key, $id, \PDO::PARAM_INT);
}
$request .= ' WHERE h.host_id IN (' . implode(',', $idsListKey) . ')';
$request = $this->translateDbName($request);
$statement = $this->db->prepare($request);
$collector->bind($statement);
$statement->execute();
while (false !== ($row = $statement->fetch(\PDO::FETCH_ASSOC))) {
$hosts[] = EntityCreator::createEntityByArray(
Host::class,
$row
);
}
return $hosts;
}
/**
* @inheritDoc
*/
public function findOneService(int $hostId, int $serviceId): ?Service
{
if ($this->hasNotEnoughRightsToContinue()) {
return null;
}
$accessGroupFilter = '';
if ($this->isAdmin() === false) {
$accessGroupIds = array_map(
function ($accessGroup) {
return $accessGroup->getId();
},
$this->accessGroups
);
$accessGroupFilter = ' INNER JOIN `:dbstg`.`centreon_acl` acl
ON acl.host_id = h.host_id
AND acl.service_id = srv.service_id
AND acl.group_id IN (' . implode(',', $accessGroupIds) . ') ';
}
$request
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | true |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Infrastructure/Monitoring/MetaService/Repository/MetaServiceMetricRepositoryRDB.php | centreon/src/Centreon/Infrastructure/Monitoring/MetaService/Repository/MetaServiceMetricRepositoryRDB.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Monitoring\MetaService\Repository;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Monitoring\MetaService\Interfaces\MetaServiceMetric\MetaServiceMetricRepositoryInterface;
use Centreon\Domain\RequestParameters\RequestParameters;
use Centreon\Infrastructure\DatabaseConnection;
use Centreon\Infrastructure\Monitoring\MetaService\Repository\Model\MetaServiceMetricFactoryRdb;
use Centreon\Infrastructure\Repository\AbstractRepositoryDRB;
use Centreon\Infrastructure\RequestParameters\SqlRequestParametersTranslator;
/**
* This class is designed to represent the MariaDb repository to manage meta service metrics.
*
* @package Centreon\Infrastructure\Monitoring\MetaService\Repository
*/
class MetaServiceMetricRepositoryRDB extends AbstractRepositoryDRB implements
MetaServiceMetricRepositoryInterface
{
/** @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 findByMetaIdAndContact(int $metaId, ContactInterface $contact): ?array
{
return $this->findMetricsRequest($metaId, $contact->getId());
}
/**
* @inheritDoc
*/
public function findByMetaId(int $metaId): ?array
{
return $this->findMetricsRequest($metaId, null);
}
/**
* @inheritDoc
*/
public function findByContactAndSqlRegexp(
string $metricName,
string $regexpString,
ContactInterface $contact,
): ?array {
return $this->findMetricsBySqlRegexpRequest($metricName, $regexpString, $contact->getId());
}
/**
* @inheritDoc
*/
public function findBySqlRegexp(string $metricName, string $regexpString): ?array
{
return $this->findMetricsBySqlRegexpRequest($metricName, $regexpString, null);
}
private function findMetricsRequest(int $metaId, ?int $contactId): array
{
$this->sqlRequestTranslator->setConcordanceArray([
'id' => 'msr.metric_id',
'name' => 'm.metric_name',
'service_description' => 'idd.service_description',
'host_name' => 'idd.host_name',
]);
$request = 'SELECT SQL_CALC_FOUND_ROWS
1 AS REALTIME,
msr.metric_id,
msr.host_id,
idd.host_name,
idd.service_id,
idd.service_description,
m.metric_name,
m.unit_name,
m.current_value
FROM `:db`.`meta_service_relation` msr
INNER JOIN `:dbstg`.`metrics` m
ON msr.metric_id = m.metric_id
INNER JOIN `:dbstg`.`index_data` idd
ON m.index_id = idd.id';
if ($contactId !== null) {
$request .= ' INNER JOIN `:db`.acl_resources_host_relations arhr
ON msr.host_id = arhr.host_host_id
INNER JOIN `:db`.acl_resources res
ON arhr.acl_res_id = res.acl_res_id
INNER JOIN `:db`.acl_res_group_relations argr
ON res.acl_res_id = argr.acl_res_id
INNER JOIN `:db`.acl_groups ag
ON argr.acl_group_id = ag.acl_group_id
LEFT JOIN `:db`.acl_group_contacts_relations agcr
ON ag.acl_group_id = agcr.acl_group_id
AND agcr.contact_contact_id = :contact_id
LEFT JOIN `:db`.acl_group_contactgroups_relations agcgr
ON ag.acl_group_id = agcgr.acl_group_id
LEFT JOIN `:db`.contactgroup_contact_relation cgcr
ON cgcr.contactgroup_cg_id = agcgr.cg_cg_id
AND cgcr.contact_contact_id = :contact_id';
}
$request = $this->translateDbName($request);
// Search
$searchRequest = $this->sqlRequestTranslator->translateSearchParameterToSql();
$request .= ! is_null($searchRequest)
? $searchRequest . ' AND msr.meta_id = :id'
: ' WHERE msr.meta_id = :id';
// Sort
$sortRequest = $this->sqlRequestTranslator->translateSortParameterToSql();
$request .= ! is_null($sortRequest)
? $sortRequest
: ' ORDER BY m.metric_name ASC';
// Pagination
$request .= $this->sqlRequestTranslator->translatePaginationToSql();
$statement = $this->db->prepare($request);
$statement->bindValue(':id', $metaId, \PDO::PARAM_INT);
if ($contactId !== null) {
$statement->bindValue(':contact_id', $contactId, \PDO::PARAM_INT);
}
$statement->execute();
$result = $this->db->query('SELECT FOUND_ROWS() AS REALTIME');
if ($result !== false && ($total = $result->fetchColumn()) !== false) {
$this->sqlRequestTranslator->getRequestParameters()->setTotal((int) $total);
}
$metaServicesMetrics = [];
while (($record = $statement->fetch(\PDO::FETCH_ASSOC)) !== false) {
$metaServicesMetrics[] = MetaServiceMetricFactoryRdb::create($record);
}
return $metaServicesMetrics;
}
private function findMetricsBySqlRegexpRequest(string $metricName, string $regexpString, ?int $contactId): array
{
$this->sqlRequestTranslator->setConcordanceArray([
'id' => 'm.metric_id',
'name' => 'm.metric_name',
'service_description' => 'idd.service_description',
'host_name' => 'idd.host_name',
]);
$request = 'SELECT SQL_CALC_FOUND_ROWS
1 AS REALTIME,
m.metric_id,
idd.host_id,
idd.host_name,
idd.service_id,
idd.service_description,
m.metric_name,
m.unit_name,
m.current_value
FROM `:dbstg`.metrics m, `:dbstg`.index_data idd';
// apply ACL filter
if ($contactId !== null) {
$request .= ' INNER JOIN `:db`.acl_resources_host_relations arhr
ON idd.host_id = arhr.host_host_id
INNER JOIN `:db`.acl_resources res
ON arhr.acl_res_id = res.acl_res_id
INNER JOIN `:db`.acl_res_group_relations argr
ON res.acl_res_id = argr.acl_res_id
INNER JOIN `:db`.acl_groups ag
ON argr.acl_group_id = ag.acl_group_id
LEFT JOIN `:db`.acl_group_contacts_relations agcr
ON ag.acl_group_id = agcr.acl_group_id
AND agcr.contact_contact_id = :contact_id
LEFT JOIN `:db`.acl_group_contactgroups_relations agcgr
ON ag.acl_group_id = agcgr.acl_group_id
LEFT JOIN `:db`.contactgroup_contact_relation cgcr
ON cgcr.contactgroup_cg_id = agcgr.cg_cg_id
AND cgcr.contact_contact_id = :contact_id';
}
$request = $this->translateDbName($request);
// Search
$searchRequest = $this->sqlRequestTranslator->translateSearchParameterToSql();
$request .= ! is_null($searchRequest)
? $searchRequest . ' AND idd.service_description LIKE :regexp AND idd.id = m.index_id'
: ' WHERE idd.service_description LIKE :regexp AND idd.id = m.index_id';
$request .= ' AND m.metric_name = :metricName';
// Sort
$sortRequest = $this->sqlRequestTranslator->translateSortParameterToSql();
$request .= ! is_null($sortRequest)
? $sortRequest
: ' ORDER BY m.metric_name ASC';
// Pagination
$request .= $this->sqlRequestTranslator->translatePaginationToSql();
$statement = $this->db->prepare($request);
$statement->bindValue(':regexp', $regexpString, \PDO::PARAM_STR);
$statement->bindValue(':metricName', $metricName, \PDO::PARAM_STR);
if ($contactId !== null) {
$statement->bindValue(':contact_id', $contactId, \PDO::PARAM_INT);
}
$statement->execute();
$result = $this->db->query('SELECT FOUND_ROWS() AS REALTIME');
if ($result !== false && ($total = $result->fetchColumn()) !== false) {
$this->sqlRequestTranslator->getRequestParameters()->setTotal((int) $total);
}
$metaServicesMetrics = [];
while (($record = $statement->fetch(\PDO::FETCH_ASSOC)) !== false) {
$metaServicesMetrics[] = MetaServiceMetricFactoryRdb::create($record);
}
return $metaServicesMetrics;
}
}
| 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/Monitoring/MetaService/Repository/Model/MetaServiceMetricFactoryRdb.php | centreon/src/Centreon/Infrastructure/Monitoring/MetaService/Repository/Model/MetaServiceMetricFactoryRdb.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Monitoring\MetaService\Repository\Model;
use Centreon\Domain\Monitoring\MetaService\Model\MetaServiceMetric;
use Centreon\Domain\Monitoring\Resource;
/**
* This class is designed to provide a way to create the MetaServiceMetric entity from the database.
*
* @package Centreon\Infrastructure\Monitoring\MetaService\Repository\Model
*/
class MetaServiceMetricFactoryRdb
{
/**
* Create a MetaServiceMetric entity from database data.
*
* @param array<string, mixed> $data
* @throws \Assert\AssertionFailedException
* @return MetaServiceMetric
*/
public static function create(array $data): MetaServiceMetric
{
$metaServiceMetric = (new MetaServiceMetric($data['metric_name']))
->setId((int) $data['metric_id'])
->setUnit($data['unit_name'])
->setValue((float) $data['current_value']);
/**
* Create the Service Resource type
*/
$resource = (new Resource())
->setId((int) $data['service_id'])
->setName($data['service_description'])
->setType(Resource::TYPE_SERVICE);
$parentResource = (new Resource())
->setId((int) $data['host_id'])
->setName($data['host_name'])
->setType(Resource::TYPE_HOST);
$resource->setParent($parentResource);
$metaServiceMetric->setResource($resource);
return $metaServiceMetric;
}
}
| 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/Monitoring/MetaService/API/Model/MetaServiceMetricFactoryV21.php | centreon/src/Centreon/Infrastructure/Monitoring/MetaService/API/Model/MetaServiceMetricFactoryV21.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Monitoring\MetaService\API\Model;
use Centreon\Domain\Monitoring\MetaService\UseCase\V21\MetaServiceMetric\FindMetaServiceMetricsResponse;
/**
* This class is designed to create the MetaServiceMetricV21 entity
*
* @package Centreon\Infrastructure\Monitoring\MetaService\API\Model
*/
class MetaServiceMetricFactoryV21
{
/**
* @param FindMetaServiceMetricsResponse $response
* @return \stdClass[]
*/
public static function createFromResponse(
FindMetaServiceMetricsResponse $response,
): array {
$metaServiceMetrics = [];
foreach ($response->getMetaServiceMetrics() as $metaServiceMetric) {
$newMetaServiceMetric = self::createEmptyClass();
$newMetaServiceMetric->id = $metaServiceMetric['id'];
$newMetaServiceMetric->name = $metaServiceMetric['name'];
$newMetaServiceMetric->unit = $metaServiceMetric['unit'];
$newMetaServiceMetric->value = $metaServiceMetric['value'];
$newMetaServiceMetric->resource = $metaServiceMetric['resource'];
$metaServiceMetrics[] = $newMetaServiceMetric;
}
return $metaServiceMetrics;
}
/**
* @return \stdClass
*/
private static function createEmptyClass(): \stdClass
{
return new class () extends \stdClass {
public $id;
public $name;
public $unit;
public $value;
public $resource;
};
}
}
| 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/Monitoring/Timeline/TimelineRepositoryRDB.php | centreon/src/Centreon/Infrastructure/Monitoring/Timeline/TimelineRepositoryRDB.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Monitoring\Timeline;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Entity\EntityCreator;
use Centreon\Domain\Monitoring\Host;
use Centreon\Domain\Monitoring\ResourceStatus;
use Centreon\Domain\Monitoring\Service;
use Centreon\Domain\Monitoring\Timeline\Interfaces\TimelineRepositoryInterface;
use Centreon\Domain\Monitoring\Timeline\TimelineContact;
use Centreon\Domain\Monitoring\Timeline\TimelineEvent;
use Centreon\Domain\RequestParameters\RequestParameters;
use Centreon\Infrastructure\CentreonLegacyDB\StatementCollector;
use Centreon\Infrastructure\DatabaseConnection;
use Centreon\Infrastructure\Repository\AbstractRepositoryDRB;
use Centreon\Infrastructure\RequestParameters\Interfaces\NormalizerInterface;
use Centreon\Infrastructure\RequestParameters\SqlRequestParametersTranslator;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
/**
* Database repository for timeline events.
*
* @package Centreon\Infrastructure\Monitoring
*/
final class TimelineRepositoryRDB extends AbstractRepositoryDRB implements TimelineRepositoryInterface
{
/** @var AccessGroup[] List of access group used to filter the requests */
private $accessGroups = [];
/** @var SqlRequestParametersTranslator */
private $sqlRequestTranslator;
/** @var ContactInterface */
private $contact;
public function __construct(DatabaseConnection $pdo)
{
$this->db = $pdo;
}
/**
* Initialized by the dependency injector.
*
* @param SqlRequestParametersTranslator $sqlRequestTranslator
*/
public function setSqlRequestTranslator(SqlRequestParametersTranslator $sqlRequestTranslator): void
{
$this->sqlRequestTranslator = $sqlRequestTranslator;
$this->sqlRequestTranslator
->getRequestParameters()
->setConcordanceStrictMode(
RequestParameters::CONCORDANCE_MODE_STRICT
);
}
/**
* @inheritDoc
*/
public function filterByAccessGroups(?array $accessGroups): TimelineRepositoryInterface
{
$this->accessGroups = $accessGroups;
return $this;
}
/**
* @inheritDoc
*/
public function findTimelineEventsByHost(Host $host): array
{
return $this->findTimelineEvents($host->getId(), null);
}
/**
* @inheritDoc
*/
public function findTimelineEventsByService(Service $service): array
{
return $this->findTimelineEvents($service->getHost()->getId(), $service->getId());
}
/**
* {@inheritDoc}
*/
public function setContact(ContactInterface $contact): TimelineRepositoryInterface
{
$this->contact = $contact;
return $this;
}
/**
* find timeline events
*
* @param int $hostId
* @param int|null $serviceId
* @return TimelineEvent[]
*/
private function findTimelineEvents(int $hostId, ?int $serviceId): array
{
$timelineEvents = [];
if (! $this->hasEnoughRightsToContinue()) {
return $timelineEvents;
}
$this->sqlRequestTranslator->setConcordanceArray([
'type' => 'log.type',
'content' => 'log.content',
'date' => 'log.date',
]);
$collector = new StatementCollector();
$request = '
SELECT SQL_CALC_FOUND_ROWS
1 AS REALTIME,
log.id,
log.type,
log.date,
log.start_date,
log.end_date,
log.content,
log.contact_id,
log.contact_name,
log.status_code,
log.status_name,
log.status_severity_code,
log.tries
FROM (
';
$subRequests = [];
// status events
$subRequests[] = $this->prepareQueryForTimelineStatusEvents($collector, $hostId, $serviceId);
// notification events
$subRequests[] = $this->prepareQueryForTimelineNotificationEvents($collector, $hostId, $serviceId);
// downtime events
$subRequests[] = $this->prepareQueryForTimelineDowntimeEvents($collector, $hostId, $serviceId);
// acknowledgement events
$subRequests[] = $this->prepareQueryForTimelineAcknowledgementEvents($collector, $hostId, $serviceId);
// comment events
$subRequests[] = $this->prepareQueryForTimelineCommentEvents($collector, $hostId, $serviceId);
$request .= implode('UNION ALL ', $subRequests);
$request .= ') AS `log` ';
/**
* Here the search filter provides a date in ISO8601.
* But the date on which we do filter (stored as ctime) is a timestamp.
* Therefore we need to normalize the data provided in the search parameter
* and translate it into a timestamp filtering search.
*/
$this->sqlRequestTranslator->addNormalizer(
'date',
new class () implements NormalizerInterface {
public function normalize($valueToNormalize): int
{
return (new \Datetime($valueToNormalize))->getTimestamp();
}
}
);
// Search
$searchRequest = $this->sqlRequestTranslator->translateSearchParameterToSql();
$whereCondition = false;
if ($searchRequest !== null) {
$whereCondition = true;
$request .= $searchRequest;
}
// set ACL limitations
if (! $this->isAdmin()) {
$request .= ($whereCondition === true) ? ' AND ' : ' WHERE ';
$request .= $this->translateDbName(
'EXISTS (SELECT host_id FROM `:dbstg`.`centreon_acl` acl WHERE acl.host_id = :host_id'
);
$collector->addValue(':host_id', $hostId, \PDO::PARAM_INT);
if ($serviceId !== null) {
$request .= ' AND acl.service_id = :service_id';
$collector->addValue(':service_id', $serviceId, \PDO::PARAM_INT);
}
$request .= ' AND acl.group_id IN (' . $this->accessGroupIdToString($this->accessGroups) . ')) ';
}
// Sort
$request .= $this->sqlRequestTranslator->translateSortParameterToSql() ?: ' ORDER BY log.date DESC';
// Pagination
$request .= $this->sqlRequestTranslator->translatePaginationToSql();
$statement = $this->db->prepare($request);
foreach ($this->sqlRequestTranslator->getSearchValues() as $key => $data) {
$type = key($data);
$value = $data[$type];
$collector->addValue($key, $value, $type);
}
$collector->bind($statement);
$statement->execute();
$result = $this->db->query('SELECT FOUND_ROWS() AS REALTIME');
$this->sqlRequestTranslator->getRequestParameters()->setTotal(
(int) $result->fetchColumn()
);
while (false !== ($result = $statement->fetch(\PDO::FETCH_ASSOC))) {
$timelineEvent = EntityCreator::createEntityByArray(
TimelineEvent::class,
$result
);
if ($result['contact_name'] !== null) {
$timelineEvent->setContact(
EntityCreator::createEntityByArray(
TimelineContact::class,
$result,
'contact_'
)
);
}
if ($result['status_code'] !== null) {
$timelineEvent->setStatus(
EntityCreator::createEntityByArray(
ResourceStatus::class,
$result,
'status_'
)
);
}
$timelineEvents[] = $timelineEvent;
}
return $timelineEvents;
}
/**
* get subquery to find status events
*
* @param StatementCollector $collector
* @param int $hostId
* @param int|null $serviceId
* @return string subquery
*/
private function prepareQueryForTimelineStatusEvents(
StatementCollector $collector,
int $hostId,
?int $serviceId,
): string {
$request = $this->translateDbName("SELECT
l.log_id AS `id`,
'event' AS `type`,
l.ctime AS `date`,
NULL AS `start_date`,
NULL AS `end_date`,
l.output AS `content`,
NULL AS `contact_id`,
NULL AS `contact_name`,
l.status AS `status_code`,
CASE
WHEN l.status = 0 THEN :status_code_0
WHEN l.status = 1 THEN :status_code_1
WHEN l.status = 2 THEN :status_code_2
WHEN l.status = 3 THEN :status_code_3
WHEN l.status = 4 THEN :status_code_4
END AS `status_name`,
CASE
WHEN l.status = 0 THEN :status_severity_code_0
WHEN l.status = 1 THEN :status_severity_code_1
WHEN l.status = 2 THEN :status_severity_code_2
WHEN l.status = 3 THEN :status_severity_code_3
WHEN l.status = 4 THEN :status_severity_code_4
END AS `status_severity_code`,
l.retry AS `tries`
FROM `:dbstg`.`logs` l
WHERE l.host_id = :host_id
AND (l.service_id = " . ($serviceId !== null ? ':service_id)' : '0 OR l.service_id IS NULL)') . "
AND l.msg_type IN (0,1,8,9)
AND l.output NOT LIKE 'INITIAL % STATE:%'
AND l.instance_name != ''
");
$collector->addValue(':host_id', $hostId, \PDO::PARAM_INT);
if ($serviceId === null) {
$collector->addValue(':status_code_0', ResourceStatus::STATUS_NAME_UP, \PDO::PARAM_STR);
$collector->addValue(':status_code_1', ResourceStatus::STATUS_NAME_DOWN, \PDO::PARAM_STR);
$collector->addValue(':status_code_2', ResourceStatus::STATUS_NAME_UNREACHABLE, \PDO::PARAM_STR);
$collector->addValue(':status_code_3', ResourceStatus::STATUS_NAME_PENDING, \PDO::PARAM_STR);
$collector->addValue(':status_code_4', null, \PDO::PARAM_STR);
$collector->addValue(':status_severity_code_0', ResourceStatus::SEVERITY_OK, \PDO::PARAM_INT);
$collector->addValue(':status_severity_code_1', ResourceStatus::SEVERITY_HIGH, \PDO::PARAM_INT);
$collector->addValue(':status_severity_code_2', ResourceStatus::SEVERITY_LOW, \PDO::PARAM_INT);
$collector->addValue(':status_severity_code_3', ResourceStatus::SEVERITY_PENDING, \PDO::PARAM_INT);
$collector->addValue(':status_severity_code_4', null, \PDO::PARAM_INT);
} else {
$collector->addValue(':service_id', $serviceId, \PDO::PARAM_INT);
$collector->addValue(':status_code_0', ResourceStatus::STATUS_NAME_OK, \PDO::PARAM_STR);
$collector->addValue(':status_code_1', ResourceStatus::STATUS_NAME_WARNING, \PDO::PARAM_STR);
$collector->addValue(':status_code_2', ResourceStatus::STATUS_NAME_CRITICAL, \PDO::PARAM_STR);
$collector->addValue(':status_code_3', ResourceStatus::STATUS_NAME_UNKNOWN, \PDO::PARAM_STR);
$collector->addValue(':status_code_4', ResourceStatus::STATUS_NAME_PENDING, \PDO::PARAM_STR);
$collector->addValue(':status_severity_code_0', ResourceStatus::SEVERITY_OK, \PDO::PARAM_INT);
$collector->addValue(':status_severity_code_1', ResourceStatus::SEVERITY_MEDIUM, \PDO::PARAM_INT);
$collector->addValue(':status_severity_code_2', ResourceStatus::SEVERITY_HIGH, \PDO::PARAM_INT);
$collector->addValue(':status_severity_code_3', ResourceStatus::SEVERITY_LOW, \PDO::PARAM_INT);
$collector->addValue(':status_severity_code_4', ResourceStatus::SEVERITY_PENDING, \PDO::PARAM_INT);
}
return $request;
}
/**
* get subquery to find notification events
*
* @param StatementCollector $collector
* @param int $hostId
* @param int|null $serviceId
* @return string subquery
*/
private function prepareQueryForTimelineNotificationEvents(
StatementCollector $collector,
int $hostId,
?int $serviceId,
): string {
$request = $this->translateDbName("SELECT
l.log_id AS `id`,
'notification' AS `type`,
l.ctime AS `date`,
NULL AS `start_date`,
NULL AS `end_date`,
l.output AS `content`,
c.contact_id AS `contact_id`,
c.contact_alias AS `contact_name`,
l.status AS `status_code`,
CASE
WHEN l.status = 0 THEN :status_code_0
WHEN l.status = 1 THEN :status_code_1
WHEN l.status = 2 THEN :status_code_2
WHEN l.status = 3 THEN :status_code_3
WHEN l.status = 4 THEN :status_code_4
END AS `status_name`,
CASE
WHEN l.status = 0 THEN :status_severity_code_0
WHEN l.status = 1 THEN :status_severity_code_1
WHEN l.status = 2 THEN :status_severity_code_2
WHEN l.status = 3 THEN :status_severity_code_3
WHEN l.status = 4 THEN :status_severity_code_4
END AS `status_severity_code`,
NULL AS `tries`
FROM `:dbstg`.`logs` l
LEFT JOIN `:db`.contact AS `c` ON c.contact_name = l.notification_contact
WHERE l.host_id = :host_id
AND (l.service_id = " . ($serviceId !== null ? ':service_id)' : '0 OR l.service_id IS NULL)') . '
AND l.msg_type IN (2,3)
');
$collector->addValue(':host_id', $hostId, \PDO::PARAM_INT);
if ($serviceId === null) {
$collector->addValue(':status_code_0', ResourceStatus::STATUS_NAME_UP, \PDO::PARAM_STR);
$collector->addValue(':status_code_1', ResourceStatus::STATUS_NAME_DOWN, \PDO::PARAM_STR);
$collector->addValue(':status_code_2', ResourceStatus::STATUS_NAME_UNREACHABLE, \PDO::PARAM_STR);
$collector->addValue(':status_code_3', ResourceStatus::STATUS_NAME_PENDING, \PDO::PARAM_STR);
$collector->addValue(':status_code_4', null, \PDO::PARAM_STR);
$collector->addValue(':status_severity_code_0', ResourceStatus::SEVERITY_OK, \PDO::PARAM_INT);
$collector->addValue(':status_severity_code_1', ResourceStatus::SEVERITY_HIGH, \PDO::PARAM_INT);
$collector->addValue(':status_severity_code_2', ResourceStatus::SEVERITY_LOW, \PDO::PARAM_INT);
$collector->addValue(':status_severity_code_3', ResourceStatus::SEVERITY_PENDING, \PDO::PARAM_INT);
$collector->addValue(':status_severity_code_4', null, \PDO::PARAM_INT);
} else {
$collector->addValue(':service_id', $serviceId, \PDO::PARAM_INT);
$collector->addValue(':status_code_0', ResourceStatus::STATUS_NAME_OK, \PDO::PARAM_STR);
$collector->addValue(':status_code_1', ResourceStatus::STATUS_NAME_WARNING, \PDO::PARAM_STR);
$collector->addValue(':status_code_2', ResourceStatus::STATUS_NAME_CRITICAL, \PDO::PARAM_STR);
$collector->addValue(':status_code_3', ResourceStatus::STATUS_NAME_UNKNOWN, \PDO::PARAM_STR);
$collector->addValue(':status_code_4', ResourceStatus::STATUS_NAME_PENDING, \PDO::PARAM_STR);
$collector->addValue(':status_severity_code_0', ResourceStatus::SEVERITY_OK, \PDO::PARAM_INT);
$collector->addValue(':status_severity_code_1', ResourceStatus::SEVERITY_MEDIUM, \PDO::PARAM_INT);
$collector->addValue(':status_severity_code_2', ResourceStatus::SEVERITY_HIGH, \PDO::PARAM_INT);
$collector->addValue(':status_severity_code_3', ResourceStatus::SEVERITY_LOW, \PDO::PARAM_INT);
$collector->addValue(':status_severity_code_4', ResourceStatus::SEVERITY_PENDING, \PDO::PARAM_INT);
}
return $request;
}
/**
* get subquery to find downtime events
*
* @param StatementCollector $collector
* @param int $hostId
* @param int|null $serviceId
* @return string subquery
*/
private function prepareQueryForTimelineDowntimeEvents(
StatementCollector $collector,
int $hostId,
?int $serviceId,
): string {
$request = $this->translateDbName("SELECT
d.downtime_id AS `id`,
'downtime' AS `type`,
d.actual_start_time AS `date`,
d.actual_start_time AS `start_date`,
d.actual_end_time AS `end_date`,
d.comment_data AS `content`,
c.contact_id AS `contact_id`,
d.author AS `contact_name`,
NULL AS `status_code`,
NULL AS `status_name`,
NULL AS `status_severity_code`,
NULL AS `tries`
FROM `:dbstg`.`downtimes` d
LEFT JOIN `:db`.contact AS `c` ON c.contact_alias = d.author
WHERE d.host_id = :host_id
AND (d.service_id = " . ($serviceId !== null ? ':service_id)' : '0 OR d.service_id IS NULL)') . '
AND d.actual_start_time < ' . time() . '
');
$collector->addValue(':host_id', $hostId, \PDO::PARAM_INT);
if ($serviceId !== null) {
$collector->addValue(':service_id', $serviceId, \PDO::PARAM_INT);
}
return $request;
}
/**
* get subquery to find acknowledgement events
*
* @param StatementCollector $collector
* @param int $hostId
* @param int|null $serviceId
* @return string subquery
*/
private function prepareQueryForTimelineAcknowledgementEvents(
StatementCollector $collector,
int $hostId,
?int $serviceId,
): string {
$request = $this->translateDbName("SELECT
a.acknowledgement_id AS `id`,
'acknowledgement' AS `type`,
a.entry_time AS `date`,
NULL AS `start_date`,
NULL AS `end_date`,
a.comment_data AS `content`,
c.contact_id AS `contact_id`,
a.author AS `contact_name`,
NULL AS `status_code`,
NULL AS `status_name`,
NULL AS `status_severity_code`,
NULL AS `tries`
FROM `:dbstg`.`acknowledgements` a
LEFT JOIN `:db`.contact AS `c` ON c.contact_alias = a.author
WHERE a.host_id = :host_id
AND (a.service_id = " . ($serviceId !== null ? ':service_id)' : '0 OR a.service_id IS NULL)') . '
');
$collector->addValue(':host_id', $hostId, \PDO::PARAM_INT);
if ($serviceId !== null) {
$collector->addValue(':service_id', $serviceId, \PDO::PARAM_INT);
}
return $request;
}
/**
* get subquery to find acknowledgement events
*
* @param StatementCollector $collector
* @param int $hostId
* @param int|null $serviceId
* @return string subquery
*/
private function prepareQueryForTimelineCommentEvents(
StatementCollector $collector,
int $hostId,
?int $serviceId,
): string {
$request = $this->translateDbName("SELECT
c.comment_id AS `id`,
'comment' AS `type`,
c.entry_time AS `date`,
NULL AS `start_date`,
NULL AS `end_date`,
c.data AS `content`,
ct.contact_id AS `contact_id`,
c.author AS `contact_name`,
NULL AS `status_code`,
NULL AS `status_name`,
NULL AS `status_severity_code`,
NULL AS `tries`
FROM `:dbstg`.`comments` c
LEFT JOIN `:db`.contact AS `ct` ON ct.contact_alias = c.author
WHERE c.host_id = :host_id
AND (c.service_id = " . ($serviceId !== null ? ':service_id)' : '0 OR c.service_id IS NULL)') . '
AND source = 1 AND c.deletion_time IS NULL
');
$collector->addValue(':host_id', $hostId, \PDO::PARAM_INT);
if ($serviceId !== null) {
$collector->addValue(':service_id', $serviceId, \PDO::PARAM_INT);
}
return $request;
}
/**
* Check if contact is an admin
*
* @return bool
*/
private function isAdmin(): bool
{
return ($this->contact !== null)
? $this->contact->isAdmin()
: false;
}
/**
* check if contact has enough rights to get events
*
* @return bool
*/
private function hasEnoughRightsToContinue(): bool
{
return ($this->contact !== null)
? ($this->contact->isAdmin() || count($this->accessGroups) > 0)
: count($this->accessGroups) > 0;
}
}
| 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/Monitoring/Metric/MetricRepositoryLegacy.php | centreon/src/Centreon/Infrastructure/Monitoring/Metric/MetricRepositoryLegacy.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Monitoring\Metric;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Monitoring\Metric\Interfaces\MetricRepositoryInterface;
use Centreon\Domain\Monitoring\Service;
/**
* Repository to get metrics data from legacy centreon classes
*
* @package Centreon\Infrastructure\Monitoring\Metric
*/
final class MetricRepositoryLegacy implements MetricRepositoryInterface
{
/** @var ContactInterface */
private $contact;
/** @var \CentreonDB */
private $dbStorage;
/**
* MetricRepositoryLegacy constructor.
*/
public function __construct()
{
global $pearDB;
$pearDB = new \CentreonDB('centreon', 3);
$this->dbStorage = new \CentreonDB('centstorage', 3);
}
/**
* @inheritDoc
*/
public function setContact(ContactInterface $contact): MetricRepositoryInterface
{
$this->contact = $contact;
return $this;
}
/**
* @inheritDoc
*/
public function findMetricsByService(Service $service, \DateTimeInterface $start, \DateTimeInterface $end): array
{
$graph = new \CentreonGraphNg($this->contact->getId());
$graph->addServiceMetrics($service->getHost()->getId(), $service->getId());
return $graph->getGraph($start->getTimestamp(), $end->getTimestamp());
}
/**
* @inheritDoc
*/
public function findStatusByService(Service $service, \DateTimeInterface $start, \DateTimeInterface $end): array
{
$indexData = \CentreonGraphStatus::getIndexId(
$service->getHost()->getId(),
$service->getId(),
$this->dbStorage
);
$graph = new \CentreonGraphStatus($indexData, $start->getTimestamp(), $end->getTimestamp());
return $graph->getData();
}
}
| 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/Monitoring/ServiceGroup/ServiceGroupRepositoryRDB.php | centreon/src/Centreon/Infrastructure/Monitoring/ServiceGroup/ServiceGroupRepositoryRDB.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Monitoring\ServiceGroup;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Entity\EntityCreator;
use Centreon\Domain\Monitoring\ServiceGroup;
use Centreon\Domain\Monitoring\ServiceGroup\Interfaces\ServiceGroupRepositoryInterface;
use Centreon\Infrastructure\DatabaseConnection;
use Centreon\Infrastructure\Repository\AbstractRepositoryDRB;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
/**
* Database repository for the real time monitoring of servicegroups.
*
* @package Centreon\Infrastructure\Monitoring
*/
final class ServiceGroupRepositoryRDB extends AbstractRepositoryDRB implements ServiceGroupRepositoryInterface
{
/** @var AccessGroup[] List of access group used to filter the requests */
private $accessGroups = [];
/** @var ContactInterface */
private $contact;
/**
* MonitoringRepositoryRDB constructor.
*
* @param DatabaseConnection $pdo
*/
public function __construct(DatabaseConnection $pdo)
{
$this->db = $pdo;
}
/**
* @inheritDoc
*/
public function filterByAccessGroups(?array $accessGroups): ServiceGroupRepositoryInterface
{
$this->accessGroups = $accessGroups;
return $this;
}
/**
* @inheritDoc
*/
public function findServiceGroupsByIds(array $serviceGroupIds): array
{
$serviceGroups = [];
if ($this->hasNotEnoughRightsToContinue() || $serviceGroupIds === []) {
return $serviceGroups;
}
$bindValues = [];
$subRequest = '';
if (! $this->isAdmin()) {
$bindValues[':contact_id'] = [\PDO::PARAM_INT => $this->contact->getId()];
// Not an admin, we must to filter on contact
$subRequest
.= ' INNER JOIN `:db`.acl_resources_sg_relations sgr
ON sgr.sg_id = sg.servicegroup_id
INNER JOIN `:db`.acl_resources res
ON res.acl_res_id = sgr.acl_res_id
AND res.acl_res_activate = \'1\'
INNER JOIN `:db`.acl_res_group_relations rgr
ON rgr.acl_res_id = res.acl_res_id
INNER JOIN `:db`.acl_groups grp
ON grp.acl_group_id IN ('
. $this->accessGroupIdToString($this->accessGroups)
. ') AND grp.acl_group_activate = \'1\'
AND grp.acl_group_id = rgr.acl_group_id
LEFT JOIN `:db`.acl_group_contacts_relations gcr
ON gcr.acl_group_id = grp.acl_group_id
LEFT JOIN `:db`.acl_group_contactgroups_relations gcgr
ON gcgr.acl_group_id = grp.acl_group_id
LEFT JOIN `:db`.contactgroup_contact_relation cgcr
ON cgcr.contactgroup_cg_id = gcgr.cg_cg_id
AND cgcr.contact_contact_id = :contact_id
OR gcr.contact_contact_id = :contact_id';
}
$request = 'SELECT DISTINCT 1 AS REALTIME, sg.* FROM `:dbstg`.`servicegroups` sg '
. $subRequest;
$request = $this->translateDbName($request);
$bindServiceGroupIds = [];
foreach ($serviceGroupIds as $index => $serviceGroupId) {
$bindServiceGroupIds[':service_group_id_' . $index] = [\PDO::PARAM_INT => $serviceGroupId];
}
$bindValues = array_merge($bindValues, $bindServiceGroupIds);
$request .= ' WHERE sg.servicegroup_id IN (' . implode(',', array_keys($bindServiceGroupIds)) . ')';
// Sort
$request .= ' ORDER BY sg.name ASC';
$statement = $this->db->prepare($request);
// We bind extra parameters according to access rights
foreach ($bindValues as $key => $data) {
$type = key($data);
$value = $data[$type];
$statement->bindValue($key, $value, $type);
}
$statement->execute();
while (false !== ($result = $statement->fetch(\PDO::FETCH_ASSOC))) {
$serviceGroups[] = EntityCreator::createEntityByArray(
ServiceGroup::class,
$result
);
}
return $serviceGroups;
}
/**
* @inheritDoc
*/
public function findServiceGroupsByNames(array $serviceGroupNames): array
{
$serviceGroups = [];
if ($this->hasNotEnoughRightsToContinue() || $serviceGroupNames === []) {
return $serviceGroups;
}
$bindValues = [];
$subRequest = '';
if (! $this->isAdmin()) {
$bindValues[':contact_id'] = [\PDO::PARAM_INT => $this->contact->getId()];
// Not an admin, we must to filter on contact
$subRequest
.= ' INNER JOIN `:db`.acl_resources_sg_relations sgr
ON sgr.sg_id = sg.servicegroup_id
INNER JOIN `:db`.acl_resources res
ON res.acl_res_id = sgr.acl_res_id
AND res.acl_res_activate = \'1\'
INNER JOIN `:db`.acl_res_group_relations rgr
ON rgr.acl_res_id = res.acl_res_id
INNER JOIN `:db`.acl_groups grp
ON grp.acl_group_id IN ('
. $this->accessGroupIdToString($this->accessGroups)
. ') AND grp.acl_group_activate = \'1\'
AND grp.acl_group_id = rgr.acl_group_id
LEFT JOIN `:db`.acl_group_contacts_relations gcr
ON gcr.acl_group_id = grp.acl_group_id
LEFT JOIN `:db`.acl_group_contactgroups_relations gcgr
ON gcgr.acl_group_id = grp.acl_group_id
LEFT JOIN `:db`.contactgroup_contact_relation cgcr
ON cgcr.contactgroup_cg_id = gcgr.cg_cg_id
AND cgcr.contact_contact_id = :contact_id
OR gcr.contact_contact_id = :contact_id';
}
$request = 'SELECT DISTINCT sg.* FROM `:dbstg`.`servicegroups` sg ' . $subRequest;
$request = $this->translateDbName($request);
$bindServiceGroupNames = [];
foreach ($serviceGroupNames as $index => $serviceGroupName) {
$bindServiceGroupNames[':service_group_name_' . $index] = [\PDO::PARAM_STR => $serviceGroupName];
}
$bindValues = array_merge($bindValues, $bindServiceGroupNames);
$request .= ' WHERE sg.name IN (' . implode(',', array_keys($bindServiceGroupNames)) . ')';
// Sort
$request .= ' ORDER BY sg.name ASC';
$statement = $this->db->prepare($request);
// We bind extra parameters according to access rights
foreach ($bindValues as $key => $data) {
$type = key($data);
$value = $data[$type];
$statement->bindValue($key, $value, $type);
}
$statement->execute();
while (false !== ($result = $statement->fetch(\PDO::FETCH_ASSOC))) {
$serviceGroups[] = EntityCreator::createEntityByArray(
ServiceGroup::class,
$result
);
}
return $serviceGroups;
}
/**
* {@inheritDoc}
*/
public function setContact(ContactInterface $contact): ServiceGroupRepositoryInterface
{
$this->contact = $contact;
return $this;
}
/**
* Check if the contact is admin
*
* @return bool
*/
private function isAdmin(): bool
{
return ($this->contact !== null)
? $this->contact->isAdmin()
: false;
}
/**
* @return bool return FALSE 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;
}
}
| 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/Monitoring/HostGroup/HostGroupRepositoryRDB.php | centreon/src/Centreon/Infrastructure/Monitoring/HostGroup/HostGroupRepositoryRDB.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Monitoring\HostGroup;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Entity\EntityCreator;
use Centreon\Domain\Monitoring\HostGroup;
use Centreon\Domain\Monitoring\HostGroup\Interfaces\HostGroupRepositoryInterface;
use Centreon\Infrastructure\DatabaseConnection;
use Centreon\Infrastructure\Repository\AbstractRepositoryDRB;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
/**
* Database repository for the real time monitoring of hostgroups.
*
* @package Centreon\Infrastructure\Monitoring
*/
final class HostGroupRepositoryRDB extends AbstractRepositoryDRB implements HostGroupRepositoryInterface
{
/** @var AccessGroup[] List of access group used to filter the requests */
private $accessGroups = [];
/** @var ContactInterface */
private $contact;
/**
* MonitoringRepositoryRDB constructor.
*
* @param DatabaseConnection $pdo
*/
public function __construct(DatabaseConnection $pdo)
{
$this->db = $pdo;
}
/**
* @inheritDoc
*/
public function filterByAccessGroups(?array $accessGroups): HostGroupRepositoryInterface
{
$this->accessGroups = $accessGroups;
return $this;
}
/**
* @inheritDoc
*/
public function findHostGroupsByNames(array $hostGroupNames): array
{
$hostGroups = [];
if ($this->hasNotEnoughRightsToContinue() || $hostGroupNames === []) {
return $hostGroups;
}
$bindValues = [];
$subRequest = '';
if (! $this->isAdmin()) {
$bindValues[':contact_id'] = [\PDO::PARAM_INT => $this->contact->getId()];
// Not an admin, we must to filter on contact
$subRequest
.= ' INNER JOIN `:db`.acl_resources_hg_relations hgr
ON hgr.hg_hg_id = hg.hostgroup_id
INNER JOIN `:db`.acl_resources res
ON res.acl_res_id = hgr.acl_res_id
AND res.acl_res_activate = \'1\'
INNER JOIN `:db`.acl_res_group_relations rgr
ON rgr.acl_res_id = res.acl_res_id
INNER JOIN `:db`.acl_groups grp
ON grp.acl_group_id IN ('
. $this->accessGroupIdToString($this->accessGroups)
. ') AND grp.acl_group_activate = \'1\'
AND grp.acl_group_id = rgr.acl_group_id
LEFT JOIN `:db`.acl_group_contacts_relations gcr
ON gcr.acl_group_id = grp.acl_group_id
LEFT JOIN `:db`.acl_group_contactgroups_relations gcgr
ON gcgr.acl_group_id = grp.acl_group_id
LEFT JOIN `:db`.contactgroup_contact_relation cgcr
ON cgcr.contactgroup_cg_id = gcgr.cg_cg_id
AND cgcr.contact_contact_id = :contact_id
OR gcr.contact_contact_id = :contact_id';
}
$request = 'SELECT DISTINCT 1 AS REALTIME, hg.* FROM `:dbstg`.`hostgroups` hg '
. $subRequest;
$request = $this->translateDbName($request);
$bindHostGroupNames = [];
foreach ($hostGroupNames as $index => $hostGroupName) {
$bindHostGroupNames[':host_group_name_' . $index] = [\PDO::PARAM_STR => $hostGroupName];
}
$bindValues = array_merge($bindValues, $bindHostGroupNames);
$request .= ' WHERE hg.name IN (' . implode(',', array_keys($bindHostGroupNames)) . ')';
// Sort
$request .= ' ORDER BY hg.name ASC';
$statement = $this->db->prepare($request);
// We bind extra parameters according to access rights
foreach ($bindValues as $key => $data) {
$type = key($data);
$value = $data[$type];
$statement->bindValue($key, $value, $type);
}
$statement->execute();
while (false !== ($result = $statement->fetch(\PDO::FETCH_ASSOC))) {
$hostGroups[] = EntityCreator::createEntityByArray(
HostGroup::class,
$result
);
}
return $hostGroups;
}
/**
* @inheritDoc
*/
public function findHostGroupsByIds(array $hostGroupIds): array
{
$hostGroups = [];
if ($this->hasNotEnoughRightsToContinue() || $hostGroupIds === []) {
return $hostGroups;
}
$bindValues = [];
$subRequest = '';
if (! $this->isAdmin()) {
$bindValues[':contact_id'] = [\PDO::PARAM_INT => $this->contact->getId()];
// Not an admin, we must to filter on contact
$subRequest
.= ' INNER JOIN `:db`.acl_resources_hg_relations hgr
ON hgr.hg_hg_id = hg.hostgroup_id
INNER JOIN `:db`.acl_resources res
ON res.acl_res_id = hgr.acl_res_id
AND res.acl_res_activate = \'1\'
INNER JOIN `:db`.acl_res_group_relations rgr
ON rgr.acl_res_id = res.acl_res_id
INNER JOIN `:db`.acl_groups grp
ON grp.acl_group_id IN ('
. $this->accessGroupIdToString($this->accessGroups)
. ') AND grp.acl_group_activate = \'1\'
AND grp.acl_group_id = rgr.acl_group_id
LEFT JOIN `:db`.acl_group_contacts_relations gcr
ON gcr.acl_group_id = grp.acl_group_id
LEFT JOIN `:db`.acl_group_contactgroups_relations gcgr
ON gcgr.acl_group_id = grp.acl_group_id
LEFT JOIN `:db`.contactgroup_contact_relation cgcr
ON cgcr.contactgroup_cg_id = gcgr.cg_cg_id
AND cgcr.contact_contact_id = :contact_id
OR gcr.contact_contact_id = :contact_id';
}
$request = 'SELECT DISTINCT 1 AS REALTIME, hg.* FROM `:dbstg`.`hostgroups` hg '
. $subRequest;
$request = $this->translateDbName($request);
$bindHostGroupIds = [];
foreach ($hostGroupIds as $index => $hostGroupId) {
$bindHostGroupIds[':host_group_id_' . $index] = [\PDO::PARAM_INT => $hostGroupId];
}
$bindValues = array_merge($bindValues, $bindHostGroupIds);
$request .= ' WHERE hg.hostgroup_id IN (' . implode(',', array_keys($bindHostGroupIds)) . ')';
// Sort
$request .= ' ORDER BY hg.name ASC';
$statement = $this->db->prepare($request);
// We bind extra parameters according to access rights
foreach ($bindValues as $key => $data) {
$type = key($data);
$value = $data[$type];
$statement->bindValue($key, $value, $type);
}
$statement->execute();
while (false !== ($result = $statement->fetch(\PDO::FETCH_ASSOC))) {
$hostGroups[] = EntityCreator::createEntityByArray(
HostGroup::class,
$result
);
}
return $hostGroups;
}
/**
* {@inheritDoc}
*/
public function setContact(ContactInterface $contact): HostGroupRepositoryInterface
{
$this->contact = $contact;
return $this;
}
/**
* Check if the contact is admin
*
* @return bool
*/
private function isAdmin(): bool
{
return ($this->contact !== null)
? $this->contact->isAdmin()
: false;
}
/**
* @return bool return FALSE 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;
}
}
| 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/PlatformInformation/Repository/PlatformInformationRepositoryRDB.php | centreon/src/Centreon/Infrastructure/PlatformInformation/Repository/PlatformInformationRepositoryRDB.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\PlatformInformation\Repository;
use Centreon\Domain\PlatformInformation\Interfaces\PlatformInformationRepositoryInterface;
use Centreon\Domain\PlatformInformation\Model\PlatformInformation;
use Centreon\Infrastructure\DatabaseConnection;
use Centreon\Infrastructure\PlatformInformation\Repository\Model\PlatformInformationFactoryRDB;
use Centreon\Infrastructure\Repository\AbstractRepositoryDRB;
/**
* This class is designed to manage the repository of the platform topology requests
*
* @package Centreon\Infrastructure\PlatformTopology
*/
class PlatformInformationRepositoryRDB extends AbstractRepositoryDRB implements PlatformInformationRepositoryInterface
{
/**
* Encryption Key.
*
* @var string|null
*/
private $encryptionFirstKey;
/**
* PlatformTopologyRepositoryRDB constructor.
* @param DatabaseConnection $db
*/
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* @inheritDoc
*/
public function setEncryptionFirstKey(?string $encryptionFirstKey): void
{
$this->encryptionFirstKey = $encryptionFirstKey;
}
/**
* @inheritDoc
*/
public function findPlatformInformation(): ?PlatformInformation
{
$statement = $this->db->prepare(
$this->translateDbName('
SELECT * FROM `:db`.informations
')
);
$result = [];
$platformInformation = null;
if ($statement->execute()) {
while ($row = $statement->fetch(\PDO::FETCH_ASSOC)) {
// Renaming one key to be more explicit
if ($row['key'] === 'authorizedMaster') {
$row['key'] = 'centralServerAddress';
}
// Renaming informations.apiCredentials to PlatformInformation encryptedApiCredentials property.
if ($row['key'] === 'apiCredentials') {
$row['key'] = 'encryptedApiCredentials';
}
if ($row['key'] === 'isRemote' || $row['key'] === 'apiPeerValidation') {
$row['value'] = $row['value'] === 'yes';
}
$result[$row['key']] = $row['value'];
}
if ($result !== []) {
/**
* @var PlatformInformation $platformInformation
*/
$platformInformationFactoryRDB = new PlatformInformationFactoryRDB($this->encryptionFirstKey);
$platformInformation = $platformInformationFactoryRDB->create($result);
}
}
return $platformInformation;
}
/**
* @inheritDoc
*/
public function updatePlatformInformation(PlatformInformation $platformInformation): void
{
try {
$this->db->beginTransaction();
$insertQuery = 'INSERT INTO `:db`.informations (`key`, `value`) VALUES ';
/**
* Store the parameters used to bindValue into the insertStatement
*/
$queryParameters = [];
$deletedKeys = [];
array_push($deletedKeys, "'isRemote'", "'isCentral'", "'apiPeerValidation'");
if ($platformInformation->isRemote() === true) {
$insertQuery .= "('isRemote', 'yes'), ('isCentral', 'no'), ";
$this->prepareInsertQueryString($platformInformation, $insertQuery, $queryParameters);
} else {
/**
* delete all keys related to a remote configuration, reinsert isCentral and isRemote.
*/
array_push(
$deletedKeys,
"'authorizedMaster'",
"'apiUsername'",
"'apiCredentials'",
"'apiScheme'",
"'apiPort'",
"'apiPath'"
);
$insertQuery .= "('isCentral', 'yes'), ('isRemote', 'no')";
}
$insertStatement = $this->db->prepare($this->translateDbName($insertQuery));
foreach ($queryParameters as $key => $bindParams) {
/**
* each key of queryParameters used into the insertStatement also needs to be deleted before
* being reinserted. So they're stored into $deletedKeys that is used into the delete query
*/
$deletedKeys[] = "'{$key}'";
foreach ($bindParams as $paramType => $paramValue) {
$insertStatement->bindValue(':' . $key, $paramValue, $paramType);
}
}
$deletedKeyList = implode(',', $deletedKeys);
/**
* Delete only the updated key
*/
$this->db->query($this->translateDbName("DELETE FROM `:db`.informations WHERE `key` IN ({$deletedKeyList})"));
/**
* Insert updated values
*/
$insertStatement->execute();
$this->db->commit();
} catch (\Exception $ex) {
$this->db->rollBack();
throw $ex;
}
}
/**
* this method is designed to prepare the insertQuery, based on the provided Information.
*
* @param PlatformInformation $platformInformation
* @param string $insertQuery
* @param array<string,array<int,mixed>> $queryParameters
* @return void
*/
private function prepareInsertQueryString(
PlatformInformation $platformInformation,
string &$insertQuery,
array &$queryParameters,
): void {
$queryValues = [];
if ($platformInformation->getCentralServerAddress() !== null) {
$queryParameters['authorizedMaster'] = [
\PDO::PARAM_STR => $platformInformation->getCentralServerAddress(),
];
$queryValues[] = "('authorizedMaster', :authorizedMaster)";
}
if ($platformInformation->getApiUsername() !== null) {
$queryParameters['apiUsername'] = [
\PDO::PARAM_STR => $platformInformation->getApiUsername(),
];
$queryValues[] = "('apiUsername', :apiUsername)";
}
if ($platformInformation->getEncryptedApiCredentials() !== null) {
$queryParameters['apiCredentials'] = [
\PDO::PARAM_STR => $platformInformation->getEncryptedApiCredentials(),
];
$queryValues[] = "('apiCredentials', :apiCredentials)";
}
if ($platformInformation->getApiScheme() !== null) {
$queryParameters['apiScheme'] = [
\PDO::PARAM_STR => $platformInformation->getApiScheme(),
];
$queryValues[] = "('apiScheme', :apiScheme)";
}
if ($platformInformation->getApiPort() !== null) {
$queryParameters['apiPort'] = [
\PDO::PARAM_INT => $platformInformation->getApiPort(),
];
$queryValues[] = "('apiPort', :apiPort)";
}
if ($platformInformation->getApiPath() !== null) {
$queryParameters['apiPath'] = [
\PDO::PARAM_STR => $platformInformation->getApiPath(),
];
$queryValues[] = "('apiPath', :apiPath)";
}
if ($platformInformation->hasApiPeerValidation() !== null) {
/**
* This key isn't put into queryParameters, so we add it directly to the deletedKey array
*/
$deletedKeys[] = "'apiPeerValidation'";
if ($platformInformation->hasApiPeerValidation() === true) {
$queryValues[] = "('apiPeerValidation', 'yes')";
} else {
$queryValues[] = "('apiPeerValidation', 'no')";
}
}
$insertQuery .= implode(', ', $queryValues);
}
}
| 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/PlatformInformation/Repository/Model/PlatformInformationFactoryRDB.php | centreon/src/Centreon/Infrastructure/PlatformInformation/Repository/Model/PlatformInformationFactoryRDB.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\PlatformInformation\Repository\Model;
use Centreon\Domain\PlatformInformation\Model\PlatformInformation;
use Security\Encryption;
class PlatformInformationFactoryRDB
{
/**
* Credentials encryption key
*/
public const ENCRYPT_SECOND_KEY = 'api_remote_credentials';
/** @var string|null */
private $encryptionFirstKey;
public function __construct(?string $encryptionFirstKey)
{
$this->encryptionFirstKey = $encryptionFirstKey;
}
/**
* @param array<string,mixed> $information
* @return PlatformInformation
*/
public function create(array $information): PlatformInformation
{
$platformInformation = new PlatformInformation($information['isRemote']);
foreach ($information as $key => $value) {
switch ($key) {
case 'centralServerAddress':
$platformInformation->setCentralServerAddress($value);
break;
case 'apiUsername':
$platformInformation->setApiUsername($value);
break;
case 'encryptedApiCredentials':
$platformInformation->setEncryptedApiCredentials($value);
$decryptedPassword = $this->decryptApiCredentials($value);
$platformInformation->setApiCredentials($decryptedPassword);
break;
case 'apiScheme':
$platformInformation->setApiScheme($value);
break;
case 'apiPort':
$platformInformation->setApiPort((int) $value);
break;
case 'apiPath':
$platformInformation->setApiPath($value);
break;
case 'apiPeerValidation':
$platformInformation->setApiPeerValidation($value);
break;
}
}
return $platformInformation;
}
/**
* @param string|null $encryptedKey
* @return string|null
*/
private function decryptApiCredentials(?string $encryptedKey): ?string
{
if (empty($encryptedKey)) {
return null;
}
if ($this->encryptionFirstKey === null) {
throw new \InvalidArgumentException(
_('Unable to find the encryption key.')
);
}
// second key
$secondKey = base64_encode(self::ENCRYPT_SECOND_KEY);
try {
$centreonEncryption = new Encryption();
$centreonEncryption->setFirstKey($this->encryptionFirstKey)->setSecondKey($secondKey);
return $centreonEncryption->decrypt($encryptedKey);
} catch (\throwable $e) {
throw new \InvalidArgumentException(
_("Unable to decipher central's credentials. Please check the credentials in the 'Remote Access' form")
);
}
}
}
| 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/Option/OptionRepositoryRDB.php | centreon/src/Centreon/Infrastructure/Option/OptionRepositoryRDB.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Option;
use Centreon\Domain\Entity\EntityCreator;
use Centreon\Domain\Option\Interfaces\OptionRepositoryInterface;
use Centreon\Domain\Option\Option;
use Centreon\Infrastructure\DatabaseConnection;
use Centreon\Infrastructure\Repository\AbstractRepositoryDRB;
/**
* This class is designed to manage the configuration options of Centreon in
* the database (table options).
*
* @package Centreon\Infrastructure\Options
*/
class OptionRepositoryRDB extends AbstractRepositoryDRB implements OptionRepositoryInterface
{
/** @var Option[] */
private $options;
/**
* @param DatabaseConnection $db
*/
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* @inheritDoc
*/
public function findAllOptions(bool $useCache = true): array
{
if ($useCache && ! empty($this->options)) {
return $this->options;
}
$request = $this->translateDbName('SELECT `key` AS `name`, `value` FROM `:db`.options');
if (false !== ($statement = $this->db->query($request))) {
$statement->execute();
while (false !== ($option = $statement->fetch(\PDO::FETCH_ASSOC))) {
$this->options[] = EntityCreator::createEntityByArray(Option::class, $option);
}
}
return $this->options;
}
}
| 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/Gorgone/CommandRepositoryAPI.php | centreon/src/Centreon/Infrastructure/Gorgone/CommandRepositoryAPI.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Gorgone;
use Centreon\Domain\Gorgone\Interfaces\CommandInterface;
use Centreon\Domain\Gorgone\Interfaces\CommandRepositoryInterface;
use Centreon\Infrastructure\Gorgone\Interfaces\ConfigurationLoaderApiInterface;
use Symfony\Component\HttpClient\CurlHttpClient;
use Symfony\Contracts\HttpClient\HttpClientInterface;
/**
* This class is designed to send commands to the Gorgone server using its API.
*
* @package Centreon\Infrastructure\Gorgone
*/
class CommandRepositoryAPI implements CommandRepositoryInterface
{
/**
* @var HttpClientInterface http client library that will be used to
* communicate with the Gorgone server through its API
*/
private $client;
/** @var ConfigurationLoaderApiInterface */
private $configuration;
/**
* @param ConfigurationLoaderApiInterface $configuration
*/
public function __construct(ConfigurationLoaderApiInterface $configuration)
{
$this->client = new CurlHttpClient();
$this->configuration = $configuration;
}
/**
* @inheritDoc
*/
public function send(CommandInterface $command): string
{
$isCertificateShouldBeVerify = $this->configuration->isSecureConnectionSelfSigned() === false;
$options = [
'body' => $command->getBodyRequest(),
'timeout' => $this->configuration->getCommandTimeout(),
'verify_peer' => $isCertificateShouldBeVerify,
'verify_host' => $isCertificateShouldBeVerify,
];
if ($this->configuration->getApiUsername() !== null) {
$options = array_merge(
$options,
['auth_basic' => $this->configuration->getApiUsername() . ':'
. $this->configuration->getApiPassword()]
);
}
try {
$uri = sprintf(
'%s://%s:%d/api/%s',
$this->configuration->isApiConnectionSecure() ? 'https' : 'http',
$this->configuration->getApiIpAddress(),
$this->configuration->getApiPort(),
$command->getUriRequest()
);
$response = $this->client->request($command->getMethod(), $uri, $options);
if ($response->getStatusCode() !== 200) {
throw new \Exception('Bad request', $response->getStatusCode());
}
$jsonResponse = json_decode($response->getContent(), true);
if (! array_key_exists('token', $jsonResponse)) {
$exceptionMessage = 'Token not found';
if (array_key_exists('message', $jsonResponse)) {
if ($jsonResponse['message'] === 'Method not implemented') {
$exceptionMessage = 'The "autodiscovery" module of Gorgone is not loaded';
} else {
$exceptionMessage = $jsonResponse['message'];
}
}
throw new CommandRepositoryException($exceptionMessage);
}
return (string) $jsonResponse['token'];
} catch (CommandRepositoryException $ex) {
throw $ex;
} catch (\Throwable $e) {
throw new \Exception($e->getMessage(), (int) $e->getCode(), $e);
}
}
}
| 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/Gorgone/ResponseRepositoryAPI.php | centreon/src/Centreon/Infrastructure/Gorgone/ResponseRepositoryAPI.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Gorgone;
use Centreon\Domain\Gorgone\Interfaces\CommandInterface;
use Centreon\Domain\Gorgone\Interfaces\ResponseRepositoryInterface;
use Centreon\Infrastructure\Gorgone\Interfaces\ConfigurationLoaderApiInterface;
use Symfony\Component\HttpClient\CurlHttpClient;
use Symfony\Contracts\HttpClient\HttpClientInterface;
/**
* This class is designed to retrieve command responses from the Gorgone server using its API.
*
* @package Centreon\Infrastructure\Gorgone
*/
class ResponseRepositoryAPI implements ResponseRepositoryInterface
{
/**
* @var HttpClientInterface http client library that will be used to
* communicate with the Gorgone server through its API
*/
private $client;
/** @var ConfigurationLoaderApiInterface */
private $configuration;
/**
* @param ConfigurationLoaderApiInterface $configuration
*/
public function __construct(ConfigurationLoaderApiInterface $configuration)
{
$this->client = new CurlHttpClient();
$this->configuration = $configuration;
}
/**
* @inheritDoc
*/
public function getResponse(CommandInterface $command): string
{
$isCertificateShouldBeVerify = $this->configuration->isSecureConnectionSelfSigned() === false;
$options = [
'timeout' => $this->configuration->getCommandTimeout(),
'verify_peer' => $isCertificateShouldBeVerify,
'verify_host' => $isCertificateShouldBeVerify,
];
if ($this->configuration->getApiUsername() !== null) {
$options = array_merge(
$options,
['auth_basic' => $this->configuration->getApiUsername() . ':'
. $this->configuration->getApiPassword()]
);
}
try {
$uri = sprintf(
'%s://%s:%d/api/nodes/%d/log/%s',
$this->configuration->isApiConnectionSecure() ? 'https' : 'http',
$this->configuration->getApiIpAddress(),
$this->configuration->getApiPort(),
$command->getMonitoringInstanceId(),
$command->getToken()
);
$response = $this->client->request('GET', $uri, $options);
if ($response->getStatusCode() !== 200) {
throw new \Exception('Request error', $response->getStatusCode());
}
return $response->getContent();
} catch (\Throwable $ex) {
throw new \Exception($ex->getMessage(), (int) $ex->getCode(), $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/Gorgone/CommandRepositoryException.php | centreon/src/Centreon/Infrastructure/Gorgone/CommandRepositoryException.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Gorgone;
class CommandRepositoryException 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/Infrastructure/Gorgone/Interfaces/ConfigurationLoaderApiInterface.php | centreon/src/Centreon/Infrastructure/Gorgone/Interfaces/ConfigurationLoaderApiInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Gorgone\Interfaces;
interface ConfigurationLoaderApiInterface
{
/**
* Indicates whether the connection to the Gorgone server used a self-signed certificate
*
* @throws \Exception
* @return bool
*/
public function isSecureConnectionSelfSigned(): bool;
/**
* Returns the IP address of the Gorgone server
*
* @throws \Exception
* @return string|null IP address
*/
public function getApiIpAddress(): ?string;
/**
* Returns the connection port of the Gorgone server
*
* @throws \Exception
* @return int|null Connection port
*/
public function getApiPort(): ?int;
/**
* Returns the API password of the Gorgone server
*
* @throws \Exception
* @return string|null API password of the Gorgone server
*/
public function getApiPassword(): ?string;
/**
* Returns the delay before the connection timeout
*
* @throws \Exception
* @return int Timeout (in seconds)
*/
public function getCommandTimeout(): int;
/**
* Indicates whether the connection to the Gorgone server is secure
*
* @throws \Exception
* @return bool
*/
public function isApiConnectionSecure(): bool;
/**
* Returns the API username of the Gorgone server
*
* @throws \Exception
* @return string|null API username of the Gorgone server
*/
public function getApiUsername(): ?string;
}
| 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/RequestParameters/SqlRequestParametersTranslator.php | centreon/src/Centreon/Infrastructure/RequestParameters/SqlRequestParametersTranslator.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\RequestParameters;
use Adaptation\Database\QueryBuilder\QueryBuilderInterface;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Centreon\Domain\RequestParameters\RequestParameters;
use Centreon\Infrastructure\DatabaseConnection;
use Centreon\Infrastructure\RequestParameters\Interfaces\NormalizerInterface;
use Utility\SqlConcatenator;
/**
* @package Centreon\Infrastructure\RequestParameters
*/
class SqlRequestParametersTranslator
{
/** @var string[] */
private $aggregateOperators = [
RequestParameters::AGGREGATE_OPERATOR_OR,
RequestParameters::AGGREGATE_OPERATOR_AND,
];
/**
* @var array<string, string> Concordance table between the search column
* and the real column name in the database. ['id' => 'my_table_id', ...]
*/
private $concordanceArray = [];
/** @var array<string, mixed> */
private $searchValues = [];
/** @var array<string, NormalizerInterface> */
private $normalizers = [];
/** @var RequestParametersInterface */
private $requestParameters;
/**
* SqlRequestParametersTranslator constructor.
* @param RequestParametersInterface $requestParameters
*/
public function __construct(RequestParametersInterface $requestParameters)
{
$this->requestParameters = $requestParameters;
}
/**
* @return RequestParametersInterface
*/
public function getRequestParameters(): RequestParametersInterface
{
return $this->requestParameters;
}
/**
* Translate the pagination (page and limit parameters) into SQL request.
*
* @return string
*/
public function translatePaginationToSql(): string
{
return sprintf(
' LIMIT %d, %d',
($this->requestParameters->getPage() - 1) * $this->requestParameters->getLimit(),
$this->requestParameters->getLimit()
);
}
/**
* Returns the rest of the query to make a filter based on the paging system.
*
* Usage:
* <code>
* list($whereQuery, $bindValues) = $pagination->createQuery([...]);
* </code>
*
* @throws RequestParametersTranslatorException
* @return string|null SQL request according to the search parameters
*/
public function translateSearchParameterToSql(): ?string
{
$whereQuery = '';
$search = $this->requestParameters->getSearch();
if (! empty($search) && is_array($search)) {
$whereQuery .= $this->createDatabaseQuery($search);
}
return ! empty($whereQuery) ? ' WHERE ' . $whereQuery : null;
}
public function appendQueryBuilderWithSearchParameter(QueryBuilderInterface $queryBuilder): void
{
$search = $this->requestParameters->getSearch();
if (! empty($search)) {
$queryBuilder->where($this->createDatabaseQuery($search));
}
}
/**
* Translate the sort parameters into SQL request.
*
* @return string|null Returns null if no sorting parameter is defined
*/
public function translateSortParameterToSql(): ?string
{
$orderQuery = '';
foreach ($this->requestParameters->getSort() as $name => $order) {
if (array_key_exists($name, $this->concordanceArray)) {
if (! empty($orderQuery)) {
$orderQuery .= ', ';
}
$orderQuery .= sprintf(
'%s IS NULL, %s %s',
$this->concordanceArray[$name],
$this->concordanceArray[$name],
$order
);
}
}
return ! empty($orderQuery) ? ' ORDER BY ' . $orderQuery : null;
}
public function appendQueryBuilderWithSortParameter(QueryBuilderInterface $queryBuilder): void
{
foreach ($this->requestParameters->getSort() as $name => $order) {
if (array_key_exists($name, $this->concordanceArray)) {
$queryBuilder->addOrderBy(
sprintf(
'%s IS NULL, %s',
$this->concordanceArray[$name],
$this->concordanceArray[$name],
),
$order
);
}
}
}
public function appendQueryBuilderWithPagination(QueryBuilderInterface $queryBuilder): void
{
$page = $this->requestParameters->getPage();
$limit = $this->requestParameters->getLimit();
$offset = ($page - 1) * $limit;
$queryBuilder
->limit($limit)
->offset($offset);
}
/**
* Facade to populate a SqlStringBuilder from a SqlRequestParametersTranslator.
*
* @param SqlConcatenator $concatenator
*/
public function translateForConcatenator(SqlConcatenator $concatenator): void
{
$concatenator->withCalcFoundRows(true);
if ($search = $this->translateSearchParameterToSql()) {
$concatenator->appendWhere($search);
}
if ($sort = $this->translateSortParameterToSql()) {
$concatenator->defineOrderBy($sort);
}
if ($pagination = $this->translatePaginationToSql()) {
$concatenator->defineLimit($pagination);
}
}
/**
* @return array<string, string>
*/
public function getConcordanceArray(): array
{
return $this->concordanceArray;
}
/**
* @param array<string, string> $concordanceArray
*/
public function setConcordanceArray(array $concordanceArray): void
{
$this->concordanceArray = $concordanceArray;
}
/**
* Add a search value
*
* @param string $key Key
* @param array<int, array<int, mixed>> $value Array [type_value => value]
*/
public function addSearchValue(string $key, array $value): void
{
$this->searchValues[$key] = $value;
}
/**
* @return array<string, array<int, mixed>>
*/
public function getSearchValues(): array
{
return $this->searchValues;
}
/**
* @param array<string, array<int, mixed>> $searchValues
*/
public function setSearchValues(array $searchValues): void
{
$this->searchValues = $searchValues;
}
/**
* Automatically bind values to a \PDOStatement.
*
* @param \PDOStatement $statement
*/
public function bindSearchValues(\PDOStatement $statement): void
{
foreach ($this->getSearchValues() as $key => $data) {
$type = key($data);
$value = $data[$type];
$statement->bindValue($key, $value, $type);
}
}
/**
* @param DatabaseConnection $db
*
* @return int|null
*/
public function calculateNumberOfRows(DatabaseConnection $db): ?int
{
if (
false === ($result = $db->query('SELECT FOUND_ROWS()'))
|| false === ($value = $result->fetchColumn())
) {
return null;
}
$this->getRequestParameters()->setTotal($nbRows = (int) $value);
return $nbRows;
}
/**
* @param int $numberOfRows
*/
public function setNumberOfRows(int $numberOfRows): void
{
$this->requestParameters->setTotal($numberOfRows);
}
/**
* Add a normalizer for a property name to be declared in the search parameters.
* <code>
* $sqlRequestTranslator = new SqlRequestParametersTranslator(new RequestParameters());
* $sqlRequestTranslator->addNormalizer(
* 'name',
* new class() implements NormalizerInterface
* {
* public function normalize($valueToNormalize)
* {
* if ($valueToNormalize === "localhost") {
* return "127.0.0.1";
* }
* return $valueToNormalize;
* }
* }
* );
* </code>
* @param string $propertyName Property name for which the normalizer is applied
* @param NormalizerInterface $normalizer Normalizer to applied
* @throws \InvalidArgumentException
*/
public function addNormalizer(string $propertyName, NormalizerInterface $normalizer): void
{
if (empty($propertyName)) {
throw new \InvalidArgumentException(_('The property name of the normalizer cannot be empty.'));
}
$this->normalizers[$propertyName] = $normalizer;
}
/**
* Create the database query based on the search parameters.
*
* @param array<mixed, mixed> $search Array containing search parameters
* @param string|null $aggregateOperator Aggregate operator
* @throws RequestParametersTranslatorException
* @return string Return the processed database query
*/
private function createDatabaseQuery(array $search, ?string $aggregateOperator = null): string
{
$databaseQuery = '';
$databaseSubQuery = '';
foreach ($search as $key => $searchRequests) {
if ($this->isAggregateOperator($key)) {
if (is_object($searchRequests) || is_array($searchRequests)) {
if (is_object($searchRequests)) {
$searchRequests = (array) $searchRequests;
}
// Recursive call until to read key/value data
$databaseSubQuery = $this->createDatabaseQuery($searchRequests, $key);
}
} elseif (is_int($key) && (is_object($searchRequests) || is_array($searchRequests))) {
// It's a list of object to process
$searchRequests = (array) $searchRequests;
if ($searchRequests !== []) {
// Recursive call until to read key/value data
$databaseSubQuery = $this->createDatabaseQuery($searchRequests, $aggregateOperator);
}
} elseif (! is_int($key)) {
// It's a pair on key/value to translate into a database query
if (is_object($searchRequests)) {
$searchRequests = (array) $searchRequests;
}
$databaseSubQuery = $this->createQueryOnKeyValue($key, $searchRequests);
}
if (! empty($databaseQuery)) {
if (is_null($aggregateOperator)) {
$aggregateOperator = RequestParameters::AGGREGATE_OPERATOR_AND;
}
if (! empty($databaseSubQuery)) {
$databaseQuery .= ' '
. $this->translateAggregateOperator($aggregateOperator)
. ' '
. $databaseSubQuery;
}
} else {
$databaseQuery .= $databaseSubQuery;
}
}
return count($search) > 1 && ! empty($databaseQuery)
? '(' . $databaseQuery . ')'
: $databaseQuery;
}
/**
* @param string $key Key representing the entity to search
* @param mixed $valueOrArray mixed value or array representing the value to search
* @throws RequestParametersTranslatorException
* @return string part of the database query
*/
private function createQueryOnKeyValue(string $key, $valueOrArray): string
{
if (
$this->requestParameters->getConcordanceStrictMode() === RequestParameters::CONCORDANCE_MODE_STRICT
&& ! array_key_exists($key, $this->concordanceArray)
) {
if (
$this->requestParameters
->getConcordanceErrorMode() === RequestParameters::CONCORDANCE_ERRMODE_EXCEPTION
) {
throw new RequestParametersTranslatorException(
sprintf(_('The parameter %s is not allowed'), $key)
);
}
return '';
}
if (is_array($valueOrArray)) {
$searchOperator = (string) key($valueOrArray);
$mixedValue = $valueOrArray[$searchOperator];
} else {
$searchOperator = RequestParameters::DEFAULT_SEARCH_OPERATOR;
$mixedValue = $valueOrArray;
}
if ($mixedValue === null) {
$mixedValue = $this->normalizeValue($key, $mixedValue);
}
if ($mixedValue === null) {
if ($searchOperator === RequestParameters::OPERATOR_EQUAL) {
$bindKey = 'NULL';
} elseif ($searchOperator === RequestParameters::OPERATOR_NOT_EQUAL) {
$bindKey = 'NOT NULL';
} else {
throw new RequestParametersTranslatorException(
'The value "null" is only supported by the operators '
. RequestParameters::OPERATOR_EQUAL
. ' and '
. RequestParameters::OPERATOR_NOT_EQUAL
);
}
} elseif (
$searchOperator === RequestParameters::OPERATOR_IN
|| $searchOperator === RequestParameters::OPERATOR_NOT_IN
) {
if (is_array($mixedValue)) {
$bindKey = '(';
foreach ($mixedValue as $index => $newValue) {
$newValue = $this->normalizeValue($key, $newValue);
$currentBindKey = ':value_' . (count($this->searchValues) + 1);
$this->searchValues[$currentBindKey] = [$this->toPdoType($newValue) => $newValue];
if ($index > 0) {
$bindKey .= ',';
}
$bindKey .= $currentBindKey;
}
$bindKey .= ')';
} else {
$mixedValue = $this->normalizeValue($key, $mixedValue);
$bindKey = ':value_' . (count($this->searchValues) + 1);
$this->searchValues[$bindKey] = [$this->toPdoType($mixedValue) => $mixedValue];
$bindKey = '(' . $bindKey . ')';
}
} elseif (
$searchOperator === RequestParameters::OPERATOR_LIKE
|| $searchOperator === RequestParameters::OPERATOR_NOT_LIKE
|| $searchOperator === RequestParameters::OPERATOR_REGEXP
) {
// We check the regex
if ($searchOperator === RequestParameters::OPERATOR_REGEXP) {
// For MySQL compatibility
if ($mixedValue === '') {
$mixedValue = '.*';
}
try {
$mixedValue = str_replace('/', '\/', $mixedValue);
preg_match('/' . $mixedValue . '/', '');
if (preg_last_error() !== PREG_NO_ERROR) {
throw new RequestParametersTranslatorException('Bad regex format \'' . $mixedValue . '\'', 0);
}
} catch (\ErrorException $exception) {
throw new RequestParametersTranslatorException(
message: 'Error while preg_match() the value : \'' . $mixedValue . '\'',
code: 0,
previous: $exception
);
}
}
$bindKey = ':value_' . (count($this->searchValues) + 1);
$this->searchValues[$bindKey] = [\PDO::PARAM_STR => $mixedValue];
} else {
$mixedValue = $this->normalizeValue($key, $mixedValue);
$bindKey = ':value_' . (count($this->searchValues) + 1);
$this->searchValues[$bindKey] = [$this->toPdoType($mixedValue) => $mixedValue];
}
return sprintf(
'%s %s %s',
(array_key_exists($key, $this->concordanceArray)
? $this->concordanceArray[$key]
: $key),
($mixedValue !== null) ? $this->translateSearchOperator($searchOperator) : 'IS',
$bindKey
);
}
/**
* Detect the correct PDO type from a php type.
*
* @param mixed $value
*
* @return int
*/
private function toPdoType(mixed $value): int
{
return match (true) {
is_int($value) => \PDO::PARAM_INT,
is_bool($value) => \PDO::PARAM_BOOL,
default => \PDO::PARAM_STR,
};
}
/**
* Indicates if the key is an aggregate operator
*
* @param mixed $key Key to test
* @return bool Return TRUE if the key is an aggregate operator otherwise FALSE
*/
private function isAggregateOperator($key): bool
{
return is_string($key) && in_array($key, $this->aggregateOperators, true);
}
/**
* @param string $aggregateOperator
* @throws RequestParametersTranslatorException
* @return string
*/
private function translateAggregateOperator(string $aggregateOperator): string
{
return match ($aggregateOperator) {
RequestParameters::AGGREGATE_OPERATOR_AND => 'AND',
RequestParameters::AGGREGATE_OPERATOR_OR => 'OR',
default => throw new RequestParametersTranslatorException(_('Bad search operator')),
};
}
/**
* Translates the search operators (RequestParameters::OPERATOR_LIKE, ...)
* in their SQL equivalent (LIKE, ...).
*
* @param string $operator Operator to translate
* @return string Operator translated in his SQL equivalent
*/
private function translateSearchOperator(string $operator): string
{
return match ($operator) {
RequestParameters::OPERATOR_LIKE => 'LIKE',
RequestParameters::OPERATOR_NOT_LIKE => 'NOT LIKE',
RequestParameters::OPERATOR_REGEXP => 'REGEXP',
RequestParameters::OPERATOR_LESS_THAN => '<',
RequestParameters::OPERATOR_LESS_THAN_OR_EQUAL => '<=',
RequestParameters::OPERATOR_GREATER_THAN => '>',
RequestParameters::OPERATOR_GREATER_THAN_OR_EQUAL => '>=',
RequestParameters::OPERATOR_NOT_EQUAL => '!=',
RequestParameters::OPERATOR_IN => 'IN',
RequestParameters::OPERATOR_NOT_IN => 'NOT IN',
default => '=',
};
}
/**
* Normalize a value.
*
* @param string $propertyName Property name to be normalized if it exists
* @param string|bool|int|null $valueToNormalize Value to be normalized
* @return string|bool|int|null
*/
private function normalizeValue(string $propertyName, $valueToNormalize)
{
if (array_key_exists($propertyName, $this->normalizers)) {
return $this->normalizers[$propertyName]->normalize($valueToNormalize);
}
return $valueToNormalize;
}
}
| 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/RequestParameters/RequestParametersTranslatorException.php | centreon/src/Centreon/Infrastructure/RequestParameters/RequestParametersTranslatorException.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\RequestParameters;
class RequestParametersTranslatorException extends \RuntimeException
{
}
| 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/RequestParameters/Interfaces/NormalizerInterface.php | centreon/src/Centreon/Infrastructure/RequestParameters/Interfaces/NormalizerInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\RequestParameters\Interfaces;
/**
* @package Centreon\Infrastructure\RequestParameters\Interfaces
*/
interface NormalizerInterface
{
/**
* Normalize a value.
*
* The objective being to modify or not the value passed in parameter.
*
* @param string|bool|int|null $valueToNormalize Value to be normalized
* @return string|bool|int|null
*/
public function normalize($valueToNormalize);
}
| 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/AccessControlList/AccessControlListRepositoryTrait.php | centreon/src/Centreon/Infrastructure/AccessControlList/AccessControlListRepositoryTrait.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AccessControlList;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
trait AccessControlListRepositoryTrait
{
/** @var ContactInterface|null */
protected $contact;
/** @var AccessGroup[] List of access group used to filter the requests */
protected $accessGroups = [];
/**
* @param ContactInterface $contact
* @return $this
*/
public function setContact(ContactInterface $contact): self
{
$this->contact = $contact;
return $this;
}
/**
* Sets the access groups that will be used to filter services and the host.
*
* @param AccessGroup[] $accessGroups
* @return $this
*/
public function filterByAccessGroups(array $accessGroups): self
{
$this->accessGroups = $accessGroups;
return $this;
}
/**
* @return bool return FALSE 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;
}
}
| 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/Provider/AutoloadServiceProvider.php | centreon/src/Centreon/Infrastructure/Provider/AutoloadServiceProvider.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Provider;
use Exception;
use Pimple\Container;
use ReflectionClass;
use Symfony\Component\Finder\Finder;
/**
* Register all service providers
*/
class AutoloadServiceProvider
{
public const ERR_TWICE_LOADED = 2001;
/**
* Register service providers
*
* @param Container $dependencyInjector
* @return void
*/
public static function register(Container $dependencyInjector): void
{
$providers = self::getProviders($dependencyInjector['finder']);
foreach ($providers as $provider) {
$dependencyInjector->register(new $provider());
}
}
/**
* Get a list of the service provider classes
*
* @param Finder $finder
* @return array
*/
private static function getProviders(Finder $finder): array
{
$providers = [];
$serviceProviders = $finder
->files()
->name('ServiceProvider.php')
->depth('== 1')
->in(__DIR__ . '/../../../../src');
foreach ($serviceProviders as $serviceProvider) {
$serviceProviderRelativePath = $serviceProvider->getRelativePath();
$object = "{$serviceProviderRelativePath}\\ServiceProvider";
if (! class_exists($object)) {
continue;
}
self::addProvider($providers, $object);
}
asort($providers);
return array_keys($providers);
}
/**
* Add classes only implement the interface AutoloadServiceProviderInterface
*
* @param array $providers
* @param string $object
* @throws Exception
* @return void
*/
private static function addProvider(array &$providers, string $object): void
{
if (array_key_exists($object, $providers)) {
throw new Exception(sprintf('Provider %s is loaded', $object), static::ERR_TWICE_LOADED);
}
$interface = AutoloadServiceProviderInterface::class;
$hasInterface = (new ReflectionClass($object))
->implementsInterface($interface);
if ($hasInterface) {
$providers[$object] = $object::order();
}
}
}
| 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/Provider/AutoloadServiceProviderInterface.php | centreon/src/Centreon/Infrastructure/Provider/AutoloadServiceProviderInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Provider;
use Pimple\ServiceProviderInterface;
interface AutoloadServiceProviderInterface extends ServiceProviderInterface
{
/**
* Set priority to load service provider
*
* @return int
*/
public static function order(): 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/Infrastructure/Engine/EngineRepositoryFile.php | centreon/src/Centreon/Infrastructure/Engine/EngineRepositoryFile.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Engine;
use Centreon\Domain\Engine\EngineException;
use Centreon\Domain\Engine\Interfaces\EngineRepositoryInterface;
final class EngineRepositoryFile implements EngineRepositoryInterface
{
/** @var string */
private $centCoreDirectory;
/** @var string */
private $centCoreFile;
/**
* EngineRepositoryFile constructor.
*
* @param string $centCoreDirectory
*/
public function __construct(string $centCoreDirectory)
{
$this->centCoreDirectory = $centCoreDirectory;
$this->centCoreFile
= $centCoreDirectory
. DIRECTORY_SEPARATOR
. 'external-cmd-' . microtime(true) . '.cmd';
}
/**
* @inheritDoc
*/
public function sendExternalCommands(array $commands): void
{
$this->send($commands);
}
/**
* @inheritDoc
*/
public function sendExternalCommand(string $command): void
{
$this->send([$command]);
}
/**
* Send all data that has been waiting to be sent.
*
* @param array $commandsAwaiting
* @throws EngineException
* @return int Returns the number of commands sent
*/
private function send(array $commandsAwaiting): int
{
$commandsToSend = '';
foreach ($commandsAwaiting as $command) {
$commandsToSend .= ! empty($commandsToSend) ? "\n" : '';
$commandsToSend .= $command;
}
if (! is_dir($this->centCoreDirectory)) {
throw new EngineException(
sprintf(_('Centcore directory %s does not exist'), $this->centCoreDirectory)
);
}
if (! empty($commandsToSend)) {
$isDataSent = file_put_contents($this->centCoreFile, $commandsToSend . "\n", FILE_APPEND);
if ($isDataSent === false) {
throw new EngineException(
sprintf(
_('Error during creation of the CentCore command file (%s)'),
$this->centCoreFile
)
);
}
}
return count($commandsAwaiting);
}
}
| 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/Engine/EngineConfigurationRepositoryRDB.php | centreon/src/Centreon/Infrastructure/Engine/EngineConfigurationRepositoryRDB.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Engine;
use Centreon\Domain\Engine\EngineConfiguration;
use Centreon\Domain\Engine\Interfaces\EngineConfigurationRepositoryInterface;
use Centreon\Domain\HostConfiguration\Host;
use Centreon\Domain\RequestParameters\RequestParameters;
use Centreon\Infrastructure\DatabaseConnection;
use Centreon\Infrastructure\Repository\AbstractRepositoryDRB;
use Centreon\Infrastructure\RequestParameters\SqlRequestParametersTranslator;
/**
* This class is designed to represent the MariaDb repository to manage Engine configuration.
*
* @package Centreon\Infrastructure\Engine
*/
class EngineConfigurationRepositoryRDB extends AbstractRepositoryDRB implements EngineConfigurationRepositoryInterface
{
/** @var SqlRequestParametersTranslator */
private $sqlRequestTranslator;
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* Initialized by the dependency injector.
*
* @param SqlRequestParametersTranslator $sqlRequestTranslator
*/
public function setSqlRequestTranslator(SqlRequestParametersTranslator $sqlRequestTranslator): void
{
$this->sqlRequestTranslator = $sqlRequestTranslator;
$this->sqlRequestTranslator
->getRequestParameters()
->setConcordanceStrictMode(
RequestParameters::CONCORDANCE_MODE_STRICT
);
}
/**
* @inheritDoc
*/
public function findCentralEngineConfiguration(): ?EngineConfiguration
{
$engineConfiguration = null;
$request = $this->translateDbName(
'SELECT cfg.* FROM `:db`.cfg_nagios cfg
INNER JOIN `:db`.nagios_server server
ON server.id = cfg.nagios_server_id
WHERE server.localhost = "1"'
);
$statement = $this->db->query($request);
if (($record = $statement->fetch(\PDO::FETCH_ASSOC)) !== false) {
$engineConfiguration = (new EngineConfiguration())
->setId((int) $record['nagios_id'])
->setName($record['nagios_name'])
->setIllegalObjectNameCharacters($record['illegal_object_name_chars'])
->setMonitoringServerId((int) $record['nagios_server_id'])
->setNotificationsEnabledOption((int) $record['enable_notifications']);
}
return $engineConfiguration;
}
/**
* @inheritDoc
*/
public function findEngineConfigurationByHost(Host $host): ?EngineConfiguration
{
if ($host->getId() === null) {
return null;
}
$request = $this->translateDbName(
'SELECT * FROM `:db`.cfg_nagios cfg
INNER JOIN `:db`.ns_host_relation nsr
ON nsr.nagios_server_id = cfg.nagios_server_id
WHERE nsr.host_host_id = :host_id'
);
$statement = $this->db->prepare($request);
$statement->bindValue(':host_id', $host->getId(), \PDO::PARAM_INT);
$statement->execute();
if (($records = $statement->fetch(\PDO::FETCH_ASSOC)) !== false) {
return (new EngineConfiguration())
->setId((int) $records['nagios_id'])
->setName($records['nagios_name'])
->setIllegalObjectNameCharacters($records['illegal_object_name_chars'])
->setMonitoringServerId((int) $records['nagios_server_id'])
->setNotificationsEnabledOption((int) $records['enable_notifications']);
}
return null;
}
/**
* {@inheritDoc}
* @throws \PDOException
*/
public function findEngineConfigurationByMonitoringServerId(int $monitoringServerId): ?EngineConfiguration
{
$statement = $this->db->prepare(
$this->translateDbName(
'SELECT cfg.nagios_id, cfg.nagios_name, cfg.illegal_object_name_chars, cfg.nagios_server_id
FROM `:db`.cfg_nagios cfg
INNER JOIN `:db`.ns_host_relation nsr
ON nsr.nagios_server_id = :monitoring_server_id'
)
);
$statement->bindValue(':monitoring_server_id', $monitoringServerId, \PDO::PARAM_INT);
$statement->execute();
if (($records = $statement->fetch(\PDO::FETCH_ASSOC)) !== false) {
return (new EngineConfiguration())
->setId((int) $records['nagios_id'])
->setName($records['nagios_name'])
->setIllegalObjectNameCharacters($records['illegal_object_name_chars'])
->setMonitoringServerId((int) $records['nagios_server_id']);
}
return null;
}
/**
* @inheritDoc
*/
public function findEngineConfigurationByName(string $engineName): ?EngineConfiguration
{
$request = $this->translateDbName(
'SELECT cfg.* FROM `:db`.cfg_nagios cfg
INNER JOIN `:db`.nagios_server server
ON server.id = cfg.nagios_server_id
WHERE server.name = :engine_name'
);
$statement = $this->db->prepare($request);
$statement->bindValue(':engine_name', $engineName, \PDO::PARAM_STR);
$statement->execute();
if (($records = $statement->fetch(\PDO::FETCH_ASSOC)) !== false) {
return (new EngineConfiguration())
->setId((int) $records['nagios_id'])
->setName($records['nagios_name'])
->setIllegalObjectNameCharacters($records['illegal_object_name_chars'])
->setMonitoringServerId((int) $records['nagios_server_id']);
}
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/Infrastructure/Repository/AbstractRepositoryDRB.php | centreon/src/Centreon/Infrastructure/Repository/AbstractRepositoryDRB.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Repository;
use Adaptation\Database\Connection\ConnectionInterface;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\Repository\RepositoryException;
use Centreon\Infrastructure\DatabaseConnection;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
use JsonSchema\Constraints\Constraint;
use JsonSchema\Exception\InvalidArgumentException;
use JsonSchema\Validator;
/**
* Class
*
* @class AbstractRepositoryDRB
* @package Centreon\Infrastructure\Repository
*
* @deprecated use {@see DatabaseRepository} instead
*/
class AbstractRepositoryDRB
{
use LoggerTrait;
/** @var DatabaseConnection */
protected ConnectionInterface $db;
/**
* Formats the access group ids in string. (values are separated by coma)
*
* @param AccessGroup[] $accessGroups
* @return string
*/
public function accessGroupIdToString(array $accessGroups): string
{
$ids = [];
foreach ($accessGroups as $accessGroup) {
$ids[] = $accessGroup->getId();
}
return implode(',', $ids);
}
/**
* Replace all instances of :dbstg and :db by the real db names.
* The table names of the database are defined in the services.yaml
* configuration file.
*
* @param string $request Request to translate
* @return string Request translated
*/
protected function translateDbName(string $request): string
{
return str_replace(
[':dbstg', ':db'],
[$this->db->getConnectionConfig()->getDatabaseNameRealTime(), $this->db->getConnectionConfig()->getDatabaseNameConfiguration()],
$request
);
}
/**
* Validate the Json of a property
*
* @param string $jsonRecord The JSON Property to validate
* @param string $jsonSchemaFilePath The JSON Schema Validation file
*
* @throws RepositoryException|InvalidArgumentException
*/
protected function validateJsonRecord(string $jsonRecord, string $jsonSchemaFilePath): void
{
$decodedRecord = json_decode($jsonRecord, true);
if (is_array($decodedRecord) === false) {
$this->critical('The property get from dbms is not a valid json');
throw new RepositoryException('Invalid Json format');
}
$decodedRecord = Validator::arrayToObjectRecursive($decodedRecord);
$validator = new Validator();
$validator->validate(
$decodedRecord,
(object) [
'$ref' => 'file://' . $jsonSchemaFilePath,
],
Constraint::CHECK_MODE_VALIDATE_SCHEMA
);
if ($validator->isValid() === false) {
$message = '';
foreach ($validator->getErrors() as $error) {
$message .= sprintf("[%s] %s\n", $error['property'], $error['message']);
}
$this->critical($message);
throw new RepositoryException('Some properties doesn\'t match the json schema :' . $message);
}
}
}
| 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/Repository/DataStorageEngineRdb.php | centreon/src/Centreon/Infrastructure/Repository/DataStorageEngineRdb.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Repository;
use Centreon\Domain\Repository\Interfaces\DataStorageEngineInterface;
use Centreon\Infrastructure\DatabaseConnection;
/**
* This class is designed to perform specific operations on the database
*
* @package Centreon\Infrastructure\Repository
*
* @deprecated instead use {@see DatabaseRepositoryManager}
*/
class DataStorageEngineRdb implements DataStorageEngineInterface
{
/**
* @param DatabaseConnection $db
*/
public function __construct(readonly private DatabaseConnection $db)
{
}
/**
* @inheritDoc
*/
public function startTransaction(): bool
{
return $this->db->beginTransaction();
}
/**
* @inheritDoc
*/
public function commitTransaction(): bool
{
return $this->db->commit();
}
/**
* @inheritDoc
*/
public function rollbackTransaction(): bool
{
return $this->db->rollBack();
}
/**
* @inheritDoc
*/
public function isAlreadyinTransaction(): bool
{
return $this->db->inTransaction();
}
}
| 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/Platform/PlatformRepositoryRDB.php | centreon/src/Centreon/Infrastructure/Platform/PlatformRepositoryRDB.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Platform;
use Centreon\Domain\Platform\Interfaces\PlatformRepositoryInterface;
use Centreon\Infrastructure\DatabaseConnection;
use Centreon\Infrastructure\Repository\AbstractRepositoryDRB;
/**
* This class is designed to read version numbers from a database.
*
* @package Centreon\Infrastructure\Platform
*/
class PlatformRepositoryRDB extends AbstractRepositoryDRB implements PlatformRepositoryInterface
{
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* @inheritDoc
*/
public function getWebVersion(): ?string
{
$request = $this->translateDbName('SELECT `value` FROM `:db`.informations WHERE `key` = "version"');
if (($statement = $this->db->query($request)) !== false) {
$result = $statement->fetch(\PDO::FETCH_ASSOC);
return (string) $result['value'];
}
return null;
}
/**
* @inheritDoc
*/
public function getModulesVersion(): array
{
$versions = [];
$request = $this->translateDbName('SELECT `name`, `mod_release` AS version FROM `:db`.modules_informations');
if (($statement = $this->db->query($request)) !== false) {
while ($result = $statement->fetch(\PDO::FETCH_ASSOC)) {
$versions[(string) $result['name']] = (string) $result['version'];
}
}
return $versions;
}
/**
* @inheritDoc
*/
public function getWidgetsVersion(string $webVersion): array
{
$versions = [];
$widgetModelsRequest = $this->translateDbName('SELECT `title`, `version`, `is_internal` FROM `:db`.widget_models');
if (($statement = $this->db->query($widgetModelsRequest)) !== false) {
while ($result = $statement->fetch(\PDO::FETCH_ASSOC)) {
$versions[(string) $result['title']] = $result['is_internal'] === 1
? $webVersion
: (string) $result['version'];
}
}
$dashboardWidgetsRequest = $this->translateDbName('SELECT `name` FROM `:db`.dashboard_widgets');
$version = $this->getWebVersion();
if (($statement = $this->db->query($dashboardWidgetsRequest)) !== false) {
while ($result = $statement->fetch(\PDO::FETCH_ASSOC)) {
$versions[(string) $result['name']] = $version;
}
}
return $versions;
}
}
| 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/Service/UploadFileService.php | centreon/src/Centreon/Infrastructure/Service/UploadFileService.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Service;
use Centreon\Infrastructure\FileManager\File;
use Psr\Container\ContainerInterface;
class UploadFileService
{
/** @var array|null */
protected $filesRequest;
protected ContainerInterface $services;
/**
* Construct
*
* @param ContainerInterface $services
* @param array $filesRequest Copy of $_FILES
*/
public function __construct(ContainerInterface $services, ?array $filesRequest = null)
{
$this->services = $services;
$this->filesRequest = $filesRequest;
}
/**
* Get all files
*
* @return array
*/
public function getFiles(string $fieldName, ?array $withExtension = null): array
{
$filesFromRequest = $this->prepare($fieldName);
$result = [];
foreach ($filesFromRequest as $data) {
$file = new File($data);
if ($withExtension !== null && in_array($file->getExtension(), $withExtension) === false) {
continue;
}
$result[] = $file;
}
return $result;
}
public function prepare(string $fieldName): array
{
$result = [];
if (array_key_exists($fieldName, $this->filesRequest) === false) {
return $result;
}
foreach ($this->filesRequest[$fieldName] as $prop => $values) {
if (is_array($values)) {
foreach ($values as $key => $value) {
$result[$key][$prop] = $value;
}
} else {
$result[0][$prop] = $values;
}
}
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/Infrastructure/Service/CentreonPaginationService.php | centreon/src/Centreon/Infrastructure/Service/CentreonPaginationService.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Service;
use App\Kernel;
use Centreon\Application\DataRepresenter;
use Centreon\Infrastructure\CentreonLegacyDB\Interfaces\PaginationRepositoryInterface;
use Centreon\ServiceProvider;
use Exception;
use JsonSerializable;
use Psr\Container\ContainerInterface;
use ReflectionClass;
use RuntimeException;
class CentreonPaginationService
{
public const LIMIT_MAX = 500;
/** @var CentreonDBManagerService */
protected $db;
/** @var \Symfony\Component\Serializer\Serializer */
protected $serializer;
/** @var mixed */
protected $filters;
/** @var int */
protected $limit;
/** @var int */
protected $offset;
/** @var string */
protected $repository;
/** @var array */
protected $ordering;
/** @var array */
protected $extras;
/** @var string */
protected $dataRepresenter;
/** @var array|null */
protected $context;
/** @var \Symfony\Component\DependencyInjection\ContainerInterface */
private $symfonyContainer;
/**
* Construct
*
* @param ContainerInterface $container
*/
public function __construct(ContainerInterface $container)
{
$this->db = $container->get(ServiceProvider::CENTREON_DB_MANAGER);
$this->serializer = $container->get(ServiceProvider::SERIALIZER);
$this->symfonyContainer = (Kernel::createForWeb())->getContainer();
}
/**
* List of required services
*
* @return array
*/
public static function dependencies(): array
{
return [
ServiceProvider::CENTREON_DB_MANAGER,
ServiceProvider::SERIALIZER,
];
}
/**
* Set pagination filters
*
* @param mixed $filters
* @return CentreonPaginationService
*/
public function setFilters($filters): self
{
$this->filters = $filters;
return $this;
}
/**
* @return \Symfony\Component\Serializer\Serializer
*/
public function getSerializer(): \Symfony\Component\Serializer\Serializer
{
return $this->serializer;
}
/**
* @return string
*/
public function getDataRepresenter(): string
{
return $this->dataRepresenter;
}
/**
* Set pagination limit
*
* @param int $limit
* @throws RuntimeException
* @return CentreonPaginationService
*/
public function setLimit(?int $limit = null): self
{
if ($limit !== null && $limit > static::LIMIT_MAX) {
throw new RuntimeException(
sprintf(_('Max value of limit has to be %d instead %d'), static::LIMIT_MAX, $limit)
);
}
if ($limit !== null && $limit < 1) {
throw new RuntimeException(sprintf(_('Minimum value of limit has to be 1 instead %d'), $limit));
}
$this->limit = $limit;
return $this;
}
/**
* Set pagination offset
*
* @param int $offset
* @throws RuntimeException
* @return CentreonPaginationService
*/
public function setOffset(?int $offset = null): self
{
if ($offset !== null && $offset < 1) {
throw new RuntimeException(sprintf(_('Minimum value of offset has to be 1 instead %d'), $offset));
}
$this->offset = $offset;
return $this;
}
/**
* Set pagination order
*
* @param mixed $field
* @param mixed $order
* @throws RuntimeException
* @return CentreonPaginationService
*/
public function setOrder($field, $order): self
{
$order = (! empty($order) && (strtoupper($order) == 'DESC')) ? $order : 'ASC';
$this->ordering = ['field' => $field, 'order' => $order];
return $this;
}
/**
* Set pagination order
*
* @param array $extras
* @throws RuntimeException
* @return CentreonPaginationService
*/
public function setExtras($extras): self
{
$this->extras = $extras;
return $this;
}
/**
* Set repository class
*
* @param string $repository
* @throws Exception
* @return CentreonPaginationService
*/
public function setRepository(string $repository): self
{
$interface = PaginationRepositoryInterface::class;
$ref = new ReflectionClass($repository);
$hasInterface = $ref->isSubclassOf($interface);
if ($hasInterface === false) {
throw new Exception(sprintf(_('Repository class %s has to implement %s'), $repository, $interface));
}
$this->repository = $repository;
return $this;
}
/**
* Set data representer class
*
* @param string $dataRepresenter
* @throws Exception
* @return CentreonPaginationService
*/
public function setDataRepresenter(string $dataRepresenter): self
{
$interface = JsonSerializable::class;
$ref = new ReflectionClass($dataRepresenter);
$hasInterface = $ref->isSubclassOf($interface);
if ($hasInterface === false) {
throw new Exception(
sprintf(_('Class %s has to implement %s to be DataRepresenter'), $dataRepresenter, $interface)
);
}
$this->dataRepresenter = $dataRepresenter;
return $this;
}
/**
* Set the Serializer context and if the context is different from null value
* the list of entities will be normalized
*
* @param array $context
* @return CentreonPaginationService
*/
public function setContext(?array $context = null): self
{
$this->context = $context;
return $this;
}
/**
* Get paginated list
*
* @return DataRepresenter\Listing
*/
public function getListing(): DataRepresenter\Listing
{
$repository = $this->symfonyContainer->get($this->repository);
$entities = $repository
->getPaginationList($this->filters, $this->limit, $this->offset, $this->ordering, $this->extras);
$total = $repository->getPaginationListTotal();
// Serialize list of entities
if ($this->context !== null) {
$entities = $this->serializer->normalize($entities, null, $this->context);
}
return new DataRepresenter\Listing($entities, $total, $this->offset, $this->limit, $this->dataRepresenter);
}
/**
* Get response data representer with paginated list
*
* @return DataRepresenter\Response
*/
public function getResponse(): DataRepresenter\Response
{
return new DataRepresenter\Response($this->getListing());
}
}
| 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/Service/CentreonClapiService.php | centreon/src/Centreon/Infrastructure/Service/CentreonClapiService.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Service;
use Centreon\Infrastructure\Service\Exception\NotFoundException;
use Centreon\Infrastructure\Service\Traits\ServiceContainerTrait;
use Psr\Container\ContainerInterface;
use ReflectionClass;
class CentreonClapiService implements ContainerInterface
{
use ServiceContainerTrait;
/**
* Register service as CLI
*
* @param string $object
* @throws NotFoundException
* @return CentreonClapiService
*/
public function add(string $object): self
{
$interface = CentreonClapiServiceInterface::class;
$hasInterface = (new ReflectionClass($object))
->implementsInterface($interface);
if ($hasInterface === false) {
throw new NotFoundException(sprintf(_('Object %s must implement %s'), $object, $interface));
}
$name = strtolower($object::getName());
$this->objects[$name] = $object;
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/Infrastructure/Service/CentcoreCommandService.php | centreon/src/Centreon/Infrastructure/Service/CentcoreCommandService.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Service;
use Centreon\Domain\Entity\Command;
class CentcoreCommandService
{
/**
* @param Command $command
* @return mixed
*/
public function sendCommand(Command $command)
{
// generate a hashed name to avoid conflict with other external commands
$commandFile = hash('sha256', $command->getCommandLine()) . '.cmd';
return file_put_contents(
_CENTREON_VARLIB_ . '/centcore/' . $commandFile,
$command->getCommandLine() . "\n",
FILE_APPEND
);
}
}
| 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/Service/CentreonClapiServiceInterface.php | centreon/src/Centreon/Infrastructure/Service/CentreonClapiServiceInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Service;
use Pimple\Container;
interface CentreonClapiServiceInterface
{
/**
* Construct
*
* @param Container $di
*/
public function __construct(Container $di);
/**
* Get name of CLAPI service
*
* @return string
*/
public static function getName(): string;
}
| 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/Service/CentcoreConfigService.php | centreon/src/Centreon/Infrastructure/Service/CentcoreConfigService.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Service;
/**
* Class CentcoreConfigService
*
* @package Centreon\Infrastructure\Service
*/
class CentcoreConfigService
{
public const CONF_WEB = 'instCentWeb.conf';
public const MACROS_DELIMITER_TEMPLATE = '@%s@';
/** @var array */
private $macros;
/**
* Macros getter
*
* @return array
*/
public function getMacros(): array
{
if ($this->macros === null) {
$this->initMacros();
}
return $this->macros;
}
/**
* Replace macros with their values
*
* @param string $string
*/
public function replaceMacros(&$string): void
{
$macros = $this->getMacros();
foreach ($macros as $key => $val) {
$key = str_replace("'", "\\'", $key);
$macro = sprintf(static::MACROS_DELIMITER_TEMPLATE, $key);
$string = str_replace($macro, $val, $string);
}
}
private function initMacros(): void
{
$data = $this->parseIniFile(_CENTREON_ETC_ . '/' . static::CONF_WEB);
$this->macros = [
'centreon_dir' => "{$data['INSTALL_DIR_CENTREON']}/",
'centreon_etc' => "{$data['CENTREON_ETC']}/",
'centreon_dir_www' => "{$data['INSTALL_DIR_CENTREON']}/www/",
'centreon_dir_rrd' => "{$data['INSTALL_DIR_CENTREON']}/rrd/",
'centreon_log' => "{$data['CENTREON_LOG']}",
'centreon_cachedir' => "{$data['CENTREON_CACHEDIR']}/",
'centreon_varlib' => "{$data['CENTREON_VARLIB']}",
'centreon_group' => "{$data['CENTREON_GROUP']}",
'centreon_user' => "{$data['CENTREON_USER']}",
'rrdtool_dir' => "{$data['BIN_RRDTOOL']}",
'apache_user' => "{$data['WEB_USER']}",
'apache_group' => "{$data['WEB_GROUP']}",
'mail' => "{$data['BIN_MAIL']}",
'broker_user' => "{$data['BROKER_USER']}",
'broker_group' => 'centreon-broker',
'broker_etc' => "{$data['BROKER_ETC']}",
'monitoring_user' => "{$data['MONITORINGENGINE_USER']}",
'monitoring_group' => "{$data['MONITORINGENGINE_GROUP']}",
'monitoring_etc' => "{$data['MONITORINGENGINE_ETC']}",
'monitoring_binary' => "{$data['MONITORINGENGINE_BINARY']}",
'monitoring_varlog' => "{$data['MONITORINGENGINE_LOG']}",
'plugin_dir' => "{$data['PLUGIN_DIR']}",
'address' => hostCentreon,
'address_storage' => hostCentstorage,
'port' => port,
'db' => db,
'db_user' => user,
'db_password' => password,
'db_storage' => dbcstg,
'monitoring_var_lib' => '/var/lib/centreon-engine',
'centreon_engine_lib' => '/usr/lib64/centreon-engine',
'centreon_engine_stats_binary' => '/usr/sbin/centenginestats',
'centreon_engine_connectors' => '/usr/lib64/centreon-connector',
'centreonbroker_lib' => '/usr/share/centreon/lib/centreon-broker',
'centreonbroker_varlib' => '/var/lib/centreon-broker',
'centreonbroker_log' => '/var/log/centreon-broker',
'centreonbroker_etc' => '/etc/centreon-broker',
'centreonplugins' => '/usr/lib/centreon/plugins',
'centreon_plugins' => '/usr/lib/centreon/plugins',
];
// @todo try to extract missing data from DB
/*
* monitoring_var_lib -> cfg_centreonbroker.cache_directory (config_id: 3, config_name: central-module-master)
* centreon_engine_lib -> broker_module.cfg_nagios_broker_module (cfg_nagios_id)
* centreon_engine_stats_binary -> nagios_server.nagiostats_bin
* centreon_engine_connectors -> nagios_server.centreonconnector_path
* centreonbroker_lib -> nagios_server.centreonbroker_module_path
* centreonbroker_varlib -> cfg_centreonbroker.cache_directory
* centreonbroker_log
* centreonbroker_etc
* centreonplugins -> cfg_resource.resource_line (resource_name: $CENTREONPLUGINS$)
* centreon_plugins
*/
}
private function parseIniFile($filename): array
{
try {
return parse_ini_file($filename);
} catch (\Exception $ex) {
return [];
}
}
}
| 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/Service/CentreonDBManagerService.php | centreon/src/Centreon/Infrastructure/Service/CentreonDBManagerService.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Service;
use Centreon\Infrastructure\CentreonLegacyDB\CentreonDBAdapter;
use Psr\Container\ContainerInterface;
/**
* Compatibility with Doctrine
*/
class CentreonDBManagerService
{
/** @var string */
private $defaultManager = 'configuration_db';
/** @var array<string,mixed> */
private $manager;
/**
* Construct
*
* @param ContainerInterface $services
*/
public function __construct(ContainerInterface $services)
{
$this->manager = [
'configuration_db' => new CentreonDBAdapter($services->get('configuration_db'), $this),
'realtime_db' => new CentreonDBAdapter($services->get('realtime_db'), $this),
];
}
public function getAdapter(string $alias): CentreonDBAdapter
{
return $this->manager[$alias] ?? null;
}
/**
* Get default adapter with DB connection
*
* @return CentreonDBAdapter
*/
public function getDefaultAdapter(): CentreonDBAdapter
{
return $this->manager[$this->defaultManager];
}
/**
* @param mixed $repository
*/
public function getRepository($repository): mixed
{
return $this->manager[$this->defaultManager]
->getRepository($repository);
}
}
| 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/Service/CentreonWebserviceService.php | centreon/src/Centreon/Infrastructure/Service/CentreonWebserviceService.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Service;
use Centreon\Infrastructure\Service\Exception\NotFoundException;
use Centreon\Infrastructure\Service\Traits\ServiceContainerTrait;
use CentreonRemote\Application\Webservice\CentreonWebServiceAbstract;
use CentreonWebService;
use Psr\Container\ContainerInterface;
use ReflectionClass;
class CentreonWebserviceService implements ContainerInterface
{
use ServiceContainerTrait;
/**
* Add webservice from DI
*
* @param string $object
* @throws NotFoundException
* @return self
*/
public function add(string $object): self
{
$centreonClass = CentreonWebService::class;
$abstractClass = CentreonWebServiceAbstract::class;
$ref = new ReflectionClass($object);
$hasInterfaces = (
$ref->isSubclassOf($centreonClass)
|| $ref->isSubclassOf($abstractClass)
);
if ($hasInterfaces === false) {
throw new NotFoundException(
sprintf(_('Object %s must extend %s class or %s class'), $object, $centreonClass, $abstractClass)
);
}
$name = strtolower($object::getName());
$this->objects[$name] = $object;
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/Infrastructure/Service/Traits/ServiceContainerTrait.php | centreon/src/Centreon/Infrastructure/Service/Traits/ServiceContainerTrait.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Service\Traits;
use Centreon\Infrastructure\Service\Exception\NotFoundException;
trait ServiceContainerTrait
{
/** @var array<string|int,mixed> */
private $objects = [];
public function has($id): bool
{
return array_key_exists(strtolower($id), $this->objects);
}
public function get($id): string
{
if ($this->has($id) === false) {
throw new NotFoundException(sprintf(_('Not found exporter with name: %d'), $id));
}
return $this->objects[strtolower($id)];
}
public function all(): array
{
return $this->objects;
}
}
| 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/Service/Exception/NotFoundException.php | centreon/src/Centreon/Infrastructure/Service/Exception/NotFoundException.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Service\Exception;
use RuntimeException;
class NotFoundException extends RuntimeException
{
}
| 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/Proxy/ProxyRepositoryRDB.php | centreon/src/Centreon/Infrastructure/Proxy/ProxyRepositoryRDB.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Proxy;
use Centreon\Domain\Proxy\Interfaces\ProxyRepositoryInterface;
use Centreon\Domain\Proxy\Proxy;
use Centreon\Infrastructure\DatabaseConnection;
use Centreon\Infrastructure\Repository\AbstractRepositoryDRB;
class ProxyRepositoryRDB extends AbstractRepositoryDRB implements ProxyRepositoryInterface
{
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* @inheritDoc
*/
public function updateProxy(Proxy $proxy): void
{
$request
= 'DELETE FROM `:db`.options
WHERE `key` IN (\'proxy_url\', \'proxy_port\', \'proxy_user\', \'proxy_password\')';
$request = $this->translateDbName($request);
$this->db->query($request);
$request = 'INSERT INTO `:db`.options (`key`,`value`) VALUES (:key, :value)';
$request = $this->translateDbName($request);
$prepareStatement = $this->db->prepare($request);
$data = [
'proxy_url' => $proxy->getUrl(),
'proxy_port' => $proxy->getPort(),
'proxy_user' => $proxy->getUser(),
'proxy_password' => $proxy->getPassword(),
];
foreach ($data as $key => $value) {
$prepareStatement->bindParam(':key', $key);
$prepareStatement->bindParam(':value', $value);
$prepareStatement->execute();
}
}
/**
* @inheritDoc
*/
public function getProxy(): Proxy
{
$request = $this->translateDbName(
'SELECT * FROM `:db`.options WHERE `key` LIKE \'proxy_%\''
);
$proxy = new Proxy();
$statement = $this->db->query($request);
if ($statement !== false) {
$proxyDetails = $statement->fetchAll(\PDO::FETCH_KEY_PAIR);
if (! empty($proxyDetails)) {
$proxy->setUrl($proxyDetails['proxy_url'] ?? null);
$proxy->setPort(isset($proxyDetails['proxy_port']) ? (int) $proxyDetails['proxy_port'] : null);
$proxy->setUser($proxyDetails['proxy_user'] ?? null);
$proxy->setPassword($proxyDetails['proxy_password'] ?? null);
}
}
return $proxy;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Security/Encryption.php | centreon/src/Security/Encryption.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Security;
use Security\Interfaces\EncryptionInterface;
class Encryption implements EncryptionInterface
{
/** @var string|null First secure key */
private $firstKey;
/** @var string|null Second secure key */
private $secondKey;
/** @var string Encryption method use to encrypt/decrypt data */
private $encryptionMethod;
/** @var string Hashing method use to hash/unhash data during */
private $hashingAlgorithm;
public function __construct(string $encryptionMethod = 'aes-256-cbc', string $hashingAlgorithm = 'sha3-512')
{
$this->encryptionMethod = $encryptionMethod;
$this->hashingAlgorithm = $hashingAlgorithm;
}
/**
* For more security, we modify the references of the first and second keys.
*
* @see Encryption::$firstKey
* @see Encryption::$secondKey
*/
public function __destruct()
{
$this->firstKey = null;
$this->secondKey = null;
}
/**
* @inheritDoc
*/
public function crypt(string $data): string
{
if ($this->firstKey === null) {
throw new \Exception('First key not defined');
}
if ($this->secondKey === null) {
throw new \Exception('Second key not defined');
}
$ivLength = openssl_cipher_iv_length($this->encryptionMethod);
if ($ivLength === false) {
throw new \Exception('Error when retrieving the cipher length', 10);
}
$iv = openssl_random_pseudo_bytes($ivLength);
if (! $iv) {
throw new \Exception('Error on generated string of bytes', 11);
}
$encryptedFirstPart = openssl_encrypt($data, $this->encryptionMethod, $this->firstKey, OPENSSL_RAW_DATA, $iv);
if ($encryptedFirstPart === false) {
throw new \Exception('Error on the encrypted string', 12);
}
$encryptedSecondPart = hash_hmac($this->hashingAlgorithm, $encryptedFirstPart, $this->secondKey, true);
return base64_encode($iv . $encryptedSecondPart . $encryptedFirstPart);
}
/**
* @inheritDoc
*/
public function decrypt(string $input): ?string
{
if ($this->firstKey === null) {
throw new \Exception('First key not defined');
}
if ($this->secondKey === null) {
throw new \Exception('Second key not defined');
}
$mix = base64_decode($input);
$ivLength = openssl_cipher_iv_length($this->encryptionMethod);
if ($ivLength === false) {
throw new \Exception('Error when retrieving the cipher length', 20);
}
$iv = substr($mix, 0, $ivLength);
if (! $iv) {
throw new \Exception('Error during the decryption process', 21);
}
$encryptedFirstPart = substr($mix, $ivLength + 64);
if (! $encryptedFirstPart) {
throw new \Exception('Error during the decryption process', 22);
}
$encryptedSecondPart = substr($mix, $ivLength, 64);
if (! $encryptedSecondPart) {
throw new \Exception('Error during the decryption process', 23);
}
$data = openssl_decrypt($encryptedFirstPart, $this->encryptionMethod, $this->firstKey, OPENSSL_RAW_DATA, $iv);
if ($data !== false) {
$secondEncryptedNew = hash_hmac($this->hashingAlgorithm, $encryptedFirstPart, $this->secondKey, true);
if (hash_equals($encryptedSecondPart, $secondEncryptedNew)) {
return $data;
}
}
return null;
}
/**
* @inheritDoc
*/
public function setSecondKey(string $secondKey): EncryptionInterface
{
$this->secondKey = base64_decode($secondKey);
return $this;
}
/**
* @inheritDoc
*/
public function setFirstKey(string $firstKey): EncryptionInterface
{
$this->firstKey = base64_decode($firstKey);
return $this;
}
/**
* @inheritDoc
*/
public static function generateRandomString(int $length = 64): string
{
$randomBytes = openssl_random_pseudo_bytes($length);
if (! $randomBytes) {
throw new \Exception('Error when generating random bytes', 30);
}
$encodedRandomBytes = base64_encode($randomBytes);
return substr($encodedRandomBytes, 0, $length);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Security/TokenAPIAuthenticator.php | centreon/src/Security/TokenAPIAuthenticator.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Security;
use Adaptation\Log\LoggerToken;
use Centreon\Domain\Contact\Interfaces\ContactRepositoryInterface;
use Centreon\Domain\Exception\ContactDisabledException;
use Centreon\Domain\Log\LoggerTrait;
use Core\Security\Token\Application\Repository\ReadTokenRepositoryInterface;
use Core\Security\Token\Domain\Model\ApiToken;
use Security\Domain\Authentication\Interfaces\AuthenticationRepositoryInterface;
use Security\Domain\Authentication\Model\LocalProvider;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Exception\CredentialsExpiredException;
use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
use Symfony\Component\Security\Core\Exception\TokenNotFoundException;
use Symfony\Component\Security\Core\Exception\UserNotFoundException;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Http\Authenticator\AbstractAuthenticator;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\SelfValidatingPassport;
use Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface;
/**
* Class used to authenticate a request by using a security token.
*/
class TokenAPIAuthenticator extends AbstractAuthenticator implements AuthenticationEntryPointInterface
{
use LoggerTrait;
/**
* TokenAPIAuthenticator constructor.
*
* @param AuthenticationRepositoryInterface $authenticationRepository
* @param ContactRepositoryInterface $contactRepository
* @param LocalProvider $localProvider
* @param ReadTokenRepositoryInterface $readTokenRepository
*/
public function __construct(
private AuthenticationRepositoryInterface $authenticationRepository,
private ContactRepositoryInterface $contactRepository,
private LocalProvider $localProvider,
private ReadTokenRepositoryInterface $readTokenRepository,
) {
}
/**
* @inheritDoc
*/
public function start(Request $request, ?AuthenticationException $authException = null): Response
{
$data = [
'message' => _('Authentication Required'),
];
return new JsonResponse($data, Response::HTTP_UNAUTHORIZED);
}
/**
* @inheritDoc
*/
public function supports(Request $request): bool
{
return $request->headers->has('X-AUTH-TOKEN');
}
/**
* @inheritDoc
*/
public function onAuthenticationFailure(Request $request, AuthenticationException $exception): ?Response
{
$data = [
'message' => strtr($exception->getMessageKey(), $exception->getMessageData()),
];
return new JsonResponse($data, Response::HTTP_UNAUTHORIZED);
}
/**
* @inheritDoc
*/
public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $providerKey): ?Response
{
$this->logTokenUsage($request);
return null;
}
/**
* {@inheritDoc}
*
* @throws CustomUserMessageAuthenticationException
* @throws TokenNotFoundException
*
* @return SelfValidatingPassport
*/
public function authenticate(Request $request): SelfValidatingPassport
{
$apiToken = $request->headers->get('X-AUTH-TOKEN');
if ($apiToken === null) {
// The token header was empty, authentication fails with HTTP Status
// Code 401 "Unauthorized"
throw new TokenNotFoundException('API token not provided');
}
return new SelfValidatingPassport(
new UserBadge(
$apiToken,
fn ($userIdentifier) => $this->getUserAndUpdateToken($userIdentifier)
)
);
}
/**
* Return a UserInterface object based on the token provided.
*
* @param string $apiToken
*
* @throws TokenNotFoundException
* @throws CredentialsExpiredException
* @throws ContactDisabledException
*
* @return UserInterface
*/
private function getUserAndUpdateToken(string $apiToken): UserInterface
{
$providerToken = $this->localProvider->getProviderToken($apiToken);
$expirationDate = $providerToken->getExpirationDate();
if ($expirationDate !== null && $expirationDate->getTimestamp() < time()) {
throw new CredentialsExpiredException();
}
$contact = $this->contactRepository->findByAuthenticationToken($providerToken->getToken());
if ($contact === null) {
throw new UserNotFoundException();
}
if (! $contact->isActive()) {
throw new ContactDisabledException();
}
if ($this->readTokenRepository->isTokenTypeAuto($apiToken)) {
$this->authenticationRepository->updateProviderTokenExpirationDate($providerToken);
}
return $contact;
}
private function logTokenUsage(Request $request): void
{
try {
$tokenString = $request->headers->get('X-AUTH-TOKEN');
if ($tokenString && ! $this->readTokenRepository->isTokenTypeAuto($tokenString)) {
/** @var ApiToken|null $apiToken */
$apiToken = $this->readTokenRepository->find($tokenString);
if ($apiToken instanceof ApiToken) {
LoggerToken::create()->success(
event: 'usage',
userId: $apiToken->getCreatorId(),
tokenName: $apiToken->getName(),
tokenType: 'api',
endpoint: $request->getRequestUri(),
httpMethod: $request->getMethod(),
);
}
}
} catch (\Throwable $ex) {
$this->error('Token usage log failure', ['exception' => $ex]);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Security/SessionAPIAuthenticator.php | centreon/src/Security/SessionAPIAuthenticator.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Security;
use Centreon\Domain\Contact\Interfaces\ContactRepositoryInterface;
use Centreon\Domain\Exception\ContactDisabledException;
use Security\Domain\Authentication\Interfaces\AuthenticationServiceInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
use Symfony\Component\Security\Core\Exception\SessionUnavailableException;
use Symfony\Component\Security\Core\Exception\TokenNotFoundException;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Http\Authenticator\AbstractAuthenticator;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\SelfValidatingPassport;
/**
* Class used to authenticate a request by using a session id.
*/
class SessionAPIAuthenticator extends AbstractAuthenticator
{
/**
* SessionAPIAuthenticator constructor.
*
* @param AuthenticationServiceInterface $authenticationService
* @param ContactRepositoryInterface $contactRepository
*/
public function __construct(
private AuthenticationServiceInterface $authenticationService,
private ContactRepositoryInterface $contactRepository,
) {
}
/**
* @inheritDoc
*/
public function supports(Request $request): bool
{
return $request->headers->has('Cookie') && ! empty($request->getSession()->getId())
&& ! $request->headers->has('X-Auth-Token');
}
/**
* @inheritDoc
*/
public function onAuthenticationFailure(Request $request, AuthenticationException $exception): ?Response
{
$data = [
'message' => strtr($exception->getMessageKey(), $exception->getMessageData()),
];
return new JsonResponse($data, Response::HTTP_UNAUTHORIZED);
}
/**
* @inheritDoc
*/
public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $providerKey): ?Response
{
return null;
}
/**
* {@inheritDoc}
*
* @throws CustomUserMessageAuthenticationException
* @throws TokenNotFoundException
*
* @return SelfValidatingPassport
*/
public function authenticate(Request $request): SelfValidatingPassport
{
/**
* @var string|null $sessionId
*/
$sessionId = $request->getSession()->getId();
if ($sessionId === null) {
// The token header was empty, authentication fails with HTTP Status
// Code 401 "Unauthorized"
throw new SessionUnavailableException('Session id not provided');
}
return new SelfValidatingPassport(
new UserBadge(
$sessionId,
function ($userIdentifier) {
return $this->getUserAndUpdateSession($userIdentifier);
}
)
);
}
/**
* Return a UserInterface object based on session id provided.
*
* @param string $sessionId
*
* @throws BadCredentialsException
* @throws SessionUnavailableException
* @throws ContactDisabledException
*
* @return UserInterface
*/
private function getUserAndUpdateSession(string $sessionId): UserInterface
{
$isValidToken = $this->authenticationService->isValidToken($sessionId);
if (! $isValidToken) {
throw new BadCredentialsException();
}
$contact = $this->contactRepository->findBySession($sessionId);
if ($contact === null) {
throw new SessionUnavailableException();
}
if ($contact->isActive() === false) {
throw new ContactDisabledException();
}
// force api access to true cause it comes from session
$contact
->setAccessToApiRealTime(true)
->setAccessToApiConfiguration(true);
// It's an internal API call, so this contact has all roles
return $contact;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Security/WebSSOAuthenticator.php | centreon/src/Security/WebSSOAuthenticator.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Security;
use Centreon\Domain\Contact\Interfaces\{ContactInterface, ContactRepositoryInterface};
use Centreon\Domain\Exception\ContactDisabledException;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\Menu\Interfaces\MenuServiceInterface;
use Centreon\Domain\Menu\Model\Page;
use Centreon\Domain\Option\Interfaces\OptionServiceInterface;
use Centreon\Domain\Platform\Interfaces\PlatformRepositoryInterface;
use Centreon\Domain\Repository\Interfaces\DataStorageEngineInterface;
use Centreon\Domain\VersionHelper;
use Core\Infrastructure\Common\Api\HttpUrlTrait;
use Core\Security\Authentication\Application\Provider\{
ProviderAuthenticationFactoryInterface,
ProviderAuthenticationInterface
};
use Core\Security\Authentication\Application\Repository\{
WriteSessionRepositoryInterface,
WriteTokenRepositoryInterface
};
use Core\Security\Authentication\Application\UseCase\Login\LoginRequest;
use Core\Security\Authentication\Domain\Exception\AuthenticationException as CentreonAuthenticationException;
use Core\Security\Authentication\Domain\Exception\SSOAuthenticationException;
use Core\Security\Authentication\Domain\Model\{NewProviderToken, ProviderToken};
use Core\Security\ProviderConfiguration\Domain\Model\Provider;
use DateInterval;
use DateTimeImmutable;
use FOS\RestBundle\View\View;
use Security\Domain\Authentication\Interfaces\{AuthenticationServiceInterface, SessionRepositoryInterface};
use Security\Domain\Authentication\Model\Session;
use Symfony\Component\HttpFoundation\{Request, Response};
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\{
AuthenticationException,
BadCredentialsException,
CredentialsExpiredException,
SessionUnavailableException,
UserNotFoundException
};
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Http\Authenticator\AbstractAuthenticator;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\SelfValidatingPassport;
class WebSSOAuthenticator extends AbstractAuthenticator
{
use HttpUrlTrait;
use LoggerTrait;
private const MINIMUM_SUPPORTED_VERSION = '22.04';
/** @var ProviderAuthenticationInterface */
private ProviderAuthenticationInterface $provider;
/**
* @param AuthenticationServiceInterface $authenticationService
* @param SessionRepositoryInterface $sessionRepository
* @param DataStorageEngineInterface $dataStorageEngine
* @param OptionServiceInterface $optionService
* @param WriteTokenRepositoryInterface $writeTokenRepository
* @param WriteSessionRepositoryInterface $writeSessionRepository
* @param ProviderAuthenticationFactoryInterface $providerFactory
* @param ContactRepositoryInterface $contactRepository
* @param MenuServiceInterface $menuService
* @param PlatformRepositoryInterface $platformRepository
*/
public function __construct(
private AuthenticationServiceInterface $authenticationService,
private SessionRepositoryInterface $sessionRepository,
private DataStorageEngineInterface $dataStorageEngine,
private OptionServiceInterface $optionService,
private WriteTokenRepositoryInterface $writeTokenRepository,
private WriteSessionRepositoryInterface $writeSessionRepository,
private ProviderAuthenticationFactoryInterface $providerFactory,
private ContactRepositoryInterface $contactRepository,
private MenuServiceInterface $menuService,
private PlatformRepositoryInterface $platformRepository,
) {
/** @var string */
$webVersion = $this->platformRepository->getWebVersion();
if (VersionHelper::compare($webVersion, self::MINIMUM_SUPPORTED_VERSION, VersionHelper::GE)) {
$this->provider = $this->providerFactory->create(Provider::WEB_SSO);
}
}
/**
* @inheritDoc
*/
public function supports(Request $request): bool
{
/** @var string */
$webVersion = $this->platformRepository->getWebVersion();
// We skip all API calls
if (
$request->headers->has('X-Auth-Token')
|| VersionHelper::compare($webVersion, self::MINIMUM_SUPPORTED_VERSION, VersionHelper::LT)
) {
return false;
}
$configuration = $this->provider->getConfiguration();
$sessionId = $request->getSession()->getId();
$isValidToken = $this->authenticationService->isValidToken($sessionId);
return ! $isValidToken && $configuration->isActive();
}
/**
* @inheritDoc
*/
public function onAuthenticationFailure(Request $request, AuthenticationException $exception): ?Response
{
$this->info(sprintf("WebSSO authentication failed: %s\n", $exception->getMessage()));
throw SSOAuthenticationException::withMessageAndCode($exception->getMessage(), $exception->getCode());
}
/**
* @inheritDoc
*/
public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $providerKey): ?Response
{
return null;
}
/**
* {@inheritDoc}
*
* @param Request $request
*
* @throws SSOAuthenticationException
* @throws CentreonAuthenticationException
*
* @return SelfValidatingPassport
*/
public function authenticate(Request $request): SelfValidatingPassport
{
try {
$this->info('Starting authentication with WebSSO');
$this->provider->authenticateOrFail(
LoginRequest::createForSSO($request->getClientIp() ?? '')
);
$user = $this->provider->findUserOrFail();
$this->createSession($request, $this->provider);
$this->info(
'Authenticated successfully',
['user' => $user->getAlias(), 'sessionId' => $request->getSession()->getId()]
);
// getRedirectionUri() expects ONLY a string as its second parameter
$referer = $request->headers->get('referer', '');
if (! empty($referer)) {
$referer = parse_url($referer, PHP_URL_QUERY);
if (! is_string($referer)) {
$referer = '';
}
}
View::createRedirect(
$this->getRedirectionUri(
$this->provider->getAuthenticatedUser(),
$referer
),
200
);
} catch (SSOAuthenticationException $exception) {
throw new AuthenticationException($exception->getMessage(), $exception->getCode());
}
return new SelfValidatingPassport(
new UserBadge(
$request->getSession()->getId(),
function ($userIdentifier) {
return $this->getUser($userIdentifier);
}
)
);
}
/**
* Return a UserInterface object based on session id provided.
*
* @param string $sessionId
*
* @throws BadCredentialsException
* @throws SessionUnavailableException
* @throws ContactDisabledException
*
* @return UserInterface
*/
private function getUser(string $sessionId): UserInterface
{
$providerToken = $this->provider->getProviderToken($sessionId);
$expirationDate = $providerToken->getExpirationDate();
if ($expirationDate !== null && $expirationDate->getTimestamp() < time()) {
throw new CredentialsExpiredException();
}
$contact = $this->contactRepository->findByAuthenticationToken($providerToken->getToken());
if ($contact === null) {
throw new UserNotFoundException();
}
if (! $contact->isActive()) {
throw new ContactDisabledException();
}
return $contact;
}
/**
* Create the session.
*
* @param Request $request
* @param ProviderAuthenticationInterface $provider
*
* @throws \Centreon\Domain\Authentication\Exception\AuthenticationException
*/
private function createSession(Request $request, ProviderAuthenticationInterface $provider): void
{
$this->debug('Creating session');
if ($this->writeSessionRepository->start($provider->getLegacySession())) {
$sessionId = $request->getSession()->getId();
// @todo: why are we not using findUserOrFail()?
$authenticatedUser = $provider->getAuthenticatedUser();
if ($authenticatedUser === null) {
throw new \Centreon\Domain\Authentication\Exception\AuthenticationException(
'No authenticated user could be found for provider'
);
}
$this->createTokenIfNotExist(
$sessionId,
$provider->getConfiguration()->getId(),
$authenticatedUser,
$request->getClientIp() ?? '' // @todo: what should happen if no IP was found?
);
$request->headers->set('Set-Cookie', 'PHPSESSID=' . $sessionId);
}
}
/**
* Create token if not exist.
*
* @param string $sessionId
* @param int $webSSOConfigurationId
* @param ContactInterface $user
* @param string $clientIp
*
* @throws \Centreon\Domain\Authentication\Exception\AuthenticationException
*/
private function createTokenIfNotExist(
string $sessionId,
int $webSSOConfigurationId,
ContactInterface $user,
string $clientIp,
): void {
$this->info('creating token');
$authenticationTokens = $this->authenticationService->findAuthenticationTokensByToken(
$sessionId
);
if ($authenticationTokens === null) {
$sessionExpireOption = $this->optionService->findSelectedOptions(['session_expire']);
$sessionExpirationDelay = (int) $sessionExpireOption[0]->getValue();
$token = new ProviderToken(
$webSSOConfigurationId,
$sessionId,
new DateTimeImmutable(),
(new DateTimeImmutable())->add(new DateInterval('PT' . $sessionExpirationDelay . 'M'))
);
$this->createAuthenticationTokens(
$sessionId,
$user,
$token,
null,
$clientIp,
);
}
}
/**
* create Authentication tokens.
*
* @param string $sessionToken
* @param ContactInterface $contact
* @param ProviderToken $providerToken
* @param ProviderToken|null $providerRefreshToken
* @param string|null $clientIp
*
* @throws CentreonAuthenticationException
*/
private function createAuthenticationTokens(
string $sessionToken,
ContactInterface $contact,
NewProviderToken $providerToken,
?NewProviderToken $providerRefreshToken,
?string $clientIp,
): void {
$isAlreadyInTransaction = $this->dataStorageEngine->isAlreadyinTransaction();
if (! $isAlreadyInTransaction) {
$this->dataStorageEngine->startTransaction();
}
try {
$session = new Session($sessionToken, $contact->getId(), $clientIp);
$this->sessionRepository->addSession($session);
$this->writeTokenRepository->createAuthenticationTokens(
$sessionToken,
$providerToken->getId(),
$contact->getId(),
$providerToken,
$providerRefreshToken
);
if (! $isAlreadyInTransaction) {
$this->dataStorageEngine->commitTransaction();
}
} catch (\Exception $ex) {
$this->error('Unable to create authentication tokens', [
'trace' => $ex->getTraceAsString(),
]);
if (! $isAlreadyInTransaction) {
$this->dataStorageEngine->rollbackTransaction();
}
throw CentreonAuthenticationException::notAuthenticated();
}
}
/**
* Get the redirection uri where user will be redirect once logged.
*
* @param null|ContactInterface $authenticatedUser
* @param string|null $refererQueryParameters
*
* @return string
*/
private function getRedirectionUri(
?ContactInterface $authenticatedUser,
?string $refererQueryParameters,
): string {
$redirectionUri = '/monitoring/resources';
if ($authenticatedUser === null) {
// The previous version assummed that if no conditions were met, just send this var as-is
return $redirectionUri;
}
$refererRedirectionPage = $this->getRedirectionPageFromRefererQueryParameters($refererQueryParameters);
if ($refererRedirectionPage !== null) {
$redirectionUri = $this->buildDefaultRedirectionUri($refererRedirectionPage);
} elseif ($authenticatedUser->getDefaultPage()?->getUrl() !== null) {
$redirectionUri = $this->buildDefaultRedirectionUri($authenticatedUser->getDefaultPage());
}
return $redirectionUri;
}
/**
* build the redirection uri based on isReact page property.
*
* @param Page $defaultPage
*
* @return string
*/
private function buildDefaultRedirectionUri(Page $defaultPage): string
{
if ($defaultPage->isReact() === true) {
return $defaultPage->getUrl();
}
$redirectUri = '/main.php?p=' . $defaultPage->getPageNumber();
if ($defaultPage->getUrlOptions() !== null) {
$redirectUri .= $defaultPage->getUrlOptions();
}
return $redirectUri;
}
/**
* Get a Page from referer page number.
*
* @param string|null $refererQueryParameters
*
* @return Page|null
*/
private function getRedirectionPageFromRefererQueryParameters(?string $refererQueryParameters): ?Page
{
if ($refererQueryParameters === null) {
return null;
}
$refererRedirectionPage = null;
$queryParameters = [];
parse_str($refererQueryParameters, $queryParameters);
if (is_string($queryParameters['redirect'] ?? null)) {
$redirectionPageParameters = [];
parse_str($queryParameters['redirect'], $redirectionPageParameters);
if (array_key_exists('p', $redirectionPageParameters)) {
$refererRedirectionPage = $this->menuService->findPageByTopologyPageNumber(
(int) $redirectionPageParameters['p']
);
unset($redirectionPageParameters['p']);
if ($refererRedirectionPage !== null) {
$refererRedirectionPage->setUrlOptions('&' . http_build_query($redirectionPageParameters));
}
}
}
return $refererRedirectionPage;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Security/Interfaces/EncryptionInterface.php | centreon/src/Security/Interfaces/EncryptionInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Security\Interfaces;
interface EncryptionInterface
{
/**
* Generates a random string.
*
* Can be use as salt with password.
*
* @param int $length Length of the generated string
*
* @throws \Exception
*
* @return string
*/
public static function generateRandomString(int $length = 64): string;
/**
* Crypt data according to first and second keys.
*
* @param string $data Data to be encrypted
*
* @throws \Exception
*
* @return string Encrypted data
*/
public function crypt(string $data): string;
/**
* Set the first secure key.
*
* @param string $firstKey
*
* @return EncryptionInterface
*/
public function setFirstKey(string $firstKey): EncryptionInterface;
/**
* Set the second secure key.
*
* @param string $secondKey
*
* @return EncryptionInterface
*/
public function setSecondKey(string $secondKey): EncryptionInterface;
/**
* Decrypt input according to first and second keys.
*
* @param string $input Data to be decrypted
*
* @throws \Exception
*
* @return string|null Data decrypted if successful otherwise null
*/
public function decrypt(string $input): ?string;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Security/Domain/Authentication/AuthenticationService.php | centreon/src/Security/Domain/Authentication/AuthenticationService.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Security\Domain\Authentication;
use Centreon\Domain\Authentication\Exception\AuthenticationException;
use Centreon\Domain\Log\LoggerTrait;
use Core\Common\Domain\Exception\RepositoryException;
use Core\Common\Infrastructure\ExceptionLogger\ExceptionLogger;
use Core\Security\Authentication\Application\Provider\ProviderAuthenticationFactoryInterface;
use Core\Security\Authentication\Application\Repository\ReadTokenRepositoryInterface;
use Core\Security\Authentication\Domain\Model\AuthenticationTokens;
use Core\Security\ProviderConfiguration\Application\Repository\ReadConfigurationRepositoryInterface;
use Security\Domain\Authentication\Exceptions\ProviderException;
use Security\Domain\Authentication\Interfaces\AuthenticationRepositoryInterface;
use Security\Domain\Authentication\Interfaces\AuthenticationServiceInterface;
use Security\Domain\Authentication\Interfaces\SessionRepositoryInterface;
class AuthenticationService implements AuthenticationServiceInterface
{
use LoggerTrait;
/**
* @param AuthenticationRepositoryInterface $authenticationRepository
* @param SessionRepositoryInterface $sessionRepository
* @param ReadConfigurationRepositoryInterface $readConfigurationFactory
* @param ProviderAuthenticationFactoryInterface $providerFactory
* @param ReadTokenRepositoryInterface $readTokenRepository
*/
public function __construct(
private AuthenticationRepositoryInterface $authenticationRepository,
private SessionRepositoryInterface $sessionRepository,
private ReadConfigurationRepositoryInterface $readConfigurationFactory,
private ProviderAuthenticationFactoryInterface $providerFactory,
private ReadTokenRepositoryInterface $readTokenRepository,
) {
}
/**
* @inheritDoc
*/
public function isValidToken(string $token): bool
{
$authenticationTokens = $this->findAuthenticationTokensByToken($token);
if ($authenticationTokens === null) {
$this->notice('[AUTHENTICATION SERVICE] token not found');
return false;
}
try {
$configuration = $this->readConfigurationFactory->getConfigurationById(
$authenticationTokens->getConfigurationProviderId()
);
} catch (RepositoryException $e) {
ExceptionLogger::create()->log($e);
return false;
}
try {
$provider = $this->providerFactory->create($configuration->getType());
} catch (ProviderException $e) {
ExceptionLogger::create()->log($e);
return false;
}
if ($authenticationTokens->getProviderToken()->isExpired()) {
if (
! $provider->canRefreshToken()
|| $authenticationTokens->getProviderRefreshToken() === null
|| $authenticationTokens->getProviderRefreshToken()->isExpired()
) {
$this->notice('Your session has expired');
return false;
}
$newAuthenticationTokens = $provider->refreshToken($authenticationTokens);
if ($newAuthenticationTokens === null) {
$this->notice('Error while refresh token');
return false;
}
$this->updateAuthenticationTokens($newAuthenticationTokens);
}
return true;
}
/**
* @inheritDoc
*/
public function deleteSession(string $sessionToken): void
{
try {
$this->authenticationRepository->deleteSecurityToken($sessionToken);
$this->sessionRepository->deleteSession($sessionToken);
} catch (\Exception $ex) {
throw AuthenticationException::deleteSession($ex);
}
}
/**
* @inheritDoc
*/
public function findAuthenticationTokensByToken(string $token): ?AuthenticationTokens
{
try {
return $this->readTokenRepository->findAuthenticationTokensByToken($token);
} catch (\Exception $ex) {
throw AuthenticationException::findAuthenticationToken($ex);
}
}
/**
* @inheritDoc
*/
public function updateAuthenticationTokens(AuthenticationTokens $authenticationToken): void
{
try {
$this->authenticationRepository->updateAuthenticationTokens($authenticationToken);
} catch (\Exception $ex) {
throw AuthenticationException::updateAuthenticationTokens($ex);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Security/Domain/Authentication/AuthenticationTokenService.php | centreon/src/Security/Domain/Authentication/AuthenticationTokenService.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Security\Domain\Authentication;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Core\Security\Authentication\Domain\Model\AuthenticationTokens;
use Security\Domain\Authentication\Exceptions\AuthenticationTokenException;
use Security\Domain\Authentication\Interfaces\AuthenticationTokenRepositoryInterface;
use Security\Domain\Authentication\Interfaces\AuthenticationTokenServiceInterface;
class AuthenticationTokenService implements AuthenticationTokenServiceInterface
{
/** @var AuthenticationTokenRepositoryInterface */
private $authenticationTokenRepository;
public function __construct(AuthenticationTokenRepositoryInterface $authenticationTokenRepository)
{
$this->authenticationTokenRepository = $authenticationTokenRepository;
}
/**
* @inheritDoc
*/
public function findByContact(ContactInterface $contact): ?AuthenticationTokens
{
try {
return $this->authenticationTokenRepository->findAuthenticationTokensByContact($contact);
} catch (\Exception $ex) {
throw AuthenticationTokenException::errorWhileSearchingAuthenticationTokens($ex);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Security/Domain/Authentication/Model/ProviderConfiguration.php | centreon/src/Security/Domain/Authentication/Model/ProviderConfiguration.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Security\Domain\Authentication\Model;
use Centreon\Domain\Common\Assertion\Assertion;
use Security\Domain\Authentication\Interfaces\ProviderConfigurationInterface;
class ProviderConfiguration implements ProviderConfigurationInterface
{
/** @var int|null */
private $id;
/** @var string Provider's type */
private $type;
/** @var string Provider configuration name */
private $name;
/** @var string */
private $centreonBaseUri = '/centreon';
/** @var bool is the provider is enabled ? */
private $isActive;
/** @var bool is the provider forced ? */
private $isForced;
/**
* @param int|null $id
* @param string $type
* @param string $name
* @param bool $isActive
* @param bool $isForced
* @param string $centreonBaseUri
*/
public function __construct(
?int $id,
string $type,
string $name,
bool $isActive,
bool $isForced,
string $centreonBaseUri = '/centreon',
) {
Assertion::minLength($type, 1, 'ConfigurationProvider::type');
Assertion::minLength($name, 1, 'ConfigurationProvider::name');
$this->id = $id;
$this->type = $type;
$this->name = $name;
$this->isActive = $isActive;
$this->isForced = $isForced;
$this->centreonBaseUri = $centreonBaseUri;
}
/**
* @return int|null
*/
public function getId(): ?int
{
return $this->id;
}
/**
* @param int $id
*
* @return ProviderConfiguration
*/
public function setId(int $id): ProviderConfiguration
{
$this->id = $id;
return $this;
}
/**
* @return string
*/
public function getType(): ?string
{
return $this->type;
}
/**
* @return string
*/
public function getName(): string
{
return $this->name;
}
/**
* Get centreon base uri.
*
* @return string
*/
public function getCentreonBaseUri(): string
{
return $this->centreonBaseUri;
}
/**
* Get the provider's authentication uri (ex: https://www.okta.com/.../auth).
*
* @return string
*/
public function getAuthenticationUri(): string
{
return $this->getCentreonBaseUri() . '/authentication/providers/configurations/'
. $this->getName();
}
/**
* @return bool
*/
public function isActive(): bool
{
return $this->isActive;
}
/**
* @return bool
*/
public function isForced(): bool
{
return $this->isForced;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Security/Domain/Authentication/Model/AuthenticationTokens.php | centreon/src/Security/Domain/Authentication/Model/AuthenticationTokens.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Security\Domain\Authentication\Model;
use Centreon\Domain\Common\Assertion\Assertion;
class AuthenticationTokens
{
private const SESSION_TOKEN_MIN_LENGTH = 1;
/** @var string */
private $sessionToken;
/** @var ProviderToken */
private $providerToken;
/** @var null|ProviderToken */
private $providerRefreshToken;
/** @var int */
private $userId;
/** @var int */
private $configurationProviderId;
/**
* @param int $userId
* @param int $configurationProviderId
* @param string $sessionToken
* @param ProviderToken $providerToken
* @param ProviderToken|null $providerRefreshToken
*
* @throws \Assert\AssertionFailedException
*/
public function __construct(
int $userId,
int $configurationProviderId,
string $sessionToken,
ProviderToken $providerToken,
?ProviderToken $providerRefreshToken,
) {
Assertion::minLength($sessionToken, self::SESSION_TOKEN_MIN_LENGTH, 'AuthenticationToken::sessionToken');
$this->userId = $userId;
$this->configurationProviderId = $configurationProviderId;
$this->sessionToken = $sessionToken;
$this->providerToken = $providerToken;
$this->providerRefreshToken = $providerRefreshToken;
}
/**
* @return string
*/
public function getSessionToken(): string
{
return $this->sessionToken;
}
/**
* @return ProviderToken
*/
public function getProviderToken(): ProviderToken
{
return $this->providerToken;
}
/**
* @return ProviderToken|null
*/
public function getProviderRefreshToken(): ?ProviderToken
{
return $this->providerRefreshToken;
}
/**
* @return int
*/
public function getUserId(): int
{
return $this->userId;
}
/**
* @return int
*/
public function getConfigurationProviderId(): int
{
return $this->configurationProviderId;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Security/Domain/Authentication/Model/LocalProvider.php | centreon/src/Security/Domain/Authentication/Model/LocalProvider.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Security\Domain\Authentication\Model;
use Centreon;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Contact\Interfaces\ContactServiceInterface;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\Option\Interfaces\OptionServiceInterface;
use CentreonAuth;
use Core\Common\Domain\Exception\RepositoryException;
use Core\Security\Authentication\Domain\Exception\AuthenticationException;
use Core\Security\Authentication\Domain\Exception\PasswordExpiredException;
use Core\Security\Authentication\Domain\Model\AuthenticationTokens;
use Core\Security\Authentication\Domain\Model\NewProviderToken;
use Core\Security\ProviderConfiguration\Application\Repository\ReadConfigurationRepositoryInterface;
use Core\Security\ProviderConfiguration\Domain\Local\Model\CustomConfiguration;
use Core\Security\ProviderConfiguration\Domain\Local\Model\SecurityPolicy;
use Core\Security\ProviderConfiguration\Domain\LoginLoggerInterface;
use Core\Security\ProviderConfiguration\Domain\Model\Configuration;
use Core\Security\ProviderConfiguration\Domain\Model\Provider;
use Core\Security\User\Application\Repository\ReadUserRepositoryInterface;
use Core\Security\User\Application\Repository\WriteUserRepositoryInterface;
use Core\Security\User\Domain\Model\User;
use DateInterval;
use DateTime;
use DateTimeImmutable;
use Pimple\Container;
use Security\Domain\Authentication\Interfaces\LocalProviderInterface;
class LocalProvider implements LocalProviderInterface
{
use LoggerTrait;
public const NAME = 'local';
/** @var int */
private $contactId;
/** @var Configuration */
private $configuration;
/** @var Centreon */
private $legacySession;
/**
* LocalProvider constructor.
*
* @param int $sessionExpirationDelay
* @param ContactServiceInterface $contactService
* @param Container $dependencyInjector
* @param OptionServiceInterface $optionService
* @param ReadUserRepositoryInterface $readUserRepository
* @param WriteUserRepositoryInterface $writeUserRepository
* @param ReadConfigurationRepositoryInterface $readConfigurationRepository
* @param LoginLoggerInterface $loginLogger
*/
public function __construct(
private int $sessionExpirationDelay,
private ContactServiceInterface $contactService,
private Container $dependencyInjector,
private OptionServiceInterface $optionService,
private ReadUserRepositoryInterface $readUserRepository,
private WriteUserRepositoryInterface $writeUserRepository,
private ReadConfigurationRepositoryInterface $readConfigurationRepository,
private readonly LoginLoggerInterface $loginLogger,
) {
}
/**
* @inheritDoc
*/
public function authenticateOrFail(array $credentials): void
{
global $pearDB;
$pearDB = $this->dependencyInjector['configuration_db'];
$log = new \CentreonUserLog(0, $this->dependencyInjector['configuration_db']);
$auth = new CentreonAuth(
$this->dependencyInjector,
$credentials['login'],
$credentials['password'],
CentreonAuth::AUTOLOGIN_DISABLE,
$this->dependencyInjector['configuration_db'],
$log,
CentreonAuth::ENCRYPT_MD5,
''
);
if ($auth->userInfos === null) {
throw AuthenticationException::notAuthenticated();
}
$this->debug(
'[LOCAL PROVIDER] local provider trying to authenticate using legacy Authentication',
[
'class' => CentreonAuth::class,
],
function () use ($auth) {
$userInfos = $auth->userInfos;
return [
'contact_id' => $userInfos['contact_id'] ?? null,
'contact_alias' => $userInfos['contact_alias'] ?? null,
'contact_auth_type' => $userInfos['contact_auth_type'] ?? null,
'contact_ldap_dn' => $userInfos['contact_ldap_dn'] ?? null,
];
}
);
$doesPasswordMatch = $auth->passwdOk === 1;
if ($auth->userInfos['contact_auth_type'] === CentreonAuth::AUTH_TYPE_LOCAL) {
try {
$user = $this->readUserRepository->findUserByAlias($auth->userInfos['contact_alias']);
} catch (RepositoryException $e) {
throw AuthenticationException::notAuthenticated($e);
}
try {
$providerConfiguration = $this->readConfigurationRepository->getConfigurationByType(Provider::LOCAL);
} catch (RepositoryException $e) {
throw AuthenticationException::notAuthenticated($e);
}
/** @var CustomConfiguration $customConfiguration */
$customConfiguration = $providerConfiguration->getCustomConfiguration();
$securityPolicy = $customConfiguration->getSecurityPolicy();
try {
$this->respectLocalSecurityPolicyOrFail($user, $securityPolicy, $doesPasswordMatch);
} catch (PasswordExpiredException $e) {
throw $e;
} catch (AuthenticationException $e) {
throw AuthenticationException::notAuthenticated($e);
}
}
if (! $doesPasswordMatch) {
$this->info(
'Local provider cannot authenticate successfully user',
[
'provider_name' => $this->getName(),
'user' => $credentials['login'],
]
);
throw AuthenticationException::notAuthenticated();
}
$this->contactId = (int) $auth->userInfos['contact_id'];
$auth->userInfos['auth_type'] = $auth->userInfos['contact_auth_type'] === CentreonAuth::AUTH_TYPE_LDAP
? $auth->userInfos['contact_auth_type']
: Provider::LOCAL;
$this->setLegacySession(new Centreon($auth->userInfos));
$this->info('[LOCAL PROVIDER] authentication succeeded');
}
/**
* @inheritDoc
*/
public function getLegacySession(): Centreon
{
return $this->legacySession;
}
/**
* @inheritDoc
*/
public function setLegacySession(Centreon $legacySession): void
{
$this->legacySession = $legacySession;
}
/**
* @inheritDoc
*/
public function canCreateUser(): bool
{
return false;
}
/**
* @inheritDoc
*/
public function refreshToken(AuthenticationTokens $authenticationTokens): ?AuthenticationTokens
{
return null;
}
/**
* @inheritDoc
*/
public function getName(): string
{
return self::NAME;
}
public function getUser(): ?ContactInterface
{
return $this->contactService->findContact($this->contactId);
}
/**
* @inheritDoc
*/
public function getConfiguration(): Configuration
{
return $this->configuration;
}
/**
* @inheritDoc
*/
public function setConfiguration(Configuration $configuration): void
{
$this->configuration = $configuration;
}
/**
* @inheritDoc
*/
public function canRefreshToken(): bool
{
return false;
}
/**
* @inheritDoc
*/
public function getProviderToken(string $token): NewProviderToken
{
$sessionExpireOption = $this->optionService->findSelectedOptions(['session_expire']);
if ($sessionExpireOption !== []) {
$this->sessionExpirationDelay = (int) $sessionExpireOption[0]->getValue();
}
return new NewProviderToken(
$token,
new DateTimeImmutable(),
(new DateTimeImmutable())->add(new DateInterval('PT' . $this->sessionExpirationDelay . 'M'))
);
}
/**
* @inheritDoc
*/
public function getProviderRefreshToken(string $token): ?\Core\Security\Authentication\Domain\Model\ProviderToken
{
return null;
}
/**
* Check if local security policy is respected.
*
* @param User $user
* @param SecurityPolicy $securityPolicy
* @param bool $doesPasswordMatch
*
* @throws AuthenticationException|PasswordExpiredException
*/
private function respectLocalSecurityPolicyOrFail(
User $user,
SecurityPolicy $securityPolicy,
bool $doesPasswordMatch,
): void {
$isUserBlocked = false;
if ($securityPolicy->getAttempts() !== null && $securityPolicy->getBlockingDuration() !== null) {
$isUserBlocked = $this->isUserBlocked($user, $securityPolicy, $doesPasswordMatch);
}
$this->writeUserRepository->updateBlockingInformation($user);
if ($isUserBlocked) {
$this->loginLogger->info(
Provider::LOCAL,
'User is blocked: maximum number of authentication attempts was reached',
['contact_alias' => $user->getAlias()]
);
$this->info(
'[LOCAL PROVIDER] authentication failed because user is blocked',
[
'contact_alias' => $user->getAlias(),
],
);
throw AuthenticationException::userBlocked();
}
if (
$securityPolicy->getPasswordExpirationDelay() !== null
&& $doesPasswordMatch
&& $this->isPasswordExpired($user, $securityPolicy)
) {
$this->info(
'[LOCAL PROVIDER] authentication failed because password is expired',
[
'contact_alias' => $user->getAlias(),
],
);
throw PasswordExpiredException::passwordIsExpired();
}
}
/**
* Check if the user is blocked.
*
* @param User $user
* @param SecurityPolicy $securityPolicy
* @param bool $doesPasswordMatch
*
* @return bool
*/
private function isUserBlocked(User $user, SecurityPolicy $securityPolicy, bool $doesPasswordMatch): bool
{
if (
$user->getBlockingTime() !== null
&& (time() - $user->getBlockingTime()->getTimestamp()) < $securityPolicy->getBlockingDuration()
) {
$this->info(
'user is blocked',
[
'contact_alias' => $user->getAlias(),
],
);
return true;
}
if ($doesPasswordMatch) {
$this->info(
'reset blocking duration values',
[
'contact_alias' => $user->getAlias(),
],
);
$user->setLoginAttempts(null);
$user->setBlockingTime(null);
} else {
$this->info(
'increment login attempts',
[
'contact_alias' => $user->getAlias(),
],
);
$user->setLoginAttempts($user->getLoginAttempts() + 1);
if ($user->getLoginAttempts() >= $securityPolicy->getAttempts()) {
$user->setBlockingTime(new DateTimeImmutable());
}
}
return $user->getBlockingTime() !== null;
}
/**
* Check if the password is expired.
*
* @param User $user
* @param SecurityPolicy $securityPolicy
*
* @return bool
*/
private function isPasswordExpired(User $user, SecurityPolicy $securityPolicy): bool
{
if (in_array($user->getAlias(), $securityPolicy->getPasswordExpirationExcludedUserAliases())) {
$this->info(
'skip password expiration policy because user is excluded',
[
'contact_alias' => $user->getAlias(),
],
);
return false;
}
$expirationDelay = $securityPolicy->getPasswordExpirationDelay();
$passwordCreationDate = $user->getPassword()->getCreationDate();
if ((time() - $passwordCreationDate->getTimestamp()) > $expirationDelay) {
$this->info(
'password is expired',
[
'contact_alias' => $user->getAlias(),
'creation_date' => $passwordCreationDate->format(DateTime::ISO8601),
'expiration_delay' => $expirationDelay,
],
);
return true;
}
return false;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Security/Domain/Authentication/Model/ProviderToken.php | centreon/src/Security/Domain/Authentication/Model/ProviderToken.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Security\Domain\Authentication\Model;
class ProviderToken
{
/** @var int|null */
private $id;
/** @var string */
private $token;
/** @var \DateTime */
private $creationDate;
/** @var \DateTime|null */
private $expirationDate;
/**
* ProviderToken constructor.
*
* @param int|null $id
* @param string $token
* @param \DateTime $creationDate
* @param \DateTime|null $expirationDate
*/
public function __construct(
?int $id,
string $token,
\DateTime $creationDate,
?\DateTime $expirationDate = null,
) {
$this->id = $id;
$this->token = $token;
$this->creationDate = $creationDate;
$this->expirationDate = $expirationDate;
}
/**
* @return int
*/
public function getId(): ?int
{
return $this->id;
}
/**
* @return string
*/
public function getToken(): string
{
return $this->token;
}
/**
* @return \DateTime
*/
public function getCreationDate(): \DateTime
{
return $this->creationDate;
}
/**
* @return \DateTime|null
*/
public function getExpirationDate(): ?\DateTime
{
return $this->expirationDate;
}
/**
* @param \DateTime|null $expirationDate
*
* @return self
*/
public function setExpirationDate(?\DateTime $expirationDate): self
{
$this->expirationDate = $expirationDate;
return $this;
}
/**
* Indicates whether or not the token is expired.
*
* @param \DateTime|null $now
*
* @return bool
*/
public function isExpired(?\DateTime $now = null): bool
{
if ($this->expirationDate === null) {
return false;
}
if ($now === null) {
$now = new \DateTime();
}
return $this->expirationDate->getTimestamp() < $now->getTimestamp();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Security/Domain/Authentication/Model/Session.php | centreon/src/Security/Domain/Authentication/Model/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 Security\Domain\Authentication\Model;
class Session
{
/**
* @param string $token
* @param int $contactId
* @param string|null $clientIp
*/
public function __construct(
private string $token,
private int $contactId,
private ?string $clientIp,
) {
}
/**
* @return string
*/
public function getToken(): string
{
return $this->token;
}
/**
* @return int
*/
public function getContactId(): int
{
return $this->contactId;
}
/**
* @return string|null
*/
public function getClientIp(): ?string
{
return $this->clientIp;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Security/Domain/Authentication/Exceptions/ProviderException.php | centreon/src/Security/Domain/Authentication/Exceptions/ProviderException.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Security\Domain\Authentication\Exceptions;
/**
* This class is designed to contain all exceptions for both contexts of SessionAPI & TokenAPI authenticators.
*/
class ProviderException extends \Exception
{
public static function providerConfigurationNotFound(string $configurationName): self
{
return new self(sprintf(_('Provider configuration (%s) not found'), $configurationName));
}
public static function providerNotFound(): self
{
return new self(_('Provider not found'));
}
public static function findProvidersConfigurations(\Throwable $e): self
{
return new self(_('Error while searching providers configurations'), previous: $e);
}
public static function findProviderConfiguration(string $providerConfigurationName, \Throwable $e): self
{
return new self(
sprintf(_("Error while searching provider configuration: '%s'"), $providerConfigurationName),
previous: $e
);
}
public static function emptyAuthenticationProvider(): self
{
return new self(_('You must at least add one authentication provider'));
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Security/Domain/Authentication/Exceptions/AuthenticationTokenException.php | centreon/src/Security/Domain/Authentication/Exceptions/AuthenticationTokenException.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Security\Domain\Authentication\Exceptions;
class AuthenticationTokenException extends \Exception
{
/**
* @param \Throwable $ex
*
* @return self
*/
public static function errorWhileSearchingAuthenticationTokens(\Throwable $ex): self
{
return new self(_('Error while searching authentication tokens'), 0, $ex);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Security/Domain/Authentication/Interfaces/AuthenticationTokenRepositoryInterface.php | centreon/src/Security/Domain/Authentication/Interfaces/AuthenticationTokenRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Security\Domain\Authentication\Interfaces;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Core\Security\Authentication\Domain\Model\AuthenticationTokens;
interface AuthenticationTokenRepositoryInterface
{
/**
* Find an authentication token by contact.
*
* @param ContactInterface $contact
*
* @throws \Exception
*
* @return AuthenticationTokens|null
*/
public function findAuthenticationTokensByContact(ContactInterface $contact): ?AuthenticationTokens;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Security/Domain/Authentication/Interfaces/OpenIdProviderInterface.php | centreon/src/Security/Domain/Authentication/Interfaces/OpenIdProviderInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Security\Domain\Authentication\Interfaces;
use Core\Security\Authentication\Domain\Model\NewProviderToken;
use Core\Security\ProviderConfiguration\Domain\Model\Configuration;
interface OpenIdProviderInterface extends ProviderInterface
{
/**
* @return Configuration
*/
public function getConfiguration(): Configuration;
/**
* @return NewProviderToken
*/
public function getProviderToken(): NewProviderToken;
/**
* @return NewProviderToken|null
*/
public function getProviderRefreshToken(): ?NewProviderToken;
/**
* Create user with informations from identity provider.
*
* @throws \Throwable
*/
public function createUser(): void;
/**
* Authenticate the user using OpenId Provider.
*
* @param string|null $authorizationCode
* @param string $clientIp
*
* @return string
*/
public function authenticateOrFail(?string $authorizationCode, string $clientIp): string;
/**
* Get User information gathered from IdP.
*
* @return array<string,mixed>
*/
public function getUserInformation(): array;
/**
* Get information store in id_token JWT Payload.
*
* @return array<string,mixed>
*/
public function getIdTokenPayload(): array;
/**
* Get ACL Conditions that has been matches.
*
* @return string[]
*/
public function getAclConditionsMatches(): array;
}
| 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.