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/Core/Security/AccessGroup/Application/Repository/WriteAccessGroupRepositoryInterface.php | centreon/src/Core/Security/AccessGroup/Application/Repository/WriteAccessGroupRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\Security\AccessGroup\Application\Repository;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
interface WriteAccessGroupRepositoryInterface
{
/**
* Delete all access groups for a given user.
*
* @param ContactInterface $user
*/
public function deleteAccessGroupsForUser(ContactInterface $user): void;
/**
* Insert access groups for a given user.
*
* @param ContactInterface $user
* @param AccessGroup[] $accessGroups
*/
public function insertAccessGroupsForUser(ContactInterface $user, array $accessGroups): void;
/**
* Add links between a "Host Group" and multiple "Acl Groups".
*
* @param int $hostGroupId
* @param AccessGroup[] $accessGroups
*/
public function addLinksBetweenHostGroupAndAccessGroups(int $hostGroupId, array $accessGroups): void;
public function addLinksBetweenHostGroupAndResourceAccessGroup(int $hostGroupId, int $resourceAccessGroup): void;
/**
* Remove links between a "Host Group" and multiple "Acl Groups".
*
* @param int $hostGroupId
* @param AccessGroup[] $accessGroups
*/
public function removeLinksBetweenHostGroupAndAccessGroups(int $hostGroupId, array $accessGroups): void;
/**
* Add links between a "Service Group" and multiple "Acl Groups".
*
* @param int $serviceGroupId
* @param AccessGroup[] $accessGroups
*/
public function addLinksBetweenServiceGroupAndAccessGroups(int $serviceGroupId, array $accessGroups): void;
/**
* Add links between a "Host Group" and multiple "Resource Ids".
*
* @param int $hostGroupId
* @param int[] $resourceIds
*/
public function addLinksBetweenHostGroupAndResourceIds(int $hostGroupId, array $resourceIds): void;
/**
* Sets the changed flag
*
* @param AccessGroup[] $accessGroupIds
*/
public function updateAclGroupsFlag(array $accessGroupIds): void;
/**
* Update the changed flag for ACL resources.
*/
public function updateAclResourcesFlag(): void;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/AccessGroup/Application/Repository/ReadAccessGroupRepositoryInterface.php | centreon/src/Core/Security/AccessGroup/Application/Repository/ReadAccessGroupRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\Security\AccessGroup\Application\Repository;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Core\Common\Domain\Exception\RepositoryException;
use Core\Security\AccessGroup\Domain\Collection\AccessGroupCollection;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
interface ReadAccessGroupRepositoryInterface
{
/**
* Find all access groups.
*
* @throws RepositoryException
*
* @return AccessGroup[]
*/
public function findAllWithFilter(): array;
/**
* Find all access groups according to a contact.
*
* @param ContactInterface $contact contact for which we want to find the access groups
*
* @throws RepositoryException
*
* @return AccessGroup[]
*/
public function findByContact(ContactInterface $contact): array;
/**
* Find all access groups according to a contact.
*
* @param int $contactId
*
* @throws RepositoryException
* @return AccessGroupCollection
*/
public function findByContactId(int $contactId): AccessGroupCollection;
/**
* Find all access groups according to a contact with filter.
*
* @param ContactInterface $contact
*
* @throws RepositoryException
*
* @return AccessGroup[]
*/
public function findByContactWithFilter(ContactInterface $contact): array;
/**
* @param int[] $accessGroupIds
*
* @throws RepositoryException
*
* @return AccessGroup[]
*/
public function findByIds(array $accessGroupIds): array;
/**
* Deterimne if any of the accessGroup are linked to an ACLResourcesGroup.
*
* @param int[] $accessGroupIds
*
* @throws RepositoryException
*
* @return bool
*/
public function hasAccessToResources(array $accessGroupIds): bool;
/**
* Finds ACL resources by a hostgroup ID.
*
* @param int $hostGroupId
*
* @throws RepositoryException
* @return int[] An array of distinct ACL resource IDs
*/
public function findAclResourcesByHostGroupId(int $hostGroupId): array;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/AccessGroup/Domain/Model/AccessGroup.php | centreon/src/Core/Security/AccessGroup/Domain/Model/AccessGroup.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\Security\AccessGroup\Domain\Model;
use Assert\AssertionFailedException;
use Centreon\Domain\Common\Assertion\Assertion;
class AccessGroup
{
/** @var bool Indicates whether this access group is enabled or disabled */
private bool $isActivate = false;
/** @var bool Indicates whether this access group has changed or not */
private bool $hasChanged = false;
/**
* @param int $id
* @param string $name
* @param string $alias
*
* @throws AssertionFailedException
*/
public function __construct(private int $id, private string $name, private string $alias)
{
Assertion::notEmpty($name, 'AccessGroup::name');
Assertion::notEmpty($alias, 'AccessGroup::alias');
}
/**
* @return int
*/
public function getId(): int
{
return $this->id;
}
/**
* @return string
*/
public function getName(): string
{
return $this->name;
}
/**
* @return string
*/
public function getAlias(): string
{
return $this->alias;
}
/**
* @return bool
*/
public function isActivate(): bool
{
return $this->isActivate;
}
/**
* @param bool $isActivate
*
* @return AccessGroup
*/
public function setActivate(bool $isActivate): self
{
$this->isActivate = $isActivate;
return $this;
}
/**
* @return bool
*/
public function hasChanged(): bool
{
return $this->hasChanged;
}
/**
* @param bool $hasChanged
*
* @return AccessGroup
*/
public function setChanged(bool $hasChanged): self
{
$this->hasChanged = $hasChanged;
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/Core/Security/AccessGroup/Domain/Collection/AccessGroupCollection.php | centreon/src/Core/Security/AccessGroup/Domain/Collection/AccessGroupCollection.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\Security\AccessGroup\Domain\Collection;
use Core\Common\Domain\Collection\ObjectCollection;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
/**
* Class
*
* @class AccessGroupCollection
* @package Core\Security\AccessGroup\Domain\Collection
* @extends ObjectCollection<AccessGroup>
*/
class AccessGroupCollection extends ObjectCollection
{
/**
* List all access group ids
*
* @return array<int>
*/
public function getIds(): array
{
return array_map(
static fn (AccessGroup $accessGroup) => $accessGroup->getId(),
$this->toArray()
);
}
/**
* @return class-string<AccessGroup>
*/
protected function itemClass(): string
{
return AccessGroup::class;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/AccessGroup/Infrastructure/Api/FindLocalUserAccessGroups/FindLocalUserAccessGroupsPresenter.php | centreon/src/Core/Security/AccessGroup/Infrastructure/Api/FindLocalUserAccessGroups/FindLocalUserAccessGroupsPresenter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\Security\AccessGroup\Infrastructure\Api\FindLocalUserAccessGroups;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Security\AccessGroup\Application\UseCase\FindLocalUserAccessGroups\FindLocalUserAccessGroupsPresenterInterface;
class FindLocalUserAccessGroupsPresenter extends AbstractPresenter implements FindLocalUserAccessGroupsPresenterInterface
{
/**
* @param RequestParametersInterface $requestParameters
* @param PresenterFormatterInterface $presenterFormatter
*/
public function __construct(
private RequestParametersInterface $requestParameters,
protected PresenterFormatterInterface $presenterFormatter,
) {
}
/**
* @param mixed $presentedData
*/
public function present(mixed $presentedData): void
{
parent::present([
'result' => $presentedData->accessGroups,
'meta' => $this->requestParameters->toArray(),
]);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/AccessGroup/Infrastructure/Api/FindLocalUserAccessGroups/FindLocalUserAccessGroupsController.php | centreon/src/Core/Security/AccessGroup/Infrastructure/Api/FindLocalUserAccessGroups/FindLocalUserAccessGroupsController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\Security\AccessGroup\Infrastructure\Api\FindLocalUserAccessGroups;
use Centreon\Application\Controller\AbstractController;
use Core\Security\AccessGroup\Application\UseCase\FindLocalUserAccessGroups\{
FindLocalUserAccessGroups,
FindLocalUserAccessGroupsPresenterInterface
};
final class FindLocalUserAccessGroupsController extends AbstractController
{
/**
* @param FindLocalUserAccessGroups $useCase
* @param FindLocalUserAccessGroupsPresenterInterface $presenter
*
* @return object
*/
public function __invoke(
FindLocalUserAccessGroups $useCase,
FindLocalUserAccessGroupsPresenterInterface $presenter,
): object {
$this->denyAccessUnlessGrantedForApiConfiguration();
$useCase($presenter);
return $presenter->show();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/AccessGroup/Infrastructure/Repository/DbReadAccessGroupRepository.php | centreon/src/Core/Security/AccessGroup/Infrastructure/Repository/DbReadAccessGroupRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\Security\AccessGroup\Infrastructure\Repository;
use Assert\AssertionFailedException;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\RequestParameters\RequestParameters;
use Centreon\Infrastructure\DatabaseConnection;
use Centreon\Infrastructure\Repository\AbstractRepositoryDRB;
use Centreon\Infrastructure\RequestParameters\SqlRequestParametersTranslator;
use Core\Common\Domain\Exception\CollectionException;
use Core\Common\Domain\Exception\RepositoryException;
use Core\Common\Infrastructure\Repository\SqlMultipleBindTrait;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Security\AccessGroup\Domain\Collection\AccessGroupCollection;
/**
* Database repository for the access groups.
*
* @phpstan-import-type _AccessGroupRecord from DbAccessGroupFactory
*/
final class DbReadAccessGroupRepository extends AbstractRepositoryDRB implements ReadAccessGroupRepositoryInterface
{
use LoggerTrait;
use SqlMultipleBindTrait;
/** @var SqlRequestParametersTranslator */
private SqlRequestParametersTranslator $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);
$this->sqlRequestTranslator->setConcordanceArray([
'id' => 'acl_group_id',
'name' => 'acl_group_name',
]);
}
/**
* @inheritDoc
*/
public function findAllWithFilter(): array
{
try {
$request = 'SELECT SQL_CALC_FOUND_ROWS * FROM acl_groups';
$searchRequest = $this->sqlRequestTranslator->translateSearchParameterToSql();
$request .= $searchRequest !== null
? $searchRequest . ' AND '
: ' WHERE ';
$request .= "acl_group_activate = '1'";
// Sort
$sortRequest = $this->sqlRequestTranslator->translateSortParameterToSql();
$request .= $sortRequest ?? ' ORDER BY acl_group_id ASC';
// Pagination
$request .= $this->sqlRequestTranslator->translatePaginationToSql();
$statement = $this->db->prepare($request);
foreach ($this->sqlRequestTranslator->getSearchValues() as $key => $data) {
/** @var int */
$type = key($data);
$value = $data[$type];
$statement->bindValue($key, $value, $type);
}
$statement->execute();
// Set total
$result = $this->db->query('SELECT FOUND_ROWS()');
if ($result !== false && ($total = $result->fetchColumn()) !== false) {
$this->sqlRequestTranslator->getRequestParameters()->setTotal((int) $total);
}
$accessGroups = [];
while ($statement !== false && is_array($result = $statement->fetch(\PDO::FETCH_ASSOC))) {
/** @var _AccessGroupRecord $result */
$accessGroups[] = DbAccessGroupFactory::createFromRecord($result);
}
return $accessGroups;
} catch (\Throwable $e) {
throw new RepositoryException(
'Error while getting all access groups with filter',
['filter' => $this->sqlRequestTranslator->getSearchValues()],
previous: $e
);
}
}
/**
* @inheritDoc
*/
public function findByContact(ContactInterface $contact): array
{
try {
$accessGroupsCollection = $this->findByContactId($contact->getId());
return $accessGroupsCollection->values();
} catch (RepositoryException $e) {
throw new RepositoryException(
'Error while getting access groups by contact',
['contact_id' => $contact->getId()],
$e
);
}
}
/**
* Find all access groups according to a contact.
*
* @param int $contactId
*
* @throws RepositoryException
* @return AccessGroupCollection
*/
public function findByContactId(int $contactId): AccessGroupCollection
{
try {
$accessGroups = new AccessGroupCollection();
/**
* Retrieve all access group from contact
* and contact groups linked to contact.
*/
$query = <<<'SQL'
SELECT *
FROM acl_groups
WHERE acl_group_activate = '1'
AND (
acl_group_id IN (
SELECT acl_group_id
FROM acl_group_contacts_relations
WHERE contact_contact_id = :contact_id
)
OR acl_group_id IN (
SELECT acl_group_id
FROM acl_group_contactgroups_relations agcr
INNER JOIN contactgroup_contact_relation cgcr
ON cgcr.contactgroup_cg_id = agcr.cg_cg_id
WHERE cgcr.contact_contact_id = :contact_id
)
)
SQL;
$statement = $this->db->prepare($query);
$statement->bindValue(':contact_id', $contactId, \PDO::PARAM_INT);
if ($statement->execute()) {
while ($result = $statement->fetch(\PDO::FETCH_ASSOC)) {
/** @var _AccessGroupRecord $result */
$accessGroup = DbAccessGroupFactory::createFromRecord($result);
$accessGroups->add($accessGroup->getId(), $accessGroup);
}
return $accessGroups;
}
return $accessGroups;
} catch (\PDOException|CollectionException|AssertionFailedException $e) {
throw new RepositoryException(
'Error while getting access groups by contact id',
['contact_id' => $contactId],
$e
);
}
}
/**
* @inheritDoc
*/
public function findByContactWithFilter(ContactInterface $contact): array
{
try {
$request = 'SELECT SQL_CALC_FOUND_ROWS * FROM acl_groups';
$searchRequest = $this->sqlRequestTranslator->translateSearchParameterToSql();
$request .= $searchRequest !== null
? $searchRequest . ' AND '
: ' WHERE ';
$request .= "acl_group_activate = '1'
AND (
acl_group_id IN (
SELECT acl_group_id FROM acl_group_contacts_relations
WHERE contact_contact_id = :contact_id
)
OR acl_group_id IN (
SELECT acl_group_id FROM acl_group_contactgroups_relations agcr
INNER JOIN contactgroup_contact_relation cgcr
ON cgcr.contactgroup_cg_id = agcr.cg_cg_id
WHERE cgcr.contact_contact_id = :contact_id
)
)";
// Sort
$sortRequest = $this->sqlRequestTranslator->translateSortParameterToSql();
$request .= $sortRequest ?? ' ORDER BY acl_group_id ASC';
// Pagination
$request .= $this->sqlRequestTranslator->translatePaginationToSql();
$statement = $this->db->prepare($request);
foreach ($this->sqlRequestTranslator->getSearchValues() as $key => $data) {
/**
* @var int
*/
$type = key($data);
$value = $data[$type];
$statement->bindValue($key, $value, $type);
}
$statement->bindValue(':contact_id', $contact->getId(), \PDO::PARAM_INT);
$statement->execute();
// Set total
$result = $this->db->query('SELECT FOUND_ROWS()');
if ($result !== false && ($total = $result->fetchColumn()) !== false) {
$this->sqlRequestTranslator->getRequestParameters()->setTotal((int) $total);
}
$accessGroups = [];
while ($statement !== false && is_array($result = $statement->fetch(\PDO::FETCH_ASSOC))) {
/** @var _AccessGroupRecord $result */
$accessGroups[] = DbAccessGroupFactory::createFromRecord($result);
}
return $accessGroups;
} catch (\Throwable $e) {
throw new RepositoryException(
'Error while getting access groups by contact with filter',
['contact_id' => $contact->getId(), 'filter' => $this->sqlRequestTranslator->getSearchValues()],
previous: $e
);
}
}
/**
* @inheritDoc
*/
public function findByIds(array $accessGroupIds): array
{
try {
$queryBindValues = [];
foreach ($accessGroupIds as $accessGroupId) {
$queryBindValues[':access_group_' . $accessGroupId] = $accessGroupId;
}
if ($queryBindValues === []) {
return [];
}
$accessGroups = [];
$boundIds = implode(', ', array_keys($queryBindValues));
$statement = $this->db->prepare(
"SELECT * FROM acl_groups WHERE acl_group_id IN ({$boundIds})"
);
foreach ($queryBindValues as $bindKey => $accessGroupId) {
$statement->bindValue($bindKey, $accessGroupId, \PDO::PARAM_INT);
}
$statement->execute();
while ($statement !== false && is_array($result = $statement->fetch(\PDO::FETCH_ASSOC))) {
/** @var _AccessGroupRecord $result */
$accessGroups[] = DbAccessGroupFactory::createFromRecord($result);
}
return $accessGroups;
} catch (\Throwable $e) {
throw new RepositoryException(
'Error while getting access groups by ids',
['ids' => $accessGroupIds],
previous: $e
);
}
}
/**
* @inheritDoc
*/
public function hasAccessToResources(array $accessGroupIds): bool
{
try {
if ($accessGroupIds === []) {
return false;
}
[$bindValues, $bindQuery] = $this->createMultipleBindQuery($accessGroupIds, ':accessGroupIds');
$statement = $this->db->prepare(
<<<SQL
SELECT 1 FROM acl_res_group_relations
WHERE acl_group_id IN ({$bindQuery})
SQL
);
foreach ($bindValues as $key => $value) {
$statement->bindValue($key, $value, \PDO::PARAM_INT);
}
$statement->execute();
return (bool) $statement->fetchColumn();
} catch (\Throwable $e) {
throw new RepositoryException(
'Error while checking access to resources',
['ids' => $accessGroupIds],
previous: $e
);
}
}
/**
* @inheritDoc
*/
public function findAclResourcesByHostGroupId(int $hostGroupId): array
{
try {
$statement = $this->db->prepare(
<<<'SQL'
SELECT DISTINCT acl_res_id
FROM acl_resources_hg_relations
WHERE hg_hg_id = :hostGroupId
SQL
);
$statement->bindValue(':hostGroupId', $hostGroupId, \PDO::PARAM_INT);
$statement->execute();
return $statement->fetchAll(\PDO::FETCH_COLUMN);
} catch (\Throwable $e) {
throw new RepositoryException(
'Error while getting acl resources by host group id',
['hostGroupId' => $hostGroupId],
previous: $e
);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/AccessGroup/Infrastructure/Repository/DbWriteAccessGroupRepository.php | centreon/src/Core/Security/AccessGroup/Infrastructure/Repository/DbWriteAccessGroupRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\Security\AccessGroup\Infrastructure\Repository;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Infrastructure\DatabaseConnection;
use Centreon\Infrastructure\Repository\AbstractRepositoryDRB;
use Core\Common\Infrastructure\Repository\SqlMultipleBindTrait;
use Core\Security\AccessGroup\Application\Repository\WriteAccessGroupRepositoryInterface;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
class DbWriteAccessGroupRepository extends AbstractRepositoryDRB implements WriteAccessGroupRepositoryInterface
{
use SqlMultipleBindTrait;
/**
* @param DatabaseConnection $db
*/
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* @inheritDoc
*/
public function deleteAccessGroupsForUser(ContactInterface $user): void
{
$statement = $this->db->prepare(
$this->translateDbName(
<<<'SQL'
DELETE FROM `:db`.`acl_group_contacts_relations`
WHERE acl_group_contacts_relations.contact_contact_id = :userId
AND acl_group_contacts_relations.acl_group_id NOT IN (
SELECT acl_group_id FROM `:db`.acl_groups WHERE cloud_specific = 1
)
SQL
)
);
$statement->bindValue(':userId', $user->getId(), \PDO::PARAM_INT);
$statement->execute();
}
/**
* @inheritDoc
*/
public function insertAccessGroupsForUser(ContactInterface $user, array $accessGroups): void
{
$statement = $this->db->prepare(
$this->translateDbName(
'INSERT INTO acl_group_contacts_relations VALUES (:userId, :accessGroupId)'
)
);
$statement->bindValue(':userId', $user->getId(), \PDO::PARAM_INT);
foreach ($accessGroups as $accessGroup) {
$statement->bindValue(':accessGroupId', $accessGroup->getId(), \PDO::PARAM_INT);
$statement->execute();
}
}
/**
* {@inheritDoc}
*
* If the ACLs are not properly set for the contact, it is possible to create
* a host group in the GUI you cannot see just after creation.
*
* This behaviour is kept here if the `$aclResourceIds` is an empty array.
*/
public function addLinksBetweenHostGroupAndAccessGroups(int $hostGroupId, array $accessGroups): void
{
$accessGroupsIds = array_map(
static fn (AccessGroup $accessGroup) => $accessGroup->getId(),
$accessGroups
);
$aclResourceIds = $this->findEnabledAclResourceIdsByAccessGroupIds($accessGroupsIds);
$this->addLinksBetweenHostGroupAndResourceIds($hostGroupId, $aclResourceIds);
}
public function addLinksBetweenHostGroupAndResourceAccessGroup(int $hostGroupId, int $resourceAccessGroup): void
{
$statement = $this->db->prepare(
$this->translateDbName(
<<<'SQL'
INSERT INTO `:db`.`acl_resources_hg_relations` (acl_res_id, hg_hg_id)
VALUES (:acl_group_id, :hg_hg_id)
SQL
)
);
$statement->bindValue(':acl_group_id', $resourceAccessGroup, \PDO::PARAM_INT);
$statement->bindValue(':hg_hg_id', $hostGroupId, \PDO::PARAM_INT);
$statement->execute();
}
public function addLinksBetweenHostGroupAndResourceIds(int $hostGroupId, array $resourceIds): void
{
if ($resourceIds === []) {
return;
}
// We build a multi-values INSERT query.
$insert = 'INSERT INTO `:db`.`acl_resources_hg_relations` (acl_res_id, hg_hg_id) VALUES';
foreach ($resourceIds as $index => $resourceId) {
$insert .= $index === 0
? " (:acl_res_id_{$index}, :hg_hg_id)"
: ", (:acl_res_id_{$index}, :hg_hg_id)";
}
// Insert in bulk
$statement = $this->db->prepare($this->translateDbName($insert));
$statement->bindValue(':hg_hg_id', $hostGroupId, \PDO::PARAM_INT);
foreach ($resourceIds as $index => $resourceId) {
$statement->bindValue(":acl_res_id_{$index}", $resourceId, \PDO::PARAM_INT);
}
$statement->execute();
}
/**
* {@inheritDoc}
*/
public function removeLinksBetweenHostGroupAndAccessGroups(int $hostGroupId, array $accessGroups): void
{
$accessGroupsIds = array_map(
static fn (AccessGroup $accessGroup) => $accessGroup->getId(),
$accessGroups
);
if ($accessGroupsIds === []) {
return;
}
[$bindValues, $bindQuery] = $this->createMultipleBindQuery($accessGroupsIds, ':group_id_');
$statement = $this->db->prepare(
$this->translateDbName(
<<<SQL
DELETE FROM `:db`.`acl_resources_hg_relations`
WHERE hg_hg_id = :hg_hg_id
AND acl_res_id IN (
SELECT acl_res_id
FROM `:db`.`acl_res_group_relations`
WHERE acl_group_id IN ({$bindQuery})
)
SQL
)
);
$statement->bindValue(':hg_hg_id', $hostGroupId, \PDO::PARAM_INT);
foreach ($bindValues as $key => $value) {
$statement->bindValue($key, $value, \PDO::PARAM_INT);
}
$statement->execute();
}
/**
* {@inheritDoc}
*
* If the ACLs are not properly set for the contact, it is possible to create
* a service group in the GUI you cannot see just after creation.
*
* This behaviour is kept here if the `$aclResourceIds` is an empty array.
*/
public function addLinksBetweenServiceGroupAndAccessGroups(int $serviceGroupId, array $accessGroups): void
{
$accessGroupsIds = array_map(
static fn (AccessGroup $accessGroup) => $accessGroup->getId(),
$accessGroups
);
$aclResourceIds = $this->findEnabledAclResourceIdsByAccessGroupIds($accessGroupsIds);
if ($aclResourceIds === []) {
return;
}
// We build a multi-values INSERT query.
$insert = 'INSERT INTO `:db`.`acl_resources_sg_relations` (acl_res_id, sg_id) VALUES';
foreach ($aclResourceIds as $index => $aclResourceId) {
$insert .= $index === 0
? " (:acl_res_id_{$index}, :sg_id)"
: ", (:acl_res_id_{$index}, :sg_id)";
}
// Insert in bulk
$statement = $this->db->prepare($this->translateDbName($insert));
$statement->bindValue(':sg_id', $serviceGroupId, \PDO::PARAM_INT);
foreach ($aclResourceIds as $index => $aclResourceId) {
$statement->bindValue(":acl_res_id_{$index}", $aclResourceId, \PDO::PARAM_INT);
}
$statement->execute();
}
/**
* {@inheritDoc}
*/
public function updateAclGroupsFlag(array $accessGroups): void
{
$accessGroupsIds = array_map(
static fn (AccessGroup $accessGroup) => $accessGroup->getId(),
$accessGroups
);
if ($accessGroupsIds === []) {
return;
}
[$bindValues, $bindQuery] = $this->createMultipleBindQuery($accessGroupsIds, ':group_id_');
$statement = $this->db->prepare(
$this->translateDbName(
<<<SQL
UPDATE `:db`.`acl_groups`
SET acl_group_changed = '1'
WHERE acl_group_id IN ({$bindQuery})
SQL
)
);
foreach ($bindValues as $key => $value) {
$statement->bindValue($key, $value, \PDO::PARAM_INT);
}
$statement->execute();
}
/**
* {@inheritDoc}
*/
public function updateAclResourcesFlag(): void
{
$this->db->query(
$this->translateDbName(
<<<'SQL'
UPDATE `:db`.`acl_resources`
SET changed = '1'
SQL
)
);
}
/**
* Find all `acl_resources` from an `acl_groups` list.
*
* @param list<int> $accessGroupIds
*
* @return list<int>
*/
private function findEnabledAclResourceIdsByAccessGroupIds(array $accessGroupIds): array
{
if ($accessGroupIds === []) {
return [];
}
$implodedAccessGroupIds = implode(',', $accessGroupIds);
$statement = $this->db->query(
$this->translateDbName(
<<<SQL
SELECT
acl.acl_res_id
FROM
`:db`.`acl_res_group_relations` argr
INNER JOIN
`:db`.`acl_resources` acl
ON acl.acl_res_id = argr.acl_res_id
WHERE
acl.acl_res_activate = '1'
AND argr.acl_group_id IN ({$implodedAccessGroupIds})
SQL
)
);
$aclResourceIds = [];
foreach ($statement ?: [] as $result) {
/** @var array{acl_res_id: int} $result */
$aclResourceIds[] = (int) $result['acl_res_id'];
}
return $aclResourceIds;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/AccessGroup/Infrastructure/Repository/DbAccessGroupFactory.php | centreon/src/Core/Security/AccessGroup/Infrastructure/Repository/DbAccessGroupFactory.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\Security\AccessGroup\Infrastructure\Repository;
use Assert\AssertionFailedException;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
/**
* @phpstan-type _AccessGroupRecord array{
* acl_group_id: int|string,
* acl_group_name: string,
* acl_group_alias: string,
* acl_group_activate: string,
* acl_group_changed: int,
* claim_value: string,
* priority: int,
* }
*/
class DbAccessGroupFactory
{
/**
* @param _AccessGroupRecord $record
*
* @throws AssertionFailedException
* @return AccessGroup
*/
public static function createFromRecord(array $record): AccessGroup
{
return (new AccessGroup((int) $record['acl_group_id'], $record['acl_group_name'], $record['acl_group_alias']))
->setActivate($record['acl_group_activate'] === '1')
->setChanged($record['acl_group_changed'] === 1);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Platform/Application/UseCase/FindFeatures/FindFeaturesResponse.php | centreon/src/Core/Platform/Application/UseCase/FindFeatures/FindFeaturesResponse.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\Platform\Application\UseCase\FindFeatures;
final class FindFeaturesResponse
{
/**
* @param bool $isCloudPlatform
* @param array<string, bool> $featureFlags
*/
public function __construct(
public bool $isCloudPlatform,
public array $featureFlags,
) {
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Platform/Application/UseCase/FindFeatures/FindFeatures.php | centreon/src/Core/Platform/Application/UseCase/FindFeatures/FindFeatures.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\Platform\Application\UseCase\FindFeatures;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Common\Application\FeatureFlagsInterface;
final class FindFeatures
{
use LoggerTrait;
public function __construct(private readonly FeatureFlagsInterface $featureFlags)
{
}
public function __invoke(FindFeaturesPresenterInterface $presenter): void
{
try {
$response = new FindFeaturesResponse(
$this->featureFlags->isCloudPlatform(),
$this->featureFlags->getAll(),
);
} catch (\Throwable $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
$response = new ErrorResponse('Error while searching for feature flags');
}
$presenter->presentResponse($response);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Platform/Application/UseCase/FindFeatures/FindFeaturesPresenterInterface.php | centreon/src/Core/Platform/Application/UseCase/FindFeatures/FindFeaturesPresenterInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\Platform\Application\UseCase\FindFeatures;
use Core\Application\Common\UseCase\ResponseStatusInterface;
interface FindFeaturesPresenterInterface
{
public function presentResponse(FindFeaturesResponse|ResponseStatusInterface $data): void;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersions.php | centreon/src/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersions.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\Platform\Application\UseCase\UpdateVersions;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use CentreonModule\Infrastructure\Service\CentreonModuleService;
use CentreonModule\ServiceProvider;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\NoContentResponse;
use Core\Engine\Application\Repository\EngineRepositoryInterface;
use Core\Installation\Infrastructure\InstallationHelper;
use Core\Platform\Application\Repository\ReadUpdateRepositoryInterface;
use Core\Platform\Application\Repository\ReadVersionRepositoryInterface;
use Core\Platform\Application\Repository\UpdateLockerRepositoryInterface;
use Core\Platform\Application\Repository\WriteUpdateRepositoryInterface;
use Core\Platform\Application\Validator\RequirementValidatorsInterface;
use Pimple\Container;
final class UpdateVersions
{
use LoggerTrait;
/** @var CentreonModuleService */
private CentreonModuleService $moduleService;
/**
* @param RequirementValidatorsInterface $requirementValidators
* @param UpdateLockerRepositoryInterface $updateLocker
* @param ReadVersionRepositoryInterface $readVersionRepository
* @param ReadUpdateRepositoryInterface $readUpdateRepository
* @param WriteUpdateRepositoryInterface $writeUpdateRepository
* @param Container $dependencyInjector
* @param ContactInterface $user
*/
public function __construct(
private readonly RequirementValidatorsInterface $requirementValidators,
private readonly UpdateLockerRepositoryInterface $updateLocker,
private readonly ReadVersionRepositoryInterface $readVersionRepository,
private readonly ReadUpdateRepositoryInterface $readUpdateRepository,
private readonly WriteUpdateRepositoryInterface $writeUpdateRepository,
Container $dependencyInjector,
private readonly ContactInterface $user,
private readonly InstallationHelper $installationHelper,
private readonly EngineRepositoryInterface $engineRepository,
) {
/** @var CentreonModuleService $service */
$service = $dependencyInjector[ServiceProvider::CENTREON_MODULE];
$this->moduleService = $service;
}
/**
* @param UpdateVersionsPresenterInterface $presenter
*/
public function __invoke(UpdateVersionsPresenterInterface $presenter): void
{
try {
if (! $this->user->isAdmin()) {
$presenter->setResponseStatus(new ForbiddenResponse('Only admin user can perform upgrades'));
return;
}
$this->validateRequirementsOrFail();
$this->lockUpdate();
$this->updateCentreonWeb();
$this->updateInstalledModules();
$this->updateInstalledWidgets();
$this->unlockUpdate();
$this->writeEngineContextConfiguration();
} catch (\Throwable $exception) {
$this->error(
$exception->getMessage(),
['trace' => $exception->getTraceAsString()],
);
$presenter->setResponseStatus(new ErrorResponse($exception->getMessage()));
return;
}
$presenter->setResponseStatus(new NoContentResponse());
}
/**
* @throws \Exception
* @throws UpdateVersionsException
* @throws \Throwable
*/
private function updateCentreonWeb(): void
{
$this->info('Starting centreon-web update process');
$availableUpdates = $this->getAvailableUpdates($this->getCurrentVersion());
if ($availableUpdates !== []) {
$this->info('Available updates found for centreon-web', ['updates' => $availableUpdates]);
$this->runUpdates($availableUpdates);
} else {
$this->info('No available updates to perform for centreon-web');
}
// Must always be run whether there is an update to execute or not.
$this->runPostUpdate($this->getCurrentVersion());
}
/**
* Validate platform requirements or fail.
*
* @throws \Exception
*/
private function validateRequirementsOrFail(): void
{
$this->info('Validating platform requirements');
$this->requirementValidators->validateRequirementsOrFail();
}
/**
* Lock update process.
*/
private function lockUpdate(): void
{
$this->info('Locking centreon update process...');
if (! $this->updateLocker->lock()) {
throw UpdateVersionsException::updateAlreadyInProgress();
}
}
/**
* Unlock update process.
*/
private function unlockUpdate(): void
{
$this->info('Unlocking centreon update process...');
$this->updateLocker->unlock();
}
/**
* Get current version or fail.
*
* @throws \Exception
*
* @return string
*/
private function getCurrentVersion(): string
{
$this->debug('Finding centreon-web current version');
try {
$currentVersion = $this->readVersionRepository->findCurrentVersion();
} catch (\Exception $exception) {
throw UpdateVersionsException::errorWhenRetrievingCurrentVersion($exception);
}
if ($currentVersion === null) {
throw UpdateVersionsException::cannotRetrieveCurrentVersion();
}
return $currentVersion;
}
/**
* Get available updates.
*
* @param string $currentVersion
*
* @return string[]
*/
private function getAvailableUpdates(string $currentVersion): array
{
try {
$this->info(
'Getting available updates',
[
'current_version' => $currentVersion,
],
);
return $this->readUpdateRepository->findOrderedAvailableUpdates($currentVersion);
} catch (\Throwable $exception) {
throw UpdateVersionsException::errorWhenRetrievingAvailableUpdates($exception);
}
}
/**
* Run given version updates.
*
* @param string[] $versions
*
* @throws \Throwable
*/
private function runUpdates(array $versions): void
{
foreach ($versions as $version) {
try {
$this->info("Running update {$version}");
$this->writeUpdateRepository->runUpdate($version);
} catch (\Throwable $exception) {
throw UpdateVersionsException::errorWhenApplyingUpdateToVersion($version, $exception->getMessage(), $exception);
}
}
}
/**
* @throws UpdateVersionsException
*/
private function updateInstalledWidgets(): void
{
$this->info('Updating installed widgets');
try {
$widgets = $this->moduleService->getList(
search: null,
installed: true,
updated: false,
typeList: ['widget']
);
foreach ($widgets['widget'] as $widget) {
$this->debug('Updating widget', ['name' => $widget->getName()]);
$this->moduleService->update($widget->getId(), 'widget');
}
} catch (\Throwable $exception) {
throw UpdateVersionsException::errorWhenApplyingUpdate($exception->getMessage(), $exception);
}
}
/**
* @throws UpdateVersionsException
*/
private function updateInstalledModules(): void
{
$this->info('Updating installed modules');
try {
$modules = $this->moduleService->getList(
search: null,
installed: true,
updated: null,
typeList: ['module']
);
foreach ($modules['module'] as $module) {
$this->debug('Updating module', ['name' => $module->getId()]);
$this->moduleService->update($module->getId(), 'module');
}
} catch (\Throwable $exception) {
throw UpdateVersionsException::errorWhenApplyingUpdate($exception->getMessage(), $exception);
}
}
/**
* Run post update actions.
*
* @param string $currentVersion
*
* @throws UpdateVersionsException
*/
private function runPostUpdate(string $currentVersion): void
{
$this->info('Running post update actions for centreon-web');
try {
$this->writeUpdateRepository->runPostUpdate($currentVersion);
} catch (\Throwable $exception) {
throw UpdateVersionsException::errorWhenApplyingPostUpdate($exception);
}
}
private function writeEngineContextConfiguration(): void
{
try {
if ($this->engineRepository->engineSecretsHasContent() === false) {
$this->installationHelper->writeEngineContextFile();
}
} catch (\Throwable $exception) {
throw UpdateVersionsException::errorWhenWritingEngineContextConfiguration($exception);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersionsPresenterInterface.php | centreon/src/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersionsPresenterInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\Platform\Application\UseCase\UpdateVersions;
use Core\Application\Common\UseCase\PresenterInterface;
interface UpdateVersionsPresenterInterface extends PresenterInterface
{
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersionsException.php | centreon/src/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersionsException.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\Platform\Application\UseCase\UpdateVersions;
class UpdateVersionsException extends \Exception
{
/**
* @return self
*/
public static function updateAlreadyInProgress(): self
{
return new self(_('Update already in progress'));
}
/**
* @param \Throwable $ex
*
* @return self
*/
public static function errorWhenRetrievingCurrentVersion(\Throwable $ex): self
{
return new self(_('An error occurred when retrieving the current version'), 0, $ex);
}
/**
* @return self
*/
public static function cannotRetrieveCurrentVersion(): self
{
return new self(_('Cannot retrieve the current version'));
}
/**
* @param \Throwable $ex
*
* @return self
*/
public static function errorWhenRetrievingAvailableUpdates(\Throwable $ex): self
{
return new self(_('An error occurred when retrieving available updates'), 0, $ex);
}
/**
* @param string $version
* @param string $technicalMessage
* @param \Throwable $ex
*
* @return self
*/
public static function errorWhenApplyingUpdateToVersion(
string $version,
string $technicalMessage,
\Throwable $ex,
): self {
return new self(
sprintf(_('An error occurred when applying the update %s (%s)'), $version, $technicalMessage),
0,
$ex
);
}
/**
* @param string $technicalMessage
* @param \Throwable $ex
*
* @return self
*/
public static function errorWhenApplyingUpdate(
string $technicalMessage,
\Throwable $ex,
): self {
return new self(
sprintf(_('An error occurred when applying the update (%s)'), $technicalMessage),
0,
$ex
);
}
/**
* @param \Throwable $ex
*
* @return self
*/
public static function errorWhenApplyingPostUpdate(\Throwable $ex): self
{
return new self(_('An error occurred when applying post update actions'), 0, $ex);
}
public static function errorWhenWritingEngineContextConfiguration(\Throwable $ex): self
{
return new self(_('An error occurred when writing engine context configuration'), 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/Core/Platform/Application/Validator/RequirementException.php | centreon/src/Core/Platform/Application/Validator/RequirementException.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\Platform\Application\Validator;
class RequirementException 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/Core/Platform/Application/Validator/RequirementValidatorInterface.php | centreon/src/Core/Platform/Application/Validator/RequirementValidatorInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\Platform\Application\Validator;
interface RequirementValidatorInterface
{
/**
* Validate requirement or fail.
*
* @throws RequirementException
*/
public function validateRequirementOrFail(): void;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Platform/Application/Validator/RequirementValidatorsInterface.php | centreon/src/Core/Platform/Application/Validator/RequirementValidatorsInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\Platform\Application\Validator;
interface RequirementValidatorsInterface
{
/**
* Validate platform requirements or fail.
*
* @throws RequirementException
*/
public function validateRequirementsOrFail(): void;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Platform/Application/Repository/UpdateLockerRepositoryInterface.php | centreon/src/Core/Platform/Application/Repository/UpdateLockerRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\Platform\Application\Repository;
interface UpdateLockerRepositoryInterface
{
/**
* Lock update process.
*
* @throws UpdateLockerException
*
* @return bool if the lock has been properly acquired
*/
public function lock(): bool;
/**
* Unlock update process.
*
* @throws UpdateLockerException
*/
public function unlock(): void;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Platform/Application/Repository/ReadUpdateRepositoryInterface.php | centreon/src/Core/Platform/Application/Repository/ReadUpdateRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\Platform\Application\Repository;
interface ReadUpdateRepositoryInterface
{
/**
* Get ordered available updates.
*
* @param string $currentVersion
*
* @return string[]
*/
public function findOrderedAvailableUpdates(string $currentVersion): array;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Platform/Application/Repository/WriteUpdateRepositoryInterface.php | centreon/src/Core/Platform/Application/Repository/WriteUpdateRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\Platform\Application\Repository;
interface WriteUpdateRepositoryInterface
{
/**
* Run update according to given version.
*
* @param string $version
*/
public function runUpdate(string $version): void;
/**
* Run post update actions.
*
* @param string $currentVersion
*/
public function runPostUpdate(string $currentVersion): void;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Platform/Application/Repository/ReadVersionRepositoryInterface.php | centreon/src/Core/Platform/Application/Repository/ReadVersionRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\Platform\Application\Repository;
interface ReadVersionRepositoryInterface
{
/**
* Get current version.
*
* @return string|null
*/
public function findCurrentVersion(): ?string;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Platform/Application/Repository/UpdateLockerException.php | centreon/src/Core/Platform/Application/Repository/UpdateLockerException.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\Platform\Application\Repository;
use Centreon\Domain\Repository\RepositoryException;
class UpdateLockerException extends RepositoryException
{
/**
* @param \Throwable $ex
*
* @return self
*/
public static function errorWhileLockingUpdate(\Throwable $ex): self
{
return new self(_('Error while locking the update process'), 0, $ex);
}
/**
* @param \Throwable $ex
*
* @return self
*/
public static function errorWhileUnlockingUpdate(\Throwable $ex): self
{
return new self(_('Error while unlocking the update process'), 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/Core/Platform/Domain/InstallationVerifierInterface.php | centreon/src/Core/Platform/Domain/InstallationVerifierInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\Platform\Domain;
interface InstallationVerifierInterface
{
/**
* Check that Centreon is installed (if the configuration exists)
*
* @return bool
*/
public function isCentreonWebInstalled(): bool;
/**
* Check if Centreon is Installable or Upgradable (if the install directory exists)
*
* @return bool
*/
public function isCentreonWebInstallableOrUpgradable(): bool;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Platform/Infrastructure/CentreonInstallationVerifier.php | centreon/src/Core/Platform/Infrastructure/CentreonInstallationVerifier.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\Platform\Infrastructure;
use Core\Platform\Domain\InstallationVerifierInterface;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
final readonly class CentreonInstallationVerifier implements InstallationVerifierInterface
{
public function __construct(
#[Autowire(param: 'centreon_etc_path')]
private string $etcDirectory,
#[Autowire(param: 'centreon_install_path')]
private string $installDirectory,
) {
}
public function isCentreonWebInstalled(): bool
{
return file_exists($this->etcDirectory . '/centreon.conf.php');
}
public function isCentreonWebInstallableOrUpgradable(): bool
{
return is_dir($this->installDirectory);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Platform/Infrastructure/Validator/RequirementValidators.php | centreon/src/Core/Platform/Infrastructure/Validator/RequirementValidators.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\Platform\Infrastructure\Validator;
use Centreon\Domain\Log\LoggerTrait;
use Core\Platform\Application\Validator\RequirementValidatorInterface;
use Core\Platform\Application\Validator\RequirementValidatorsInterface;
class RequirementValidators implements RequirementValidatorsInterface
{
use LoggerTrait;
/** @var RequirementValidatorInterface[] */
private $requirementValidators;
/**
* @param \Traversable<RequirementValidatorInterface> $requirementValidators
*
* @throws \Exception
*/
public function __construct(
\Traversable $requirementValidators,
) {
if (iterator_count($requirementValidators) === 0) {
throw new \Exception('Requirement validators not found');
}
$this->requirementValidators = iterator_to_array($requirementValidators);
}
/**
* @inheritDoc
*/
public function validateRequirementsOrFail(): void
{
foreach ($this->requirementValidators as $requirementValidator) {
$this->info('Validating platform requirement with ' . $requirementValidator::class);
$requirementValidator->validateRequirementOrFail();
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Platform/Infrastructure/Validator/RequirementValidators/PhpRequirementException.php | centreon/src/Core/Platform/Infrastructure/Validator/RequirementValidators/PhpRequirementException.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\Platform\Infrastructure\Validator\RequirementValidators;
use Core\Platform\Application\Validator\RequirementException;
class PhpRequirementException extends RequirementException
{
/**
* @param string $requiredPhpVersion
* @param string $installedPhpVersion
*
* @return self
*/
public static function badPhpVersion(string $requiredPhpVersion, string $installedPhpVersion): self
{
return new self(
sprintf(
_('PHP version %s required (%s installed)'),
$requiredPhpVersion,
$installedPhpVersion,
),
);
}
/**
* @param string $extensionName
*
* @return self
*/
public static function phpExtensionNotLoaded(string $extensionName): self
{
return new self(
sprintf(
_('PHP extension %s not loaded'),
$extensionName,
),
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Platform/Infrastructure/Validator/RequirementValidators/PhpRequirementValidator.php | centreon/src/Core/Platform/Infrastructure/Validator/RequirementValidators/PhpRequirementValidator.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\Platform\Infrastructure\Validator\RequirementValidators;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\VersionHelper;
use Core\Platform\Application\Validator\RequirementValidatorInterface;
class PhpRequirementValidator implements RequirementValidatorInterface
{
use LoggerTrait;
public const EXTENSION_REQUIREMENTS = [
'pdo_mysql',
'gd',
'ldap',
'xmlwriter',
'mbstring',
'pdo_sqlite',
'intl',
];
/**
* @param string $requiredPhpVersion
*/
public function __construct(private string $requiredPhpVersion)
{
}
/**
* {@inheritDoc}
*
* @throws PhpRequirementException
*/
public function validateRequirementOrFail(): void
{
$this->validatePhpVersionOrFail();
$this->validatePhpExtensionsOrFail();
}
/**
* Check installed php version.
*
* @throws PhpRequirementException
*/
private function validatePhpVersionOrFail(): void
{
$currentPhpMajorVersion = VersionHelper::regularizeDepthVersion(PHP_VERSION, 1);
$this->info(
'Comparing current PHP version ' . $currentPhpMajorVersion
. ' to required version ' . $this->requiredPhpVersion
);
if (! VersionHelper::compare($currentPhpMajorVersion, $this->requiredPhpVersion, VersionHelper::EQUAL)) {
throw PhpRequirementException::badPhpVersion($this->requiredPhpVersion, $currentPhpMajorVersion);
}
}
/**
* Check if required php extensions are loaded.
*
* @throws PhpRequirementException
*/
private function validatePhpExtensionsOrFail(): void
{
$this->info('Checking PHP extensions');
foreach (self::EXTENSION_REQUIREMENTS as $extensionName) {
$this->validatePhpExtensionOrFail($extensionName);
}
}
/**
* check if given php extension is loaded.
*
* @param string $extensionName
*
* @throws PhpRequirementException
*/
private function validatePhpExtensionOrFail(string $extensionName): void
{
$this->info('Checking PHP extension ' . $extensionName);
if (! extension_loaded($extensionName)) {
$this->error('PHP extension ' . $extensionName . ' is not loaded');
throw PhpRequirementException::phpExtensionNotLoaded($extensionName);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Platform/Infrastructure/Validator/RequirementValidators/DatabaseRequirementException.php | centreon/src/Core/Platform/Infrastructure/Validator/RequirementValidators/DatabaseRequirementException.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\Platform\Infrastructure\Validator\RequirementValidators;
use Core\Platform\Application\Validator\RequirementException;
class DatabaseRequirementException extends RequirementException
{
/**
* @param \Throwable $ex
*
* @return self
*/
public static function errorWhenGettingDatabaseVersion(\Throwable $ex): self
{
return new self(
_('Error when retrieving the database version'),
0,
$ex,
);
}
/**
* @return self
*/
public static function cannotRetrieveVersionInformation(): self
{
return new self(_('Cannot retrieve the database version information'));
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Platform/Infrastructure/Validator/RequirementValidators/DatabaseRequirementValidator.php | centreon/src/Core/Platform/Infrastructure/Validator/RequirementValidators/DatabaseRequirementValidator.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\Platform\Infrastructure\Validator\RequirementValidators;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Infrastructure\DatabaseConnection;
use Centreon\Infrastructure\Repository\AbstractRepositoryDRB;
use Core\Platform\Application\Validator\RequirementValidatorInterface;
class DatabaseRequirementValidator extends AbstractRepositoryDRB implements RequirementValidatorInterface
{
use LoggerTrait;
/** @var string */
private string $version = '';
/** @var string */
private string $versionComment = '';
/** @var DatabaseRequirementValidatorInterface[] */
private $dbRequirementValidators;
/**
* @param DatabaseConnection $db
* @param \Traversable<DatabaseRequirementValidatorInterface> $dbRequirementValidators
*
* @throws \Exception
*/
public function __construct(
DatabaseConnection $db,
\Traversable $dbRequirementValidators,
) {
$this->db = $db;
if (iterator_count($dbRequirementValidators) === 0) {
throw new \Exception('Database requirement validators not found');
}
$this->dbRequirementValidators = iterator_to_array($dbRequirementValidators);
}
/**
* {@inheritDoc}
*
* @throws DatabaseRequirementException
*/
public function validateRequirementOrFail(): void
{
$this->initDatabaseVersionInformation();
foreach ($this->dbRequirementValidators as $dbRequirementValidator) {
if ($dbRequirementValidator->isValidFor($this->versionComment)) {
$this->info(
'Validating requirement by ' . $dbRequirementValidator::class,
[
'current_version' => $this->version,
],
);
$dbRequirementValidator->validateRequirementOrFail($this->version);
$this->info('Requirement validated by ' . $dbRequirementValidator::class);
}
}
}
/**
* Get database version information.
*
* @throws DatabaseRequirementException
*/
private function initDatabaseVersionInformation(): void
{
$this->info('Getting database version information');
try {
$statement = $this->db->query("SHOW VARIABLES WHERE Variable_name IN ('version', 'version_comment')");
while ($statement !== false && is_array($row = $statement->fetch(\PDO::FETCH_ASSOC))) {
if ($row['Variable_name'] === 'version') {
$this->info('Retrieved DBMS version: ' . $row['Value']);
$this->version = $row['Value'];
} elseif ($row['Variable_name'] === 'version_comment') {
$this->info('Retrieved DBMS version comment: ' . $row['Value']);
$this->versionComment = $row['Value'];
}
}
} catch (\Throwable $ex) {
$this->error(
'Error when getting DBMS version from database',
[
'message' => $ex->getMessage(),
'trace' => $ex->getTraceAsString(),
],
);
throw DatabaseRequirementException::errorWhenGettingDatabaseVersion($ex);
}
if (empty($this->version) || empty($this->versionComment)) {
$this->info('Cannot retrieve the database version information');
throw DatabaseRequirementException::cannotRetrieveVersionInformation();
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Platform/Infrastructure/Validator/RequirementValidators/DatabaseRequirementValidatorInterface.php | centreon/src/Core/Platform/Infrastructure/Validator/RequirementValidators/DatabaseRequirementValidatorInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\Platform\Infrastructure\Validator\RequirementValidators;
interface DatabaseRequirementValidatorInterface
{
/**
* Check if database validator is valid for given version and version comment.
*
* @param string $versionComment
*
* @return bool
*/
public function isValidFor(string $versionComment): bool;
/**
* Validate requirement or fail.
*
* @param string $version
*
* @throws DatabaseRequirementException
*/
public function validateRequirementOrFail(string $version): void;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Platform/Infrastructure/Validator/RequirementValidators/DatabaseRequirementValidators/MariaDbRequirementValidator.php | centreon/src/Core/Platform/Infrastructure/Validator/RequirementValidators/DatabaseRequirementValidators/MariaDbRequirementValidator.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\Platform\Infrastructure\Validator\RequirementValidators\DatabaseRequirementValidators;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\VersionHelper;
use Core\Platform\Infrastructure\Validator\RequirementValidators\DatabaseRequirementValidatorInterface;
class MariaDbRequirementValidator implements DatabaseRequirementValidatorInterface
{
use LoggerTrait;
/**
* @param string $requiredMariaDbMinVersion
*/
public function __construct(
private string $requiredMariaDbMinVersion,
) {
}
/**
* @inheritDoc
*/
public function isValidFor(string $versionComment): bool
{
$this->info(
'Checking if version comment contains MariaDB string',
[
'version_comment' => $versionComment,
],
);
return str_contains($versionComment, 'MariaDB');
}
/**
* {@inheritDoc}
*
* @throws MariaDbRequirementException
*/
public function validateRequirementOrFail(string $version): void
{
$currentMariaDBMajorVersion = VersionHelper::regularizeDepthVersion($version, 1);
$this->info(
'Comparing current MariaDB version ' . $currentMariaDBMajorVersion
. ' to minimal required version ' . $this->requiredMariaDbMinVersion
);
if (
VersionHelper::compare($currentMariaDBMajorVersion, $this->requiredMariaDbMinVersion, VersionHelper::LT)
) {
$this->error('MariaDB requirement is not validated');
throw MariaDbRequirementException::badMariaDbVersion(
$this->requiredMariaDbMinVersion,
$currentMariaDBMajorVersion,
);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Platform/Infrastructure/Validator/RequirementValidators/DatabaseRequirementValidators/MariaDbRequirementException.php | centreon/src/Core/Platform/Infrastructure/Validator/RequirementValidators/DatabaseRequirementValidators/MariaDbRequirementException.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\Platform\Infrastructure\Validator\RequirementValidators\DatabaseRequirementValidators;
use Core\Platform\Application\Validator\RequirementException;
class MariaDbRequirementException extends RequirementException
{
/**
* @param string $requiredMariaDbVersion
* @param string $installedMariaDbVersion
*
* @return self
*/
public static function badMariaDbVersion(string $requiredMariaDbVersion, string $installedMariaDbVersion): self
{
return new self(
sprintf(
_('MariaDB version %s required (%s installed)'),
$requiredMariaDbVersion,
$installedMariaDbVersion,
),
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Platform/Infrastructure/Repository/DbReadVersionRepository.php | centreon/src/Core/Platform/Infrastructure/Repository/DbReadVersionRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\Platform\Infrastructure\Repository;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Infrastructure\DatabaseConnection;
use Centreon\Infrastructure\Repository\AbstractRepositoryDRB;
use Core\Platform\Application\Repository\ReadVersionRepositoryInterface;
class DbReadVersionRepository extends AbstractRepositoryDRB implements ReadVersionRepositoryInterface
{
use LoggerTrait;
/**
* @param DatabaseConnection $db
*/
public function __construct(
DatabaseConnection $db,
) {
$this->db = $db;
}
/**
* @inheritDoc
*/
public function findCurrentVersion(): ?string
{
$statement = $this->db->query(
<<<'SQL'
SELECT `value`
FROM `informations`
WHERE `key` = 'version'
SQL
);
if ($statement !== false) {
return (string) $statement->fetchColumn();
}
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/Core/Platform/Infrastructure/Repository/SymfonyUpdateLockerRepository.php | centreon/src/Core/Platform/Infrastructure/Repository/SymfonyUpdateLockerRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\Platform\Infrastructure\Repository;
use Centreon\Domain\Log\LoggerTrait;
use Core\Platform\Application\Repository\UpdateLockerException;
use Core\Platform\Application\Repository\UpdateLockerRepositoryInterface;
use Symfony\Component\Lock\LockFactory;
use Symfony\Component\Lock\LockInterface;
class SymfonyUpdateLockerRepository implements UpdateLockerRepositoryInterface
{
use LoggerTrait;
private const LOCK_NAME = 'update-centreon';
/** @var LockInterface */
private LockInterface $lock;
/**
* @param LockFactory $lockFactory
*/
public function __construct(
LockFactory $lockFactory,
) {
$this->lock = $lockFactory->createLock(self::LOCK_NAME);
}
/**
* @inheritDoc
*/
public function lock(): bool
{
$this->info('Locking centreon update process on filesystem...');
try {
return $this->lock->acquire();
} catch (\Throwable $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
throw UpdateLockerException::errorWhileLockingUpdate($ex);
}
}
/**
* @inheritDoc
*/
public function unlock(): void
{
$this->info('Unlocking centreon update process from filesystem...');
try {
$this->lock->release();
} catch (\Throwable $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
throw UpdateLockerException::errorWhileUnlockingUpdate($ex);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Platform/Infrastructure/Repository/DbWriteUpdateRepository.php | centreon/src/Core/Platform/Infrastructure/Repository/DbWriteUpdateRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\Platform\Infrastructure\Repository;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\Repository\RepositoryException;
use Centreon\Infrastructure\DatabaseConnection;
use Centreon\Infrastructure\Repository\AbstractRepositoryDRB;
use Core\Platform\Application\Repository\WriteUpdateRepositoryInterface;
use Pimple\Container;
use Symfony\Component\Filesystem\Filesystem;
class DbWriteUpdateRepository extends AbstractRepositoryDRB implements WriteUpdateRepositoryInterface
{
use LoggerTrait;
/**
* @param string $libDir
* @param string $installDir
* @param Container $dependencyInjector
* @param DatabaseConnection $db
* @param Filesystem $filesystem
*/
public function __construct(
private string $libDir,
private string $installDir,
private Container $dependencyInjector,
DatabaseConnection $db,
private Filesystem $filesystem,
) {
$this->db = $db;
}
/**
* @inheritDoc
*/
public function runUpdate(string $version): void
{
$this->runMonitoringSql($version);
$this->runScript($version);
$this->runConfigurationSql($version);
$this->runPostScript($version);
$this->updateVersionInformation($version);
}
/**
* @inheritDoc
*/
public function runPostUpdate(string $currentVersion): void
{
if (! $this->filesystem->exists($this->installDir)) {
return;
}
$this->backupInstallDirectory($currentVersion);
$this->removeInstallDirectory();
}
/**
* Backup installation directory.
*
* @param string $currentVersion
*/
private function backupInstallDirectory(string $currentVersion): void
{
$backupDirectory = $this->libDir . '/installs/install-' . $currentVersion . '-' . date('Ymd_His');
$this->info(
'Backing up installation directory',
[
'source' => $this->installDir,
'destination' => $backupDirectory,
],
);
$this->filesystem->mirror(
$this->installDir,
$backupDirectory,
);
}
/**
* Remove installation directory.
*/
private function removeInstallDirectory(): void
{
$this->info(
'Removing installation directory',
[
'installation_directory' => $this->installDir,
],
);
$this->filesystem->remove($this->installDir);
}
/**
* Run sql queries on monitoring database.
*
* @param string $version
*/
private function runMonitoringSql(string $version): void
{
$upgradeFilePath = $this->installDir . '/sql/centstorage/Update-CSTG-' . $version . '.sql';
if (is_readable($upgradeFilePath)) {
$this->db->switchToDb($this->db->getConnectionConfig()->getDatabaseNameRealTime());
$this->runSqlFile($upgradeFilePath);
}
}
/**
* Run php upgrade script.
*
* @param string $version
*/
private function runScript(string $version): void
{
$pearDB = $this->dependencyInjector['configuration_db'];
$pearDBO = $this->dependencyInjector['realtime_db'];
$upgradeFilePath = $this->installDir . '/php/Update-' . $version . '.php';
if (is_readable($upgradeFilePath)) {
include_once $upgradeFilePath;
}
}
/**
* Run sql queries on configuration database.
*
* @param string $version
*/
private function runConfigurationSql(string $version): void
{
$upgradeFilePath = $this->installDir . '/sql/centreon/Update-DB-' . $version . '.sql';
if (is_readable($upgradeFilePath)) {
$this->db->switchToDb($this->db->getConnectionConfig()->getDatabaseNameConfiguration());
$this->runSqlFile($upgradeFilePath);
}
}
/**
* Run php post upgrade script.
*
* @param string $version
*/
private function runPostScript(string $version): void
{
$pearDB = $this->dependencyInjector['configuration_db'];
$pearDBO = $this->dependencyInjector['realtime_db'];
$upgradeFilePath = $this->installDir . '/php/Update-' . $version . '.post.php';
if (is_readable($upgradeFilePath)) {
include_once $upgradeFilePath;
}
}
/**
* Update version information.
*
* @param string $version
*/
private function updateVersionInformation(string $version): void
{
$statement = $this->db->prepare(
$this->translateDbName(
"UPDATE `:db`.`informations` SET `value` = :version WHERE `key` = 'version'"
)
);
$statement->bindValue(':version', $version, \PDO::PARAM_STR);
$statement->execute();
}
/**
* Run sql file and use temporary file to store last executed line.
*
* @param string $filePath
*/
private function runSqlFile(string $filePath): void
{
set_time_limit(0);
$fileName = basename($filePath);
$tmpFile = $this->installDir . '/tmp/' . $fileName;
$alreadyExecutedQueriesCount = $this->getAlreadyExecutedQueriesCount($tmpFile);
if (is_readable($filePath)) {
$fileStream = fopen($filePath, 'r');
if (is_resource($fileStream)) {
$query = '';
$currentLineNumber = 0;
$executedQueriesCount = 0;
try {
while (! feof($fileStream)) {
$currentLineNumber++;
$currentLine = fgets($fileStream);
if ($currentLine && ! $this->isSqlComment($currentLine)) {
$query .= ' ' . trim($currentLine);
}
if ($this->isSqlCompleteQuery($query)) {
$executedQueriesCount++;
if ($executedQueriesCount > $alreadyExecutedQueriesCount) {
try {
$this->executeQuery($query);
} catch (RepositoryException $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
throw $ex;
}
$this->writeExecutedQueriesCountInTemporaryFile($tmpFile, $executedQueriesCount);
}
$query = '';
}
}
} catch (\Throwable $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
throw $ex;
} finally {
fclose($fileStream);
}
}
}
}
/**
* Get stored executed queries count in temporary file to retrieve next query to run in case of an error occurred.
*
* @param string $tmpFile
*
* @return int
*/
private function getAlreadyExecutedQueriesCount(string $tmpFile): int
{
$startLineNumber = 0;
if (is_readable($tmpFile)) {
$lineNumber = file_get_contents($tmpFile);
if (is_numeric($lineNumber)) {
$startLineNumber = (int) $lineNumber;
}
}
return $startLineNumber;
}
/**
* Write executed queries count in temporary file to retrieve upgrade when an error occurred.
*
* @param string $tmpFile
* @param int $count
*/
private function writeExecutedQueriesCountInTemporaryFile(string $tmpFile, int $count): void
{
if (! file_exists($tmpFile) || is_writable($tmpFile)) {
$this->info('Writing in temporary file : ' . $tmpFile);
file_put_contents($tmpFile, $count);
} else {
$this->warning('Cannot write in temporary file : ' . $tmpFile);
}
}
/**
* Check if a line a sql comment.
*
* @param string $line
*
* @return bool
*/
private function isSqlComment(string $line): bool
{
return str_starts_with(trim($line), '--');
}
/**
* Check if a query is complete (trailing semicolon).
*
* @param string $query
*
* @return bool
*/
private function isSqlCompleteQuery(string $query): bool
{
return ! empty(trim($query)) && preg_match('/;\s*$/', $query);
}
/**
* Execute sql query.
*
* @param string $query
*
* @throws \Exception
*/
private function executeQuery(string $query): void
{
try {
$this->db->query($query);
} catch (\Exception $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
throw new RepositoryException('Cannot execute query: ' . $query, 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/Core/Platform/Infrastructure/Repository/FsReadUpdateRepository.php | centreon/src/Core/Platform/Infrastructure/Repository/FsReadUpdateRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\Platform\Infrastructure\Repository;
use Centreon\Domain\Log\LoggerTrait;
use Core\Platform\Application\Repository\ReadUpdateRepositoryInterface;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Finder\Finder;
class FsReadUpdateRepository implements ReadUpdateRepositoryInterface
{
use LoggerTrait;
/**
* @param string $installDir
* @param Filesystem $filesystem
* @param Finder $finder
*/
public function __construct(
private string $installDir,
private Filesystem $filesystem,
private Finder $finder,
) {
}
/**
* @inheritDoc
*/
public function findOrderedAvailableUpdates(string $currentVersion): array
{
$availableUpdates = $this->findAvailableUpdates($currentVersion);
return $this->orderUpdates($availableUpdates);
}
/**
* Get available updates.
*
* @param string $currentVersion
*
* @return string[]
*/
private function findAvailableUpdates(string $currentVersion): array
{
$fileNameVersionRegex = '/Update-(?<version>[a-zA-Z0-9\-\.]+)\.php/';
$updates = [];
if ($this->filesystem->exists($this->installDir)) {
$files = $this->finder->files()
->in($this->installDir)
->name($fileNameVersionRegex);
foreach ($files as $file) {
if (preg_match($fileNameVersionRegex, $file->getFilename(), $matches)) {
if (version_compare($matches['version'], $currentVersion, '>')) {
$updates[] = $matches['version'];
}
}
}
}
return $updates;
}
/**
* Order updates.
*
* @param string[] $updates
*
* @return string[]
*/
private function orderUpdates(array $updates): array
{
usort(
$updates,
fn (string $versionA, string $versionB) => version_compare($versionA, $versionB),
);
return $updates;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Platform/Infrastructure/API/FindFeatures/FindFeaturesController.php | centreon/src/Core/Platform/Infrastructure/API/FindFeatures/FindFeaturesController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\Platform\Infrastructure\API\FindFeatures;
use Centreon\Application\Controller\AbstractController;
use Centreon\Domain\Log\LoggerTrait;
use Core\Platform\Application\UseCase\FindFeatures\FindFeatures;
use Core\Platform\Application\UseCase\FindFeatures\FindFeaturesPresenterInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
final class FindFeaturesController extends AbstractController
{
use LoggerTrait;
/**
* @param FindFeatures $useCase
* @param FindFeaturesPresenter $presenter
*
* @throws AccessDeniedException
*
* @return Response
*/
public function __invoke(
FindFeatures $useCase,
FindFeaturesPresenterInterface $presenter,
): Response {
// This endpoint is public.
$useCase($presenter);
return $presenter->show();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Platform/Infrastructure/API/FindFeatures/FindFeaturesPresenter.php | centreon/src/Core/Platform/Infrastructure/API/FindFeatures/FindFeaturesPresenter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\Platform\Infrastructure\API\FindFeatures;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Platform\Application\UseCase\FindFeatures\FindFeaturesPresenterInterface;
use Core\Platform\Application\UseCase\FindFeatures\FindFeaturesResponse;
final class FindFeaturesPresenter extends AbstractPresenter implements FindFeaturesPresenterInterface
{
public function presentResponse(FindFeaturesResponse|ResponseStatusInterface $data): void
{
if ($data instanceof FindFeaturesResponse) {
$this->present([
'is_cloud_platform' => $data->isCloudPlatform,
'feature_flags' => $data->featureFlags,
]);
} else {
$this->setResponseStatus($data);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Platform/Infrastructure/API/UpdateVersions/UpdateVersionsController.php | centreon/src/Core/Platform/Infrastructure/API/UpdateVersions/UpdateVersionsController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\Platform\Infrastructure\API\UpdateVersions;
use Centreon\Application\Controller\AbstractController;
use Centreon\Domain\Log\LoggerTrait;
use Core\Platform\Application\UseCase\UpdateVersions\{
UpdateVersions,
UpdateVersionsPresenterInterface,
};
final class UpdateVersionsController extends AbstractController
{
use LoggerTrait;
/**
* @param UpdateVersions $useCase
* @param UpdateVersionsPresenterInterface $presenter
*
* @return object
*/
public function __invoke(
UpdateVersions $useCase,
UpdateVersionsPresenterInterface $presenter,
): object {
$this->denyAccessUnlessGrantedForApiConfiguration();
$useCase($presenter);
return $presenter->show();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Platform/Infrastructure/API/UpdateVersions/UpdateVersionsPresenter.php | centreon/src/Core/Platform/Infrastructure/API/UpdateVersions/UpdateVersionsPresenter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\Platform\Infrastructure\API\UpdateVersions;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Platform\Application\UseCase\UpdateVersions\UpdateVersionsPresenterInterface;
class UpdateVersionsPresenter extends AbstractPresenter implements UpdateVersionsPresenterInterface
{
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/GraphTemplate/Application/UseCase/FindGraphTemplates/FindGraphTemplatesResponse.php | centreon/src/Core/GraphTemplate/Application/UseCase/FindGraphTemplates/FindGraphTemplatesResponse.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\GraphTemplate\Application\UseCase\FindGraphTemplates;
final class FindGraphTemplatesResponse
{
/** @var GraphTemplateDto[] */
public array $graphTemplates = [];
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/GraphTemplate/Application/UseCase/FindGraphTemplates/FindGraphTemplatesPresenterInterface.php | centreon/src/Core/GraphTemplate/Application/UseCase/FindGraphTemplates/FindGraphTemplatesPresenterInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\GraphTemplate\Application\UseCase\FindGraphTemplates;
use Core\Application\Common\UseCase\ResponseStatusInterface;
interface FindGraphTemplatesPresenterInterface
{
public function presentResponse(FindGraphTemplatesResponse|ResponseStatusInterface $response): void;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/GraphTemplate/Application/UseCase/FindGraphTemplates/FindGraphTemplates.php | centreon/src/Core/GraphTemplate/Application/UseCase/FindGraphTemplates/FindGraphTemplates.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\GraphTemplate\Application\UseCase\FindGraphTemplates;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Centreon\Infrastructure\RequestParameters\RequestParametersTranslatorException;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\GraphTemplate\Application\Exception\GraphTemplateException;
use Core\GraphTemplate\Application\Repository\ReadGraphTemplateRepositoryInterface;
use Core\GraphTemplate\Domain\Model\GraphTemplate;
final class FindGraphTemplates
{
use LoggerTrait;
public function __construct(
private readonly RequestParametersInterface $requestParameters,
private readonly ReadGraphTemplateRepositoryInterface $readGraphTemplateRepository,
private readonly ContactInterface $contact,
) {
}
/**
* @param FindGraphTemplatesPresenterInterface $presenter
*/
public function __invoke(FindGraphTemplatesPresenterInterface $presenter): void
{
try {
if (
! $this->contact->hasTopologyRole(Contact::ROLE_CONFIGURATION_GRAPH_TEMPLATES_R)
&& ! $this->contact->hasTopologyRole(Contact::ROLE_CONFIGURATION_GRAPH_TEMPLATES_RW)
) {
$this->error(
"User doesn't have sufficient rights to see graph templates",
['user_id' => $this->contact->getId()]
);
$presenter->presentResponse(
new ForbiddenResponse(GraphTemplateException::accessNotAllowed())
);
return;
}
$graphTemplates = $this->readGraphTemplateRepository->findByRequestParameters($this->requestParameters);
$presenter->presentResponse($this->createResponse($graphTemplates));
} catch (RequestParametersTranslatorException $ex) {
$presenter->presentResponse(new ErrorResponse($ex->getMessage()));
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
} catch (\Throwable $ex) {
$presenter->presentResponse(new ErrorResponse(GraphTemplateException::errorWhileSearching($ex)));
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
}
}
/**
* @param GraphTemplate[] $graphTemplates
*
* @return FindGraphTemplatesResponse
*/
private function createResponse(array $graphTemplates): FindGraphTemplatesResponse
{
$response = new FindGraphTemplatesResponse();
foreach ($graphTemplates as $graphTemplate) {
$graphTemplateDto = new GraphTemplateDto();
$graphTemplateDto->id = $graphTemplate->getId();
$graphTemplateDto->name = $graphTemplate->getName();
$graphTemplateDto->verticalAxisLabel = $graphTemplate->getVerticalAxisLabel();
$graphTemplateDto->height = $graphTemplate->getHeight();
$graphTemplateDto->width = $graphTemplate->getWidth();
$graphTemplateDto->base = $graphTemplate->getBase();
$graphTemplateDto->gridLowerLimit = $graphTemplate->getGridLowerLimit();
$graphTemplateDto->gridUpperLimit = $graphTemplate->getGridUpperLimit();
$graphTemplateDto->isUpperLimitSizedToMax = $graphTemplate->isUpperLimitSizedToMax();
$graphTemplateDto->isGraphScaled = $graphTemplate->isGraphScaled();
$graphTemplateDto->isDefaultCentreonTemplate = $graphTemplate->isDefaultCentreonTemplate();
$response->graphTemplates[] = $graphTemplateDto;
}
return $response;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/GraphTemplate/Application/UseCase/FindGraphTemplates/GraphTemplateDto.php | centreon/src/Core/GraphTemplate/Application/UseCase/FindGraphTemplates/GraphTemplateDto.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\GraphTemplate\Application\UseCase\FindGraphTemplates;
class GraphTemplateDto
{
public int $id = 0;
public string $name = '';
public string $verticalAxisLabel = '';
public int $width = 0;
public int $height = 0;
public int $base = 0;
public ?float $gridLowerLimit = null;
public ?float $gridUpperLimit = null;
public bool $isUpperLimitSizedToMax = false;
public bool $isGraphScaled = false;
public bool $isDefaultCentreonTemplate = false;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/GraphTemplate/Application/Exception/GraphTemplateException.php | centreon/src/Core/GraphTemplate/Application/Exception/GraphTemplateException.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\GraphTemplate\Application\Exception;
final class GraphTemplateException extends \Exception
{
/**
* @return self
*/
public static function accessNotAllowed(): self
{
return new self(_('You are not allowed to access graph templates'));
}
/**
* @param \Throwable $ex
*
* @return self
*/
public static function errorWhileSearching(\Throwable $ex): self
{
return new self(_('Error while searching for graph templates'), 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/Core/GraphTemplate/Application/Repository/ReadGraphTemplateRepositoryInterface.php | centreon/src/Core/GraphTemplate/Application/Repository/ReadGraphTemplateRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\GraphTemplate\Application\Repository;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\GraphTemplate\Domain\Model\GraphTemplate;
interface ReadGraphTemplateRepositoryInterface
{
/**
* Determine if a graph template exists by its ID.
*
* @param int $id
*
* @throws \Throwable
*
* @return bool
*/
public function exists(int $id): bool;
/**
* Search for all commands based on request parameters.
*
* @param RequestParametersInterface $requestParameters
*
* @throws \Throwable
*
* @return GraphTemplate[]
*/
public function findByRequestParameters(RequestParametersInterface $requestParameters): array;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/GraphTemplate/Domain/Model/GraphTemplate.php | centreon/src/Core/GraphTemplate/Domain/Model/GraphTemplate.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\GraphTemplate\Domain\Model;
use Assert\AssertionFailedException;
use Centreon\Domain\Common\Assertion\Assertion;
class GraphTemplate
{
public const NAME_MAX_LENGTH = 200;
public const LABEL_MAX_LENGTH = 200;
public const BASE_ALLOWED_VALUES = [1000, 1024];
/**
* @param int $id
* @param string $name
* @param string $verticalAxisLabel
* @param int $width
* @param int $height
* @param int $base
* @param null|float $gridLowerLimit
* @param null|float $gridUpperLimit
* @param bool $isUpperLimitSizedToMax
* @param bool $isGraphScaled
* @param bool $isDefaultCentreonTemplate
*
* @throws AssertionFailedException
*/
public function __construct(
private readonly int $id,
private string $name,
private string $verticalAxisLabel,
private int $width,
private int $height,
private int $base = 1000,
private ?float $gridLowerLimit = null,
private ?float $gridUpperLimit = null,
private bool $isUpperLimitSizedToMax = false,
private bool $isGraphScaled = false,
private bool $isDefaultCentreonTemplate = false,
) {
Assertion::positiveInt($id, 'GraphTemplate::id');
$this->name = trim($name);
Assertion::notEmptyString($this->name, 'GraphTemplate::name');
Assertion::maxLength($this->name, self::NAME_MAX_LENGTH, 'GraphTemplate::name');
$this->verticalAxisLabel = trim($verticalAxisLabel);
Assertion::notEmptyString($this->verticalAxisLabel, 'GraphTemplate::verticalAxisLabel');
Assertion::maxLength($this->verticalAxisLabel, self::LABEL_MAX_LENGTH, 'GraphTemplate::verticalAxisLabel');
Assertion::inArray($base, self::BASE_ALLOWED_VALUES, 'GraphTemplate::base');
// if isUpperLimitSizedToMax is set to true, gridUpperLimit is silently set to null
if ($this->isUpperLimitSizedToMax) {
$this->gridUpperLimit = null;
}
}
public function getId(): int
{
return $this->id;
}
public function getName(): string
{
return $this->name;
}
public function getVerticalAxisLabel(): string
{
return $this->verticalAxisLabel;
}
public function getWidth(): int
{
return $this->width;
}
public function getHeight(): int
{
return $this->height;
}
public function getBase(): int
{
return $this->base;
}
public function getGridLowerLimit(): ?float
{
return $this->gridLowerLimit;
}
public function getGridUpperLimit(): ?float
{
return $this->gridUpperLimit;
}
public function isUpperLimitSizedToMax(): bool
{
return $this->isUpperLimitSizedToMax;
}
public function isGraphScaled(): bool
{
return $this->isGraphScaled;
}
public function isDefaultCentreonTemplate(): bool
{
return $this->isDefaultCentreonTemplate;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/GraphTemplate/Infrastructure/Repository/DbReadGraphTemplateRepository.php | centreon/src/Core/GraphTemplate/Infrastructure/Repository/DbReadGraphTemplateRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\GraphTemplate\Infrastructure\Repository;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Centreon\Domain\RequestParameters\RequestParameters;
use Centreon\Infrastructure\DatabaseConnection;
use Centreon\Infrastructure\RequestParameters\SqlRequestParametersTranslator;
use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB;
use Core\GraphTemplate\Application\Repository\ReadGraphTemplateRepositoryInterface;
use Core\GraphTemplate\Domain\Model\GraphTemplate;
use Utility\SqlConcatenator;
/**
* @phpstan-type _GraphTemplate array{
* graph_id: int,
* name: string,
* vertical_label: string,
* width: int,
* height: int,
* base: int,
* lower_limit: float|null,
* upper_limit: float|null,
* size_to_max: int,
* scaled: string,
* default_tpl1: string,
* }
*/
class DbReadGraphTemplateRepository extends AbstractRepositoryRDB implements ReadGraphTemplateRepositoryInterface
{
/**
* @param DatabaseConnection $db
*/
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* @inheritDoc
*/
public function exists(int $id): bool
{
$request = $this->translateDbName(
<<<'SQL'
SELECT 1
FROM `:db`.giv_graphs_template
WHERE graph_id = :id
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':id', $id, \PDO::PARAM_INT);
$statement->execute();
return (bool) $statement->fetchColumn();
}
/**
* @inheritDoc
*/
public function findByRequestParameters(RequestParametersInterface $requestParameters): array
{
$sqlTranslator = new SqlRequestParametersTranslator($requestParameters);
$sqlTranslator->getRequestParameters()->setConcordanceStrictMode(RequestParameters::CONCORDANCE_MODE_STRICT);
$sqlTranslator->setConcordanceArray([
'id' => 'graph_id',
'name' => 'name',
]);
$sqlConcatenator = new SqlConcatenator();
$sqlConcatenator->defineSelect(
<<<'SQL'
SELECT
gt.graph_id,
gt.name,
gt.vertical_label,
gt.width,
gt.height,
gt.base,
gt.lower_limit,
gt.upper_limit,
gt.size_to_max,
gt.default_tpl1,
gt.scaled
FROM `:db`.`giv_graphs_template` gt
SQL
);
$sqlTranslator->translateForConcatenator($sqlConcatenator);
$statement = $this->db->prepare($this->translateDbName((string) $sqlConcatenator));
$sqlTranslator->bindSearchValues($statement);
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$statement->execute();
$sqlTranslator->calculateNumberOfRows($this->db);
$graphTemplates = [];
foreach ($statement as $result) {
/** @var _GraphTemplate $result */
$graphTemplates[] = new GraphTemplate(
id: $result['graph_id'],
name: $result['name'],
verticalAxisLabel: $result['vertical_label'],
width: $result['width'],
height: $result['height'],
base: $result['base'],
gridLowerLimit: $result['lower_limit'],
gridUpperLimit: $result['upper_limit'],
isUpperLimitSizedToMax: (bool) $result['size_to_max'],
isGraphScaled: (bool) $result['scaled'],
isDefaultCentreonTemplate: (bool) $result['default_tpl1'],
);
}
return $graphTemplates;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/GraphTemplate/Infrastructure/API/FindGraphTemplates/FindGraphTemplatesPresenter.php | centreon/src/Core/GraphTemplate/Infrastructure/API/FindGraphTemplates/FindGraphTemplatesPresenter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\GraphTemplate\Infrastructure\API\FindGraphTemplates;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\GraphTemplate\Application\UseCase\FindGraphTemplates\FindGraphTemplatesPresenterInterface;
use Core\GraphTemplate\Application\UseCase\FindGraphTemplates\FindGraphTemplatesResponse;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
class FindGraphTemplatesPresenter extends AbstractPresenter implements FindGraphTemplatesPresenterInterface
{
public function __construct(
private readonly RequestParametersInterface $requestParameters,
protected PresenterFormatterInterface $presenterFormatter,
) {
parent::__construct($presenterFormatter);
}
public function presentResponse(ResponseStatusInterface|FindGraphTemplatesResponse $response): void
{
if ($response instanceof ResponseStatusInterface) {
$this->setResponseStatus($response);
} else {
$result = [];
foreach ($response->graphTemplates as $graphTemplate) {
$result[] = [
'id' => $graphTemplate->id,
'name' => $graphTemplate->name,
'vertical_axis_label' => $graphTemplate->verticalAxisLabel,
'width' => $graphTemplate->width,
'height' => $graphTemplate->height,
'grid' => [
'lower_limit' => $graphTemplate->gridLowerLimit,
'upper_limit' => $graphTemplate->gridUpperLimit,
'is_upper_limit_sized_to_max' => $graphTemplate->isUpperLimitSizedToMax,
],
'base' => $graphTemplate->base,
'is_graph_scaled' => $graphTemplate->isGraphScaled,
'is_default_centreon_template' => $graphTemplate->isDefaultCentreonTemplate,
];
}
$this->present([
'result' => $result,
'meta' => $this->requestParameters->toArray(),
]);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/GraphTemplate/Infrastructure/API/FindGraphTemplates/FindGraphTemplatesController.php | centreon/src/Core/GraphTemplate/Infrastructure/API/FindGraphTemplates/FindGraphTemplatesController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\GraphTemplate\Infrastructure\API\FindGraphTemplates;
use Centreon\Application\Controller\AbstractController;
use Core\GraphTemplate\Application\UseCase\FindGraphTemplates\FindGraphTemplates;
use Core\GraphTemplate\Application\UseCase\FindGraphTemplates\FindGraphTemplatesPresenterInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
final class FindGraphTemplatesController extends AbstractController
{
/**
* @param FindGraphTemplates $useCase
* @param FindGraphTemplatesPresenter $presenter
*
* @throws AccessDeniedException
*
* @return Response
*/
public function __invoke(FindGraphTemplates $useCase, FindGraphTemplatesPresenterInterface $presenter): Response
{
$this->denyAccessUnlessGrantedForApiConfiguration();
$useCase($presenter);
return $presenter->show();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ResourceAccess/Application/UseCase/AddRule/AddRulePresenterInterface.php | centreon/src/Core/ResourceAccess/Application/UseCase/AddRule/AddRulePresenterInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\ResourceAccess\Application\UseCase\AddRule;
use Core\Application\Common\UseCase\PresenterInterface;
use Core\Application\Common\UseCase\ResponseStatusInterface;
interface AddRulePresenterInterface extends PresenterInterface
{
public function presentResponse(AddRuleResponse|ResponseStatusInterface $response): void;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ResourceAccess/Application/UseCase/AddRule/AddRuleValidation.php | centreon/src/Core/ResourceAccess/Application/UseCase/AddRule/AddRuleValidation.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\ResourceAccess\Application\UseCase\AddRule;
use Centreon\Domain\Log\LoggerTrait;
use Core\Common\Domain\Exception\RepositoryException;
use Core\Contact\Application\Repository\ReadContactGroupRepositoryInterface;
use Core\Contact\Application\Repository\ReadContactRepositoryInterface;
use Core\ResourceAccess\Application\Exception\RuleException;
use Core\ResourceAccess\Application\Providers\DatasetProviderInterface;
use Core\ResourceAccess\Application\Repository\ReadResourceAccessRepositoryInterface;
use Core\ResourceAccess\Domain\Model\NewRule;
class AddRuleValidation
{
use LoggerTrait;
/** @var DatasetProviderInterface[] */
private array $repositoryProviders;
/**
* @param ReadResourceAccessRepositoryInterface $repository
* @param ReadContactRepositoryInterface $contactRepository
* @param ReadContactGroupRepositoryInterface $contactGroupRepository
* @param \Traversable<DatasetProviderInterface> $repositoryProviders
*/
public function __construct(
private readonly ReadResourceAccessRepositoryInterface $repository,
private readonly ReadContactRepositoryInterface $contactRepository,
private readonly ReadContactGroupRepositoryInterface $contactGroupRepository,
\Traversable $repositoryProviders,
) {
$this->repositoryProviders = iterator_to_array($repositoryProviders);
}
/**
* Validates that the name provided for the rule is not already used.
*
* @param string $name
*
* @throws RuleException
*/
public function assertIsValidName(string $name): void
{
if ($this->repository->existsByName(NewRule::formatName($name))) {
$this->error('Resource access rule name already used', ['name' => $name]);
throw RuleException::nameAlreadyExists(NewRule::formatName($name), $name);
}
}
/**
* @param int[] $contactIds
*
* @throws RuleException
*/
public function assertContactIdsAreValid(array $contactIds): void
{
$validIds = $this->contactRepository->exist($contactIds);
if ([] !== ($invalidIds = array_diff($contactIds, $validIds))) {
throw RuleException::idsDoNotExist('contactIds', $invalidIds);
}
}
/**
* @param int[] $contactGroupIds
*
* @throws RuleException
*/
public function assertContactGroupIdsAreValid(array $contactGroupIds): void
{
$validIds = $this->contactGroupRepository->exist($contactGroupIds);
if ([] !== ($invalidIds = array_diff($contactGroupIds, $validIds))) {
throw RuleException::idsDoNotExist('contactGroupIds', $invalidIds);
}
}
/**
* @param string $type
* @param int[] $ids
*
* @throws RuleException
* @throws RepositoryException
*/
public function assertIdsAreValid(string $type, array $ids): void
{
$validIds = [];
foreach ($this->repositoryProviders as $repository) {
if ($repository->isValidFor($type) === true) {
$validIds = $repository->areResourcesValid($ids);
}
}
if ([] !== ($invalidIds = array_diff($ids, $validIds))) {
throw RuleException::idsDoNotExist($type, $invalidIds);
}
}
/**
* @param int[] $contactIds
* @param int[] $contactGroupIds
* @param bool $applyToAllContacts
* @param bool $applyToAllContactGroups
*
* @throws RuleException
*/
public function assertContactsAndContactGroupsAreNotEmpty(
array $contactIds,
array $contactGroupIds,
bool $applyToAllContacts,
bool $applyToAllContactGroups,
): void {
if (
$contactIds === []
&& $contactGroupIds === []
&& $applyToAllContacts === false
&& $applyToAllContactGroups === false
) {
throw RuleException::noLinkToContactsOrContactGroups();
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ResourceAccess/Application/UseCase/AddRule/AddRuleResponse.php | centreon/src/Core/ResourceAccess/Application/UseCase/AddRule/AddRuleResponse.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\ResourceAccess\Application\UseCase\AddRule;
final class AddRuleResponse
{
public int $id = 0;
public string $name = '';
public ?string $description = null;
public bool $isEnabled = true;
public bool $applyToAllContacts = false;
public bool $applyToAllContactGroups = false;
/** @var int[] */
public array $contactIds = [];
/** @var int[] */
public array $contactGroupIds = [];
/** @var mixed[] */
public array $datasetFilters = [];
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ResourceAccess/Application/UseCase/AddRule/AddRule.php | centreon/src/Core/ResourceAccess/Application/UseCase/AddRule/AddRule.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\ResourceAccess\Application\UseCase\AddRule;
use Assert\AssertionFailedException;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Repository\Interfaces\DataStorageEngineInterface;
use Core\Application\Common\UseCase\ConflictResponse;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\Common\Domain\Exception\RepositoryException;
use Core\ResourceAccess\Application\Exception\RuleException;
use Core\ResourceAccess\Application\Repository\ReadResourceAccessRepositoryInterface;
use Core\ResourceAccess\Application\Repository\WriteResourceAccessRepositoryInterface;
use Core\ResourceAccess\Domain\Model\DatasetFilter\DatasetFilter;
use Core\ResourceAccess\Domain\Model\DatasetFilter\DatasetFilterValidator;
use Core\ResourceAccess\Domain\Model\NewRule;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
final readonly class AddRule
{
public const AUTHORIZED_ACL_GROUPS = ['customer_admin_acl'];
/**
* @param ReadResourceAccessRepositoryInterface $readRepository
* @param WriteResourceAccessRepositoryInterface $writeRepository
* @param ContactInterface $user
* @param DataStorageEngineInterface $dataStorageEngine
* @param AddRuleValidation $validator
* @param ReadAccessGroupRepositoryInterface $accessGroupRepository
* @param DatasetFilterValidator $datasetValidator
* @param bool $isCloudPlatform
*/
public function __construct(
private ReadResourceAccessRepositoryInterface $readRepository,
private WriteResourceAccessRepositoryInterface $writeRepository,
private ContactInterface $user,
private DataStorageEngineInterface $dataStorageEngine,
private AddRuleValidation $validator,
private ReadAccessGroupRepositoryInterface $accessGroupRepository,
private DatasetFilterValidator $datasetValidator,
private bool $isCloudPlatform,
) {
}
/**
* @param AddRuleRequest $request
* @param AddRulePresenterInterface $presenter
*/
public function __invoke(
AddRuleRequest $request,
AddRulePresenterInterface $presenter,
): void {
try {
if (! $this->isAuthorized()) {
$presenter->presentResponse(
new ForbiddenResponse(
message: RuleException::notAllowed()->getMessage(),
context: ['user_id' => $this->user->getId(), 'request' => $request]
)
);
return;
}
try {
$this->dataStorageEngine->startTransaction();
/**
* Validate that data provided for name if valid (not already used)
* Validate that ids provided for contact and contactgroups are valid (exist).
*/
$this->validator->assertIsValidName($request->name);
// At least one ID must be provided for contact or contactgroup
$this->validator->assertContactsAndContactGroupsAreNotEmpty(
$request->contactIds,
$request->contactGroupIds,
$request->applyToAllContacts,
$request->applyToAllContactGroups
);
/**
* Contact and ContactGroup IDs need validation only if IDs are provided and that all property is not
* set to true.
*/
if (
! $request->applyToAllContacts
&& $request->contactIds !== []
) {
$this->validator->assertContactIdsAreValid($request->contactIds);
}
if (
! $request->applyToAllContactGroups
&& $request->contactGroupIds !== []
) {
$this->validator->assertContactGroupIdsAreValid($request->contactGroupIds);
}
$datasetFilters = $this->validateAndCreateDatasetFiltersFromRequest($request);
$rule = $this->createRuleFromRequest($request, $datasetFilters);
$ruleId = $this->addRule($rule);
// add relations
$this->linkContacts($ruleId, $rule);
$this->linkContactGroups($ruleId, $rule);
$this->linkResources($ruleId, $rule);
$this->dataStorageEngine->commitTransaction();
} catch (\Throwable $exception) {
$this->dataStorageEngine->rollbackTransaction();
throw $exception;
}
$presenter->presentResponse($this->createResponse($ruleId));
} catch (AssertionFailedException|\ValueError $exception) {
$presenter->presentResponse(
new InvalidArgumentResponse(
message: $exception->getMessage(),
context: ['exception' => $exception, 'request' => $request]
)
);
} catch (RuleException $exception) {
$presenter->presentResponse(
match ($exception->getCode()) {
RuleException::CODE_CONFLICT => new ConflictResponse(
message: $exception->getMessage(),
context: ['exception' => $exception, 'request' => $request]
),
default => new ErrorResponse(
message: $exception->getMessage(),
context: ['request' => $request],
exception: $exception
),
}
);
} catch (\Throwable $exception) {
$presenter->presentResponse(
new ErrorResponse(
message: RuleException::addRule(),
context: ['request' => $request],
exception: $exception,
)
);
}
}
/**
* Check if current user is authorized to perform the action.
* Only users linked to AUTHORIZED_ACL_GROUPS acl_group and having access in Read/Write rights on the page
* are authorized to add a Resource Access Rule.
*
* @throws RepositoryException
* @return bool
*/
private function isAuthorized(): bool
{
if ($this->user->isAdmin()) {
return true;
}
$userAccessGroupNames = array_map(
static fn (AccessGroup $accessGroup): string => $accessGroup->getName(),
$this->accessGroupRepository->findByContact($this->user)
);
return ! (empty(array_intersect($userAccessGroupNames, self::AUTHORIZED_ACL_GROUPS)))
&& $this->user->hasTopologyRole(Contact::ROLE_ADMINISTRATION_ACL_RESOURCE_ACCESS_MANAGEMENT_RW)
&& $this->isCloudPlatform;
}
/**
* @param int $ruleId
* @param int $datasetId
* @param DatasetFilter $filter
*/
private function saveDatasetFiltersHierarchy(int $ruleId, int $datasetId, DatasetFilter $filter): void
{
$parentFilterId = null;
$saveDatasetFiltersHierarchy
= function (int $ruleId, int $datasetId, DatasetFilter $filter) use (&$parentFilterId, &$saveDatasetFiltersHierarchy): void {
// First iteration we save the root filter
$parentFilterId = $this->writeRepository->addDatasetFilter(
$ruleId,
$datasetId,
$filter,
$parentFilterId
);
// if there is a next level then save next level until final level reached
if ($filter->getDatasetFilter() !== null) {
$saveDatasetFiltersHierarchy($ruleId, $datasetId, $filter->getDatasetFilter());
}
};
$saveDatasetFiltersHierarchy($ruleId, $datasetId, $filter);
}
/**
* @param int $ruleId
* @param string $datasetName
* @param DatasetFilter $datasetFilter
*/
private function createFullAccessDatasetFilter(int $ruleId, string $datasetName, DatasetFilter $datasetFilter): void
{
$datasetId = $this->writeRepository->addDataset(
name: $datasetName,
accessAllHosts: true,
accessAllHostGroups: true,
accessAllServiceGroups: true,
accessAllImageFolders: true
);
// And link it to the rule
$this->writeRepository->linkDatasetToRule($ruleId, $datasetId);
// dedicated table used in order to keep filters hierarchy for GET matters
$this->saveDatasetFiltersHierarchy($ruleId, $datasetId, $datasetFilter);
}
/**
* @param int $ruleId
* @param NewRule $rule
*
* @throws \InvalidArgumentException
*/
private function linkResources(int $ruleId, NewRule $rule): void
{
$index = 0;
foreach ($rule->getDatasetFilters() as $datasetFilter) {
// create formatted name for dataset
$datasetName = 'dataset_for_rule_' . $ruleId . '_' . $index;
if ($datasetFilter->getType() === DatasetFilterValidator::ALL_RESOURCES_FILTER) {
$this->createFullAccessDatasetFilter(
ruleId: $ruleId,
datasetName: $datasetName,
datasetFilter: $datasetFilter
);
} else {
// create dataset
$datasetId = $this->writeRepository->addDataset(
name: $datasetName,
accessAllHosts: false,
accessAllHostGroups: false,
accessAllServiceGroups: false,
accessAllImageFolders: false
);
// And link it to the rule
$this->writeRepository->linkDatasetToRule(ruleId: $ruleId, datasetId: $datasetId);
// dedicated table used in order to keep filters hierarchy for GET matters
$this->saveDatasetFiltersHierarchy(ruleId: $ruleId, datasetId: $datasetId, filter: $datasetFilter);
// Extract from the DatasetFilter the final filter level and its parent.
[
'parent' => $parentApplicableFilter,
'last' => $applicableFilter,
] = DatasetFilter::findApplicableFilters($datasetFilter);
/* Specific behaviour when the last level of filtering is of type
* *Category|*Group and that the parent of this filter is also of the same type.
* Then we need to save both types as those are on the same hierarchy level.
*
* Important also to mention a specific behaviour
* When the type matches hostgroup / servicegroup or host and that no
* resource IDs were provided it means 'all_type'. The specific behaviour describe
* above also applies.
*/
if ($parentApplicableFilter !== null) {
if ($this->shouldBothFiltersBeSaved($parentApplicableFilter, $applicableFilter)) {
if ($this->shouldUpdateDatasetAccesses($parentApplicableFilter)) {
$this->writeRepository->updateDatasetAccess(
ruleId: $ruleId,
datasetId: $datasetId,
resourceType: $parentApplicableFilter->getType(),
fullAccess: true
);
} else {
$this->writeRepository->linkResourcesToDataset(
ruleId: $ruleId,
datasetId: $datasetId,
resourceType: $parentApplicableFilter->getType(),
resourceIds: $parentApplicableFilter->getResourceIds()
);
}
}
}
if ($this->shouldUpdateDatasetAccesses($applicableFilter)) {
$this->writeRepository->updateDatasetAccess(
ruleId: $ruleId,
datasetId: $datasetId,
resourceType: $applicableFilter->getType(),
fullAccess: true
);
} else {
$this->writeRepository->linkResourcesToDataset(
ruleId: $ruleId,
datasetId: $datasetId,
resourceType: $applicableFilter->getType(),
resourceIds: $applicableFilter->getResourceIds()
);
}
}
$index++;
}
}
/**
* @param DatasetFilter $datasetFilter
*
* @return bool
*/
private function shouldUpdateDatasetAccesses(DatasetFilter $datasetFilter): bool
{
return $datasetFilter->getResourceIds() === []
&& $this->datasetValidator->canResourceIdsBeEmpty($datasetFilter->getType());
}
/**
* @param DatasetFilter $parent
* @param DatasetFilter $child
*
* @return bool
*/
private function shouldBothFiltersBeSaved(DatasetFilter $parent, DatasetFilter $child): bool
{
return DatasetFilter::isGroupOrCategoryFilter($child)
&& DatasetFilter::isGroupOrCategoryFilter($parent);
}
/**
* @param NewRule $rule
*
* @return int
*/
private function addRule(NewRule $rule): int
{
return $this->writeRepository->add($rule);
}
/**
* @param int $ruleId
* @param NewRule $rule
*/
private function linkContacts(int $ruleId, NewRule $rule): void
{
$this->writeRepository->linkContactsToRule($ruleId, $rule->getLinkedContactIds());
}
/**
* @param int $ruleId
* @param NewRule $rule
*/
private function linkContactGroups(int $ruleId, NewRule $rule): void
{
$this->writeRepository->linkContactGroupsToRule($ruleId, $rule->getLinkedContactGroupIds());
}
/**
* This method will ensure that the ids provided for the dataset filters are valid
* and that the structure of the dataset is correct regarding the hierarchy defined in the DatasetFilter entity.
*
* @param AddRuleRequest $request
*
* @throws RuleException
* @throws \InvalidArgumentException
* @throws RepositoryException
* @throws AssertionFailedException
*
* @return DatasetFilter[]
*/
private function validateAndCreateDatasetFiltersFromRequest(AddRuleRequest $request): array
{
$datasetFilters = [];
$validateAndBuildDatasetFilter = function (
array $data,
?DatasetFilter $parentDatasetFilter,
) use (&$validateAndBuildDatasetFilter, &$datasetFilter): void {
/**
* In any case we want to make sure that
* - resources provided are valid (exist) if not in case of all, all_servicegroups, all_hostgroups, all_hosts
* identified by the fact that $data['resources'] is empty for those types
* - the datasetfilter type provided is valid (validated by entity)
* - that the dataset filter hierarchy is valid (validated by entity).
*/
if ($data['resources'] !== []) {
$this->validator->assertIdsAreValid($data['type'], $data['resources']);
}
// first iteration we want to create the root filter
if ($datasetFilter === null) {
$datasetFilter = new DatasetFilter(
type: $data['type'],
resourceIds: $data['resources'],
validator: $this->datasetValidator
);
if ($data['dataset_filter'] !== null) {
$validateAndBuildDatasetFilter($data['dataset_filter'], null);
}
} elseif ($parentDatasetFilter === null) {
// we want to create the first children
$filter = new DatasetFilter(
type: $data['type'],
resourceIds: $data['resources'],
validator: $this->datasetValidator
);
$datasetFilter->setDatasetFilter($filter);
if ($data['dataset_filter'] !== null) {
$validateAndBuildDatasetFilter($data['dataset_filter'], $datasetFilter->getDatasetFilter());
}
} else {
$childrenDatasetFilter = new DatasetFilter(
type: $data['type'],
resourceIds: $data['resources'],
validator: $this->datasetValidator
);
$parentDatasetFilter->setDatasetFilter($childrenDatasetFilter);
if ($data['dataset_filter'] !== null) {
$validateAndBuildDatasetFilter($data['dataset_filter'], $childrenDatasetFilter);
}
}
};
foreach ($request->datasetFilters as $dataset) {
$datasetFilter = null;
$validateAndBuildDatasetFilter($dataset, $datasetFilter);
/** @var DatasetFilter $datasetFilter */
$datasetFilters[] = $datasetFilter;
}
return $datasetFilters;
}
/**
* @param AddRuleRequest $request
* @param DatasetFilter[] $datasets
*
* @throws AssertionFailedException
* @return NewRule
*/
private function createRuleFromRequest(AddRuleRequest $request, array $datasets): NewRule
{
return new NewRule(
name: $request->name,
description: $request->description,
applyToAllContacts: $request->applyToAllContacts,
linkedContactIds: $request->contactIds,
applyToAllContactGroups: $request->applyToAllContactGroups,
linkedContactGroupIds: $request->contactGroupIds,
datasetFilters: $datasets,
isEnabled: $request->isEnabled
);
}
/**
* @param int $ruleId
*
* @throws RuleException
*
* @return AddRuleResponse
*/
private function createResponse(int $ruleId): AddRuleResponse
{
$rule = $this->readRepository->findById($ruleId);
if (! $rule) {
throw RuleException::errorWhileRetrievingARule();
}
// convert recursively DatasetFilter entities to array
$datasetFilterToArray = function (DatasetFilter $datasetFilter) use (&$datasetFilterToArray): array {
$data['type'] = $datasetFilter->getType();
$data['resources'] = $datasetFilter->getResourceIds();
$data['dataset_filter'] = null;
if ($datasetFilter->getDatasetFilter() !== null) {
$data['dataset_filter'] = $datasetFilterToArray($datasetFilter->getDatasetFilter());
}
return $data;
};
$response = new AddRuleResponse();
$response->id = $rule->getId();
$response->name = $rule->getName();
$response->description = $rule->getDescription();
$response->isEnabled = $rule->isEnabled();
$response->contactIds = $rule->getLinkedContactIds();
$response->contactGroupIds = $rule->getLinkedContactGroupIds();
$response->applyToAllContacts = $rule->doesApplyToAllContacts();
$response->applyToAllContactGroups = $rule->doesApplyToAllContactGroups();
foreach ($rule->getDatasetFilters() as $datasetFilter) {
$response->datasetFilters[] = $datasetFilterToArray($datasetFilter);
}
return $response;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ResourceAccess/Application/UseCase/AddRule/AddRuleRequest.php | centreon/src/Core/ResourceAccess/Application/UseCase/AddRule/AddRuleRequest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\ResourceAccess\Application\UseCase\AddRule;
final class AddRuleRequest
{
public string $name = '';
public string $description = '';
public bool $isEnabled = true;
public bool $applyToAllContacts = false;
public bool $applyToAllContactGroups = false;
/** @var int[] */
public array $contactIds = [];
/** @var int[] */
public array $contactGroupIds = [];
/** @var array{
* array{
* type:string,
* resources: list<int>,
* ...
* }
* }|array{} $datasetFilters
*/
public array $datasetFilters = [];
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ResourceAccess/Application/UseCase/PartialRuleUpdate/PartialRuleUpdate.php | centreon/src/Core/ResourceAccess/Application/UseCase/PartialRuleUpdate/PartialRuleUpdate.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\ResourceAccess\Application\UseCase\PartialRuleUpdate;
use Assert\AssertionFailedException;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\ConflictResponse;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\Application\Common\UseCase\NoContentResponse;
use Core\Application\Common\UseCase\NotFoundResponse;
use Core\Application\Common\UseCase\PresenterInterface;
use Core\Common\Application\Type\NoValue;
use Core\ResourceAccess\Application\Exception\RuleException;
use Core\ResourceAccess\Application\Repository\ReadResourceAccessRepositoryInterface;
use Core\ResourceAccess\Application\Repository\WriteResourceAccessRepositoryInterface;
use Core\ResourceAccess\Application\UseCase\UpdateRule\UpdateRuleValidation;
use Core\ResourceAccess\Domain\Model\Rule;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
final class PartialRuleUpdate
{
use LoggerTrait;
public const AUTHORIZED_ACL_GROUPS = ['customer_admin_acl'];
/**
* @param ContactInterface $user
* @param ReadAccessGroupRepositoryInterface $accessGroupRepository
* @param ReadResourceAccessRepositoryInterface $readRepository
* @param WriteResourceAccessRepositoryInterface $writeRepository
* @param UpdateRuleValidation $validator
* @param bool $isCloudPlatform
*/
public function __construct(
private readonly ContactInterface $user,
private readonly ReadAccessGroupRepositoryInterface $accessGroupRepository,
private readonly ReadResourceAccessRepositoryInterface $readRepository,
private readonly WriteResourceAccessRepositoryInterface $writeRepository,
private readonly UpdateRuleValidation $validator,
private readonly bool $isCloudPlatform,
) {
}
/**
* @param PartialRuleUpdateRequest $request
* @param PresenterInterface $presenter
*/
public function __invoke(
PartialRuleUpdateRequest $request,
PresenterInterface $presenter,
): void {
try {
$this->info('Start resource access rule update process');
if (! $this->isAuthorized()) {
$this->error(
"User doesn't have sufficient rights to create a resource access rule",
[
'user_id' => $this->user->getId(),
]
);
$presenter->setResponseStatus(
new ForbiddenResponse(RuleException::notAllowed()->getMessage())
);
return;
}
$this->debug('Find resource access rule to partially update', ['id' => $request->id]);
$rule = $this->readRepository->findById($request->id);
if ($rule === null) {
$presenter->setResponseStatus(new NotFoundResponse('Resource access rule'));
return;
}
$this->updatePropertiesInTransaction($rule, $request);
$presenter->setResponseStatus(new NoContentResponse());
} catch (RuleException $exception) {
$presenter->setResponseStatus(
match ($exception->getCode()) {
RuleException::CODE_CONFLICT => new ConflictResponse($exception),
default => new ErrorResponse($exception),
}
);
$this->error($exception->getMessage(), ['trace' => $exception->getTraceAsString()]);
} catch (AssertionFailedException $ex) {
$presenter->setResponseStatus(new InvalidArgumentResponse($ex));
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
} catch (\Throwable $exception) {
$presenter->setResponseStatus(new ErrorResponse(RuleException::addRule()));
$this->error($exception->getMessage(), ['trace' => $exception->getTraceAsString()]);
}
}
/**
* @param Rule $rule
* @param PartialRuleUpdateRequest $request
*
* @throws RuleException
* @throws AssertionFailedException
* @throws \Exception
*/
private function updatePropertiesInTransaction(Rule $rule, PartialRuleUpdateRequest $request): void
{
$this->info('Partial resource access rule update', ['rule_id' => $rule->getId()]);
if (! $request->name instanceof NoValue) {
$this->validator->assertIsValidName($request->name);
$rule->setName($request->name);
}
if (! $request->description instanceof NoValue) {
$rule->setDescription($request->description ?? '');
}
if (! $request->isEnabled instanceof NoValue) {
$rule->setIsEnabled($request->isEnabled);
}
$this->writeRepository->update($rule);
}
/**
* Check if current user is authorized to perform the action.
* Only users linked to AUTHORIZED_ACL_GROUPS acl_group and having access in Read/Write rights on the page
* are authorized to add a Resource Access Rule.
*
* @return bool
*/
private function isAuthorized(): bool
{
if ($this->user->isAdmin()) {
return true;
}
$userAccessGroupNames = array_map(
static fn (AccessGroup $accessGroup): string => $accessGroup->getName(),
$this->accessGroupRepository->findByContact($this->user)
);
return ! (empty(array_intersect($userAccessGroupNames, self::AUTHORIZED_ACL_GROUPS)))
&& $this->user->hasTopologyRole(Contact::ROLE_ADMINISTRATION_ACL_RESOURCE_ACCESS_MANAGEMENT_RW)
&& $this->isCloudPlatform;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ResourceAccess/Application/UseCase/PartialRuleUpdate/PartialRuleUpdateRequest.php | centreon/src/Core/ResourceAccess/Application/UseCase/PartialRuleUpdate/PartialRuleUpdateRequest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\ResourceAccess\Application\UseCase\PartialRuleUpdate;
use Core\Common\Application\Type\NoValue;
final class PartialRuleUpdateRequest
{
/**
* @param int $id
* @param NoValue|string $name
* @param NoValue|null|string $description
* @param NoValue|bool $isEnabled
*/
public function __construct(
public int $id = 0,
public NoValue|string $name = new NoValue(),
public NoValue|null|string $description = new NoValue(),
public NoValue|bool $isEnabled = new NoValue(),
) {
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ResourceAccess/Application/UseCase/DeleteRule/DeleteRule.php | centreon/src/Core/ResourceAccess/Application/UseCase/DeleteRule/DeleteRule.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\ResourceAccess\Application\UseCase\DeleteRule;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\NoContentResponse;
use Core\Application\Common\UseCase\NotFoundResponse;
use Core\Application\Common\UseCase\PresenterInterface;
use Core\ResourceAccess\Application\Exception\RuleException;
use Core\ResourceAccess\Application\Repository\ReadResourceAccessRepositoryInterface;
use Core\ResourceAccess\Application\Repository\WriteResourceAccessRepositoryInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
final class DeleteRule
{
use LoggerTrait;
public const AUTHORIZED_ACL_GROUPS = ['customer_admin_acl'];
/**
* @param ReadResourceAccessRepositoryInterface $readRepository
* @param WriteResourceAccessRepositoryInterface $writeRepository
* @param ContactInterface $user
* @param ReadAccessGroupRepositoryInterface $accessGroupRepository
* @param bool $isCloudPlatform
*/
public function __construct(
private readonly ReadResourceAccessRepositoryInterface $readRepository,
private readonly WriteResourceAccessRepositoryInterface $writeRepository,
private readonly ContactInterface $user,
private readonly ReadAccessGroupRepositoryInterface $accessGroupRepository,
private readonly bool $isCloudPlatform,
) {
}
/**
* @param int $ruleId
* @param PresenterInterface $presenter
*/
public function __invoke(int $ruleId, PresenterInterface $presenter): void
{
try {
if (! $this->isAuthorized()) {
$this->error(
"User doesn't have sufficient rights to delete a resource access rule",
[
'user_id' => $this->user->getId(),
]
);
$presenter->setResponseStatus(
new ForbiddenResponse(RuleException::notAllowed()->getMessage())
);
return;
}
$this->info('Starting resource access rule deletion', ['rule_id' => $ruleId]);
if (! $this->readRepository->exists($ruleId)) {
$this->error('Resource access rule not found', ['rule_id' => $ruleId]);
$presenter->setResponseStatus(new NotFoundResponse('Resource access rule'));
return;
}
$this->deleteRule($ruleId);
$presenter->setResponseStatus(new NoContentResponse());
} catch (\Throwable $exception) {
$presenter->setResponseStatus(new ErrorResponse(RuleException::errorWhileDeleting($exception)));
$this->error($exception->getMessage(), ['trace' => $exception->getTraceAsString()]);
}
}
/**
* Check if current user is authorized to perform the action.
* Only users linked to AUTHORIZED_ACL_GROUPS acl_group and having access in Read/Write rights on the page
* are authorized to add a Resource Access Rule.
*
* @return bool
*/
private function isAuthorized(): bool
{
if ($this->user->isAdmin()) {
return true;
}
$userAccessGroupNames = array_map(
static fn (AccessGroup $accessGroup): string => $accessGroup->getName(),
$this->accessGroupRepository->findByContact($this->user)
);
/**
* User must be
* - An admin (belongs to the centreon_admin_acl ACL group)
* - authorized to reach the Resource Access Management page.
*/
return ! (empty(array_intersect($userAccessGroupNames, self::AUTHORIZED_ACL_GROUPS)))
&& $this->user->hasTopologyRole(Contact::ROLE_ADMINISTRATION_ACL_RESOURCE_ACCESS_MANAGEMENT_RW)
&& $this->isCloudPlatform;
}
/**
* @param int $ruleId
*
* @throws \Exception
* @throws \Throwable
*/
private function deleteRule(int $ruleId): void
{
$this->debug('Starting transaction');
$this->writeRepository->deleteRuleAndDatasets($ruleId);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ResourceAccess/Application/UseCase/DeleteRules/DeleteRules.php | centreon/src/Core/ResourceAccess/Application/UseCase/DeleteRules/DeleteRules.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\ResourceAccess\Application\UseCase\DeleteRules;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\Repository\Interfaces\DataStorageEngineInterface;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\NoContentResponse;
use Core\Application\Common\UseCase\NotFoundResponse;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\ResourceAccess\Application\Exception\RuleException;
use Core\ResourceAccess\Application\Repository\ReadResourceAccessRepositoryInterface;
use Core\ResourceAccess\Application\Repository\WriteResourceAccessRepositoryInterface;
use Core\ResourceAccess\Domain\Model\ResponseCode;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
final class DeleteRules
{
use LoggerTrait;
public const AUTHORIZED_ACL_GROUPS = ['customer_admin_acl'];
/**
* @param ReadResourceAccessRepositoryInterface $readRepository
* @param WriteResourceAccessRepositoryInterface $writeRepository
* @param ContactInterface $user
* @param ReadAccessGroupRepositoryInterface $accessGroupRepository
* @param DataStorageEngineInterface $dataStorageEngine
* @param bool $isCloudPlatform
*/
public function __construct(
private readonly ReadResourceAccessRepositoryInterface $readRepository,
private readonly WriteResourceAccessRepositoryInterface $writeRepository,
private readonly ContactInterface $user,
private readonly ReadAccessGroupRepositoryInterface $accessGroupRepository,
private readonly DataStorageEngineInterface $dataStorageEngine,
private readonly bool $isCloudPlatform,
) {
}
/**
* @param DeleteRulesRequest $request
* @param DeleteRulesPresenterInterface $presenter
*/
public function __invoke(DeleteRulesRequest $request, DeleteRulesPresenterInterface $presenter): void
{
try {
if (! $this->isAuthorized()) {
$this->error(
"User doesn't have sufficient rights to delete a resource access rule",
[
'user_id' => $this->user->getId(),
]
);
$response = new ForbiddenResponse(RuleException::notAllowed()->getMessage());
} else {
$this->debug('Starting transaction');
$this->dataStorageEngine->startTransaction();
$response = new DeleteRulesResponse();
foreach ($request->ids as $ruleId) {
try {
$statusResponse = $this->deleteRule($ruleId);
$response->responseStatuses[] = $this->createResponseStatusDto($ruleId, $statusResponse);
} catch (\Throwable $exception) {
$statusResponse = new ErrorResponse(RuleException::errorWhileDeleting($exception));
$response->responseStatuses[] = $this->createResponseStatusDto($ruleId, $statusResponse);
$this->error($exception->getMessage(), ['trace' => $exception->getTraceAsString()]);
}
}
$this->debug('Commit transaction');
$this->dataStorageEngine->commitTransaction();
}
} catch (\Throwable $exception) {
$this->error($exception->getMessage(), ['trace' => $exception->getTraceAsString()]);
$response = new ErrorResponse(RuleException::errorWhileDeleting($exception));
}
$presenter->presentResponse($response);
}
/**
* Check if current user is authorized to perform the action.
* Only users linked to AUTHORIZED_ACL_GROUPS acl_group and having access in Read/Write rights on the page
* are authorized to add a Resource Access Rule.
*
* @return bool
*/
private function isAuthorized(): bool
{
if ($this->user->isAdmin()) {
return true;
}
$userAccessGroupNames = array_map(
static fn (AccessGroup $accessGroup): string => $accessGroup->getName(),
$this->accessGroupRepository->findByContact($this->user)
);
/**
* User must be
* - An admin (belongs to the centreon_admin_acl ACL group)
* - authorized to reach the Resource Access Management page.
*/
return ! (empty(array_intersect($userAccessGroupNames, self::AUTHORIZED_ACL_GROUPS)))
&& $this->user->hasTopologyRole(Contact::ROLE_ADMINISTRATION_ACL_RESOURCE_ACCESS_MANAGEMENT_RW)
&& $this->isCloudPlatform;
}
/**
* @param int $ruleId
*
* @throws \Exception
* @throws \Throwable
*/
private function deleteRule(int $ruleId): ResponseStatusInterface
{
$this->info('Start resource access rule deletion', ['rule_id' => $ruleId]);
if (! $this->readRepository->exists($ruleId)) {
$this->error('Resource access rule not found', ['rule_id' => $ruleId]);
return new NotFoundResponse('Resource access rule');
}
$this->writeRepository->deleteRuleAndDatasets($ruleId);
return new NoContentResponse();
}
/**
* @param int $ruleId
* @param ResponseStatusInterface $statusResponse
*
* @return DeleteRulesStatusResponse
*/
private function createResponseStatusDto(
int $ruleId,
ResponseStatusInterface $statusResponse,
): DeleteRulesStatusResponse {
$dto = new DeleteRulesStatusResponse();
$dto->id = $ruleId;
if ($statusResponse instanceof NotFoundResponse) {
$dto->status = ResponseCode::NotFound;
$dto->message = $statusResponse->getMessage();
} elseif ($statusResponse instanceof NoContentResponse) {
$dto->status = ResponseCode::OK;
$dto->message = null;
} else {
$dto->status = ResponseCode::Error;
$dto->message = $statusResponse->getMessage();
}
return $dto;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ResourceAccess/Application/UseCase/DeleteRules/DeleteRulesRequest.php | centreon/src/Core/ResourceAccess/Application/UseCase/DeleteRules/DeleteRulesRequest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\ResourceAccess\Application\UseCase\DeleteRules;
final class DeleteRulesRequest
{
/** @var int[] */
public array $ids = [];
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ResourceAccess/Application/UseCase/DeleteRules/DeleteRulesResponse.php | centreon/src/Core/ResourceAccess/Application/UseCase/DeleteRules/DeleteRulesResponse.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\ResourceAccess\Application\UseCase\DeleteRules;
final class DeleteRulesResponse
{
/** @var DeleteRulesStatusResponse[] */
public array $responseStatuses = [];
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ResourceAccess/Application/UseCase/DeleteRules/DeleteRulesPresenterInterface.php | centreon/src/Core/ResourceAccess/Application/UseCase/DeleteRules/DeleteRulesPresenterInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\ResourceAccess\Application\UseCase\DeleteRules;
use Core\Application\Common\UseCase\ResponseStatusInterface;
interface DeleteRulesPresenterInterface
{
/**
* @param DeleteRulesResponse|ResponseStatusInterface $data
*/
public function presentResponse(DeleteRulesResponse|ResponseStatusInterface $data): void;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ResourceAccess/Application/UseCase/DeleteRules/DeleteRulesStatusResponse.php | centreon/src/Core/ResourceAccess/Application/UseCase/DeleteRules/DeleteRulesStatusResponse.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\ResourceAccess\Application\UseCase\DeleteRules;
use Core\ResourceAccess\Domain\Model\ResponseCode;
final class DeleteRulesStatusResponse
{
public int $id = 0;
public ResponseCode $status = ResponseCode::OK;
public ?string $message = null;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ResourceAccess/Application/UseCase/UpdateRule/UpdateRuleRequest.php | centreon/src/Core/ResourceAccess/Application/UseCase/UpdateRule/UpdateRuleRequest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\ResourceAccess\Application\UseCase\UpdateRule;
final class UpdateRuleRequest
{
public int $id = 0;
public string $name = '';
public string $description = '';
public bool $isEnabled = true;
public bool $applyToAllContacts = false;
public bool $applyToAllContactGroups = false;
/** @var int[] */
public array $contactIds = [];
/** @var int[] */
public array $contactGroupIds = [];
/** @var array{
* array{
* type:string,
* resources: list<int>,
* ...
* }
* }|array{} $datasetFilters
*/
public array $datasetFilters = [];
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ResourceAccess/Application/UseCase/UpdateRule/UpdateRule.php | centreon/src/Core/ResourceAccess/Application/UseCase/UpdateRule/UpdateRule.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\ResourceAccess\Application\UseCase\UpdateRule;
use Assert\AssertionFailedException;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Core\Application\Common\UseCase\ConflictResponse;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\Application\Common\UseCase\NoContentResponse;
use Core\Application\Common\UseCase\NotFoundResponse;
use Core\Common\Application\Repository\RepositoryManagerInterface;
use Core\Common\Domain\Exception\RepositoryException;
use Core\ResourceAccess\Application\Exception\RuleException;
use Core\ResourceAccess\Application\Repository\ReadResourceAccessRepositoryInterface;
use Core\ResourceAccess\Application\Repository\WriteResourceAccessRepositoryInterface;
use Core\ResourceAccess\Domain\Model\DatasetFilter\DatasetFilter;
use Core\ResourceAccess\Domain\Model\DatasetFilter\DatasetFilterValidator;
use Core\ResourceAccess\Domain\Model\NewRule;
use Core\ResourceAccess\Domain\Model\Rule;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
final readonly class UpdateRule
{
public const AUTHORIZED_ACL_GROUPS = ['customer_admin_acl'];
/**
* @param ContactInterface $user
* @param ReadAccessGroupRepositoryInterface $accessGroupRepository
* @param ReadResourceAccessRepositoryInterface $readRepository
* @param WriteResourceAccessRepositoryInterface $writeRepository
* @param UpdateRuleValidation $validator
* @param DatasetFilterValidator $datasetValidator
* @param RepositoryManagerInterface $repositoryManager
* @param bool $isCloudPlatform
*/
public function __construct(
private ContactInterface $user,
private ReadAccessGroupRepositoryInterface $accessGroupRepository,
private ReadResourceAccessRepositoryInterface $readRepository,
private WriteResourceAccessRepositoryInterface $writeRepository,
private UpdateRuleValidation $validator,
private DatasetFilterValidator $datasetValidator,
private RepositoryManagerInterface $repositoryManager,
private bool $isCloudPlatform,
) {
}
/**
* @param UpdateRuleRequest $request
* @param UpdateRulePresenterInterface $presenter
*/
public function __invoke(UpdateRuleRequest $request, UpdateRulePresenterInterface $presenter): void
{
try {
if (! $this->isAuthorized()) {
$presenter->presentResponse(
new ForbiddenResponse(
message: RuleException::notAllowed()->getMessage(),
context: ['user_id' => $this->user->getId(), 'request' => $request]
)
);
return;
}
$rule = $this->readRepository->findById($request->id);
if ($rule === null) {
$presenter->presentResponse(new NotFoundResponse('Resource access rule'));
return;
}
$this->updateInTransaction($rule, $request);
$presenter->presentResponse(new NoContentResponse());
} catch (AssertionFailedException|\ValueError $exception) {
$presenter->presentResponse(
new InvalidArgumentResponse(
message: $exception->getMessage(),
context: [
'user_id' => $this->user->getId(),
'request' => $request,
'exception' => $exception,
]
)
);
} catch (RuleException $exception) {
$presenter->presentResponse(
match ($exception->getCode()) {
RuleException::CODE_CONFLICT => new ConflictResponse(
message: $exception->getMessage(),
context: [
'user_id' => $this->user->getId(),
'request' => $request,
'exception' => $exception,
]
),
default => new ErrorResponse(
message: $exception->getMessage(),
context: [
'user_id' => $this->user->getId(),
'request' => $request,
],
exception: $exception,
),
}
);
} catch (\Throwable $exception) {
$presenter->presentResponse(
new ErrorResponse(
message: RuleException::updateRule(),
context: [
'user_id' => $this->user->getId(),
'request' => $request,
],
exception: $exception,
)
);
}
}
/**
* @param Rule $rule
* @param UpdateRuleRequest $request
*
* @throws \Throwable
*/
private function updateInTransaction(Rule $rule, UpdateRuleRequest $request): void
{
try {
$this->repositoryManager->startTransaction();
$this->updateBasicInformation($rule, $request);
// At least one ID must be provided for contact or contactgroup
$this->validator->assertContactsAndContactGroupsAreNotEmpty(
$request->contactIds,
$request->contactGroupIds,
$request->applyToAllContacts,
$request->applyToAllContactGroups
);
$this->updateLinkedContacts($rule, $request);
$this->updateLinkedContactGroups($rule, $request);
$this->updateResourceLinks($request);
$this->repositoryManager->commitTransaction();
} catch (\Throwable $exception) {
$this->repositoryManager->rollbackTransaction();
throw $exception;
}
}
/**
* This method will ensure that the ids provided for the dataset filters are valid
* and that the structure of the dataset is correct regarding the hierarchy defined in the DatasetFilter entity.
*
* @param UpdateRuleRequest $request
*
* @throws RuleException
* @throws \InvalidArgumentException
* @throws AssertionFailedException
* @throws RepositoryException
*
* @return DatasetFilter[]
*/
private function validateAndCreateDatasetFiltersFromRequest(UpdateRuleRequest $request): array
{
$datasetFilters = [];
$validateAndBuildDatasetFilter = function (
array $data,
?DatasetFilter $parentDatasetFilter,
) use (&$validateAndBuildDatasetFilter, &$datasetFilter): void {
/**
* In any case we want to make sure that
* - resources provided are valid (exist) if not in case of all, all_servicegroups, all_hostgroups, all_hosts
* identified by the fact that $data['resources'] is empty for those types
* - the datasetfilter type provided is valid (validated by entity)
* - that the dataset filter hierarchy is valid (validated by entity).
*/
if ($data['resources'] !== []) {
$this->validator->assertIdsAreValid($data['type'], $data['resources']);
}
// first iteration we want to create the root filter
if ($datasetFilter === null) {
$datasetFilter = new DatasetFilter(
type: $data['type'],
resourceIds: $data['resources'],
validator: $this->datasetValidator
);
if ($data['dataset_filter'] !== null) {
$validateAndBuildDatasetFilter($data['dataset_filter'], null);
}
} elseif ($parentDatasetFilter === null) {
// we want to create the first children
$filter = new DatasetFilter(
type: $data['type'],
resourceIds: $data['resources'],
validator: $this->datasetValidator
);
$datasetFilter->setDatasetFilter($filter);
if ($data['dataset_filter'] !== null) {
$validateAndBuildDatasetFilter($data['dataset_filter'], $datasetFilter->getDatasetFilter());
}
} else {
$childrenDatasetFilter = new DatasetFilter(
type: $data['type'],
resourceIds: $data['resources'],
validator: $this->datasetValidator
);
$parentDatasetFilter->setDatasetFilter($childrenDatasetFilter);
if ($data['dataset_filter'] !== null) {
$validateAndBuildDatasetFilter($data['dataset_filter'], $childrenDatasetFilter);
}
}
};
foreach ($request->datasetFilters as $dataset) {
$datasetFilter = null;
$validateAndBuildDatasetFilter($dataset, $datasetFilter);
/** @var DatasetFilter $datasetFilter */
$datasetFilters[] = $datasetFilter;
}
return $datasetFilters;
}
/**
* @param int $ruleId
* @param int $datasetId
* @param DatasetFilter $filter
*/
private function saveDatasetFiltersHierarchy(int $ruleId, int $datasetId, DatasetFilter $filter): void
{
$parentFilterId = null;
$saveDatasetFiltersHierarchy = function (
int $ruleId,
int $datasetId,
DatasetFilter $filter,
) use (&$parentFilterId, &$saveDatasetFiltersHierarchy): void {
// First iteration we save the root filter
$parentFilterId = $this->writeRepository->addDatasetFilter($ruleId, $datasetId, $filter, $parentFilterId);
// if there is a next level then save next level until final level reached
if ($filter->getDatasetFilter() !== null) {
$saveDatasetFiltersHierarchy($ruleId, $datasetId, $filter->getDatasetFilter());
}
};
$saveDatasetFiltersHierarchy($ruleId, $datasetId, $filter);
}
/**
* @param UpdateRuleRequest $updateRequest
*
* @throws AssertionFailedException
* @throws RepositoryException
* @throws RuleException
*/
private function updateResourceLinks(UpdateRuleRequest $updateRequest): void
{
// validate the updated datasets sent before doing anything
$datasetFilters = $this->validateAndCreateDatasetFiltersFromRequest($updateRequest);
/*
* At this point we've made sure that the updated dataset filters are valid. Update can start...
* Update will consist in a delete / add actions (replace)
*/
$datasetIds = $this->readRepository->findDatasetIdsByRuleId($updateRequest->id);
/* Deleting datasets found. Constraint on the database tables will automatically
* - delete the dataset_filters associated to the dataset
* - delete the relations between datasets and the rule
*/
$this->writeRepository->deleteDatasets($datasetIds);
$index = 0;
foreach ($datasetFilters as $datasetFilter) {
// create formatted name for dataset
$datasetName = 'dataset_for_rule_' . $updateRequest->id . '_' . $index;
if ($datasetFilter->getType() === DatasetFilterValidator::ALL_RESOURCES_FILTER) {
$this->createFullAccessDatasetFilter(
ruleId: $updateRequest->id,
datasetName: $datasetName,
datasetFilter: $datasetFilter
);
} else {
// create dataset
$datasetId = $this->writeRepository->addDataset(
name: $datasetName,
accessAllHosts: false,
accessAllHostGroups: false,
accessAllServiceGroups: false,
accessAllImageFolders: false
);
// And link it to the rule
$this->writeRepository->linkDatasetToRule(ruleId: $updateRequest->id, datasetId: $datasetId);
// dedicated table used in order to keep filters hierarchy for GET matters
$this->saveDatasetFiltersHierarchy(ruleId: $updateRequest->id, datasetId: $datasetId, filter: $datasetFilter);
// Extract from the DatasetFilter the final filter level and its parent.
[
'parent' => $parentApplicableFilter,
'last' => $applicableFilter,
] = DatasetFilter::findApplicableFilters($datasetFilter);
/* Specific behaviour when the last level of filtering is of type
* *Category|*Group and that the parent of this filter is also of the same type.
* Then we need to save both types as those are on the same hierarchy level.
*
* Important also to mention a specific behaviour
* When the type matches hostgroup / servicegroup or host and that no
* resource IDs were provided it means 'all_type'. The specific behaviour describe
* above also applies.
*/
if ($parentApplicableFilter !== null) {
if ($this->shouldBothFiltersBeSaved($parentApplicableFilter, $applicableFilter)) {
if ($this->shouldUpdateDatasetAccesses($parentApplicableFilter)) {
$this->writeRepository->updateDatasetAccess(
ruleId: $updateRequest->id,
datasetId: $datasetId,
resourceType: $parentApplicableFilter->getType(),
fullAccess: true
);
} else {
$this->writeRepository->linkResourcesToDataset(
ruleId: $updateRequest->id,
datasetId: $datasetId,
resourceType: $parentApplicableFilter->getType(),
resourceIds: $parentApplicableFilter->getResourceIds()
);
}
}
}
if ($this->shouldUpdateDatasetAccesses($applicableFilter)) {
$this->writeRepository->updateDatasetAccess(
ruleId: $updateRequest->id,
datasetId: $datasetId,
resourceType: $applicableFilter->getType(),
fullAccess: true
);
} else {
$this->writeRepository->linkResourcesToDataset(
ruleId: $updateRequest->id,
datasetId: $datasetId,
resourceType: $applicableFilter->getType(),
resourceIds: $applicableFilter->getResourceIds()
);
}
}
$index++;
}
}
/**
* @param DatasetFilter $parent
* @param DatasetFilter $child
*
* @return bool
*/
private function shouldBothFiltersBeSaved(DatasetFilter $parent, DatasetFilter $child): bool
{
return DatasetFilter::isGroupOrCategoryFilter($child)
&& DatasetFilter::isGroupOrCategoryFilter($parent);
}
/**
* @param DatasetFilter $datasetFilter
*
* @return bool
*/
private function shouldUpdateDatasetAccesses(DatasetFilter $datasetFilter): bool
{
return $datasetFilter->getResourceIds() === []
&& $this->datasetValidator->canResourceIdsBeEmpty($datasetFilter->getType());
}
/**
* @param int $ruleId
* @param string $datasetName
* @param DatasetFilter $datasetFilter
*/
private function createFullAccessDatasetFilter(int $ruleId, string $datasetName, DatasetFilter $datasetFilter): void
{
$datasetId = $this->writeRepository->addDataset(
name: $datasetName,
accessAllHosts: true,
accessAllHostGroups: true,
accessAllServiceGroups: true,
accessAllImageFolders: true
);
// And link it to the rule
$this->writeRepository->linkDatasetToRule($ruleId, $datasetId);
// dedicated table used in order to keep filters hierarchy for GET matters
$this->saveDatasetFiltersHierarchy($ruleId, $datasetId, $datasetFilter);
}
/**
* @param Rule $rule
* @param UpdateRuleRequest $updateRequest
*
* @throws RuleException
*/
private function updateLinkedContactGroups(Rule $rule, UpdateRuleRequest $updateRequest): void
{
/**
* Do not do uneccessary database calls if nothing has changed
* if all contact groups are linked to this rule.
*/
if (
$this->shouldUpdateContactOrContactGroupRelations(
$rule->getLinkedContactGroupIds(),
$updateRequest->contactGroupIds
)
&& ! $updateRequest->applyToAllContactGroups
) {
$this->validator->assertContactGroupIdsAreValid($updateRequest->contactGroupIds);
$this->writeRepository->deleteContactGroupRuleRelations($updateRequest->id);
$this->writeRepository->linkContactGroupsToRule($updateRequest->id, $updateRequest->contactGroupIds);
}
}
/**
* @param Rule $rule
* @param UpdateRuleRequest $updateRequest
*
* @throws RuleException
*/
private function updateLinkedContacts(Rule $rule, UpdateRuleRequest $updateRequest): void
{
/**
* Do not do uneccessary database calls if nothing has changed
* if all contacts are linked to this rule.
*/
if (
$this->shouldUpdateContactOrContactGroupRelations(
$rule->getLinkedContactIds(),
$updateRequest->contactIds
)
&& ! $updateRequest->applyToAllContacts
) {
$this->validator->assertContactIdsAreValid($updateRequest->contactIds);
$this->writeRepository->deleteContactRuleRelations($updateRequest->id);
$this->writeRepository->linkContactsToRule($updateRequest->id, $updateRequest->contactIds);
}
}
/**
* @param Rule $rule
* @param UpdateRuleRequest $updateRequest
*
* @throws RuleException
* @throws AssertionFailedException
*/
private function updateBasicInformation(Rule $rule, UpdateRuleRequest $updateRequest): void
{
// Do not do uneccessary database calls if nothing has changed
if ($this->shouldUpdateBasicInformation($rule, $updateRequest)) {
if ($rule->getName() !== NewRule::formatName($updateRequest->name)) {
$this->validator->assertIsValidName($updateRequest->name);
$rule->setName($updateRequest->name);
}
$rule->setIsEnabled($updateRequest->isEnabled);
$rule->setDescription($updateRequest->description);
$rule->setApplyToAllContacts($updateRequest->applyToAllContacts);
$rule->setApplyToAllContactGroups($updateRequest->applyToAllContactGroups);
$this->writeRepository->update($rule);
}
}
/**
* @param int[] $current
* @param int[] $update
*
* @return bool
*/
private function shouldUpdateContactOrContactGroupRelations(array $current, array $update): bool
{
sort($current);
sort($update);
return $current !== $update;
}
/**
* @param Rule $current
* @param UpdateRuleRequest $updateRequest
*
* @return bool
*/
private function shouldUpdateBasicInformation(Rule $current, UpdateRuleRequest $updateRequest): bool
{
return
$current->getName() !== NewRule::formatName($updateRequest->name)
|| $current->getDescription() !== $updateRequest->description
|| $current->isEnabled() !== $updateRequest->isEnabled
|| $current->doesApplyToAllContactGroups() !== $updateRequest->applyToAllContactGroups
|| $current->doesApplyToAllContacts() !== $updateRequest->applyToAllContacts;
}
/**
* Check if current user is authorized to perform the action.
* Only users linked to AUTHORIZED_ACL_GROUPS acl_group and having access in Read/Write rights on the page
* are authorized to add a Resource Access Rule.
*
* @throws RepositoryException
* @return bool
*/
private function isAuthorized(): bool
{
if ($this->user->isAdmin()) {
return true;
}
$userAccessGroupNames = array_map(
static fn (AccessGroup $accessGroup): string => $accessGroup->getName(),
$this->accessGroupRepository->findByContact($this->user)
);
return ! (empty(array_intersect($userAccessGroupNames, self::AUTHORIZED_ACL_GROUPS)))
&& $this->user->hasTopologyRole(Contact::ROLE_ADMINISTRATION_ACL_RESOURCE_ACCESS_MANAGEMENT_RW)
&& $this->isCloudPlatform;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ResourceAccess/Application/UseCase/UpdateRule/UpdateRuleValidation.php | centreon/src/Core/ResourceAccess/Application/UseCase/UpdateRule/UpdateRuleValidation.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\ResourceAccess\Application\UseCase\UpdateRule;
use Centreon\Domain\Log\LoggerTrait;
use Core\Common\Domain\Exception\RepositoryException;
use Core\Contact\Application\Repository\ReadContactGroupRepositoryInterface;
use Core\Contact\Application\Repository\ReadContactRepositoryInterface;
use Core\ResourceAccess\Application\Exception\RuleException;
use Core\ResourceAccess\Application\Providers\DatasetProviderInterface;
use Core\ResourceAccess\Application\Repository\ReadResourceAccessRepositoryInterface;
use Core\ResourceAccess\Domain\Model\NewRule;
class UpdateRuleValidation
{
use LoggerTrait;
/** @var DatasetProviderInterface[] */
private array $repositoryProviders;
/**
* @param ReadResourceAccessRepositoryInterface $repository
* @param ReadContactRepositoryInterface $contactRepository
* @param ReadContactGroupRepositoryInterface $contactGroupRepository
* @param \Traversable<DatasetProviderInterface> $repositoryProviders
*/
public function __construct(
private readonly ReadResourceAccessRepositoryInterface $repository,
private readonly ReadContactRepositoryInterface $contactRepository,
private readonly ReadContactGroupRepositoryInterface $contactGroupRepository,
\Traversable $repositoryProviders,
) {
$this->repositoryProviders = iterator_to_array($repositoryProviders);
}
/**
* Validates that the name provided for the rule is not already used.
*
* @param string $name
*
* @throws RuleException
*/
public function assertIsValidName(string $name): void
{
$this->debug('Check that resource access rule name is not already used', ['name' => $name]);
if ($this->repository->existsByName(NewRule::formatName($name))) {
$this->error('Resource access rule name already used', ['name' => $name]);
throw RuleException::nameAlreadyExists(NewRule::formatName($name), $name);
}
}
/**
* @param int[] $contactIds
*
* @throws RuleException
*/
public function assertContactIdsAreValid(array $contactIds): void
{
$contactIds = array_values(array_unique($contactIds));
$validIds = $this->contactRepository->exist($contactIds);
if ([] !== ($invalidIds = array_diff($contactIds, $validIds))) {
throw RuleException::idsDoNotExist('contactIds', $invalidIds);
}
}
/**
* @param int[] $contactGroupIds
*
* @throws RuleException
*/
public function assertContactGroupIdsAreValid(array $contactGroupIds): void
{
$contactGroupIds = array_values(array_unique($contactGroupIds));
$validIds = $this->contactGroupRepository->exist($contactGroupIds);
if ([] !== ($invalidIds = array_diff($contactGroupIds, $validIds))) {
throw RuleException::idsDoNotExist('contactGroupIds', $invalidIds);
}
}
/**
* @param string $type
* @param int[] $ids
*
* @throws RuleException
* @throws RepositoryException
*/
public function assertIdsAreValid(string $type, array $ids): void
{
$validIds = [];
foreach ($this->repositoryProviders as $repository) {
if ($repository->isValidFor($type) === true) {
$validIds = $repository->areResourcesValid($ids);
}
}
if ([] !== ($invalidIds = array_diff($ids, $validIds))) {
throw RuleException::idsDoNotExist($type, $invalidIds);
}
}
/**
* @param int[] $contactIds
* @param int[] $contactGroupIds
* @param bool $applyToAllContacts
* @param bool $applyToAllContactGroups
*
* @throws RuleException
*/
public function assertContactsAndContactGroupsAreNotEmpty(
array $contactIds,
array $contactGroupIds,
bool $applyToAllContacts,
bool $applyToAllContactGroups,
): void {
if (
$contactIds === []
&& $contactGroupIds === []
&& $applyToAllContacts === false
&& $applyToAllContactGroups === false
) {
throw RuleException::noLinkToContactsOrContactGroups();
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ResourceAccess/Application/UseCase/UpdateRule/UpdateRulePresenterInterface.php | centreon/src/Core/ResourceAccess/Application/UseCase/UpdateRule/UpdateRulePresenterInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\ResourceAccess\Application\UseCase\UpdateRule;
use Core\Application\Common\UseCase\PresenterInterface;
use Core\Application\Common\UseCase\ResponseStatusInterface;
interface UpdateRulePresenterInterface extends PresenterInterface
{
public function presentResponse(ResponseStatusInterface $response): void;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ResourceAccess/Application/UseCase/FindRules/TinyRuleDto.php | centreon/src/Core/ResourceAccess/Application/UseCase/FindRules/TinyRuleDto.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\ResourceAccess\Application\UseCase\FindRules;
final class TinyRuleDto
{
public ?string $description = null;
public function __construct(
public int $id,
public string $name,
public bool $isEnabled,
) {
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ResourceAccess/Application/UseCase/FindRules/FindRulesResponse.php | centreon/src/Core/ResourceAccess/Application/UseCase/FindRules/FindRulesResponse.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\ResourceAccess\Application\UseCase\FindRules;
final class FindRulesResponse
{
/** @var TinyRuleDto[] */
public array $rulesDto = [];
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ResourceAccess/Application/UseCase/FindRules/FindRulesPresenterInterface.php | centreon/src/Core/ResourceAccess/Application/UseCase/FindRules/FindRulesPresenterInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\ResourceAccess\Application\UseCase\FindRules;
use Core\Application\Common\UseCase\PresenterInterface;
use Core\Application\Common\UseCase\ResponseStatusInterface;
interface FindRulesPresenterInterface extends PresenterInterface
{
public function presentResponse(FindRulesResponse|ResponseStatusInterface $response): void;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ResourceAccess/Application/UseCase/FindRules/FindRules.php | centreon/src/Core/ResourceAccess/Application/UseCase/FindRules/FindRules.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\ResourceAccess\Application\UseCase\FindRules;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Centreon\Infrastructure\RequestParameters\RequestParametersTranslatorException;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Contact\Domain\AdminResolver;
use Core\ResourceAccess\Application\Exception\RuleException;
use Core\ResourceAccess\Application\Repository\ReadResourceAccessRepositoryInterface;
use Core\ResourceAccess\Domain\Model\TinyRule;
final class FindRules
{
use LoggerTrait;
public function __construct(
private readonly ContactInterface $user,
private readonly ReadResourceAccessRepositoryInterface $repository,
private readonly RequestParametersInterface $requestParameters,
private readonly AdminResolver $adminResolver,
) {
}
/**
* @param FindRulesPresenterInterface $presenter
*/
public function __invoke(FindRulesPresenterInterface $presenter): void
{
try {
$presenter->presentResponse(
$this->createResponse(
$this->adminResolver->isAdmin($this->user)
? $this->repository->findAllByRequestParameters($this->requestParameters)
: $this->repository->findAllByRequestParametersAndUserId($this->requestParameters, $this->user->getId())
)
);
} catch (RequestParametersTranslatorException $ex) {
$presenter->presentResponse(new ErrorResponse($ex->getMessage()));
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
} catch (\Throwable $ex) {
$presenter->presentResponse(new ErrorResponse(RuleException::errorWhileSearchingRules()));
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
}
}
/**
* @param TinyRule[] $rules
*
* @return FindRulesResponse
*/
private function createResponse(array $rules): FindRulesResponse
{
$response = new FindRulesResponse();
foreach ($rules as $rule) {
$dto = new TinyRuleDto(
$rule->getId(),
$rule->getName(),
$rule->isEnabled()
);
$dto->description = $rule->getDescription();
$response->rulesDto[] = $dto;
}
return $response;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ResourceAccess/Application/UseCase/FindRule/FindRuleResponse.php | centreon/src/Core/ResourceAccess/Application/UseCase/FindRule/FindRuleResponse.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\ResourceAccess\Application\UseCase\FindRule;
final class FindRuleResponse
{
public int $id = 0;
public string $name = '';
public ?string $description = null;
public bool $isEnabled = true;
public bool $applyToAllContacts = false;
public bool $applyToAllContactGroups = false;
/** @var array<int, array{id: int, alias: string}> */
public array $contacts = [];
/** @var array<int, array{id: int, name: string}> */
public array $contactGroups = [];
/** @var mixed[] */
public array $datasetFilters = [];
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ResourceAccess/Application/UseCase/FindRule/FindRule.php | centreon/src/Core/ResourceAccess/Application/UseCase/FindRule/FindRule.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\ResourceAccess\Application\UseCase\FindRule;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\NotFoundResponse;
use Core\Common\Domain\Exception\RepositoryException;
use Core\Contact\Application\Repository\ReadContactGroupRepositoryInterface;
use Core\Contact\Application\Repository\ReadContactRepositoryInterface;
use Core\ResourceAccess\Application\Exception\RuleException;
use Core\ResourceAccess\Application\Providers\DatasetProviderInterface;
use Core\ResourceAccess\Application\Repository\ReadResourceAccessRepositoryInterface;
use Core\ResourceAccess\Domain\Model\DatasetFilter\DatasetFilter;
use Core\ResourceAccess\Domain\Model\DatasetFilter\DatasetFilterValidator;
use Core\ResourceAccess\Domain\Model\Rule;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
final readonly class FindRule
{
public const AUTHORIZED_ACL_GROUPS = ['customer_admin_acl'];
/** @var DatasetProviderInterface[] */
private array $repositoryProviders;
/**
* @param ContactInterface $user
* @param ReadAccessGroupRepositoryInterface $accessGroupRepository
* @param ReadResourceAccessRepositoryInterface $repository
* @param ReadContactRepositoryInterface $contactRepository
* @param ReadContactGroupRepositoryInterface $contactGroupRepository
* @param DatasetFilterValidator $datasetFilterValidator
* @param bool $isCloudPlatform
* @param \Traversable<DatasetProviderInterface> $repositoryProviders
*/
public function __construct(
private ContactInterface $user,
private ReadAccessGroupRepositoryInterface $accessGroupRepository,
private ReadResourceAccessRepositoryInterface $repository,
private ReadContactRepositoryInterface $contactRepository,
private ReadContactGroupRepositoryInterface $contactGroupRepository,
private DatasetFilterValidator $datasetFilterValidator,
private bool $isCloudPlatform,
\Traversable $repositoryProviders,
) {
$this->repositoryProviders = iterator_to_array($repositoryProviders);
}
/**
* @param int $ruleId
* @param FindRulePresenterInterface $presenter
*/
public function __invoke(int $ruleId, FindRulePresenterInterface $presenter): void
{
try {
$response = $this->isAuthorized()
? $this->findRule($ruleId)
: new ForbiddenResponse(RuleException::notAllowed()->getMessage());
$presenter->presentResponse($response);
} catch (\Throwable $ex) {
$presenter->presentResponse(
new ErrorResponse(
message: RuleException::errorWhileSearchingRules(),
context: [
'user_id' => $this->user->getId(),
'rule_id' => $ruleId,
],
exception: $ex
)
);
}
}
/**
* @param int $ruleId
*
* @throws RepositoryException
* @return FindRuleResponse|NotFoundResponse
*/
private function findRule(int $ruleId): FindRuleResponse|NotFoundResponse
{
$rule = $this->repository->findById($ruleId);
if ($rule === null) {
return new NotFoundResponse('Resource Access Rule');
}
return $this->createResponse($rule);
}
/**
* @param Rule $rule
*
* @throws RepositoryException
*
* @return FindRuleResponse
*/
private function createResponse(Rule $rule): FindRuleResponse
{
$response = new FindRuleResponse();
$response->id = $rule->getId();
$response->name = $rule->getName();
$response->description = $rule->getDescription();
$response->isEnabled = $rule->isEnabled();
$response->applyToAllContacts = $rule->doesApplyToAllContacts();
$response->applyToAllContactGroups = $rule->doesApplyToAllContactGroups();
// retrieve names of linked contact IDs
$response->contacts = array_values(
$this->contactRepository->findAliasesByIds(...$rule->getLinkedContactIds())
);
// retrieve names of linked contact group IDs
$response->contactGroups = array_values(
$this->contactGroupRepository->findNamesByIds(...$rule->getLinkedContactGroupIds())
);
// convert recursively DatasetFilter entities to array
$datasetFilterToArray = function (DatasetFilter $datasetFilter) use (&$datasetFilterToArray): array {
$data['type'] = $datasetFilter->getType();
if (
$datasetFilter->getResourceIds() === []
&& $this->datasetFilterValidator->canResourceIdsBeEmpty($data['type'])
) {
$data['resources'] = [];
// special 'ALL' type dataset_filter type case
if ($data['type'] === DatasetFilterValidator::ALL_RESOURCES_FILTER) {
$data['dataset_filter'] = null;
return $data;
}
} else {
$resourcesNamesById = null;
foreach ($this->repositoryProviders as $provider) {
if ($provider->isValidFor($data['type'])) {
$resourcesNamesById = $provider->findResourceNamesByIds($datasetFilter->getResourceIds());
}
}
if ($resourcesNamesById === null) {
throw new \InvalidArgumentException('No repository providers found');
}
$data['resources'] = array_map(
static fn (int $resourceId): array => ['id' => $resourceId, 'name' => $resourcesNamesById->getName($resourceId)],
$datasetFilter->getResourceIds()
);
}
$data['dataset_filter'] = null;
if ($datasetFilter->getDatasetFilter() !== null) {
$data['dataset_filter'] = $datasetFilterToArray($datasetFilter->getDatasetFilter());
}
return $data;
};
foreach ($rule->getDatasetFilters() as $datasetFilter) {
$response->datasetFilters[] = $datasetFilterToArray($datasetFilter);
}
return $response;
}
/**
* Check if current user is authorized to perform the action.
* Only users linked to AUTHORIZED_ACL_GROUPS acl_group and having access in Read/Write rights on the page
* are authorized to add a Resource Access Rule.
*
* @throws RepositoryException
* @return bool
*/
private function isAuthorized(): bool
{
if ($this->user->isAdmin()) {
return true;
}
$userAccessGroupNames = array_map(
static fn (AccessGroup $accessGroup): string => $accessGroup->getName(),
$this->accessGroupRepository->findByContact($this->user)
);
/**
* User must be
* - An admin (belongs to the centreon_admin_acl ACL group)
* - authorized to reach the Resource Access Management page.
*/
return ! (empty(array_intersect($userAccessGroupNames, self::AUTHORIZED_ACL_GROUPS)))
&& $this->user->hasTopologyRole(Contact::ROLE_ADMINISTRATION_ACL_RESOURCE_ACCESS_MANAGEMENT_RW)
&& $this->isCloudPlatform;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ResourceAccess/Application/UseCase/FindRule/FindRulePresenterInterface.php | centreon/src/Core/ResourceAccess/Application/UseCase/FindRule/FindRulePresenterInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\ResourceAccess\Application\UseCase\FindRule;
use Core\Application\Common\UseCase\PresenterInterface;
use Core\Application\Common\UseCase\ResponseStatusInterface;
interface FindRulePresenterInterface extends PresenterInterface
{
public function presentResponse(FindRuleResponse|ResponseStatusInterface $response): void;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ResourceAccess/Application/Exception/RuleException.php | centreon/src/Core/ResourceAccess/Application/Exception/RuleException.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\ResourceAccess\Application\Exception;
class RuleException extends \Exception
{
public const CODE_CONFLICT = 1;
/**
* @param \Throwable $ex
*
* @return self
*/
public static function errorWhileDeleting(\Throwable $ex): self
{
return new self(_('Error while deleting the resource access rule'), 0, $ex);
}
/**
* @return self
*/
public static function notAllowed(): self
{
return new self(_('You are not allowed to list resource access rules'));
}
/**
* @return self
*/
public static function errorWhileSearchingRules(): self
{
return new self(_('Error while search resource access rules'));
}
/**
* @param string $formattedName
* @param string $originalName
*
* @return self
*/
public static function nameAlreadyExists(string $formattedName, string $originalName = 'undefined'): self
{
return new self(
sprintf(_('The name %s (original name: %s) already exists'), $formattedName, $originalName),
self::CODE_CONFLICT
);
}
public static function errorWhileRetrievingARule(): self
{
return new self(_('Error while retrieving a resource access rule'));
}
public static function addRule(): self
{
return new self(_('Error while adding a resource access rule'));
}
public static function updateRule(): self
{
return new self(_('Error while updating the resource access rule'));
}
/**
* @param string $propertyName
* @param int[] $propertyValues
*
* @return self
*/
public static function idsDoNotExist(string $propertyName, array $propertyValues): self
{
return new self(
sprintf(
_("The %s does not exist with ID(s) '%s'"),
$propertyName,
implode(',', $propertyValues)
)
);
}
public static function noLinkToContactsOrContactGroups(): self
{
return new self(_('At least one contact or contactgroup should be linked to the rule'));
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ResourceAccess/Application/Providers/HostCategoryProvider.php | centreon/src/Core/ResourceAccess/Application/Providers/HostCategoryProvider.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\ResourceAccess\Application\Providers;
use Centreon\Domain\Log\LoggerTrait;
use Core\Common\Infrastructure\Repository\RepositoryTrait;
use Core\HostCategory\Application\Repository\ReadHostCategoryRepositoryInterface;
use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\HostCategoryFilterType;
use Core\ResourceAccess\Domain\Model\DatasetFilter\ResourceNamesById;
final class HostCategoryProvider implements DatasetProviderInterface
{
use LoggerTrait;
use RepositoryTrait;
/**
* @param ReadHostCategoryRepositoryInterface $repository
*/
public function __construct(private readonly ReadHostCategoryRepositoryInterface $repository)
{
}
/**
* {@inheritDoc}
*/
public function findResourceNamesByIds(array $ids): ResourceNamesById
{
$names = $this->repository->findNames($ids);
return (new ResourceNamesById())->setNames($names->getNames());
}
/**
* @inheritDoc
*/
public function isValidFor(string $type): bool
{
return $type === HostCategoryFilterType::TYPE_NAME;
}
/**
* @inheritDoc
*
* @throws \Throwable
*/
public function areResourcesValid(array $resourceIds): array
{
return $this->repository->exist($resourceIds);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ResourceAccess/Application/Providers/DatasetProviderInterface.php | centreon/src/Core/ResourceAccess/Application/Providers/DatasetProviderInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\ResourceAccess\Application\Providers;
use Core\Common\Domain\Exception\RepositoryException;
use Core\ResourceAccess\Domain\Model\DatasetFilter\ResourceNamesById;
interface DatasetProviderInterface
{
/**
* @param string $type
*
* @return bool
*/
public function isValidFor(string $type): bool;
/**
* @param int[] $resourceIds
*
* @throws RepositoryException
*
* @return int[]
*/
public function areResourcesValid(array $resourceIds): array;
/**
* @param int[] $ids
*
* @throws RepositoryException
*
* @return ResourceNamesById
*/
public function findResourceNamesByIds(array $ids): ResourceNamesById;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ResourceAccess/Application/Providers/ImageFolderProvider.php | centreon/src/Core/ResourceAccess/Application/Providers/ImageFolderProvider.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\ResourceAccess\Application\Providers;
use Core\Media\Application\Repository\ReadImageFolderRepositoryInterface;
use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\ImageFolderFilterType;
use Core\ResourceAccess\Domain\Model\DatasetFilter\ResourceNamesById;
final class ImageFolderProvider implements DatasetProviderInterface
{
public function __construct(
private readonly ReadImageFolderRepositoryInterface $repository,
) {
}
/**
* @inheritDoc
*/
public function isValidFor(string $type): bool
{
return $type === ImageFolderFilterType::TYPE_NAME;
}
/**
* @inheritDoc
*/
public function areResourcesValid(array $resourceIds): array
{
return $this->repository->findExistingFolderIds($resourceIds);
}
/**
* @inheritDoc
*/
public function findResourceNamesByIds(array $ids): ResourceNamesById
{
return $this->repository->findFolderNames($ids);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ResourceAccess/Application/Providers/MetaServiceProvider.php | centreon/src/Core/ResourceAccess/Application/Providers/MetaServiceProvider.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\ResourceAccess\Application\Providers;
use Core\Application\Configuration\MetaService\Repository\ReadMetaServiceRepositoryInterface;
use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\MetaServiceFilterType;
use Core\ResourceAccess\Domain\Model\DatasetFilter\ResourceNamesById;
final class MetaServiceProvider implements DatasetProviderInterface
{
/**
* @param ReadMetaServiceRepositoryInterface $repository
*/
public function __construct(private readonly ReadMetaServiceRepositoryInterface $repository)
{
}
/**
* {@inheritDoc}
*/
public function findResourceNamesByIds(array $ids): ResourceNamesById
{
$names = $this->repository->findNames(...$ids);
return (new ResourceNamesById())->setNames($names->getNames());
}
/**
* @inheritDoc
*/
public function isValidFor(string $type): bool
{
return $type === MetaServiceFilterType::TYPE_NAME;
}
/**
* @inheritDoc
*/
public function areResourcesValid(array $resourceIds): array
{
return $this->repository->exist($resourceIds);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ResourceAccess/Application/Providers/HostProvider.php | centreon/src/Core/ResourceAccess/Application/Providers/HostProvider.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\ResourceAccess\Application\Providers;
use Centreon\Domain\Log\LoggerTrait;
use Core\Host\Application\Repository\ReadHostRepositoryInterface;
use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\HostFilterType;
use Core\ResourceAccess\Domain\Model\DatasetFilter\ResourceNamesById;
final class HostProvider implements DatasetProviderInterface
{
use LoggerTrait;
/**
* @param ReadHostRepositoryInterface $repository
*/
public function __construct(private readonly ReadHostRepositoryInterface $repository)
{
}
/**
* {@inheritDoc}
*/
public function findResourceNamesByIds(array $ids): ResourceNamesById
{
$names = $this->repository->findNames($ids);
return (new ResourceNamesById())->setNames($names->getNames());
}
/**
* @inheritDoc
*/
public function isValidFor(string $type): bool
{
return $type === HostFilterType::TYPE_NAME;
}
/**
* @inheritDoc
*/
public function areResourcesValid(array $resourceIds): array
{
return $this->repository->exist($resourceIds);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ResourceAccess/Application/Providers/HostGroupProvider.php | centreon/src/Core/ResourceAccess/Application/Providers/HostGroupProvider.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\ResourceAccess\Application\Providers;
use Centreon\Domain\Log\LoggerTrait;
use Core\HostGroup\Application\Repository\ReadHostGroupRepositoryInterface;
use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\HostGroupFilterType;
use Core\ResourceAccess\Domain\Model\DatasetFilter\ResourceNamesById;
final class HostGroupProvider implements DatasetProviderInterface
{
use LoggerTrait;
/**
* @param ReadHostGroupRepositoryInterface $repository
*/
public function __construct(private readonly ReadHostGroupRepositoryInterface $repository)
{
}
/**
* {@inheritDoc}
*/
public function findResourceNamesByIds(array $ids): ResourceNamesById
{
$names = $this->repository->findNames($ids);
return (new ResourceNamesById())->setNames($names->getNames());
}
/**
* @inheritDoc
*/
public function isValidFor(string $type): bool
{
return $type === HostGroupFilterType::TYPE_NAME;
}
/**
* @inheritDoc
*/
public function areResourcesValid(array $resourceIds): array
{
return $this->repository->exist($resourceIds);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ResourceAccess/Application/Providers/ServiceCategoryProvider.php | centreon/src/Core/ResourceAccess/Application/Providers/ServiceCategoryProvider.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\ResourceAccess\Application\Providers;
use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\ServiceCategoryFilterType;
use Core\ResourceAccess\Domain\Model\DatasetFilter\ResourceNamesById;
use Core\ServiceCategory\Application\Repository\ReadServiceCategoryRepositoryInterface;
final class ServiceCategoryProvider implements DatasetProviderInterface
{
/**
* @param ReadServiceCategoryRepositoryInterface $repository
*/
public function __construct(private readonly ReadServiceCategoryRepositoryInterface $repository)
{
}
/**
* {@inheritDoc}
*/
public function findResourceNamesByIds(array $ids): ResourceNamesById
{
$names = $this->repository->findNames($ids);
return (new ResourceNamesById())->setNames($names->getNames());
}
/**
* @inheritDoc
*/
public function isValidFor(string $type): bool
{
return $type === ServiceCategoryFilterType::TYPE_NAME;
}
/**
* @inheritDoc
*/
public function areResourcesValid(array $resourceIds): array
{
return $this->repository->exist($resourceIds);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ResourceAccess/Application/Providers/ServiceGroupProvider.php | centreon/src/Core/ResourceAccess/Application/Providers/ServiceGroupProvider.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\ResourceAccess\Application\Providers;
use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\ServiceGroupFilterType;
use Core\ResourceAccess\Domain\Model\DatasetFilter\ResourceNamesById;
use Core\ServiceGroup\Application\Repository\ReadServiceGroupRepositoryInterface;
final class ServiceGroupProvider implements DatasetProviderInterface
{
/**
* @param ReadServiceGroupRepositoryInterface $repository
*/
public function __construct(private readonly ReadServiceGroupRepositoryInterface $repository)
{
}
/**
* {@inheritDoc}
*/
public function findResourceNamesByIds(array $ids): ResourceNamesById
{
$names = $this->repository->findNames($ids);
return (new ResourceNamesById())->setNames($names->getNames());
}
/**
* @inheritDoc
*/
public function isValidFor(string $type): bool
{
return $type === ServiceGroupFilterType::TYPE_NAME;
}
/**
* @inheritDoc
*/
public function areResourcesValid(array $resourceIds): array
{
return $this->repository->exist($resourceIds);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ResourceAccess/Application/Repository/WriteDatasetRepositoryInterface.php | centreon/src/Core/ResourceAccess/Application/Repository/WriteDatasetRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\ResourceAccess\Application\Repository;
use Core\Common\Domain\Exception\RepositoryException;
interface WriteDatasetRepositoryInterface
{
/**
* @param int $ruleId
* @param int $datasetId
* @param int[] $resourceIds
*
* @throws RepositoryException
*/
public function linkResourcesToDataset(int $ruleId, int $datasetId, array $resourceIds): void;
/**
* @param string $type
*
* @return bool
*/
public function isValidFor(string $type): bool;
/**
* @param int $ruleId
* @param int $datasetId
* @param bool $fullAccess
*
* @throws RepositoryException
*/
public function updateDatasetAccess(int $ruleId, int $datasetId, bool $fullAccess): void;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ResourceAccess/Application/Repository/ReadDatasetRepositoryInterface.php | centreon/src/Core/ResourceAccess/Application/Repository/ReadDatasetRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\ResourceAccess\Application\Repository;
interface ReadDatasetRepositoryInterface
{
/**
* @param string $type
*
* @return bool
*/
public function isValidFor(string $type): bool;
/**
* @param int[] $ids
*
* @return array{id: int, name: string}
*/
public function findResourceNamesByIds(array $ids): array;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ResourceAccess/Application/Repository/ReadResourceAccessRepositoryInterface.php | centreon/src/Core/ResourceAccess/Application/Repository/ReadResourceAccessRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\ResourceAccess\Application\Repository;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Contact\Domain\Model\ContactGroup;
use Core\ResourceAccess\Domain\Model\DatasetFilter\DatasetFilterRelation;
use Core\ResourceAccess\Domain\Model\Rule;
use Core\ResourceAccess\Domain\Model\TinyRule;
interface ReadResourceAccessRepositoryInterface
{
/**
* List all rules.
*
* @param RequestParametersInterface $requestParameters
*
* @return TinyRule[]
*/
public function findAllByRequestParameters(RequestParametersInterface $requestParameters): array;
/**
* List all rules the user is linked to.
*
* @param RequestParametersInterface $requestParameters
* @param int $userId
*
* @return TinyRule[]
*/
public function findAllByRequestParametersAndUserId(RequestParametersInterface $requestParameters, int $userId): array;
/**
* Checks if the rule name provided as been already used for a rule.
*
* @param string $name
*
* @return bool
*/
public function existsByName(string $name): bool;
/**
* @param int $ruleId
*
* @return null|Rule
*/
public function findById(int $ruleId): ?Rule;
/**
* @param int $ruleId
*
* @return int[]
*/
public function findDatasetIdsByRuleId(int $ruleId): array;
/**
* Checks if the rule identified by ruleId exists.
*
* @param int $ruleId
*
* @return bool
*/
public function exists(int $ruleId): bool;
/**
* Retrieve Datasets by Host Group ID.
*
* @param int $hostGroupId
*
* @throws \Throwable
*
* @return array<int, array<int>> [datasetId => [ResourceId1,ResourceId2, ...]]
*/
public function findDatasetResourceIdsByHostGroupId(int $hostGroupId): array;
/**
* Return the list of rule ids that exist from the given rule IDs.
*
* @param int[] $ruleIds
* @return int[]
*/
public function exist(array $ruleIds): array;
/**
* Check if a rule exists by contact.
* Existing rules are linked to the user ID or has "all_contacts" flag.
*
* @param int[] $ruleIds
* @param int $userId
*
* @return int[]
*/
public function existByContact(array $ruleIds, int $userId): array;
/**
* Check if a rule exists by contact groups.
* Existing rules are linked to the contact group IDs or has "all_contact_groups" flag.
*
* @param int[] $ruleIds
* @param ContactGroup[] $contactGroups
*
* @return int[]
*/
public function existByContactGroup(array $ruleIds, array $contactGroups): array;
/**
* Retrieve Datasets by Rule IDs and Dataset type where there is no parent dataset.
*
* @param int[] $ruleIds
* @param string $type
*
* @throws \Throwable
*
* @return DatasetFilterRelation[]
*/
public function findLastLevelDatasetFilterByRuleIdsAndType(array $ruleIds, string $type): array;
/**
* Check if rules exists by type and resource ID.
*
* @param string $type
* @param int $resourceId
* @return int[] array of Rule IDs
*/
public function existByTypeAndResourceId(string $type, int $resourceId): array;
/**
* Retrieve rules by host group ID and type (include 'all' type).
*
* @param string $type dataset filter type
* @param int $resourceId
*
* @throws \Throwable
*
* @return TinyRule[]
*/
public function findRuleByResourceId(string $type, int $resourceId): array;
/**
* Retrieve rules by resource ID and user ID for a specified type.
*
* @param string $type dataset filter type
* @param int $resourceId
* @param int $userId
*
* @throws \Throwable
*
* @return TinyRule[]
*/
public function findRuleByResourceIdAndContactId(string $type, int $resourceId, int $userId): array;
/**
* Retrieve rules by resource ID and contact groups for a specified type.
*
* @param string $type dataset filter type
* @param ContactGroup[] $contactGroups
* @param int $resourceId
*
* @throws \Throwable
*
* @return TinyRule[]
*/
public function findRuleByResourceIdAndContactGroups(string $type, int $resourceId, array $contactGroups): array;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ResourceAccess/Application/Repository/WriteResourceAccessRepositoryInterface.php | centreon/src/Core/ResourceAccess/Application/Repository/WriteResourceAccessRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\ResourceAccess\Application\Repository;
use Core\ResourceAccess\Domain\Model\DatasetFilter\DatasetFilter;
use Core\ResourceAccess\Domain\Model\NewRule;
use Core\ResourceAccess\Domain\Model\Rule;
interface WriteResourceAccessRepositoryInterface
{
/**
* @param NewRule $rule
*
* @return int
*/
public function add(NewRule $rule): int;
/**
* @param Rule $rule
*/
public function update(Rule $rule): void;
/**
* @param int $ruleId
* @param int[] $contactIds
*/
public function linkContactsToRule(int $ruleId, array $contactIds): void;
/**
* @param int $ruleId
*/
public function deleteContactRuleRelations(int $ruleId): void;
/**
* @param int $ruleId
* @param int[] $contactGroupIds
*/
public function linkContactGroupsToRule(int $ruleId, array $contactGroupIds): void;
/**
* @param int $ruleId
*/
public function deleteContactGroupRuleRelations(int $ruleId): void;
/**
* @param string $name
* @param bool $accessAllHosts
* @param bool $accessAllHostGroups
* @param bool $accessAllServiceGroups
* @param bool $accessAllImageFolders
*
* @return int
*/
public function addDataset(
string $name,
bool $accessAllHosts,
bool $accessAllHostGroups,
bool $accessAllServiceGroups,
bool $accessAllImageFolders,
): int;
/**
* @param int $ruleId
* @param int $datasetId
* @param string $resourceType (possible values: hostgroups, servicegroups, hosts)
* @param bool $fullAccess
*/
public function updateDatasetAccess(int $ruleId, int $datasetId, string $resourceType, bool $fullAccess): void;
/**
* @param int $ruleId
* @param int $datasetId
*/
public function linkDatasetToRule(int $ruleId, int $datasetId): void;
/**
* @param int $ruleId
* @param int $datasetId
* @param DatasetFilter $filter
* @param null|int $parentFilterId
*
* @return int
*/
public function addDatasetFilter(int $ruleId, int $datasetId, DatasetFilter $filter, ?int $parentFilterId): int;
/**
* @param int $datasetId
* @param int[] $resourceIds
* @param string $resourceType
* @param int $ruleId
*/
public function linkResourcesToDataset(int $ruleId, int $datasetId, string $resourceType, array $resourceIds): void;
/**
* @param int $ruleId
*/
public function deleteRuleAndDatasets(int $ruleId): void;
/**
* @param int[] $ids
*/
public function deleteDatasets(array $ids): void;
/**
* @param int $datasetId
* @param int[] $resourceIds
*
* @throws \Throwable
*/
public function updateDatasetResources(int $datasetId, array $resourceIds): void;
/**
* @param int $datasetFilterId
*
* @throws \Throwable
*/
public function deleteDatasetFilter(int $datasetFilterId): void;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ResourceAccess/Domain/Model/ResponseCode.php | centreon/src/Core/ResourceAccess/Domain/Model/ResponseCode.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\ResourceAccess\Domain\Model;
enum ResponseCode
{
case OK;
case NotFound;
case Error;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ResourceAccess/Domain/Model/NewRule.php | centreon/src/Core/ResourceAccess/Domain/Model/NewRule.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\ResourceAccess\Domain\Model;
use Assert\AssertionFailedException;
use Centreon\Domain\Common\Assertion\Assertion;
use Core\ResourceAccess\Domain\Model\DatasetFilter\DatasetFilter;
class NewRule
{
public const MAX_NAME_LENGTH = 255;
/**
* @param string $name
* @param null|string $description
* @param bool $applyToAllContacts
* @param int[] $linkedContactIds
* @param bool $applyToAllContactGroups
* @param int[] $linkedContactGroupIds
* @param DatasetFilter[] $datasetFilters
* @param bool $isEnabled
*
* @throws AssertionFailedException
*/
public function __construct(
protected string $name,
protected ?string $description = null,
protected bool $applyToAllContacts = false,
protected array $linkedContactIds = [],
protected bool $applyToAllContactGroups = false,
protected array $linkedContactGroupIds = [],
protected array $datasetFilters = [],
protected bool $isEnabled = true,
) {
$shortName = (new \ReflectionClass($this))->getShortName();
$this->name = self::formatName($name);
Assertion::notEmptyString($this->name, "{$shortName}::name");
Assertion::maxLength($this->name, self::MAX_NAME_LENGTH, "{$shortName}::name");
if ($linkedContactIds !== []) {
Assertion::arrayOfTypeOrNull('int', $this->linkedContactIds, "{$shortName}::linkedContactIds");
}
if ($linkedContactGroupIds !== []) {
Assertion::arrayOfTypeOrNull('int', $this->linkedContactGroupIds, "{$shortName}::linkedContactGroupIds");
}
Assertion::notEmpty($this->datasetFilters, "{$shortName}::datasetFilters");
}
/**
* Format a string as per domain rules for a rule name.
*
* @param string $name
*/
final public static function formatName(string $name): string
{
return str_replace(' ', '_', trim($name));
}
/**
* @return string
*/
public function getName(): string
{
return $this->name;
}
/**
* @return null|string
*/
public function getDescription(): ?string
{
return $this->description;
}
/**
* @return bool
*/
public function isEnabled(): bool
{
return $this->isEnabled;
}
/**
* @return int[]
*/
public function getLinkedContactIds(): array
{
return $this->linkedContactIds;
}
/**
* @return int[]
*/
public function getLinkedContactGroupIds(): array
{
return $this->linkedContactGroupIds;
}
/**
* @return DatasetFilter[]
*/
public function getDatasetFilters(): array
{
return $this->datasetFilters;
}
/**
* @return bool
*/
public function doesApplyToAllContacts(): bool
{
return $this->applyToAllContacts;
}
/**
* @return bool
*/
public function doesApplyToAllContactGroups(): bool
{
return $this->applyToAllContactGroups;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ResourceAccess/Domain/Model/TinyRule.php | centreon/src/Core/ResourceAccess/Domain/Model/TinyRule.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\ResourceAccess\Domain\Model;
use Assert\AssertionFailedException;
use Centreon\Domain\Common\Assertion\Assertion;
class TinyRule
{
public const MAX_NAME_LENGTH = 255;
/**
* @param int $id
* @param string $name
* @param null|string $description
* @param bool $isEnabled
*
* @throws AssertionFailedException
*/
public function __construct(
private readonly int $id,
private readonly string $name,
private readonly ?string $description = null,
private readonly bool $isEnabled = true,
) {
$shortName = (new \ReflectionClass($this))->getShortName();
Assertion::notEmptyString($this->name, "{$shortName}::name");
Assertion::maxLength($this->name, self::MAX_NAME_LENGTH, "{$shortName}::name");
}
/**
* @return int
*/
public function getId(): int
{
return $this->id;
}
/**
* @return string
*/
public function getName(): string
{
return $this->name;
}
/**
* @return null|string
*/
public function getDescription(): ?string
{
return $this->description;
}
/**
* @return bool
*/
public function isEnabled(): bool
{
return $this->isEnabled;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ResourceAccess/Domain/Model/Rule.php | centreon/src/Core/ResourceAccess/Domain/Model/Rule.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\ResourceAccess\Domain\Model;
use Assert\AssertionFailedException;
use Centreon\Domain\Common\Assertion\Assertion;
use Core\ResourceAccess\Domain\Model\DatasetFilter\DatasetFilter;
class Rule extends NewRule
{
private string $shortName = '';
/**
* @param int $id
* @param string $name
* @param ?string $description
* @param int[] $linkedContacts
* @param int[] $linkedContactGroups
* @param DatasetFilter[] $datasets
* @param bool $isEnabled
* @param bool $applyToAllContacts
* @param bool $applyToAllContactGroups
*
* @throws AssertionFailedException
*/
public function __construct(
private readonly int $id,
string $name,
?string $description = null,
bool $applyToAllContacts = false,
array $linkedContacts = [],
bool $applyToAllContactGroups = false,
array $linkedContactGroups = [],
array $datasets = [],
bool $isEnabled = true,
) {
$this->shortName = (new \ReflectionClass($this))->getShortName();
Assertion::positiveInt($id, "{$this->shortName}::id");
parent::__construct(
name: $name,
description: $description,
applyToAllContacts: $applyToAllContacts,
linkedContactIds: $linkedContacts,
applyToAllContactGroups: $applyToAllContactGroups,
linkedContactGroupIds: $linkedContactGroups,
datasetFilters: $datasets,
isEnabled: $isEnabled
);
}
/**
* @return int
*/
public function getId(): int
{
return $this->id;
}
/**
* @param null|string $description
*/
public function setDescription(?string $description): void
{
$this->description = $description;
}
/**
* @param string $name
*
* @throws AssertionFailedException
*/
public function setName(string $name): void
{
$this->name = $name;
Assertion::notEmptyString($this->name, "{$this->shortName}::name");
Assertion::minLength($this->name, 1, "{$this->shortName}::name");
Assertion::maxLength($this->name, self::MAX_NAME_LENGTH, "{$this->shortName}::name");
}
/**
* @param bool $isEnabled
*/
public function setIsEnabled(bool $isEnabled): void
{
$this->isEnabled = $isEnabled;
}
/**
* @param int[] $contacts
*/
public function setLinkedContacts(array $contacts): void
{
$this->linkedContactIds = $contacts;
}
/**
* @param int[] $contactGroups
*/
public function setLinkedContactGroups(array $contactGroups): void
{
$this->linkedContactGroupIds = $contactGroups;
}
/**
* @param bool $applyToAllContacts
*/
public function setApplyToAllContacts(bool $applyToAllContacts): void
{
$this->applyToAllContacts = $applyToAllContacts;
}
/**
* @param bool $applyToAllContactGroups
*/
public function setApplyToAllContactGroups(bool $applyToAllContactGroups): void
{
$this->applyToAllContactGroups = $applyToAllContactGroups;
}
/**
* @param DatasetFilter $datasetFilter
*/
public function addDataset(DatasetFilter $datasetFilter): void
{
$this->datasetFilters[] = $datasetFilter;
}
/**
* @param DatasetFilter[] $datasets
*/
public function setDatasets(array $datasets): void
{
foreach ($datasets as $dataset) {
$this->addDataset($dataset);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ResourceAccess/Domain/Model/DatasetFilter/DatasetFilter.php | centreon/src/Core/ResourceAccess/Domain/Model/DatasetFilter/DatasetFilter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\ResourceAccess\Domain\Model\DatasetFilter;
use Assert\AssertionFailedException;
use Centreon\Domain\Common\Assertion\Assertion;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\HostCategoryFilterType;
use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\HostGroupFilterType;
use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\ServiceCategoryFilterType;
use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\ServiceGroupFilterType;
class DatasetFilter
{
public const ERROR_NOT_A_DATASET_FILTER_TYPE = 1;
public const ERROR_DATASET_FILTER_HIERARCHY_NOT_VALID = 2;
private ?self $datasetFilter = null;
/**
* @param string $type
* @param int[] $resourceIds
* @param DatasetFilterValidator $validator
*
* @throws AssertionFailedException
* @throws AssertionException
* @throws \InvalidArgumentException
*/
public function __construct(
private readonly string $type,
private readonly array $resourceIds,
private readonly DatasetFilterValidator $validator,
) {
$shortName = (new \ReflectionClass($this))->getShortName();
Assertion::notEmptyString($type, "{$shortName}::type");
$this->assertTypeIsValid($type);
// if it can be empty it does not mean that it is empty.
// So we need to check if not empty that we do receive an array of ints.
if ($this->validator->canResourceIdsBeEmpty($type)) {
if ($resourceIds !== []) {
Assertion::arrayOfTypeOrNull('int', $this->resourceIds, "{$shortName}::resourceIds");
}
} else {
Assertion::notEmpty($this->resourceIds, "{$shortName}::resourceIds");
Assertion::arrayOfTypeOrNull('int', $this->resourceIds, "{$shortName}::resourceIds");
}
}
/**
* @return string
*/
public function getType(): string
{
return $this->type;
}
/**
* @return int[]
*/
public function getResourceIds(): array
{
return $this->resourceIds;
}
/**
* @param DatasetFilter|null $datasetFilter
*
* @throws \InvalidArgumentException
*/
public function setDatasetFilter(?self $datasetFilter): void
{
if ($datasetFilter !== null) {
$this->assertDatasetFilterHierarchyIsValid($datasetFilter->getType());
}
$this->datasetFilter = $datasetFilter;
}
/**
* @return null|DatasetFilter
*/
public function getDatasetFilter(): ?self
{
return $this->datasetFilter;
}
/**
* @param DatasetFilter $filter
*
* @return array{parent: DatasetFilter|null, last: DatasetFilter}
*/
public static function findApplicableFilters(self $filter): array
{
$lastLevelFilter = null;
$parentLastLevelFilter = null;
/**
* Recursive method to find the last 'stage' of filters (descending filters) that should be applied
* and its parent.
* Uses $findApplicableFilters for recursivity, lastLevelFilter and parentLastLevelFilter
* which are DatasetFilters entities (or null for parent).
*/
$findApplicableFilters = function (DatasetFilter $filter) use (&$findApplicableFilters, &$lastLevelFilter, &$parentLastLevelFilter): array {
// initialize the $applicableFilter which is initially NULL
if ($lastLevelFilter === null) {
$lastLevelFilter = $filter;
$findApplicableFilters($filter);
}
// if there is a level then keep digging
elseif ($filter->getDatasetFilter() !== null) {
$parentLastLevelFilter = $filter;
$lastLevelFilter = $filter->getDatasetFilter();
$findApplicableFilters($lastLevelFilter);
}
return ['parent' => $parentLastLevelFilter, 'last' => $lastLevelFilter];
};
return $findApplicableFilters($filter);
}
/**
* @param DatasetFilter $filter
*
* @return bool
*/
public static function isGroupOrCategoryFilter(self $filter): bool
{
return in_array(
$filter->getType(),
[
HostGroupFilterType::TYPE_NAME,
HostCategoryFilterType::TYPE_NAME,
ServiceCategoryFilterType::TYPE_NAME,
ServiceGroupFilterType::TYPE_NAME,
],
true
);
}
/**
* @param string $type
*
* @throws \InvalidArgumentException
*/
private function assertTypeIsValid(string $type): void
{
if (! $this->validator->isDatasetFilterTypeValid($type)) {
$message = sprintf('Value provided is not supported for dataset filter type (was: %s)', $type);
throw new \InvalidArgumentException($message, self::ERROR_NOT_A_DATASET_FILTER_TYPE);
}
}
/**
* @param string $childType
*
* @throws \InvalidArgumentException
*/
private function assertDatasetFilterHierarchyIsValid(string $childType): void
{
if (! $this->validator->isDatasetFilterHierarchyValid($this->type, $childType)) {
$message = sprintf('Dataset filter hierarchy assertion failed (%s not a sub-filter of %s)', $childType, $this->type);
throw new \InvalidArgumentException($message, self::ERROR_DATASET_FILTER_HIERARCHY_NOT_VALID);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ResourceAccess/Domain/Model/DatasetFilter/ResourceNamesById.php | centreon/src/Core/ResourceAccess/Domain/Model/DatasetFilter/ResourceNamesById.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\ResourceAccess\Domain\Model\DatasetFilter;
use Core\Common\Domain\TrimmedString;
class ResourceNamesById
{
/** @var array<int,TrimmedString> */
private array $names = [];
/**
* @param int $resourceId
* @param TrimmedString $resourceName
*/
public function addName(int $resourceId, TrimmedString $resourceName): void
{
$this->names[$resourceId] = $resourceName;
}
/**
* @param int $resourceId
*
* @return null|string
*/
public function getName(int $resourceId): ?string
{
return isset($this->names[$resourceId]) ? $this->names[$resourceId]->value : null;
}
/**
* @param array<int,TrimmedString> $names
*
* @return ResourceNamesById
*/
public function setNames(array $names): self
{
foreach ($names as $id => $name) {
$this->addName($id, $name);
}
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/Core/ResourceAccess/Domain/Model/DatasetFilter/AbstractDatasetFilterType.php | centreon/src/Core/ResourceAccess/Domain/Model/DatasetFilter/AbstractDatasetFilterType.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\ResourceAccess\Domain\Model\DatasetFilter;
abstract class AbstractDatasetFilterType implements DatasetFilterTypeInterface
{
protected string $name = '';
/** @var string[] */
protected array $possibleChildren = [];
/**
* @inheritDoc
*/
public function getName(): string
{
return $this->name;
}
/**
* @inheritDoc
*/
public function isValidFor(string $name): bool
{
return $this->name === $name;
}
/**
* @inheritDoc
*/
public function getPossibleChildren(): array
{
return $this->possibleChildren;
}
/**
* @inheritDoc
*/
public function canResourceIdsBeEmpty(): bool
{
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/Core/ResourceAccess/Domain/Model/DatasetFilter/DatasetFilterRelation.php | centreon/src/Core/ResourceAccess/Domain/Model/DatasetFilter/DatasetFilterRelation.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\ResourceAccess\Domain\Model\DatasetFilter;
final class DatasetFilterRelation
{
/**
* @param int $datasetFilterId
* @param string $datasetFilterType
* @param null|int $parentId
* @param int $resourceAccessGroupId
* @param int $aclGroupId
* @param int[] $resourceIds
*/
public function __construct(
private readonly int $datasetFilterId,
private readonly string $datasetFilterType,
private readonly ?int $parentId,
private readonly int $resourceAccessGroupId,
private readonly int $aclGroupId,
private readonly array $resourceIds,
) {
}
public function getDatasetFilterId(): int
{
return $this->datasetFilterId;
}
public function getDatasetFilterType(): string
{
return $this->datasetFilterType;
}
public function getParentId(): ?int
{
return $this->parentId;
}
public function getResourceAccessGroupId(): int
{
return $this->resourceAccessGroupId;
}
public function getAclGroupId(): int
{
return $this->aclGroupId;
}
/**
* @return int[]
*/
public function getResourceIds(): array
{
return $this->resourceIds;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ResourceAccess/Domain/Model/DatasetFilter/DatasetFilterTypeInterface.php | centreon/src/Core/ResourceAccess/Domain/Model/DatasetFilter/DatasetFilterTypeInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\ResourceAccess\Domain\Model\DatasetFilter;
interface DatasetFilterTypeInterface
{
/**
* @return string
*/
public function getName(): string;
/**
* @param string $name
*
* @return bool
*/
public function isValidFor(string $name): bool;
/**
* @return string[]|array{}
*/
public function getPossibleChildren(): array;
/**
* @return bool
*/
public function canResourceIdsBeEmpty(): bool;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ResourceAccess/Domain/Model/DatasetFilter/DatasetFilterValidator.php | centreon/src/Core/ResourceAccess/Domain/Model/DatasetFilter/DatasetFilterValidator.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\ResourceAccess\Domain\Model\DatasetFilter;
class DatasetFilterValidator
{
public const ALL_RESOURCES_FILTER = 'all';
/** @var DatasetFilterTypeInterface[] */
private array $filterTypes = [];
/** @var array<string, array<string>> */
private array $hiearchy = [];
/**
* @param \Traversable<DatasetFilterTypeInterface> $datasetFilterTypes
*/
public function __construct(\Traversable $datasetFilterTypes)
{
$this->filterTypes = iterator_to_array($datasetFilterTypes);
foreach ($this->filterTypes as $filterType) {
$this->hiearchy[$filterType->getName()] = $filterType->getPossibleChildren();
}
if ($this->hiearchy === []) {
throw new \InvalidArgumentException('You must add at least one dataset filter type provider');
}
// Add special case of all resources filter type
$this->hiearchy[self::ALL_RESOURCES_FILTER] = [];
}
/**
* This method indicates for a given type if the resourceIds array can be empty.
* If it is empty is means 'ALL' (of the given resource type that is allowed to).
*
* @param string $type
*
* @return bool
*/
public function canResourceIdsBeEmpty(string $type): bool
{
if ($type === self::ALL_RESOURCES_FILTER) {
return true;
}
foreach ($this->filterTypes as $filterType) {
if ($filterType->isValidFor($type)) {
return $filterType->canResourceIdsBeEmpty();
}
}
return false;
}
/**
* @param string $type
*
* @return bool
*/
public function isDatasetFilterTypeValid(string $type): bool
{
return \in_array($type, array_keys($this->hiearchy), true);
}
/**
* @param string $parentType
* @param string $childType
*
* @return bool
*/
public function isDatasetFilterHierarchyValid(string $parentType, string $childType): bool
{
return \in_array($childType, $this->hiearchy[$parentType], true);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ResourceAccess/Domain/Model/DatasetFilter/Providers/ServiceGroupFilterType.php | centreon/src/Core/ResourceAccess/Domain/Model/DatasetFilter/Providers/ServiceGroupFilterType.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\ResourceAccess\Domain\Model\DatasetFilter\Providers;
use Core\ResourceAccess\Domain\Model\DatasetFilter\AbstractDatasetFilterType;
class ServiceGroupFilterType extends AbstractDatasetFilterType
{
public const TYPE_NAME = 'servicegroup';
protected string $name = self::TYPE_NAME;
protected array $possibleChildren = [
ServiceCategoryFilterType::TYPE_NAME,
ServiceFilterType::TYPE_NAME,
];
/**
* @inheritDoc
*/
public function canResourceIdsBeEmpty(): bool
{
return true;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ResourceAccess/Domain/Model/DatasetFilter/Providers/HostFilterType.php | centreon/src/Core/ResourceAccess/Domain/Model/DatasetFilter/Providers/HostFilterType.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\ResourceAccess\Domain\Model\DatasetFilter\Providers;
use Core\ResourceAccess\Domain\Model\DatasetFilter\AbstractDatasetFilterType;
class HostFilterType extends AbstractDatasetFilterType
{
public const TYPE_NAME = 'host';
protected string $name = self::TYPE_NAME;
protected array $possibleChildren = [
ServiceGroupFilterType::TYPE_NAME,
ServiceCategoryFilterType::TYPE_NAME,
ServiceFilterType::TYPE_NAME,
];
/**
* @inheritDoc
*/
public function canResourceIdsBeEmpty(): bool
{
return true;
}
}
| 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.