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/AdditionalConnectorConfiguration/Application/Repository/WriteAccRepositoryInterface.php | centreon/src/Core/AdditionalConnectorConfiguration/Application/Repository/WriteAccRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AdditionalConnectorConfiguration\Application\Repository;
use Core\AdditionalConnectorConfiguration\Domain\Model\Acc;
use Core\AdditionalConnectorConfiguration\Domain\Model\NewAcc;
interface WriteAccRepositoryInterface
{
/**
* Create a new additional connector (ACC).
*
* @param NewAcc $acc
*
* @throws \Throwable
*
* @return int
*/
public function add(NewAcc $acc): int;
/**
* Update an additional connector (ACC).
*
* @param Acc $acc
*
* @throws \Throwable
*/
public function update(Acc $acc): void;
/**
* Delete an additonal connector configuration.
*
* @param int $id
*
* @throws \Throwable
*/
public function delete(int $id): void;
/**
* Link listed poller to the additional connector (ACC).
*
* @param int $accId
* @param int[] $pollers
*
* @throws \Throwable
*/
public function linkToPollers(int $accId, array $pollers): void;
/**
* Unlink all pollers from the additional connector (ACC).
*
* @param int $accId
*
* @throws \Throwable
*/
public function removePollers(int $accId): 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/AdditionalConnectorConfiguration/Application/Repository/WriteVaultAccRepositoryInterface.php | centreon/src/Core/AdditionalConnectorConfiguration/Application/Repository/WriteVaultAccRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AdditionalConnectorConfiguration\Application\Repository;
use Core\AdditionalConnectorConfiguration\Domain\Model\Acc;
use Core\AdditionalConnectorConfiguration\Domain\Model\AccParametersInterface;
use Core\AdditionalConnectorConfiguration\Domain\Model\Type;
interface WriteVaultAccRepositoryInterface
{
public function isValidFor(Type $type): bool;
/**
* save credentials in vault and return the parameters updated with vaultPaths.
*
* @param AccParametersInterface $parameters
*
* @throws \Throwable
*
* @return AccParametersInterface
*/
public function saveCredentialInVault(AccParametersInterface $parameters): AccParametersInterface;
/**
* Delete an ACC credentials from vault.
*
* @param Acc $acc
*
* @throws \Throwable
*/
public function deleteFromVault(Acc $acc): 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/AdditionalConnectorConfiguration/Application/Factory/AccFactory.php | centreon/src/Core/AdditionalConnectorConfiguration/Application/Factory/AccFactory.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AdditionalConnectorConfiguration\Application\Factory;
use Core\AdditionalConnectorConfiguration\Domain\Model\Acc;
use Core\AdditionalConnectorConfiguration\Domain\Model\NewAcc;
use Core\AdditionalConnectorConfiguration\Domain\Model\Type;
use Core\AdditionalConnectorConfiguration\Domain\Model\VmWareV6\VmWareV6Parameters;
use Security\Interfaces\EncryptionInterface;
/**
* @phpstan-import-type _VmWareV6Parameters from VmWareV6Parameters
*/
class AccFactory
{
public function __construct(private readonly EncryptionInterface $encryption)
{
}
/**
* @param string $name
* @param Type $type
* @param int $createdBy
* @param array<string,mixed> $parameters
* @param null|string $description
*
* @return NewAcc
*/
public function createNewAcc(
string $name,
Type $type,
int $createdBy,
array $parameters,
?string $description = null,
): NewAcc {
return new NewAcc(
name: $name,
type: $type,
createdBy: $createdBy,
description: $description,
parameters: match ($type) {
Type::VMWARE_V6 => new VmWareV6Parameters($this->encryption, $parameters),
}
);
}
/**
* @param int $id
* @param string $name
* @param Type $type
* @param null|int $createdBy
* @param null|int $updatedBy
* @param \DateTimeImmutable $createdAt
* @param \DateTimeImmutable $updatedAt
* @param array<string,mixed> $parameters
* @param null|string $description
*
* @return Acc
*/
public function createAcc(
int $id,
string $name,
Type $type,
?int $createdBy,
?int $updatedBy,
\DateTimeImmutable $createdAt,
\DateTimeImmutable $updatedAt,
array $parameters,
?string $description = null,
): Acc {
return new Acc(
id: $id,
name: $name,
type: $type,
createdBy: $createdBy,
updatedBy: $updatedBy,
createdAt: $createdAt,
updatedAt: $updatedAt,
description: $description,
parameters: match ($type->value) {
Type::VMWARE_V6->value => new VmWareV6Parameters($this->encryption, $parameters),
}
);
}
/**
* @param Acc $acc
* @param string $name
* @param int $updatedBy
* @param array<string,mixed> $parameters
* @param null|string $description
*
* @return Acc
*/
public function updateAcc(
Acc $acc,
string $name,
int $updatedBy,
array $parameters,
?string $description = null,
): Acc {
return new Acc(
id: $acc->getId(),
name: $name,
type: $acc->getType(),
createdBy: $acc->getCreatedBy(),
updatedBy: $updatedBy,
createdAt: $acc->getCreatedAt(),
updatedAt: new \DateTimeImmutable(),
description: $description,
parameters: match ($acc->getType()) {
Type::VMWARE_V6 => VmWareV6Parameters::update($this->encryption, $acc->getParameters(), $parameters),
}
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/AdditionalConnectorConfiguration/Domain/Model/Type.php | centreon/src/Core/AdditionalConnectorConfiguration/Domain/Model/Type.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AdditionalConnectorConfiguration\Domain\Model;
enum Type: string
{
/*
* TODO: when enum will contain more than one case:
* - remove corresponding ignoreErrors in phpstan.core.neon and phpstan.neon,
* - update skipped tests in UpdateAdditionalConnector/ValidatorTests
*/
case VMWARE_V6 = 'vmware_v6';
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/AdditionalConnectorConfiguration/Domain/Model/AccParametersInterface.php | centreon/src/Core/AdditionalConnectorConfiguration/Domain/Model/AccParametersInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AdditionalConnectorConfiguration\Domain\Model;
use Security\Interfaces\EncryptionInterface;
interface AccParametersInterface
{
/**
* @param EncryptionInterface $encryption
* @param AccParametersInterface $currentObj
* @param array<string,mixed> $newDatas
*
* @return AccParametersInterface
*/
public static function update(
EncryptionInterface $encryption,
self $currentObj,
array $newDatas,
): self;
/**
* @return array<string,mixed>
*/
public function getEncryptedData(): array;
/**
* @return array<string,mixed>
*/
public function getDecryptedData(): array;
/**
* @return array<string,mixed>
*/
public function getData(): array;
/**
* @return array<string,mixed>
*/
public function getDataWithoutCredentials(): 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/AdditionalConnectorConfiguration/Domain/Model/Poller.php | centreon/src/Core/AdditionalConnectorConfiguration/Domain/Model/Poller.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AdditionalConnectorConfiguration\Domain\Model;
/**
* @immutable
*/
class Poller
{
public function __construct(
public readonly int $id,
public readonly string $name,
) {
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/AdditionalConnectorConfiguration/Domain/Model/Acc.php | centreon/src/Core/AdditionalConnectorConfiguration/Domain/Model/Acc.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AdditionalConnectorConfiguration\Domain\Model;
use Assert\AssertionFailedException;
use Core\AdditionalConnectorConfiguration\Domain\Validation\AccValidationTrait;
/**
* @immutable
*/
class Acc
{
use AccValidationTrait;
public const MAX_NAME_LENGTH = 255;
public const MAX_DESCRIPTION_LENGTH = 65535;
public const ENCRYPTION_KEY = 'additional_connector_configuration';
private string $name = '';
/**
* @param int $id
* @param string $name
* @param Type $type
* @param ?int $createdBy
* @param ?int $updatedBy
* @param \DateTimeImmutable $createdAt
* @param \DateTimeImmutable $updatedAt
* @param AccParametersInterface $parameters
* @param ?string $description
*
* @throws AssertionFailedException
*/
public function __construct(
private readonly int $id,
string $name,
private readonly Type $type,
private readonly ?int $createdBy,
private readonly ?int $updatedBy,
private readonly \DateTimeImmutable $createdAt,
private readonly \DateTimeImmutable $updatedAt,
private readonly AccParametersInterface $parameters,
private ?string $description = null,
) {
$this->name = trim($name);
$this->ensureValidName($this->name);
$this->ensureNullablePositiveInt($this->createdBy, 'createdBy');
$this->ensureNullablePositiveInt($this->updatedBy, 'updatedBy');
$this->setDescription($description);
}
public function getId(): int
{
return $this->id;
}
public function getCreatedBy(): ?int
{
return $this->createdBy;
}
public function getUpdatedBy(): ?int
{
return $this->updatedBy;
}
public function getCreatedAt(): \DateTimeImmutable
{
return $this->createdAt;
}
public function getUpdatedAt(): \DateTimeImmutable
{
return $this->updatedAt;
}
public function getName(): string
{
return $this->name;
}
public function getDescription(): ?string
{
return $this->description;
}
public function getType(): Type
{
return $this->type;
}
/**
* @return AccParametersInterface
*/
public function getParameters(): AccParametersInterface
{
return $this->parameters;
}
/**
* @param string|null $description
*
* @throws AssertionFailedException
*
* @return $this
*/
private function setDescription(?string $description): self
{
if (! is_string($description)) {
$this->description = $description;
} else {
$this->description = trim($description);
$this->ensureValidDescription($this->description);
}
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/AdditionalConnectorConfiguration/Domain/Model/NewAcc.php | centreon/src/Core/AdditionalConnectorConfiguration/Domain/Model/NewAcc.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AdditionalConnectorConfiguration\Domain\Model;
use Assert\AssertionFailedException;
use Core\AdditionalConnectorConfiguration\Domain\Validation\AccValidationTrait;
/**
* @immutable
*/
class NewAcc
{
use AccValidationTrait;
public const MAX_NAME_LENGTH = 255;
public const MAX_DESCRIPTION_LENGTH = 65535;
private string $name;
private int $updatedBy;
private \DateTimeImmutable $createdAt;
private \DateTimeImmutable $updatedAt;
/**
* @param string $name
* @param Type $type
* @param int $createdBy
* @param AccParametersInterface $parameters
* @param ?string $description
*
* @throws AssertionFailedException
*/
public function __construct(
string $name,
private readonly Type $type,
private int $createdBy,
private AccParametersInterface $parameters,
private ?string $description = null,
) {
$this->setName($name);
$this->setCreatedBy($createdBy);
$this->updatedBy = $this->createdBy;
$this->createdAt = new \DateTimeImmutable();
$this->updatedAt = $this->createdAt;
$this->setDescription($description);
}
public function getCreatedBy(): int
{
return $this->createdBy;
}
public function getUpdatedBy(): int
{
return $this->updatedBy;
}
public function getCreatedAt(): \DateTimeImmutable
{
return $this->createdAt;
}
public function getUpdatedAt(): \DateTimeImmutable
{
return $this->updatedAt;
}
public function getName(): string
{
return $this->name;
}
public function getDescription(): ?string
{
return $this->description;
}
public function getType(): Type
{
return $this->type;
}
/**
* @return AccParametersInterface
*/
public function getParameters(): AccParametersInterface
{
return $this->parameters;
}
/**
* @param string $name
*
* @throws AssertionFailedException
*/
public function setName(string $name): void
{
$this->name = trim($name);
$this->ensureValidName($this->name);
}
/**
* @param string|null $description
*
* @throws AssertionFailedException
*/
public function setDescription(?string $description): void
{
if (! is_string($description)) {
$this->description = $description;
return;
}
$this->description = trim($description);
$this->ensureValidDescription($this->description);
}
/**
* @param int $userId
*
* @throws AssertionFailedException
*/
private function setCreatedBy(int $userId): void
{
$this->ensurePositiveInt($this->createdBy, 'createdBy');
$this->createdBy = $userId;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/AdditionalConnectorConfiguration/Domain/Model/VmWareV6/VSphereServer.php | centreon/src/Core/AdditionalConnectorConfiguration/Domain/Model/VmWareV6/VSphereServer.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AdditionalConnectorConfiguration\Domain\Model\VmWareV6;
class VSphereServer
{
public function __construct(
private readonly string $name,
private readonly string $url,
private readonly string $username,
private readonly string $password,
) {
}
public function getName(): string
{
return $this->name;
}
public function getUrl(): string
{
return $this->url;
}
public function getUsername(): string
{
return $this->username;
}
public function getPassword(): string
{
return $this->password;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/AdditionalConnectorConfiguration/Domain/Model/VmWareV6/VmWareConfig.php | centreon/src/Core/AdditionalConnectorConfiguration/Domain/Model/VmWareV6/VmWareConfig.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AdditionalConnectorConfiguration\Domain\Model\VmWareV6;
use Assert\AssertionFailedException;
use Centreon\Domain\Common\Assertion\Assertion;
class VmWareConfig
{
/**
* @param VSphereServer[] $vSphereServers
* @param int $port
*
* @throws AssertionFailedException
*/
public function __construct(private readonly array $vSphereServers, private readonly int $port)
{
foreach ($vSphereServers as $vSphereServer) {
Assertion::isInstanceOf(
$vSphereServer,
VSphereServer::class,
(new \ReflectionClass($this))->getShortName() . '::vSphereServers'
);
}
}
/**
* @return VSphereServer[]
*/
public function getVSphereServers(): array
{
return $this->vSphereServers;
}
public function getPort(): int
{
return $this->port;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/AdditionalConnectorConfiguration/Domain/Model/VmWareV6/VmWareV6Parameters.php | centreon/src/Core/AdditionalConnectorConfiguration/Domain/Model/VmWareV6/VmWareV6Parameters.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AdditionalConnectorConfiguration\Domain\Model\VmWareV6;
use Centreon\Domain\Common\Assertion\Assertion;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\AdditionalConnectorConfiguration\Domain\Model\AccParametersInterface;
use Core\Security\Vault\Domain\Model\VaultConfiguration;
use Security\Interfaces\EncryptionInterface;
/**
* @phpstan-type _VmWareV6Parameters array{
* port:int,
* vcenters:array<array{name:string,url:string,username:string,password:string}>
* }
* @phpstan-type _VmWareV6ParametersRequest array{
* port:int,
* vcenters:array<array{name:string,url:string,scheme:string|null,username:string,password:string}>
* }
* @phpstan-type _VmWareV6ParametersWithoutCredentials array{
* port:int,
* vcenters:array<array{name:string,url:string,username:null,password:null}>
* }
*/
class VmWareV6Parameters implements AccParametersInterface
{
public const MAX_LENGTH = 255;
private const SECOND_KEY = 'additional_connector_configuration_vmware_v6';
/** @var _VmWareV6Parameters */
private array $parameters;
/**
* @param EncryptionInterface $encryption
* @param array<string,mixed> $parameters
* @param bool $isEncrypted
*
* @throws AssertionException
*/
public function __construct(
private readonly EncryptionInterface $encryption,
array $parameters,
private readonly bool $isEncrypted = false,
) {
/** @var _VmWareV6ParametersRequest $parameters */
Assertion::range($parameters['port'], 0, 65535, 'parameters.port');
foreach ($parameters['vcenters'] as $index => $vcenter) {
// Validate min length
Assertion::notEmptyString($vcenter['name'], "parameters.vcenters[{$index}].name");
Assertion::notEmptyString($vcenter['username'], "parameters.vcenters[{$index}].username");
Assertion::notEmptyString($vcenter['password'], "parameters.vcenters[{$index}].password");
Assertion::notEmptyString($vcenter['url'], "parameters.vcenters[{$index}].url");
// Validate max length
Assertion::maxLength($vcenter['name'], self::MAX_LENGTH, "parameters.vcenters[{$index}].name");
Assertion::maxLength($vcenter['username'], self::MAX_LENGTH, "parameters.vcenters[{$index}].username");
Assertion::maxLength($vcenter['password'], self::MAX_LENGTH, "parameters.vcenters[{$index}].password");
Assertion::maxLength($vcenter['url'], self::MAX_LENGTH, "parameters.vcenters[{$index}].url");
// This is a temporary fix to handle the case where the scheme should be not be a part of the URL.
// The scheme is removed after being reunified with the url to ensure this is not stored.
$parameters['vcenters'][$index]['url'] = isset($vcenter['scheme'])
? $vcenter['scheme'] . '://' . $vcenter['url']
: $vcenter['url'];
unset($parameters['vcenters'][$index]['scheme']);
// Validate specific format
Assertion::urlOrIpOrDomain($parameters['vcenters'][$index]['url'], "parameters.vcenters[{$index}].url");
}
$this->parameters = $parameters;
$this->encryption->setSecondKey(self::SECOND_KEY);
}
/**
* @inheritDoc
*
* @return VmWareV6Parameters
*/
public static function update(
EncryptionInterface $encryption,
AccParametersInterface $currentObj,
array $newDatas,
): self {
/** @var _VmWareV6Parameters|_VmWareV6ParametersWithoutCredentials $newDatas */
/** @var _VmWareV6Parameters $parameters */
$parameters = $currentObj->getDecryptedData();
$requestedVcenters = [];
foreach ($newDatas['vcenters'] as $index => $vcenter) {
$requestedVcenters[$vcenter['name']] = $vcenter;
}
$parameters['port'] = $newDatas['port'];
foreach ($parameters['vcenters'] as $index => $vcenter) {
// Remove vcenter
if (! array_key_exists($vcenter['name'], $requestedVcenters)) {
unset($parameters['vcenters'][$index]);
continue;
}
// Update vcenter
$updatedVcenter = $requestedVcenters[$vcenter['name']];
$updatedVcenter['username'] ??= $vcenter['username'];
$updatedVcenter['password'] ??= $vcenter['password'];
$parameters['vcenters'][$index] = $updatedVcenter;
unset($requestedVcenters[$vcenter['name']]);
}
// Add new vcenter
if ($requestedVcenters !== []) {
foreach ($requestedVcenters as $newVcenter) {
$parameters['vcenters'][] = $newVcenter;
}
}
$parameters['vcenters'] = array_values($parameters['vcenters']);
return new self($encryption, $parameters);
}
/**
* @inheritDoc
*
* @return _VmWareV6Parameters
*/
public function getData(): array
{
return $this->parameters;
}
public function isEncrypted(): bool
{
return $this->isEncrypted;
}
/**
* @inheritDoc
*
* @return _VmWareV6Parameters
*/
public function getEncryptedData(): array
{
if ($this->isEncrypted === true) {
return $this->parameters;
}
$parameters = $this->parameters;
foreach ($parameters['vcenters'] as $index => $vcenter) {
$parameters['vcenters'][$index]['username'] = str_starts_with(
$vcenter['username'],
VaultConfiguration::VAULT_PATH_PATTERN
) ? $vcenter['username'] : $this->encryption->crypt($vcenter['username']);
$parameters['vcenters'][$index]['password'] = str_starts_with(
$vcenter['password'],
VaultConfiguration::VAULT_PATH_PATTERN
) ? $vcenter['password'] : $this->encryption->crypt($vcenter['password']);
}
return $parameters;
}
/**
* @inheritDoc
*
* @return _VmWareV6Parameters
*/
public function getDecryptedData(): array
{
if ($this->isEncrypted === false) {
return $this->parameters;
}
$parameters = $this->parameters;
foreach ($parameters['vcenters'] as $index => $vcenter) {
$parameters['vcenters'][$index]['username'] = str_starts_with(
$vcenter['username'],
VaultConfiguration::VAULT_PATH_PATTERN
) ? $vcenter['username'] : $this->encryption->decrypt($vcenter['username']) ?? '';
$parameters['vcenters'][$index]['password'] = str_starts_with(
$vcenter['password'],
VaultConfiguration::VAULT_PATH_PATTERN
) ? $vcenter['password'] : $this->encryption->decrypt($vcenter['password']) ?? '';
}
return $parameters;
}
/**
* @inheritDoc
*
* @return _VmWareV6ParametersWithoutCredentials
*/
public function getDataWithoutCredentials(): array
{
$parameters = $this->parameters;
foreach ($parameters['vcenters'] as $index => $vcenter) {
$parameters['vcenters'][$index]['username'] = null;
$parameters['vcenters'][$index]['password'] = null;
}
/** @var _VmWareV6ParametersWithoutCredentials $parameters */
return $parameters;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/AdditionalConnectorConfiguration/Domain/Validation/AccValidationTrait.php | centreon/src/Core/AdditionalConnectorConfiguration/Domain/Validation/AccValidationTrait.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AdditionalConnectorConfiguration\Domain\Validation;
use Assert\AssertionFailedException;
use Centreon\Domain\Common\Assertion\Assertion;
use Core\AdditionalConnectorConfiguration\Domain\Model\Acc;
/**
* This trait exists only here for DRY reasons.
*
* It gathers all the guard methods of common fields from {@see Acc} and {@see NewAcc} entities.
*/
trait AccValidationTrait
{
/**
* @param string $name
*
* @throws AssertionFailedException
*/
private function ensureValidName(string $name): void
{
$shortName = (new \ReflectionClass($this))->getShortName();
Assertion::maxLength($name, Acc::MAX_NAME_LENGTH, $shortName . '::name');
Assertion::notEmptyString($name, $shortName . '::name');
}
/**
* @param string $description
*
* @throws AssertionFailedException
*/
private function ensureValidDescription(string $description): void
{
$shortName = (new \ReflectionClass($this))->getShortName();
Assertion::maxLength($description, Acc::MAX_DESCRIPTION_LENGTH, $shortName . '::description');
}
/**
* @param int $value
* @param string $propertyName
*
* @throws AssertionFailedException
*/
private function ensurePositiveInt(int $value, string $propertyName): void
{
$shortName = (new \ReflectionClass($this))->getShortName();
Assertion::positiveInt($value, $shortName . '::' . $propertyName);
}
/**
* @param ?int $value
* @param string $propertyName
*
* @throws AssertionFailedException
*/
private function ensureNullablePositiveInt(?int $value, string $propertyName): void
{
if ($value !== null) {
$this->ensurePositiveInt($value, $propertyName);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/AdditionalConnectorConfiguration/Infrastructure/Repository/DbWriteAccRepository.php | centreon/src/Core/AdditionalConnectorConfiguration/Infrastructure/Repository/DbWriteAccRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AdditionalConnectorConfiguration\Infrastructure\Repository;
use Centreon\Infrastructure\DatabaseConnection;
use Core\AdditionalConnectorConfiguration\Application\Repository\WriteAccRepositoryInterface;
use Core\AdditionalConnectorConfiguration\Domain\Model\Acc;
use Core\AdditionalConnectorConfiguration\Domain\Model\NewAcc;
use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB;
use Core\Common\Infrastructure\Repository\RepositoryTrait;
class DbWriteAccRepository extends AbstractRepositoryRDB implements WriteAccRepositoryInterface
{
use RepositoryTrait;
/**
* @param DatabaseConnection $db
*/
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* @inheritDoc
*/
public function add(NewAcc $acc): int
{
$statement = $this->db->prepare($this->translateDbName(
<<<'SQL'
INSERT INTO `:db`.`additional_connector_configuration`
(type, name, description, parameters, created_by, created_at, updated_by, updated_at)
VALUES (:type, :name, :description, :parameters, :createdBy, :createdAt, :createdBy, :createdAt)
SQL
));
$statement->bindValue(':type', $acc->getType()->value, \PDO::PARAM_STR);
$statement->bindValue(':name', $acc->getName(), \PDO::PARAM_STR);
$statement->bindValue(':description', $acc->getDescription(), \PDO::PARAM_STR);
$statement->bindValue(':parameters', json_encode($acc->getParameters()->getEncryptedData()));
$statement->bindValue(':createdBy', $acc->getCreatedBy(), \PDO::PARAM_INT);
$statement->bindValue(':createdAt', $acc->getCreatedAt()->getTimestamp(), \PDO::PARAM_INT);
$statement->execute();
return (int) $this->db->lastInsertId();
}
/**
* @inheritDoc
*/
public function update(Acc $acc): void
{
$statement = $this->db->prepare($this->translateDbName(
<<<'SQL'
UPDATE `:db`.`additional_connector_configuration`
SET
`name` = :name,
`description` = :description,
`parameters` = :parameters,
`updated_by` = :updatedBy,
`updated_at` = :updatedAt
WHERE
`id` = :id
SQL
));
$statement->bindValue(':id', $acc->getId(), \PDO::PARAM_INT);
$statement->bindValue(':name', $acc->getName(), \PDO::PARAM_STR);
$statement->bindValue(':description', $acc->getDescription(), \PDO::PARAM_STR);
$statement->bindValue(':parameters', json_encode($acc->getParameters()->getEncryptedData()));
$statement->bindValue(':updatedBy', $acc->getUpdatedBy(), \PDO::PARAM_INT);
$statement->bindValue(':updatedAt', $acc->getUpdatedAt()->getTimestamp(), \PDO::PARAM_INT);
$statement->execute();
}
/**
* @inheritDoc
*/
public function delete(int $id): void
{
$statement = $this->db->prepare($this->translateDbName(
<<<'SQL'
DELETE FROM `:db`.`additional_connector_configuration`
WHERE
`id` = :id
SQL
));
$statement->bindValue(':id', $id, \PDO::PARAM_INT);
$statement->execute();
}
/**
* @inheritDoc
*/
public function linkToPollers(int $accId, array $pollers): void
{
$statement = $this->db->prepare($this->translateDbName(
<<<'SQL'
INSERT INTO `:db`.`acc_poller_relation`
(acc_id, poller_id)
VALUES (:acc_id, :poller_id)
SQL
));
$statement->bindValue(':acc_id', $accId, \PDO::PARAM_INT);
foreach ($pollers as $pollerId) {
$statement->bindValue(':poller_id', $pollerId, \PDO::PARAM_INT);
$statement->execute();
}
}
/**
* @inheritDoc
*/
public function removePollers(int $accId): void
{
$statement = $this->db->prepare($this->translateDbName(
<<<'SQL'
DELETE FROM `:db`.`acc_poller_relation`
WHERE acc_id = :acc_id
SQL
));
$statement->bindValue(':acc_id', $accId, \PDO::PARAM_INT);
$statement->execute();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/AdditionalConnectorConfiguration/Infrastructure/Repository/DbReadAccRepository.php | centreon/src/Core/AdditionalConnectorConfiguration/Infrastructure/Repository/DbReadAccRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AdditionalConnectorConfiguration\Infrastructure\Repository;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Centreon\Infrastructure\DatabaseConnection;
use Centreon\Infrastructure\RequestParameters\SqlRequestParametersTranslator;
use Core\AdditionalConnectorConfiguration\Application\Repository\ReadAccRepositoryInterface;
use Core\AdditionalConnectorConfiguration\Domain\Model\Acc;
use Core\AdditionalConnectorConfiguration\Domain\Model\Poller;
use Core\AdditionalConnectorConfiguration\Domain\Model\Type;
use Core\AdditionalConnectorConfiguration\Domain\Model\VmWareV6\VmWareV6Parameters;
use Core\Common\Domain\TrimmedString;
use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB;
use Core\Common\Infrastructure\Repository\RepositoryTrait;
use Core\MonitoringServer\Infrastructure\Repository\MonitoringServerRepositoryTrait;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
use Security\Interfaces\EncryptionInterface;
/**
* @phpstan-type _Acc array{
* id:int,
* type:string,
* name:string,
* description:null|string,
* parameters:string,
* created_at:int,
* updated_at:int,
* created_by:null|int,
* updated_by:null|int
* }
*/
class DbReadAccRepository extends AbstractRepositoryRDB implements ReadAccRepositoryInterface
{
use RepositoryTrait;
use MonitoringServerRepositoryTrait;
public function __construct(
private readonly EncryptionInterface $encryption,
DatabaseConnection $db,
) {
$this->db = $db;
}
/**
* @inheritDoc
*/
public function existsByName(TrimmedString $name): bool
{
$request = $this->translateDbName(
<<<'SQL'
SELECT 1
FROM `:db`.`additional_connector_configuration`
WHERE name = :name
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':name', $name->value, \PDO::PARAM_STR);
$statement->execute();
return (bool) $statement->fetchColumn();
}
/**
* @inheritDoc
*/
public function find(int $accId): ?Acc
{
$sql = <<<'SQL'
SELECT *
FROM `:db`.`additional_connector_configuration` acc
WHERE acc.`id` = :id
SQL;
// Prepare SQL + bind values
$statement = $this->db->prepare($this->translateDbName($sql));
$statement->bindValue(':id', $accId, \PDO::PARAM_INT);
$statement->execute();
if ($result = $statement->fetch()) {
/** @var _Acc $result */
return $this->createFromArray($result);
}
return null;
}
/**
* @inheritDoc
*/
public function findAll(): array
{
$sql = <<<'SQL'
SELECT *
FROM `:db`.`additional_connector_configuration` acc
SQL;
// Prepare SQL + bind values
$statement = $this->db->prepare($this->translateDbName($sql));
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$statement->execute();
$additionalConnectors = [];
foreach ($statement as $result) {
/** @var _Acc $result */
$additionalConnectors[] = $this->createFromArray($result);
}
return $additionalConnectors;
}
/**
* @inheritDoc
*/
public function findPollersByType(Type $type): array
{
$sql = <<<'SQL'
SELECT
rel.`poller_id` as id,
ng.`name`
FROM `:db`.`acc_poller_relation` rel
JOIN `:db`.`additional_connector_configuration` acc
ON rel.acc_id = acc.id
JOIN `:db`.`nagios_server` ng
ON rel.poller_id = ng.id
WHERE acc.`type` = :type
SQL;
// Prepare SQL + bind values
$statement = $this->db->prepare($this->translateDbName($sql));
$statement->bindValue(':type', $type->value, \PDO::PARAM_STR);
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$statement->execute();
// Retrieve data
$pollers = [];
foreach ($statement as $result) {
/** @var array{id:int,name:string} $result */
$pollers[] = new Poller($result['id'], $result['name']);
}
return $pollers;
}
/**
* @inheritDoc
*/
public function findPollersByAccId(int $accId): array
{
$statement = $this->db->prepare($this->translateDbName(
<<<'SQL'
SELECT
rel.`poller_id` as id,
ng.`name`
FROM `:db`.`acc_poller_relation` rel
JOIN `:db`.`nagios_server` ng
ON rel.poller_id = ng.id
WHERE rel.`acc_id` = :id
SQL
));
$statement->bindValue(':id', $accId, \PDO::PARAM_INT);
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$statement->execute();
// Retrieve data
$pollers = [];
foreach ($statement as $result) {
/** @var array{id:int,name:string} $result */
$pollers[] = new Poller($result['id'], $result['name']);
}
return $pollers;
}
/**
* @inheritDoc
*/
public function findByRequestParameters(RequestParametersInterface $requestParameters): array
{
$sqlTranslator = new SqlRequestParametersTranslator($requestParameters);
$sqlTranslator->setConcordanceArray([
'name' => 'acc.name',
'type' => 'acc.type',
'poller.id' => 'rel.poller_id',
'poller.name' => 'ns.name',
]);
$request = <<<'SQL_WRAP'
SELECT SQL_CALC_FOUND_ROWS
acc.*
FROM `:db`.`additional_connector_configuration` acc
LEFT JOIN `:db`.`acc_poller_relation` rel
ON acc.id = rel.acc_id
INNER JOIN `:db`.`nagios_server` ns
ON rel.poller_id = ns.id
SQL_WRAP;
// Search
$request .= $sqlTranslator->translateSearchParameterToSql();
$request .= ' GROUP BY acc.name';
// Sort
$sortRequest = $sqlTranslator->translateSortParameterToSql();
$request .= ! is_null($sortRequest)
? $sortRequest
: ' ORDER BY acc.id ASC';
// Pagination
$request .= $sqlTranslator->translatePaginationToSql();
$statement = $this->db->prepare($this->translateDbName($request));
foreach ($sqlTranslator->getSearchValues() as $key => $data) {
$type = key($data);
if ($type !== null) {
$value = $data[$type];
$statement->bindValue($key, $value, $type);
}
}
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$statement->execute();
// Set total
$result = $this->db->query('SELECT FOUND_ROWS()');
if ($result !== false && ($total = $result->fetchColumn()) !== false) {
$sqlTranslator->getRequestParameters()->setTotal((int) $total);
}
$additionalConnectors = [];
foreach ($statement as $result) {
/** @var _Acc $result */
$additionalConnectors[] = $this->createFromArray($result);
}
return $additionalConnectors;
}
/**
* @inheritDoc
*/
public function findByRequestParametersAndAccessGroups(
RequestParametersInterface $requestParameters,
array $accessGroups,
): array {
if ($accessGroups === []) {
return [];
}
$accessGroupIds = array_map(
static fn (AccessGroup $accessGroup): int => $accessGroup->getId(),
$accessGroups
);
if (! $this->hasRestrictedAccessToMonitoringServers($accessGroupIds)) {
return $this->findByRequestParameters($requestParameters);
}
$sqlTranslator = new SqlRequestParametersTranslator($requestParameters);
$sqlTranslator->setConcordanceArray([
'name' => 'acc.name',
'type' => 'acc.type',
'poller.id' => 'rel.poller_id',
'poller.name' => 'ns.name',
]);
[$accessGroupsBindValues, $accessGroupIdsQuery] = $this->createMultipleBindQuery(
array_map(fn (AccessGroup $accessGroup) => $accessGroup->getId(), $accessGroups),
':acl_'
);
$request = <<<SQL
SELECT SQL_CALC_FOUND_ROWS
acc.*
FROM `:db`.`additional_connector_configuration` acc
INNER JOIN `:db`.`acc_poller_relation` rel
ON acc.id = rel.acc_id
INNER JOIN `:db`.`nagios_server` ns
ON rel.poller_id = ns.id
INNER JOIN `:db`.acl_resources_poller_relations arpr
ON ns.id = arpr.poller_id
INNER JOIN `:db`.acl_res_group_relations argr
ON argr.acl_res_id = arpr.acl_res_id
AND argr.acl_group_id IN ({$accessGroupIdsQuery})
SQL;
// Search
$request .= $search = $sqlTranslator->translateSearchParameterToSql();
$request .= $search !== null
? ' AND '
: ' WHERE ';
$request .= ' acc.id NOT IN (
SELECT rel.acc_id
FROM `acc_poller_relation` rel
LEFT JOIN acl_resources_poller_relations arpr ON rel.poller_id = arpr.poller_id
LEFT JOIN acl_res_group_relations argr ON argr.acl_res_id = arpr.acl_res_id
WHERE argr.acl_group_id IS NULL
)';
$request .= ' GROUP BY acc.name';
// Sort
$sortRequest = $sqlTranslator->translateSortParameterToSql();
$request .= ! is_null($sortRequest)
? $sortRequest
: ' ORDER BY acc.id ASC';
// Pagination
$request .= $sqlTranslator->translatePaginationToSql();
$statement = $this->db->prepare($this->translateDbName($request));
foreach ($sqlTranslator->getSearchValues() as $key => $data) {
$type = key($data);
if ($type !== null) {
$value = $data[$type];
$statement->bindValue($key, $value, $type);
}
}
foreach ($accessGroupsBindValues as $bindKey => $hostGroupId) {
$statement->bindValue($bindKey, $hostGroupId, \PDO::PARAM_INT);
}
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$statement->execute();
// Set total
$result = $this->db->query('SELECT FOUND_ROWS()');
if ($result !== false && ($total = $result->fetchColumn()) !== false) {
$sqlTranslator->getRequestParameters()->setTotal((int) $total);
}
$additionalConnectors = [];
foreach ($statement as $result) {
/** @var _Acc $result */
$additionalConnectors[] = $this->createFromArray($result);
}
return $additionalConnectors;
}
/**
* @inheritDoc
*/
public function findByPollerAndType(int $pollerId, string $type): ?Acc
{
$statement = $this->db->prepare($this->translateDbName(
<<<'SQL'
SELECT
acc.*
FROM `:db`.`additional_connector_configuration` acc
JOIN `:db`.`acc_poller_relation` rel
ON acc.id = rel.acc_id
WHERE rel.poller_id = :poller_id
AND acc.type = :type
LIMIT 1
SQL
));
$statement->bindValue(':poller_id', $pollerId, \PDO::PARAM_INT);
$statement->bindValue(':type', $type, \PDO::PARAM_STR);
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$statement->execute();
foreach ($statement as $result) {
/** @var _Acc $result */
return $this->createFromArray($result);
}
return null;
}
/**
* @param _Acc $row
*
* @return Acc
*/
private function createFromArray(array $row): Acc
{
/** @var array<string,mixed> $parameters */
$parameters = json_decode(json: $row['parameters'], associative: true, flags: JSON_OBJECT_AS_ARRAY);
$type = Type::from($row['type']);
return new Acc(
id: $row['id'],
name: $row['name'],
type: $type,
createdBy: $row['created_by'],
updatedBy: $row['updated_by'],
createdAt: $this->timestampToDateTimeImmutable($row['created_at']),
updatedAt: $this->timestampToDateTimeImmutable($row['updated_at']),
description: $this->emptyStringAsNull($row['description'] ?? ''),
parameters: match ($type->value) {
Type::VMWARE_V6->value => (new VmWareV6Parameters($this->encryption, $parameters, 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/AdditionalConnectorConfiguration/Infrastructure/Repository/Vault/VmWareV6WriteVaultAccRepository.php | centreon/src/Core/AdditionalConnectorConfiguration/Infrastructure/Repository/Vault/VmWareV6WriteVaultAccRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AdditionalConnectorConfiguration\Infrastructure\Repository\Vault;
use Core\AdditionalConnectorConfiguration\Application\Repository\WriteVaultAccRepositoryInterface;
use Core\AdditionalConnectorConfiguration\Domain\Model\Acc;
use Core\AdditionalConnectorConfiguration\Domain\Model\AccParametersInterface;
use Core\AdditionalConnectorConfiguration\Domain\Model\Type;
use Core\AdditionalConnectorConfiguration\Domain\Model\VmWareV6\VmWareV6Parameters;
use Core\Common\Application\Repository\WriteVaultRepositoryInterface;
use Core\Common\Application\UseCase\VaultTrait;
use Core\Common\Infrastructure\Repository\AbstractVaultRepository;
use Core\Security\Vault\Domain\Model\VaultConfiguration;
use Security\Interfaces\EncryptionInterface;
/**
* @phpstan-import-type _VmWareV6Parameters from VmWareV6Parameters
*/
class VmWareV6WriteVaultAccRepository implements WriteVaultAccRepositoryInterface
{
use VaultTrait;
public function __construct(
private readonly EncryptionInterface $encryption,
private readonly WriteVaultRepositoryInterface $writeVaultRepository,
) {
$this->writeVaultRepository->setCustomPath(AbstractVaultRepository::ACC_VAULT_PATH);
}
/**
* @inheritDoc
*/
public function isValidFor(Type $type): bool
{
return $type === Type::VMWARE_V6;
}
/**
* @inheritDoc
*/
public function saveCredentialInVault(AccParametersInterface $parameters): AccParametersInterface
{
if ($this->writeVaultRepository->isVaultConfigured() === false) {
return $parameters;
}
/** @var _VmWareV6Parameters $data */
$data = $parameters->getData();
$inserts = [];
foreach ($data['vcenters'] as $vcenter) {
$inserts[$vcenter['name'] . '_username'] = $vcenter['username'];
$inserts[$vcenter['name'] . '_password'] = $vcenter['password'];
}
$vaultPaths = $this->writeVaultRepository->upsert(null, $inserts);
foreach ($data['vcenters'] as $index => $vcenter) {
if (in_array($vcenter['name'] . '_username', array_keys($vaultPaths), true)) {
$data['vcenters'][$index]['username'] = $vaultPaths[$vcenter['name'] . '_username'];
$data['vcenters'][$index]['password'] = $vaultPaths[$vcenter['name'] . '_password'];
}
}
return new VmWareV6Parameters($this->encryption, $data);
}
/**
* @inheritDoc
*/
public function deleteFromVault(Acc $acc): void
{
if ($this->writeVaultRepository->isVaultConfigured() === false) {
return;
}
/** @var _VmWareV6Parameters $parameters */
$parameters = $acc->getParameters()->getData();
$vaultPath = null;
foreach ($parameters['vcenters'] as $vcenter) {
if (str_starts_with($vcenter['password'], VaultConfiguration::VAULT_PATH_PATTERN) === true) {
$vaultPath = $vcenter['password'];
break;
}
}
if ($vaultPath !== null && null !== $uuid = $this->getUuidFromPath($vaultPath)) {
$this->writeVaultRepository->delete($uuid);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/AdditionalConnectorConfiguration/Infrastructure/Repository/Vault/VmWareV6ReadVaultAccRepository.php | centreon/src/Core/AdditionalConnectorConfiguration/Infrastructure/Repository/Vault/VmWareV6ReadVaultAccRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AdditionalConnectorConfiguration\Infrastructure\Repository\Vault;
use Core\AdditionalConnectorConfiguration\Application\Repository\ReadVaultAccRepositoryInterface;
use Core\AdditionalConnectorConfiguration\Domain\Model\AccParametersInterface;
use Core\AdditionalConnectorConfiguration\Domain\Model\Type;
use Core\AdditionalConnectorConfiguration\Domain\Model\VmWareV6\VmWareV6Parameters;
use Core\Common\Application\Repository\ReadVaultRepositoryInterface;
use Core\Common\Application\UseCase\VaultTrait;
use Core\Common\Infrastructure\Repository\AbstractVaultRepository;
use Core\Security\Vault\Domain\Model\VaultConfiguration;
use Security\Interfaces\EncryptionInterface;
/**
* @phpstan-import-type _VmWareV6Parameters from VmWareV6Parameters
*/
class VmWareV6ReadVaultAccRepository implements ReadVaultAccRepositoryInterface
{
use VaultTrait;
public function __construct(
private readonly EncryptionInterface $encryption,
private readonly ReadVaultRepositoryInterface $readVaultRepository,
) {
$this->readVaultRepository->setCustomPath(AbstractVaultRepository::ACC_VAULT_PATH);
}
/**
* @inheritDoc
*/
public function isValidFor(Type $type): bool
{
return $type === Type::VMWARE_V6;
}
/**
* @inheritDoc
*/
public function getCredentialsFromVault(AccParametersInterface $parameters): AccParametersInterface
{
if ($this->readVaultRepository->isVaultConfigured() === false) {
return $parameters;
}
/** @var _VmWareV6Parameters $data */
$data = $parameters->getData();
$vaultPath = null;
foreach ($data['vcenters'] as $vcenter) {
if (str_starts_with($vcenter['username'], VaultConfiguration::VAULT_PATH_PATTERN)) {
$vaultPath = $vcenter['username'];
break;
}
if (str_starts_with($vcenter['password'], VaultConfiguration::VAULT_PATH_PATTERN)) {
$vaultPath = $vcenter['password'];
break;
}
}
if ($vaultPath === null) {
return $parameters;
}
$vaultDatas = $this->readVaultRepository->findFromPath($vaultPath);
foreach ($data['vcenters'] as $index => $vcenter) {
if (in_array($vcenter['name'] . '_username', array_keys($vaultDatas), true)) {
$data['vcenters'][$index]['username'] = $vaultDatas[$vcenter['name'] . '_username'];
$data['vcenters'][$index]['password'] = $vaultDatas[$vcenter['name'] . '_password'];
}
}
return new VmWareV6Parameters($this->encryption, $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/AdditionalConnectorConfiguration/Infrastructure/API/DeleteAcc/DeleteAccController.php | centreon/src/Core/AdditionalConnectorConfiguration/Infrastructure/API/DeleteAcc/DeleteAccController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AdditionalConnectorConfiguration\Infrastructure\API\DeleteAcc;
use Centreon\Application\Controller\AbstractController;
use Centreon\Domain\Log\LoggerTrait;
use Core\AdditionalConnectorConfiguration\Application\UseCase\DeleteAcc\DeleteAcc;
use Core\Infrastructure\Common\Api\DefaultPresenter;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
final class DeleteAccController extends AbstractController
{
use LoggerTrait;
/**
* @param int $id
* @param DeleteAcc $useCase
* @param DefaultPresenter $presenter
*
* @throws AccessDeniedException
*
* @return Response
*/
public function __invoke(
int $id,
DeleteAcc $useCase,
DefaultPresenter $presenter,
): Response {
$this->denyAccessUnlessGrantedForApiConfiguration();
$useCase($id, $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/AdditionalConnectorConfiguration/Infrastructure/API/AddAcc/AddAccPresenter.php | centreon/src/Core/AdditionalConnectorConfiguration/Infrastructure/API/AddAcc/AddAccPresenter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AdditionalConnectorConfiguration\Infrastructure\API\AddAcc;
use Core\AdditionalConnectorConfiguration\Application\UseCase\AddAcc\AddAccPresenterInterface;
use Core\AdditionalConnectorConfiguration\Application\UseCase\AddAcc\AddAccResponse;
use Core\AdditionalConnectorConfiguration\Domain\Model\Poller;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\CreatedResponse;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Infrastructure\Common\Presenter\PresenterTrait;
class AddAccPresenter extends AbstractPresenter implements AddAccPresenterInterface
{
use PresenterTrait;
/**
* @inheritDoc
*/
public function presentResponse(AddAccResponse|ResponseStatusInterface $response): void
{
if ($response instanceof ResponseStatusInterface) {
$this->setResponseStatus($response);
} else {
$this->present(
new CreatedResponse(
$response->id,
[
'id' => $response->id,
'name' => $response->name,
'type' => $response->type->value,
'description' => $response->description,
'parameters' => $response->parameters,
'pollers' => array_map(fn (Poller $poller) => ['id' => $poller->id, 'name' => $poller->name], $response->pollers),
'created_by' => $response->createdBy,
'created_at' => $this->formatDateToIso8601($response->createdAt),
]
)
);
// NOT setting location as required route does not currently exist
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/AdditionalConnectorConfiguration/Infrastructure/API/AddAcc/AddAccController.php | centreon/src/Core/AdditionalConnectorConfiguration/Infrastructure/API/AddAcc/AddAccController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AdditionalConnectorConfiguration\Infrastructure\API\AddAcc;
use Centreon\Application\Controller\AbstractController;
use Centreon\Domain\Log\LoggerTrait;
use Core\AdditionalConnectorConfiguration\Application\UseCase\AddAcc\AddAcc;
use Core\AdditionalConnectorConfiguration\Application\UseCase\AddAcc\AddAccRequest;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use InvalidArgumentException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
final class AddAccController extends AbstractController
{
use LoggerTrait;
/**
* @param Request $request
* @param AddAcc $useCase
* @param AddAccPresenter $presenter
*
* @throws AccessDeniedException
*
* @return Response
*/
public function __invoke(
Request $request,
AddAcc $useCase,
AddAccPresenter $presenter,
): Response {
$this->denyAccessUnlessGrantedForApiConfiguration();
try {
$addAccRequest = $this->createRequest($request);
$useCase($addAccRequest, $presenter);
} catch (InvalidArgumentException $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
$presenter->setResponseStatus(new InvalidArgumentResponse($ex));
} catch (\Throwable $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
$presenter->setResponseStatus(new ErrorResponse($ex));
}
return $presenter->show();
}
/**
* @param Request $request
*
* @throws InvalidArgumentException
*
* @return AddAccRequest
*/
private function createRequest(Request $request): AddAccRequest
{
/** @var array{
* name:string,
* type:string,
* description:?string,
* pollers:int[],
* parameters:array<string,mixed>
* } $data
*/
$data = $this->validateAndRetrieveDataSent($request, __DIR__ . '/AddAccSchema.json');
$schemaFile = match ($data['type']) {
'vmware_v6' => 'VmWareV6Schema.json',
default => throw new InvalidArgumentException(sprintf("Unknown parameter type with value '%s'", $data['type'])),
};
$this->validateDataSent($request, __DIR__ . "/../Schema/{$schemaFile}");
$addAccRequest = new AddAccRequest();
$addAccRequest->type = $data['type'];
$addAccRequest->name = $data['name'];
$addAccRequest->description = $data['description'];
$addAccRequest->pollers = $data['pollers'];
$addAccRequest->parameters = $data['parameters'];
return $addAccRequest;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/AdditionalConnectorConfiguration/Infrastructure/API/FindAcc/FindAccController.php | centreon/src/Core/AdditionalConnectorConfiguration/Infrastructure/API/FindAcc/FindAccController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AdditionalConnectorConfiguration\Infrastructure\API\FindAcc;
use Centreon\Application\Controller\AbstractController;
use Centreon\Domain\Log\LoggerTrait;
use Core\AdditionalConnectorConfiguration\Application\UseCase\FindAcc\FindAcc;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
final class FindAccController extends AbstractController
{
use LoggerTrait;
/**
* @param int $id
* @param FindAcc $useCase
* @param FindAccPresenter $presenter
*
* @throws AccessDeniedException
*
* @return Response
*/
public function __invoke(
int $id,
FindAcc $useCase,
FindAccPresenter $presenter,
): Response {
$this->denyAccessUnlessGrantedForApiConfiguration();
$useCase($id, $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/AdditionalConnectorConfiguration/Infrastructure/API/FindAcc/FindAccPresenter.php | centreon/src/Core/AdditionalConnectorConfiguration/Infrastructure/API/FindAcc/FindAccPresenter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AdditionalConnectorConfiguration\Infrastructure\API\FindAcc;
use Core\AdditionalConnectorConfiguration\Application\UseCase\FindAcc\FindAccPresenterInterface;
use Core\AdditionalConnectorConfiguration\Application\UseCase\FindAcc\FindAccResponse;
use Core\AdditionalConnectorConfiguration\Domain\Model\Poller;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Infrastructure\Common\Presenter\PresenterTrait;
class FindAccPresenter extends AbstractPresenter implements FindAccPresenterInterface
{
use PresenterTrait;
/**
* @inheritDoc
*/
public function presentResponse(FindAccResponse|ResponseStatusInterface $response): void
{
if ($response instanceof ResponseStatusInterface) {
$this->setResponseStatus($response);
} else {
$this->present([
'id' => $response->id,
'name' => $response->name,
'type' => $response->type->value,
'description' => $response->description,
'parameters' => $response->parameters,
'pollers' => array_map(
static fn (Poller $poller): array => ['id' => $poller->id, 'name' => $poller->name],
$response->pollers
),
'created_at' => $this->formatDateToIso8601($response->createdAt),
'created_by' => $response->createdBy,
'updated_at' => $this->formatDateToIso8601($response->updatedAt),
'updated_by' => $response->updatedBy,
]);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/AdditionalConnectorConfiguration/Infrastructure/API/FindAccs/FindAccsPresenter.php | centreon/src/Core/AdditionalConnectorConfiguration/Infrastructure/API/FindAccs/FindAccsPresenter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AdditionalConnectorConfiguration\Infrastructure\API\FindAccs;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\AdditionalConnectorConfiguration\Application\UseCase\FindAccs\FindAccsPresenterInterface;
use Core\AdditionalConnectorConfiguration\Application\UseCase\FindAccs\FindAccsResponse;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Infrastructure\Common\Presenter\PresenterTrait;
class FindAccsPresenter extends AbstractPresenter implements FindAccsPresenterInterface
{
use PresenterTrait;
public function __construct(
protected RequestParametersInterface $requestParameters,
PresenterFormatterInterface $presenterFormatter,
) {
parent::__construct($presenterFormatter);
}
/**
* @inheritDoc
*/
public function presentResponse(FindAccsResponse|ResponseStatusInterface $response): void
{
if ($response instanceof ResponseStatusInterface) {
$this->setResponseStatus($response);
} else {
$result = [];
foreach ($response->accs as $acc) {
$result[] = [
'id' => $acc->id,
'name' => $acc->name,
'type' => $acc->type->value,
'description' => $acc->description,
'created_at' => $this->formatDateToIso8601($acc->createdAt),
'created_by' => $acc->createdBy,
'updated_at' => $this->formatDateToIso8601($acc->updatedAt),
'updated_by' => $acc->updatedBy,
];
}
$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/AdditionalConnectorConfiguration/Infrastructure/API/FindAccs/FindAccsController.php | centreon/src/Core/AdditionalConnectorConfiguration/Infrastructure/API/FindAccs/FindAccsController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AdditionalConnectorConfiguration\Infrastructure\API\FindAccs;
use Centreon\Application\Controller\AbstractController;
use Centreon\Domain\Log\LoggerTrait;
use Core\AdditionalConnectorConfiguration\Application\UseCase\FindAccs\FindAccs;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
final class FindAccsController extends AbstractController
{
use LoggerTrait;
/**
* @param FindAccs $useCase
* @param FindAccsPresenter $presenter
*
* @throws AccessDeniedException
*
* @return Response
*/
public function __invoke(
FindAccs $useCase,
FindAccsPresenter $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/AdditionalConnectorConfiguration/Infrastructure/API/UpdateAcc/UpdateAccController.php | centreon/src/Core/AdditionalConnectorConfiguration/Infrastructure/API/UpdateAcc/UpdateAccController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AdditionalConnectorConfiguration\Infrastructure\API\UpdateAcc;
use Centreon\Application\Controller\AbstractController;
use Centreon\Domain\Log\LoggerTrait;
use Core\AdditionalConnectorConfiguration\Application\UseCase\UpdateAcc\UpdateAcc;
use Core\AdditionalConnectorConfiguration\Application\UseCase\UpdateAcc\UpdateAccRequest;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\Infrastructure\Common\Api\DefaultPresenter;
use InvalidArgumentException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
final class UpdateAccController extends AbstractController
{
use LoggerTrait;
/**
* @param int $id
* @param Request $request
* @param UpdateAcc $useCase
* @param DefaultPresenter $presenter
*
* @throws AccessDeniedException
*
* @return Response
*/
public function __invoke(
int $id,
Request $request,
UpdateAcc $useCase,
DefaultPresenter $presenter,
): Response {
$this->denyAccessUnlessGrantedForApiConfiguration();
try {
$addAccRequest = $this->createRequest($id, $request);
$useCase($addAccRequest, $presenter);
} catch (InvalidArgumentException $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
$presenter->setResponseStatus(new InvalidArgumentResponse($ex));
} catch (\Throwable $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
$presenter->setResponseStatus(new ErrorResponse($ex));
}
return $presenter->show();
}
/**
* @param int $id
* @param Request $request
*
* @throws InvalidArgumentException
*
* @return UpdateAccRequest
*/
private function createRequest(int $id, Request $request): UpdateAccRequest
{
/** @var array{
* name:string,
* type:string,
* description:?string,
* pollers:int[],
* parameters:array<string,mixed>
* } $data
*/
$data = $this->validateAndRetrieveDataSent($request, __DIR__ . '/UpdateAccSchema.json');
$schemaFile = match ($data['type']) {
'vmware_v6' => 'VmWareV6Schema.json',
default => throw new InvalidArgumentException(sprintf("Unknow parameter type with value '%s'", $data['type'])),
};
$this->validateDataSent($request, __DIR__ . "/../Schema/{$schemaFile}");
$accRequest = new UpdateAccRequest();
$accRequest->id = $id;
$accRequest->type = $data['type'];
$accRequest->name = $data['name'];
$accRequest->description = $data['description'];
$accRequest->pollers = $data['pollers'];
$accRequest->parameters = $data['parameters'];
return $accRequest;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ActionLog/Application/Repository/WriteActionLogRepositoryInterface.php | centreon/src/Core/ActionLog/Application/Repository/WriteActionLogRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\ActionLog\Application\Repository;
use Core\ActionLog\Domain\Model\ActionLog;
use Core\Common\Domain\Exception\RepositoryException;
/**
* Interface
*
* @class WriteActionLogRepositoryInterface
* @package Core\ActionLog\Application\Repository
*/
interface WriteActionLogRepositoryInterface
{
/**
* @param ActionLog $actionLog
*
* @throws RepositoryException
* @return int
*/
public function addAction(ActionLog $actionLog): int;
/**
* @param ActionLog $actionLog
* @param array<string, string|int|bool> $details
*
* @throws RepositoryException
*/
public function addActionDetails(ActionLog $actionLog, array $details): 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/ActionLog/Domain/Model/ActionLog.php | centreon/src/Core/ActionLog/Domain/Model/ActionLog.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\ActionLog\Domain\Model;
class ActionLog
{
public const ACTION_TYPE_ADD = 'a';
public const ACTION_TYPE_CHANGE = 'c';
public const ACTION_TYPE_MASS_CHANGE = 'mc';
public const ACTION_TYPE_DELETE = 'd';
public const ACTION_TYPE_ENABLE = 'enable';
public const ACTION_TYPE_DISABLE = 'disable';
public const OBJECT_TYPE_COMMAND = 'command';
public const OBJECT_TYPE_TIMEPERIOD = 'timeperiod';
public const OBJECT_TYPE_CONTACT = 'contact';
public const OBJECT_TYPE_CONTACTGROUP = 'contactgroup';
public const OBJECT_TYPE_HOST = 'host';
public const OBJECT_TYPE_HOST_TEMPLATE = 'host';
public const OBJECT_TYPE_HOSTGROUP = 'hostgroup';
public const OBJECT_TYPE_SERVICE = 'service';
public const OBJECT_TYPE_SERVICEGROUP = 'servicegroup';
public const OBJECT_TYPE_TRAPS = 'traps';
public const OBJECT_TYPE_ESCALATION = 'escalation';
public const OBJECT_TYPE_HOST_DEPENDENCY = 'host dependency';
public const OBJECT_TYPE_HOSTGROUP_DEPENDENCY = 'hostgroup dependency';
public const OBJECT_TYPE_SERVICE_DEPENDENCY = 'service dependency';
public const OBJECT_TYPE_SERVICEGROUP_DEPENDENCY = 'servicegroup dependency';
public const OBJECT_TYPE_POLLER = 'poller';
public const OBJECT_TYPE_ENGINE = 'engine';
public const OBJECT_TYPE_BROKER = 'broker';
public const OBJECT_TYPE_RESOURCES = 'resources';
public const OBJECT_TYPE_META = 'meta';
public const OBJECT_TYPE_ACCESS_GROUP = 'access group';
public const OBJECT_TYPE_MENU_ACCESS = 'menu access';
public const OBJECT_TYPE_RESOURCE_ACCESS = 'resource access';
public const OBJECT_TYPE_ACTION_ACCESS = 'action access';
public const OBJECT_TYPE_MANUFACTURER = 'manufacturer';
public const OBJECT_TYPE_HOSTCATEGORIES = 'hostcategories';
public const OBJECT_TYPE_SERVICECATEGORIES = 'servicecategories';
public const OBJECT_TYPE_SERVICE_SEVERITY = 'serviceseverity';
public const OBJECT_TYPE_HOST_SEVERITY = 'hostseverity';
public const AVAILABLE_OBJECT_TYPES = [
self::OBJECT_TYPE_COMMAND,
self::OBJECT_TYPE_TIMEPERIOD,
self::OBJECT_TYPE_CONTACT,
self::OBJECT_TYPE_CONTACTGROUP,
self::OBJECT_TYPE_HOST,
self::OBJECT_TYPE_HOSTGROUP,
self::OBJECT_TYPE_SERVICE,
self::OBJECT_TYPE_SERVICEGROUP,
self::OBJECT_TYPE_TRAPS,
self::OBJECT_TYPE_ESCALATION,
self::OBJECT_TYPE_HOST_DEPENDENCY,
self::OBJECT_TYPE_HOSTGROUP_DEPENDENCY,
self::OBJECT_TYPE_SERVICE_DEPENDENCY,
self::OBJECT_TYPE_SERVICEGROUP_DEPENDENCY,
self::OBJECT_TYPE_POLLER,
self::OBJECT_TYPE_ENGINE,
self::OBJECT_TYPE_BROKER,
self::OBJECT_TYPE_RESOURCES,
self::OBJECT_TYPE_META,
self::OBJECT_TYPE_ACCESS_GROUP,
self::OBJECT_TYPE_MENU_ACCESS,
self::OBJECT_TYPE_RESOURCE_ACCESS,
self::OBJECT_TYPE_ACTION_ACCESS,
self::OBJECT_TYPE_MANUFACTURER,
self::OBJECT_TYPE_HOSTCATEGORIES,
self::OBJECT_TYPE_SERVICECATEGORIES,
];
private ?int $id = null;
private \DateTime $creationDate;
/**
* @param string $objectType
* @param int $objectId
* @param string $objectName
* @param string $actionType
* @param int $contactId
* @param \DateTime|null $creationDate
*/
public function __construct(
private readonly string $objectType,
private readonly int $objectId,
private readonly string $objectName,
private readonly string $actionType,
private readonly int $contactId,
?\DateTime $creationDate = null,
) {
if ($creationDate === null) {
$this->creationDate = new \DateTime();
}
}
/**
* @return int|null
*/
public function getId(): ?int
{
return $this->id;
}
/**
* @param int|null $id
*
* @return ActionLog
*/
public function setId(?int $id): self
{
$this->id = $id;
return $this;
}
/**
* @return \DateTime
*/
public function getCreationDate(): \DateTime
{
return $this->creationDate;
}
/**
* @return string
*/
public function getObjectType(): string
{
return $this->objectType;
}
/**
* @return int
*/
public function getObjectId(): int
{
return $this->objectId;
}
/**
* @return string
*/
public function getObjectName(): string
{
return $this->objectName;
}
/**
* @return string
*/
public function getActionType(): string
{
return $this->actionType;
}
/**
* @return int
*/
public function getContactId(): int
{
return $this->contactId;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/ActionLog/Infrastructure/Repository/DbWriteActionLogRepository.php | centreon/src/Core/ActionLog/Infrastructure/Repository/DbWriteActionLogRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\ActionLog\Infrastructure\Repository;
use Adaptation\Database\Connection\Collection\BatchInsertParameters;
use Adaptation\Database\Connection\Collection\QueryParameters;
use Adaptation\Database\Connection\Exception\ConnectionException;
use Adaptation\Database\Connection\ValueObject\QueryParameter;
use Adaptation\Database\QueryBuilder\Exception\QueryBuilderException;
use Centreon\Domain\Log\LoggerTrait;
use Core\ActionLog\Application\Repository\WriteActionLogRepositoryInterface;
use Core\ActionLog\Domain\Model\ActionLog;
use Core\Common\Domain\Exception\CollectionException;
use Core\Common\Domain\Exception\RepositoryException;
use Core\Common\Domain\Exception\ValueObjectException;
use Core\Common\Infrastructure\Repository\DatabaseRepository;
/**
* Class
*
* @class DbWriteActionLogRepository
* @package Core\ActionLog\Infrastructure\Repository
*/
class DbWriteActionLogRepository extends DatabaseRepository implements WriteActionLogRepositoryInterface
{
use LoggerTrait;
/**
* @param ActionLog $actionLog
*
* @throws RepositoryException
* @return int
*/
public function addAction(ActionLog $actionLog): int
{
try {
$query = $this->connection->createQueryBuilder()
->insert('`:dbstg`.log_action')
->values([
'action_log_date' => ':creation_date',
'object_type' => ':object_type',
'object_id' => ':object_id',
'object_name' => ':object_name',
'action_type' => ':action_type',
'log_contact_id' => ':contact_id',
])
->getQuery();
$this->connection->insert($this->translateDbName($query), QueryParameters::create([
QueryParameter::int('creation_date', $actionLog->getCreationDate()->getTimestamp()),
QueryParameter::string('object_type', $actionLog->getObjectType()),
QueryParameter::int('object_id', $actionLog->getObjectId()),
QueryParameter::string('object_name', $actionLog->getObjectName()),
QueryParameter::string('action_type', $actionLog->getActionType()),
QueryParameter::int('contact_id', $actionLog->getContactId()),
]));
return (int) $this->connection->getLastInsertId();
} catch (QueryBuilderException|ValueObjectException|CollectionException|ConnectionException $exception) {
$this->error(
"Add action log failed : {$exception->getMessage()}",
[
'action_log' => $actionLog,
'exception' => $exception->getContext(),
]
);
throw new RepositoryException(
"Add action log failed : {$exception->getMessage()}",
['action_log' => $actionLog],
$exception
);
}
}
/**
* @param ActionLog $actionLog
* @param array<string,mixed> $details
*
* @throws RepositoryException
* @return void
*/
public function addActionDetails(ActionLog $actionLog, array $details): void
{
if ($details === []) {
return;
}
if ($actionLog->getId() === null) {
throw new RepositoryException('Action log id is required to add details');
}
$isTransactionActive = $this->connection->isTransactionActive();
try {
if (! $isTransactionActive) {
$this->connection->startTransaction();
}
$batchQueryParameters = [];
foreach ($details as $fieldName => $fieldValue) {
$batchQueryParameters[] = QueryParameters::create([
QueryParameter::string('field_name', $fieldName),
QueryParameter::string('field_value', (string) $fieldValue),
QueryParameter::int('action_log_id', (int) $actionLog->getId()),
]);
}
$this->connection->batchInsert(
$this->translateDbName('`:dbstg`.`log_action_modification`'),
['`field_name`', '`field_value`', '`action_log_id`'],
BatchInsertParameters::create($batchQueryParameters)
);
if (! $isTransactionActive) {
$this->connection->commitTransaction();
}
} catch (ValueObjectException|CollectionException|ConnectionException $exception) {
$this->error(
"Add action log failed : {$exception->getMessage()}",
[
'action_log' => $actionLog,
'exception' => $exception->getContext(),
]
);
if (! $isTransactionActive) {
try {
$this->connection->rollBackTransaction();
} catch (ConnectionException $rollbackException) {
$this->error(
"Rollback failed for action logs: {$rollbackException->getMessage()}",
[
'action_log' => $actionLog,
'exception' => $rollbackException->getContext(),
]
);
throw new RepositoryException(
"Rollback failed for action logs: {$rollbackException->getMessage()}",
['action_log' => $actionLog],
$rollbackException
);
}
}
throw new RepositoryException(
"Add action log failed : {$exception->getMessage()}",
['action_log' => $actionLog],
$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/AgentConfiguration/Application/UseCase/FindAgentConfiguration/FindAgentConfiguration.php | centreon/src/Core/AgentConfiguration/Application/UseCase/FindAgentConfiguration/FindAgentConfiguration.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AgentConfiguration\Application\UseCase\FindAgentConfiguration;
use Centreon\Domain\Log\LoggerTrait;
use Core\AgentConfiguration\Application\Exception\AgentConfigurationException;
use Core\AgentConfiguration\Application\Repository\ReadAgentConfigurationRepositoryInterface;
use Core\AgentConfiguration\Domain\Model\Type;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\NotFoundResponse;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Host\Application\Repository\ReadHostRepositoryInterface;
final class FindAgentConfiguration
{
use LoggerTrait;
/**
* FindAgentConfiguration constructor.
*
* @param ReadAgentConfigurationRepositoryInterface $readRepository repository to read agent configurations
* @param ReadHostRepositoryInterface $readHostRepository
*/
public function __construct(
private readonly ReadAgentConfigurationRepositoryInterface $readRepository,
private readonly ReadHostRepositoryInterface $readHostRepository,
) {
}
/**
* Retrieves an agent configuration with associated pollers.
*
* @param int $agentConfigurationId
*
* @return FindAgentConfigurationResponse|ResponseStatusInterface
*/
public function __invoke(int $agentConfigurationId): FindAgentConfigurationResponse|ResponseStatusInterface
{
$this->info('Find agent configuration', ['agent_configuration_id' => $agentConfigurationId]);
try {
if (null === $agentConfiguration = $this->readRepository->find($agentConfigurationId)) {
$this->error('Agent configuration not found', ['agent_configuration_id' => $agentConfigurationId]);
return new NotFoundResponse('Agent Configuration');
}
$this->info(
'Retrieved agent configuration',
['agent_configuration_id' => $agentConfigurationId]
);
$pollers = $this->readRepository->findPollersByAcId($agentConfigurationId);
$configuration = $agentConfiguration->getConfiguration()->getData();
if ($agentConfiguration->getType() === Type::CMA) {
$hostIds = array_map(static fn (array $host): int => $host['id'], $configuration['hosts']);
if ($hostIds !== []) {
$hostNamesById = $this->readHostRepository->findNames($hostIds);
foreach ($configuration['hosts'] as $index => $host) {
$configuration['hosts'][$index]['name'] = $hostNamesById->getName($host['id']);
}
}
}
return new FindAgentConfigurationResponse($agentConfiguration, $hostNamesById ?? null, $pollers);
} catch (\Throwable $ex) {
$this->error($ex->getMessage(), [
'exception' => [
'type' => $ex::class,
'message' => $ex->getMessage(),
'previous_type' => ! is_null($ex->getPrevious()) ? $ex->getPrevious()::class : null,
'previous_message' => $ex->getPrevious()?->getMessage() ?? null,
'trace' => $ex->getTraceAsString(),
],
]);
return new ErrorResponse(AgentConfigurationException::errorWhileRetrievingObject());
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/AgentConfiguration/Application/UseCase/FindAgentConfiguration/FindAgentConfigurationResponse.php | centreon/src/Core/AgentConfiguration/Application/UseCase/FindAgentConfiguration/FindAgentConfigurationResponse.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AgentConfiguration\Application\UseCase\FindAgentConfiguration;
use Core\AgentConfiguration\Domain\Model\AgentConfiguration;
use Core\AgentConfiguration\Domain\Model\Poller;
use Core\Application\Common\UseCase\StandardResponseInterface;
use Core\Host\Domain\Model\HostNamesById;
final class FindAgentConfigurationResponse implements StandardResponseInterface
{
/**
* FindAgentConfigurationResponse constructor.
*
* @param AgentConfiguration $agentConfiguration
* @param Poller[] $pollers
* @param ?HostNamesById $hostNamesById
*/
public function __construct(
public readonly AgentConfiguration $agentConfiguration,
public readonly ?HostNamesById $hostNamesById,
public readonly array $pollers,
) {
}
/**
* @inheritDoc
*/
public function getData(): mixed
{
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/AgentConfiguration/Application/UseCase/UpdateAgentConfiguration/Validator.php | centreon/src/Core/AgentConfiguration/Application/UseCase/UpdateAgentConfiguration/Validator.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\AgentConfiguration\Application\UseCase\UpdateAgentConfiguration;
use Assert\AssertionFailedException;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Core\AgentConfiguration\Application\Exception\AgentConfigurationException;
use Core\AgentConfiguration\Application\Repository\ReadAgentConfigurationRepositoryInterface;
use Core\AgentConfiguration\Application\Validation\TypeValidatorInterface;
use Core\AgentConfiguration\Domain\Model\AgentConfiguration;
use Core\AgentConfiguration\Domain\Model\Poller;
use Core\AgentConfiguration\Domain\Model\Type;
use Core\Common\Domain\TrimmedString;
use Core\MonitoringServer\Application\Repository\ReadMonitoringServerRepositoryInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use ValueError;
class Validator
{
use LoggerTrait;
/** @var TypeValidatorInterface[] */
private array $parametersValidators = [];
/**
* @param ReadAgentConfigurationRepositoryInterface $readAcRepository
* @param ContactInterface $user
* @param ReadAccessGroupRepositoryInterface $readAccessGroupRepository
* @param ReadMonitoringServerRepositoryInterface $readMonitoringServerRepository
* @param \Traversable<TypeValidatorInterface> $parametersValidators
*/
public function __construct(
private readonly ReadAgentConfigurationRepositoryInterface $readAcRepository,
private readonly ContactInterface $user,
private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepository,
private readonly ReadMonitoringServerRepositoryInterface $readMonitoringServerRepository,
\Traversable $parametersValidators,
) {
$this->parametersValidators = iterator_to_array($parametersValidators);
}
/**
* @param UpdateAgentConfigurationRequest $request
* @param AgentConfiguration $agentConfiguration
*
* @throws AgentConfigurationException|ValueError|AssertionFailedException
*/
public function validateRequestOrFail(
UpdateAgentConfigurationRequest $request,
AgentConfiguration $agentConfiguration,
): void {
$this->validateNameOrFail($request, $agentConfiguration);
$this->validatePollersOrFail($request, $agentConfiguration);
$this->validateTypeOrFail($request, $agentConfiguration);
$this->validateParametersOrFail($request);
}
/**
* Validate that AC name is not already used.
*
* @param UpdateAgentConfigurationRequest $request
* @param AgentConfiguration $agentConfiguration
*
* @throws AgentConfigurationException
*/
public function validateNameOrFail(
UpdateAgentConfigurationRequest $request,
AgentConfiguration $agentConfiguration,
): void {
$trimmedName = new TrimmedString($request->name);
if (
$agentConfiguration->getName() !== $trimmedName->value
&& $this->readAcRepository->existsByName($trimmedName)
) {
throw AgentConfigurationException::nameAlreadyExists($trimmedName->value);
}
}
/**
* Check type validity.
*
* @param UpdateAgentConfigurationRequest $request
* @param AgentConfiguration $agentConfiguration
*
* @throws AgentConfigurationException|ValueError
*/
public function validateTypeOrFail(
UpdateAgentConfigurationRequest $request,
AgentConfiguration $agentConfiguration,
): void {
$type = Type::from($request->type);
if ($type->name !== $agentConfiguration->getType()->name) {
throw AgentConfigurationException::typeChangeNotAllowed();
}
}
/**
* Validate that requesting user has access to pollers.
* Check that pollers are not already linked to same AC type.
*
* @param UpdateAgentConfigurationRequest $request
* @param AgentConfiguration $agentConfiguration
*
* @throws AgentConfigurationException
*/
public function validatePollersOrFail(
UpdateAgentConfigurationRequest $request,
AgentConfiguration $agentConfiguration,
): void {
if ($request->pollerIds === []) {
throw AgentConfigurationException::arrayCanNotBeEmpty('pollerIds');
}
// Check pollers have valid IDs according to user permissions.
$invalidPollers = [];
foreach ($request->pollerIds as $pollerId) {
$isPollerIdValid = false;
if ($this->user->isAdmin()) {
$isPollerIdValid = $this->readMonitoringServerRepository->exists($pollerId);
} else {
$agentConfigurationcessGroups = $this->readAccessGroupRepository->findByContact($this->user);
$isPollerIdValid = $this->readMonitoringServerRepository->existsByAccessGroups($pollerId, $agentConfigurationcessGroups);
}
if ($isPollerIdValid === false) {
$invalidPollers[] = $pollerId;
}
}
if ($invalidPollers !== []) {
throw AgentConfigurationException::idsDoNotExist('pollerIds', $invalidPollers);
}
// Check pollers are not already associated to an AC.
$actualPollers = $this->readAcRepository->findPollersByAcId($agentConfiguration->getId());
$actualPollerIds = array_map(fn (Poller $poller) => $poller->id, $actualPollers);
$unavailablePollers = [];
foreach (Type::cases() as $type) {
$unavailablePollers = array_merge(
$unavailablePollers,
$this->readAcRepository->findPollersByType($type)
);
}
$unavailablePollerIds = array_map(fn (Poller $poller) => $poller->id, $unavailablePollers);
$unavailablePollerIds = array_diff($unavailablePollerIds, $actualPollerIds);
if ([] !== $invalidPollers = array_intersect($unavailablePollerIds, $request->pollerIds)) {
throw AgentConfigurationException::alreadyAssociatedPollers($invalidPollers);
}
}
/**
* @param UpdateAgentConfigurationRequest $request
*
* @throws AgentConfigurationException|AssertionFailedException
*/
public function validateParametersOrFail(UpdateAgentConfigurationRequest $request): void
{
foreach ($this->parametersValidators as $validator) {
if ($validator->isValidFor(Type::from($request->type))) {
$validator->validateParametersOrFail($request);
}
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/AgentConfiguration/Application/UseCase/UpdateAgentConfiguration/UpdateAgentConfiguration.php | centreon/src/Core/AgentConfiguration/Application/UseCase/UpdateAgentConfiguration/UpdateAgentConfiguration.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AgentConfiguration\Application\UseCase\UpdateAgentConfiguration;
use Assert\AssertionFailedException;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Core\AgentConfiguration\Application\Exception\AgentConfigurationException;
use Core\AgentConfiguration\Application\Factory\AgentConfigurationFactory;
use Core\AgentConfiguration\Application\Repository\ReadAgentConfigurationRepositoryInterface;
use Core\AgentConfiguration\Application\Repository\WriteAgentConfigurationRepositoryInterface;
use Core\AgentConfiguration\Domain\Model\AgentConfiguration;
use Core\AgentConfiguration\Domain\Model\Poller;
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\Repository\RepositoryManagerInterface;
use Core\MonitoringServer\Application\Repository\ReadMonitoringServerRepositoryInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
final class UpdateAgentConfiguration
{
use LoggerTrait;
public function __construct(
private readonly ReadAgentConfigurationRepositoryInterface $readAcRepository,
private readonly WriteAgentConfigurationRepositoryInterface $writeAcRepository,
private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepository,
private readonly ReadMonitoringServerRepositoryInterface $readMonitoringServerRepository,
private readonly Validator $validator,
private readonly RepositoryManagerInterface $repositoryManager,
private readonly ContactInterface $user,
private readonly bool $isCloudPlatform,
) {
}
public function __invoke(
UpdateAgentConfigurationRequest $request,
PresenterInterface $presenter,
): void {
try {
if (! $this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_POLLERS_AGENT_CONFIGURATIONS_RW)) {
$this->error(
"User doesn't have sufficient rights to access poller/agent configurations",
[
'user_id' => $this->user->getId(),
'ac_id' => $request->id,
'ac_name' => $request->name,
'ac_type' => $request->type,
],
);
$presenter->setResponseStatus(
new ForbiddenResponse(AgentConfigurationException::accessNotAllowed())
);
return;
}
if ($this->isCloudPlatform && ! $this->user->isAdmin()) {
$linkedPollerIds = array_map(
static fn (Poller $poller): int => $poller->id,
$this->readAcRepository->findPollersByAcId($request->id)
);
$centralPoller = $this->readMonitoringServerRepository->findCentralByIds($linkedPollerIds);
if ($centralPoller !== null) {
$presenter->setResponseStatus(
new ForbiddenResponse(AgentConfigurationException::accessNotAllowed())
);
return;
}
}
if (null === $agentConfiguration = $this->getAgentConfiguration($request->id)) {
$presenter->setResponseStatus(
new NotFoundResponse('Poller/agent Configuration')
);
return;
}
$request->pollerIds = array_unique($request->pollerIds);
$this->validator->validateRequestOrFail($request, $agentConfiguration);
$updatedAgentConfiguration = AgentConfigurationFactory::createAgentConfiguration(
id: $agentConfiguration->getId(),
name: $request->name,
type: $agentConfiguration->getType(),
parameters: $request->configuration,
connectionMode: $request->connectionMode,
);
$this->save($updatedAgentConfiguration, $request->pollerIds);
$presenter->setResponseStatus(new NoContentResponse());
} catch (AssertionFailedException|\InvalidArgumentException $ex) {
$this->error($ex->getMessage(), [
'user_id' => $this->user->getId(),
'ac_id' => $request->id,
'ac_name' => $request->name,
'ac_type' => $request->type,
'exception' => [
'type' => $ex::class,
'message' => $ex->getMessage(),
'previous_type' => ! is_null($ex->getPrevious()) ? $ex->getPrevious()::class : null,
'previous_message' => $ex->getPrevious()?->getMessage() ?? null,
'trace' => $ex->getTraceAsString(),
],
]);
$presenter->setResponseStatus(new InvalidArgumentResponse($ex));
} catch (\Throwable $ex) {
$this->error($ex->getMessage(), [
'user_id' => $this->user->getId(),
'ac_id' => $request->id,
'ac_name' => $request->name,
'ac_type' => $request->type,
'exception' => [
'type' => $ex::class,
'message' => $ex->getMessage(),
'previous_type' => ! is_null($ex->getPrevious()) ? $ex->getPrevious()::class : null,
'previous_message' => $ex->getPrevious()?->getMessage() ?? null,
'trace' => $ex->getTraceAsString(),
],
]);
$presenter->setResponseStatus(
new ErrorResponse(
$ex instanceof AgentConfigurationException
? $ex : AgentConfigurationException::updateAc()
)
);
}
}
/**
* Get AC based on user rights.
*
* @param int $id
*
* @throws \Throwable
*
* @return null|AgentConfiguration
*/
private function getAgentConfiguration(int $id): null|AgentConfiguration
{
if (null === $agentConfiguration = $this->readAcRepository->find($id)) {
return null;
}
if (! $this->user->isAdmin()) {
$pollerIds = array_map(
static fn (Poller $poller): int => $poller->id,
$this->readAcRepository->findPollersByAcId($agentConfiguration->getId())
);
$accessGroups = $this->readAccessGroupRepository->findByContact($this->user);
$validPollerIds = $this->readMonitoringServerRepository->existByAccessGroups($pollerIds, $accessGroups);
if (array_diff($pollerIds, $validPollerIds) !== []) {
return null;
}
}
return $agentConfiguration;
}
/**
* @param AgentConfiguration $agentConfiguration
* @param int[] $pollers
*
* @throws \Throwable
*/
private function save(AgentConfiguration $agentConfiguration, array $pollers): void
{
try {
$this->repositoryManager->startTransaction();
$this->writeAcRepository->update($agentConfiguration);
$this->writeAcRepository->removePollers($agentConfiguration->getId());
$this->writeAcRepository->linkToPollers($agentConfiguration->getId(), $pollers);
$this->repositoryManager->commitTransaction();
} catch (\Throwable $ex) {
$this->error("Rollback of 'UpdateAgentConfiguration' transaction.");
$this->repositoryManager->rollbackTransaction();
throw $ex;
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/AgentConfiguration/Application/UseCase/UpdateAgentConfiguration/UpdateAgentConfigurationRequest.php | centreon/src/Core/AgentConfiguration/Application/UseCase/UpdateAgentConfiguration/UpdateAgentConfigurationRequest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AgentConfiguration\Application\UseCase\UpdateAgentConfiguration;
use Core\AgentConfiguration\Domain\Model\ConnectionModeEnum;
final class UpdateAgentConfigurationRequest
{
public int $id = 0;
public string $name = '';
public string $type = '';
public ConnectionModeEnum $connectionMode = ConnectionModeEnum::SECURE;
/** @var int[] */
public array $pollerIds = [];
/** @var array<string,mixed> */
public array $configuration = [];
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/AgentConfiguration/Application/UseCase/DeleteAgentConfiguration/DeleteAgentConfiguration.php | centreon/src/Core/AgentConfiguration/Application/UseCase/DeleteAgentConfiguration/DeleteAgentConfiguration.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AgentConfiguration\Application\UseCase\DeleteAgentConfiguration;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Core\AgentConfiguration\Application\Exception\AgentConfigurationException;
use Core\AgentConfiguration\Application\Repository\ReadAgentConfigurationRepositoryInterface;
use Core\AgentConfiguration\Application\Repository\WriteAgentConfigurationRepositoryInterface;
use Core\AgentConfiguration\Domain\Model\Poller;
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\MonitoringServer\Application\Repository\ReadMonitoringServerRepositoryInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
final class DeleteAgentConfiguration
{
use LoggerTrait;
public function __construct(
private readonly ReadAgentConfigurationRepositoryInterface $readAcRepository,
private readonly WriteAgentConfigurationRepositoryInterface $writeAcRepository,
private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepository,
private readonly ReadMonitoringServerRepositoryInterface $readMonitoringServerRepository,
private readonly ContactInterface $user,
private readonly bool $isCloudPlatform,
) {
}
public function __invoke(
int $id,
PresenterInterface $presenter,
): void {
try {
if (! $this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_POLLERS_AGENT_CONFIGURATIONS_RW)) {
$this->error(
"User doesn't have sufficient rights to access poller/agent configurations",
[
'user_id' => $this->user->getId(),
'ac_id' => $id,
],
);
$presenter->setResponseStatus(
new ForbiddenResponse(AgentConfigurationException::accessNotAllowed())
);
return;
}
if ($this->readAcRepository->find($id) === null) {
$presenter->setResponseStatus(new NotFoundResponse('Poller/agent Configuration'));
return;
}
$linkedPollerIds = array_map(
static fn (Poller $poller): int => $poller->id,
$this->readAcRepository->findPollersByAcId($id)
);
if ($this->user->isAdmin() === false) {
// non admin cannot delete central on cloud platform
if ($this->isCloudPlatform) {
$centralPoller = $this->readMonitoringServerRepository->findCentralByIds($linkedPollerIds);
if ($centralPoller !== null) {
$presenter->setResponseStatus(new ForbiddenResponse(
AgentConfigurationException::accessNotAllowed()
));
return;
}
}
$accessGroups = $this->readAccessGroupRepository->findByContact($this->user);
$accessiblePollerIds = $this->readMonitoringServerRepository->existByAccessGroups(
$linkedPollerIds,
$accessGroups
);
if (array_diff($linkedPollerIds, $accessiblePollerIds)) {
$presenter->setResponseStatus(
new ForbiddenResponse(AgentConfigurationException::unsufficientRights())
);
return;
}
}
$this->writeAcRepository->delete($id);
$presenter->setResponseStatus(new NoContentResponse());
} catch (\Throwable $ex) {
$this->error($ex->getMessage(), [
'user_id' => $this->user->getId(),
'ac_id' => $id,
'exception' => [
'type' => $ex::class,
'message' => $ex->getMessage(),
'previous_type' => ! is_null($ex->getPrevious()) ? $ex->getPrevious()::class : null,
'previous_message' => $ex->getPrevious()?->getMessage() ?? null,
'trace' => $ex->getTraceAsString(),
],
]);
$presenter->setResponseStatus(new ErrorResponse(
$ex instanceof AgentConfigurationException
? $ex : AgentConfigurationException::deleteAc()
));
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/AgentConfiguration/Application/UseCase/FindAgentConfigurations/FindAgentConfigurations.php | centreon/src/Core/AgentConfiguration/Application/UseCase/FindAgentConfigurations/FindAgentConfigurations.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AgentConfiguration\Application\UseCase\FindAgentConfigurations;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\AgentConfiguration\Application\Exception\AgentConfigurationException;
use Core\AgentConfiguration\Application\Repository\ReadAgentConfigurationRepositoryInterface;
use Core\AgentConfiguration\Domain\Model\AgentConfiguration;
use Core\AgentConfiguration\Domain\Model\Poller;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
final class FindAgentConfigurations
{
use LoggerTrait;
/**
* @param ContactInterface $user
* @param ReadAgentConfigurationRepositoryInterface $readRepository
* @param RequestParametersInterface $requestParameters
* @param ReadAccessGroupRepositoryInterface $readAccessGroupRepository
*/
public function __construct(
private readonly ContactInterface $user,
private readonly ReadAgentConfigurationRepositoryInterface $readRepository,
private readonly RequestParametersInterface $requestParameters,
private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepository,
) {
}
/**
* Finds all agent configurations.
*
* @param FindAgentConfigurationsPresenterInterface $presenter
*/
public function __invoke(FindAgentConfigurationsPresenterInterface $presenter): void
{
try {
if (! $this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_POLLERS_AGENT_CONFIGURATIONS_RW)) {
$this->error(
"User doesn't have sufficient rights to access poller/agent configurations",
['user_id' => $this->user->getId()]
);
$presenter->presentResponse(
new ForbiddenResponse(AgentConfigurationException::accessNotAllowed())
);
return;
}
$agentConfigurations = $this->user->isAdmin()
? $this->readRepository->findAllByRequestParameters($this->requestParameters)
: $this->readRepository->findAllByRequestParametersAndAccessGroups(
$this->requestParameters,
$this->readAccessGroupRepository->findByContact($this->user)
);
$presenter->presentResponse($this->createResponse($agentConfigurations));
} catch (\Throwable $ex) {
$this->error($ex->getMessage(), [
'user_id' => $this->user->getId(),
'exception' => [
'type' => $ex::class,
'message' => $ex->getMessage(),
'previous_type' => ! is_null($ex->getPrevious()) ? $ex->getPrevious()::class : null,
'previous_message' => $ex->getPrevious()?->getMessage() ?? null,
'trace' => $ex->getTraceAsString(),
],
]);
$presenter->presentResponse(new ErrorResponse(AgentConfigurationException::errorWhileRetrievingObjects()));
}
}
/**
* Creates a response from the given array of agent configurations.
*
* @param AgentConfiguration[] $agentConfigurations
*
* @return FindAgentConfigurationsResponse
*/
private function createResponse(array $agentConfigurations): FindAgentConfigurationsResponse
{
$response = new FindAgentConfigurationsResponse();
$agentConfigurationDtos = [];
foreach ($agentConfigurations as $agentConfiguration) {
$pollers = $this->readRepository->findPollersByAcId($agentConfiguration->getId());
$agentConfigurationDto = new AgentConfigurationDto();
$agentConfigurationDto->id = $agentConfiguration->getId();
$agentConfigurationDto->type = $agentConfiguration->getType();
$agentConfigurationDto->name = $agentConfiguration->getName();
$agentConfigurationDto->pollers = array_map(function (Poller $poller) {
$pollerDto = new PollerDto();
$pollerDto->id = $poller->getId();
$pollerDto->name = $poller->getName();
$pollerDto->isCentral = $poller->isCentral() ?? false;
return $pollerDto;
}, $pollers);
$agentConfigurationDtos[] = $agentConfigurationDto;
}
$response->agentConfigurations = $agentConfigurationDtos;
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/AgentConfiguration/Application/UseCase/FindAgentConfigurations/FindAgentConfigurationsPresenterInterface.php | centreon/src/Core/AgentConfiguration/Application/UseCase/FindAgentConfigurations/FindAgentConfigurationsPresenterInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AgentConfiguration\Application\UseCase\FindAgentConfigurations;
use Core\Application\Common\UseCase\ResponseStatusInterface;
interface FindAgentConfigurationsPresenterInterface
{
public function presentResponse(FindAgentConfigurationsResponse|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/AgentConfiguration/Application/UseCase/FindAgentConfigurations/FindAgentConfigurationsResponse.php | centreon/src/Core/AgentConfiguration/Application/UseCase/FindAgentConfigurations/FindAgentConfigurationsResponse.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AgentConfiguration\Application\UseCase\FindAgentConfigurations;
final class FindAgentConfigurationsResponse
{
/** @var AgentConfigurationDto[] */
public array $agentConfigurations = [];
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/AgentConfiguration/Application/UseCase/FindAgentConfigurations/AgentConfigurationDto.php | centreon/src/Core/AgentConfiguration/Application/UseCase/FindAgentConfigurations/AgentConfigurationDto.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AgentConfiguration\Application\UseCase\FindAgentConfigurations;
use Core\AgentConfiguration\Domain\Model\Type;
final class AgentConfigurationDto
{
public int $id;
public Type $type;
public string $name;
/** @var PollerDto[] */
public array $pollers;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/AgentConfiguration/Application/UseCase/FindAgentConfigurations/PollerDto.php | centreon/src/Core/AgentConfiguration/Application/UseCase/FindAgentConfigurations/PollerDto.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AgentConfiguration\Application\UseCase\FindAgentConfigurations;
final class PollerDto
{
public int $id;
public string $name;
public bool $isCentral;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/AgentConfiguration/Application/UseCase/DeleteAgentConfigurationPollerLink/DeleteAgentConfigurationPollerLink.php | centreon/src/Core/AgentConfiguration/Application/UseCase/DeleteAgentConfigurationPollerLink/DeleteAgentConfigurationPollerLink.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AgentConfiguration\Application\UseCase\DeleteAgentConfigurationPollerLink;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Core\AgentConfiguration\Application\Exception\AgentConfigurationException;
use Core\AgentConfiguration\Application\Repository\ReadAgentConfigurationRepositoryInterface;
use Core\AgentConfiguration\Application\Repository\WriteAgentConfigurationRepositoryInterface;
use Core\AgentConfiguration\Domain\Model\Poller;
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\MonitoringServer\Application\Repository\ReadMonitoringServerRepositoryInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
final class DeleteAgentConfigurationPollerLink
{
use LoggerTrait;
public function __construct(
private readonly ReadAgentConfigurationRepositoryInterface $readAcRepository,
private readonly WriteAgentConfigurationRepositoryInterface $writeAcRepository,
private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepository,
private readonly ReadMonitoringServerRepositoryInterface $readMonitoringServerRepository,
private readonly ContactInterface $user,
private readonly bool $isCloudPlatform,
) {
}
public function __invoke(
int $acId,
int $pollerId,
PresenterInterface $presenter,
): void {
try {
if (! $this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_POLLERS_AGENT_CONFIGURATIONS_RW)) {
$this->error(
"User doesn't have sufficient rights to access poller/agent configurations",
[
'user_id' => $this->user->getId(),
'ac_id' => $acId,
'poller_id' => $pollerId,
],
);
$presenter->setResponseStatus(
new ForbiddenResponse(AgentConfigurationException::accessNotAllowed())
);
return;
}
if ($this->readAcRepository->find($acId) === null) {
$presenter->setResponseStatus(new NotFoundResponse('Poller/agent Configuration'));
return;
}
$linkedPollerIds = array_map(
static fn (Poller $poller): int => $poller->id,
$this->readAcRepository->findPollersByAcId($acId)
);
if ($this->user->isAdmin() === false) {
// non admin cannot delete servers on cloud platform if among them a central linked to the ac
if ($this->isCloudPlatform) {
$centralPoller = $this->readMonitoringServerRepository->findCentralByIds($linkedPollerIds);
if ($centralPoller !== null) {
$presenter->setResponseStatus(
new ForbiddenResponse(AgentConfigurationException::accessNotAllowed())
);
return;
}
}
$accessGroups = $this->readAccessGroupRepository->findByContact($this->user);
$accessiblePollerIds = $this->readMonitoringServerRepository->existByAccessGroups(
$linkedPollerIds,
$accessGroups
);
if (array_diff($linkedPollerIds, $accessiblePollerIds)) {
$presenter->setResponseStatus(
new ForbiddenResponse(AgentConfigurationException::unsufficientRights())
);
return;
}
}
if (count($linkedPollerIds) === 1 && $pollerId = $linkedPollerIds[0]) {
throw AgentConfigurationException::onlyOnePoller($pollerId, $acId);
}
$this->writeAcRepository->removePoller($acId, $pollerId);
$presenter->setResponseStatus(new NoContentResponse());
} catch (\Throwable $ex) {
$this->error($ex->getMessage(), [
'user_id' => $this->user->getId(),
'ac_id' => $acId,
'poller_id' => $pollerId,
'exception' => [
'type' => $ex::class,
'message' => $ex->getMessage(),
'previous_type' => ! is_null($ex->getPrevious()) ? $ex->getPrevious()::class : null,
'previous_message' => $ex->getPrevious()?->getMessage() ?? null,
'trace' => $ex->getTraceAsString(),
],
]);
$presenter->setResponseStatus(new ErrorResponse(
$ex instanceof AgentConfigurationException
? $ex
: AgentConfigurationException::deleteAc()
));
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/AgentConfiguration/Application/UseCase/AddAgentConfiguration/AddAgentConfigurationPresenterInterface.php | centreon/src/Core/AgentConfiguration/Application/UseCase/AddAgentConfiguration/AddAgentConfigurationPresenterInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AgentConfiguration\Application\UseCase\AddAgentConfiguration;
use Core\Application\Common\UseCase\ResponseStatusInterface;
interface AddAgentConfigurationPresenterInterface
{
public function presentResponse(AddAgentConfigurationResponse|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/AgentConfiguration/Application/UseCase/AddAgentConfiguration/AddAgentConfigurationRequest.php | centreon/src/Core/AgentConfiguration/Application/UseCase/AddAgentConfiguration/AddAgentConfigurationRequest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AgentConfiguration\Application\UseCase\AddAgentConfiguration;
use Core\AgentConfiguration\Domain\Model\ConnectionModeEnum;
final class AddAgentConfigurationRequest
{
public string $name = '';
public string $type = '';
public ConnectionModeEnum $connectionMode = ConnectionModeEnum::SECURE;
/** @var int[] */
public array $pollerIds = [];
/** @var array<string,mixed> */
public array $configuration = [];
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/AgentConfiguration/Application/UseCase/AddAgentConfiguration/AddAgentConfigurationResponse.php | centreon/src/Core/AgentConfiguration/Application/UseCase/AddAgentConfiguration/AddAgentConfigurationResponse.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AgentConfiguration\Application\UseCase\AddAgentConfiguration;
use Core\AgentConfiguration\Domain\Model\ConnectionModeEnum;
use Core\AgentConfiguration\Domain\Model\Poller;
use Core\AgentConfiguration\Domain\Model\Type;
final class AddAgentConfigurationResponse
{
/**
* @param int $id
* @param Type $type
* @param string $name
* @param array<string,mixed> $configuration
* @param Poller[] $pollers
* @param ConnectionModeEnum $connectionMode
*/
public function __construct(
public int $id = 0,
public Type $type = Type::TELEGRAF,
public ConnectionModeEnum $connectionMode = ConnectionModeEnum::SECURE,
public string $name = '',
public array $configuration = [],
public array $pollers = [],
) {
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/AgentConfiguration/Application/UseCase/AddAgentConfiguration/Validator.php | centreon/src/Core/AgentConfiguration/Application/UseCase/AddAgentConfiguration/Validator.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\AgentConfiguration\Application\UseCase\AddAgentConfiguration;
use Assert\AssertionFailedException;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Core\AgentConfiguration\Application\Exception\AgentConfigurationException;
use Core\AgentConfiguration\Application\Repository\ReadAgentConfigurationRepositoryInterface;
use Core\AgentConfiguration\Application\Validation\TypeValidatorInterface;
use Core\AgentConfiguration\Domain\Model\Poller;
use Core\AgentConfiguration\Domain\Model\Type;
use Core\Common\Domain\TrimmedString;
use Core\MonitoringServer\Application\Repository\ReadMonitoringServerRepositoryInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use ValueError;
class Validator
{
use LoggerTrait;
/** @var TypeValidatorInterface[] */
private array $parametersValidators = [];
/**
* @param ReadAgentConfigurationRepositoryInterface $readAcRepository
* @param ContactInterface $user
* @param ReadAccessGroupRepositoryInterface $readAccessGroupRepository
* @param ReadMonitoringServerRepositoryInterface $readMonitoringServerRepository
* @param \Traversable<TypeValidatorInterface> $parametersValidators
*/
public function __construct(
private readonly ReadAgentConfigurationRepositoryInterface $readAcRepository,
private readonly ContactInterface $user,
private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepository,
private readonly ReadMonitoringServerRepositoryInterface $readMonitoringServerRepository,
\Traversable $parametersValidators,
) {
$this->parametersValidators = iterator_to_array($parametersValidators);
}
/**
* @param AddAgentConfigurationRequest $request
*
* @throws AgentConfigurationException|ValueError|AssertionFailedException
*/
public function validateRequestOrFail(AddAgentConfigurationRequest $request): void
{
$this->validateNameOrFail($request);
$this->validatePollersOrFail($request);
$this->validateTypeOrFail($request);
$this->validateParametersOrFail($request);
}
/**
* Validate that AC name is not already used.
*
* @param AddAgentConfigurationRequest $request
*
* @throws AgentConfigurationException
*/
public function validateNameOrFail(AddAgentConfigurationRequest $request): void
{
$trimmedName = new TrimmedString($request->name);
if ($this->readAcRepository->existsByName($trimmedName)) {
throw AgentConfigurationException::nameAlreadyExists($trimmedName->value);
}
}
/**
* Validate that requesting user has access to pollers.
* Check that pollers are not already linked to same AC type.
*
* @param AddAgentConfigurationRequest $request
*
* @throws AgentConfigurationException
*/
public function validatePollersOrFail(AddAgentConfigurationRequest $request): void
{
if ($request->pollerIds === []) {
throw AgentConfigurationException::arrayCanNotBeEmpty('pollerIds');
}
// Check pollers have valid IDs according to user permissions.
$invalidPollers = [];
foreach ($request->pollerIds as $pollerId) {
$isPollerIdValid = false;
if ($this->user->isAdmin()) {
$isPollerIdValid = $this->readMonitoringServerRepository->exists($pollerId);
} else {
$agentConfigurationcessGroups = $this->readAccessGroupRepository->findByContact($this->user);
$isPollerIdValid = $this->readMonitoringServerRepository->existsByAccessGroups($pollerId, $agentConfigurationcessGroups);
}
if ($isPollerIdValid === false) {
$invalidPollers[] = $pollerId;
}
}
if ($invalidPollers !== []) {
throw AgentConfigurationException::idsDoNotExist('pollerIds', $invalidPollers);
}
// Check pollers are not already associated to an AC.
$unavailablePollers = [];
foreach (Type::cases() as $type) {
$unavailablePollers = array_merge(
$unavailablePollers,
$this->readAcRepository->findPollersByType($type)
);
}
$pollerIds = array_map(fn (Poller $poller) => $poller->id, $unavailablePollers);
if ([] !== $invalidPollers = array_intersect($pollerIds, $request->pollerIds)) {
throw AgentConfigurationException::alreadyAssociatedPollers($invalidPollers);
}
}
/**
* Check type validity.
*
* @param AddAgentConfigurationRequest $request
*
* @throws ValueError
*/
public function validateTypeOrFail(AddAgentConfigurationRequest $request): void
{
Type::from($request->type);
}
/**
* @param AddAgentConfigurationRequest $request
*
* @throws AgentConfigurationException|AssertionFailedException
*/
public function validateParametersOrFail(AddAgentConfigurationRequest $request): void
{
foreach ($this->parametersValidators as $validator) {
if ($validator->isValidFor(Type::from($request->type))) {
$validator->validateParametersOrFail($request);
}
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/AgentConfiguration/Application/UseCase/AddAgentConfiguration/AddAgentConfiguration.php | centreon/src/Core/AgentConfiguration/Application/UseCase/AddAgentConfiguration/AddAgentConfiguration.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AgentConfiguration\Application\UseCase\AddAgentConfiguration;
use Assert\AssertionFailedException;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Core\AgentConfiguration\Application\Exception\AgentConfigurationException;
use Core\AgentConfiguration\Application\Factory\AgentConfigurationFactory;
use Core\AgentConfiguration\Application\Repository\ReadAgentConfigurationRepositoryInterface;
use Core\AgentConfiguration\Application\Repository\WriteAgentConfigurationRepositoryInterface;
use Core\AgentConfiguration\Domain\Model\AgentConfiguration;
use Core\AgentConfiguration\Domain\Model\NewAgentConfiguration;
use Core\AgentConfiguration\Domain\Model\Poller;
use Core\AgentConfiguration\Domain\Model\Type;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\Common\Application\Repository\RepositoryManagerInterface;
use Core\Host\Application\Repository\ReadHostRepositoryInterface;
use Core\MonitoringServer\Application\Repository\ReadMonitoringServerRepositoryInterface;
final class AddAgentConfiguration
{
use LoggerTrait;
public function __construct(
private readonly ReadAgentConfigurationRepositoryInterface $readAcRepository,
private readonly WriteAgentConfigurationRepositoryInterface $writeAcRepository,
private readonly ReadHostRepositoryInterface $readHostRepository,
private readonly ReadMonitoringServerRepositoryInterface $readMsRepository,
private readonly Validator $validator,
private readonly RepositoryManagerInterface $repositoryManager,
private readonly ContactInterface $user,
private readonly bool $isCloudPlatform,
) {
}
public function __invoke(
AddAgentConfigurationRequest $request,
AddAgentConfigurationPresenterInterface $presenter,
): void {
try {
if (! $this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_POLLERS_AGENT_CONFIGURATIONS_RW)) {
$this->error(
"User doesn't have sufficient rights to access poller/agent configurations",
[
'user_id' => $this->user->getId(),
'ac_type' => $request->type,
'ac_name' => $request->name,
],
);
$presenter->presentResponse(
new ForbiddenResponse(AgentConfigurationException::accessNotAllowed())
);
return;
}
$request->pollerIds = array_unique($request->pollerIds);
if ($this->isCloudPlatform && ! $this->user->isAdmin()) {
$centralPoller = $this->readMsRepository->findCentralByIds($request->pollerIds);
if ($centralPoller !== null) {
$presenter->presentResponse(
new ForbiddenResponse(AgentConfigurationException::accessNotAllowed())
);
return;
}
}
$type = Type::from($request->type);
$this->validator->validateRequestOrFail($request);
$newAc = AgentConfigurationFactory::createNewAgentConfiguration(
name: $request->name,
type: $type,
connectionMode: $request->connectionMode,
parameters: $request->configuration,
);
[$module, $needBrokerDirectivePollers] = $this->checkNeedForBrokerDirective(
$newAc,
$request->pollerIds
);
$agentConfigurationId = $this->save(
$newAc,
$request->pollerIds,
$module,
$needBrokerDirectivePollers
);
if (null === $agentConfiguration = $this->readAcRepository->find($agentConfigurationId)) {
throw AgentConfigurationException::errorWhileRetrievingObject();
}
$pollers = $this->readAcRepository->findPollersByAcId($agentConfigurationId);
$presenter->presentResponse($this->createResponse($agentConfiguration, $pollers));
} catch (AssertionFailedException|\InvalidArgumentException $ex) {
$this->error($ex->getMessage(), [
'user_id' => $this->user->getId(),
'ac_type' => $request->type,
'ac_name' => $request->name,
'exception' => [
'type' => $ex::class,
'message' => $ex->getMessage(),
'previous_type' => ! is_null($ex->getPrevious()) ? $ex->getPrevious()::class : null,
'previous_message' => $ex->getPrevious()?->getMessage() ?? null,
'trace' => $ex->getTraceAsString(),
],
]);
$presenter->presentResponse(new InvalidArgumentResponse($ex));
} catch (\Throwable $ex) {
$this->error($ex->getMessage(), [
'user_id' => $this->user->getId(),
'ac_type' => $request->type,
'ac_name' => $request->name,
'exception' => [
'type' => $ex::class,
'message' => $ex->getMessage(),
'previous_type' => ! is_null($ex->getPrevious()) ? $ex->getPrevious()::class : null,
'previous_message' => $ex->getPrevious()?->getMessage() ?? null,
'trace' => $ex->getTraceAsString(),
],
]);
$presenter->presentResponse(new ErrorResponse(
$ex instanceof AgentConfigurationException
? $ex : AgentConfigurationException::addAc()
));
}
}
/**
* @param NewAgentConfiguration $agentConfiguration
* @param int[] $pollers
* @param null|string $module
* @param int[] $needBrokerDirectives
*
* @throws \Throwable
*
* @return int
*/
private function save(
NewAgentConfiguration $agentConfiguration,
array $pollers,
?string $module,
array $needBrokerDirectives,
): int {
try {
$this->repositoryManager->startTransaction();
$newAcId = $this->writeAcRepository->add($agentConfiguration);
$this->writeAcRepository->linkToPollers($newAcId, $pollers);
if ($module !== null && $needBrokerDirectives !== []) {
$this->writeAcRepository->addBrokerDirective($module, $needBrokerDirectives);
}
$this->repositoryManager->commitTransaction();
} catch (\Throwable $ex) {
$this->error("Rollback of 'AddAgentConfiguration' transaction.");
$this->repositoryManager->rollbackTransaction();
throw $ex;
}
return $newAcId;
}
/**
* Return the module directive and the poller IDs that need the AC type related broker directive to be added.
*
* @param NewAgentConfiguration $newAc
* @param int[] $pollerIds
*
* @throws \Throwable
*
* @return array{?string,int[]}
*/
private function checkNeedForBrokerDirective(NewAgentConfiguration $newAc, array $pollerIds): array
{
$module = $newAc->getConfiguration()->getBrokerDirective();
$needBrokerDirectivePollers = [];
if ($module !== null) {
$haveBrokerDirectivePollers = $this->readAcRepository->findPollersWithBrokerDirective(
$module
);
$needBrokerDirectivePollers = array_diff(
$pollerIds,
$haveBrokerDirectivePollers
);
}
return [$module, $needBrokerDirectivePollers];
}
/**
* @param AgentConfiguration $agentConfiguration
* @param Poller[] $pollers
*
* @return AddAgentConfigurationResponse
*/
private function createResponse(AgentConfiguration $agentConfiguration, array $pollers): AddAgentConfigurationResponse
{
$configuration = $agentConfiguration->getConfiguration()->getData();
if ($agentConfiguration->getType() === Type::CMA) {
$hostIds = array_map(static fn (array $host): int => $host['id'], $configuration['hosts']);
if ($hostIds !== []) {
$hostNamesById = $this->readHostRepository->findNames($hostIds);
foreach ($configuration['hosts'] as $index => $host) {
$configuration['hosts'][$index]['name'] = $hostNamesById->getName($host['id']);
}
}
}
return new AddAgentConfigurationResponse(
id: $agentConfiguration->getId(),
type: $agentConfiguration->getType(),
connectionMode: $agentConfiguration->getConnectionMode(),
name: $agentConfiguration->getName(),
configuration: $configuration,
pollers: $pollers
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/AgentConfiguration/Application/Validation/TelegrafValidator.php | centreon/src/Core/AgentConfiguration/Application/Validation/TelegrafValidator.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AgentConfiguration\Application\Validation;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\AgentConfiguration\Application\UseCase\AddAgentConfiguration\AddAgentConfigurationRequest;
use Core\AgentConfiguration\Application\UseCase\UpdateAgentConfiguration\UpdateAgentConfigurationRequest;
use Core\AgentConfiguration\Domain\Model\ConfigurationParameters\TelegrafConfigurationParameters;
use Core\AgentConfiguration\Domain\Model\Type;
/**
* @phpstan-import-type _TelegrafParameters from TelegrafConfigurationParameters
*/
class TelegrafValidator implements TypeValidatorInterface
{
/**
* @inheritDoc
*/
public function isValidFor(Type $type): bool
{
return $type === Type::TELEGRAF;
}
/**
* @inheritDoc
*/
public function validateParametersOrFail(AddAgentConfigurationRequest|UpdateAgentConfigurationRequest $request): void
{
/** @var _TelegrafParameters $configuration */
$configuration = $request->configuration;
foreach ($configuration as $key => $value) {
// validate file extension
if (str_ends_with($key, '_certificate') && (is_string($value) || is_null($value))) {
if (preg_match('/^(?!.*\.(cer|crt)$).+$/', (string) $value) === 1) {
throw new AssertionException(
sprintf("File path or format '%s' (%s) is invalid", (string) $value, "configuration.{$key}")
);
}
} elseif (str_ends_with($key, '_key') && (is_string($value) || is_null($value))) {
if (preg_match('/^(?!.*\.key$).+$/', (string) $value) === 1) {
throw new AssertionException(
sprintf("File path or format '%s' (%s) is invalid", (string) $value, "configuration.{$key}")
);
}
}
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/AgentConfiguration/Application/Validation/TypeValidatorInterface.php | centreon/src/Core/AgentConfiguration/Application/Validation/TypeValidatorInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AgentConfiguration\Application\Validation;
use Assert\AssertionFailedException;
use Core\AgentConfiguration\Application\Exception\AgentConfigurationException;
use Core\AgentConfiguration\Application\UseCase\AddAgentConfiguration\AddAgentConfigurationRequest;
use Core\AgentConfiguration\Application\UseCase\UpdateAgentConfiguration\UpdateAgentConfigurationRequest;
use Core\AgentConfiguration\Domain\Model\Type;
interface TypeValidatorInterface
{
/**
* @param Type $type
*
* @return bool
*/
public function isValidFor(Type $type): bool;
/**
* @param AddAgentConfigurationRequest|UpdateAgentConfigurationRequest $request
*
* @throws AgentConfigurationException|AssertionFailedException
*/
public function validateParametersOrFail(AddAgentConfigurationRequest|UpdateAgentConfigurationRequest $request): 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/AgentConfiguration/Application/Validation/CmaValidator.php | centreon/src/Core/AgentConfiguration/Application/Validation/CmaValidator.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AgentConfiguration\Application\Validation;
use Centreon\Domain\Common\Assertion\AssertionException;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Core\AgentConfiguration\Application\Exception\AgentConfigurationException;
use Core\AgentConfiguration\Application\UseCase\AddAgentConfiguration\AddAgentConfigurationRequest;
use Core\AgentConfiguration\Application\UseCase\UpdateAgentConfiguration\UpdateAgentConfigurationRequest;
use Core\AgentConfiguration\Domain\Model\ConfigurationParameters\CmaConfigurationParameters;
use Core\AgentConfiguration\Domain\Model\ConnectionModeEnum;
use Core\AgentConfiguration\Domain\Model\Type;
use Core\Host\Application\Repository\ReadHostRepositoryInterface;
use Core\Security\Token\Application\Repository\ReadTokenRepositoryInterface;
use Core\Security\Token\Domain\Model\JwtToken;
/**
* @phpstan-import-type _CmaParameters from CmaConfigurationParameters
*/
class CmaValidator implements TypeValidatorInterface
{
public function __construct(
private readonly ReadHostRepositoryInterface $readHostRepository,
private readonly ReadTokenRepositoryInterface $tokenRepository,
private readonly ContactInterface $user,
) {
}
/**
* @inheritDoc
*/
public function isValidFor(Type $type): bool
{
return $type === Type::CMA;
}
/**
* @inheritDoc
*/
public function validateParametersOrFail(AddAgentConfigurationRequest|UpdateAgentConfigurationRequest $request): void
{
/** @var _CmaParameters $configuration */
$configuration = $request->configuration;
if ($configuration['agent_initiated'] === false && $configuration['poller_initiated'] === false) {
throw AgentConfigurationException::atLeastOneConnectionModeIsRequired();
}
$this->validateAgentInitiatedConnection($configuration, $request->connectionMode);
$this->validatePollerInitiatedConnection($configuration);
}
/**
* @param _CmaParameters $configuration
* @param ConnectionModeEnum $connectionMode
*/
private function validateAgentInitiatedConnection(array $configuration, ConnectionModeEnum $connectionMode): void
{
if ($configuration['agent_initiated'] === false) {
return;
}
if ($configuration['port'] === null) {
throw AgentConfigurationException::portIsMandatory();
}
if ($connectionMode !== ConnectionModeEnum::NO_TLS) {
$this->validateFilename(
'configuration.otel_public_certificate',
$configuration['otel_public_certificate'],
true
);
$this->validateFilename(
'configuration.otel_ca_certificate',
$configuration['otel_ca_certificate'],
true
);
$this->validateFilename(
'configuration.otel_private_key',
$configuration['otel_private_key'],
false
);
}
if ($configuration['tokens'] === []) {
throw AgentConfigurationException::tokensAreMandatory();
}
$this->validateTokens($configuration['tokens']);
}
/**
* @param _CmaParameters $configuration
*/
private function validatePollerInitiatedConnection(array $configuration): void
{
if ($configuration['poller_initiated'] === false) {
return;
}
foreach ($configuration['hosts'] as $host) {
$this->validateFilename('configuration.hosts[].poller_ca_certificate', $host['poller_ca_certificate'], true);
if (! $this->readHostRepository->exists(hostId: $host['id'])) {
throw AgentConfigurationException::invalidHostId($host['id']);
}
if ($host['token'] === null) {
throw AgentConfigurationException::tokensAreMandatory();
}
$this->validateTokens([$host['token']]);
}
}
/**
* Validates filename extension.
*
* @param string $name
* @param ?string $value
* @param bool $isCertificate (default true)
*
* @throws AssertionException
*/
private function validateFilename(string $name, ?string $value, bool $isCertificate = true): void
{
$pattern = $isCertificate
? '/^(?!.*\.(cer|crt)$).+$/'
: '/^(?!.*\.key$).+$/';
if ($value !== null && preg_match($pattern, $value)) {
throw new AssertionException(
sprintf("File path or format '%s' (%s) is invalid", $value, $name)
);
}
}
/**
* @param array<array{name:string,creator_id:int}> $tokens
*
* @throws AgentConfigurationException
*/
private function validateTokens(array $tokens): void
{
foreach ($tokens as $token) {
if (! $this->user->isAdmin() && $token['creator_id'] !== $this->user->getId() && ! $this->user->hasRole('ROLE_MANAGE_TOKENS')) {
throw AgentConfigurationException::invalidToken($token['name'], $token['creator_id']);
}
$tokenObj = $this->tokenRepository->findByNameAndUserId($token['name'], $token['creator_id']);
if (
$tokenObj === null
|| ! $tokenObj instanceof JwtToken
|| $tokenObj->isRevoked()
|| ($tokenObj->getExpirationDate() !== null && $tokenObj->getExpirationDate() < new \DateTimeImmutable())
) {
throw AgentConfigurationException::invalidToken($token['name'], $token['creator_id']);
}
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/AgentConfiguration/Application/Exception/AgentConfigurationException.php | centreon/src/Core/AgentConfiguration/Application/Exception/AgentConfigurationException.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AgentConfiguration\Application\Exception;
class AgentConfigurationException extends \Exception
{
public const CODE_CONFLICT = 1;
public static function addAc(): self
{
return new self(_('Error while adding a poller/agent configuration'));
}
public static function updateAc(): self
{
return new self(_('Error while updating a poller/agent configuration'));
}
public static function deleteAc(): self
{
return new self(_('Error while deleting a poller/agent configuration'));
}
public static function accessNotAllowed(): self
{
return new self(_('You are not allowed to access poller/agent configurations'));
}
public static function unsufficientRights(): self
{
return new self(_("You don't have sufficient permissions for this action"));
}
/**
* @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)
),
self::CODE_CONFLICT
);
}
/**
* @param int[] $invalidPollers
*
* @return self
*/
public static function alreadyAssociatedPollers(array $invalidPollers): self
{
return new self(
sprintf(
_("A poller/agent configuration is already associated with poller ID(s) '%s'"),
implode(',', $invalidPollers)
),
self::CODE_CONFLICT
);
}
public static function duplicatesNotAllowed(string $propertyName): self
{
return new self(
sprintf(
_("Duplicates not allowed for property '%s'"),
$propertyName
),
self::CODE_CONFLICT
);
}
public static function arrayCanNotBeEmpty(string $propertyName): self
{
return new self(
sprintf(
_("'%s' must contain at least one element"),
$propertyName
),
self::CODE_CONFLICT
);
}
public static function errorWhileRetrievingObject(): self
{
return new self(_('Error while retrieving a poller/agent configuration'));
}
public static function errorWhileRetrievingObjects(): self
{
return new self(_('Error while retrieving multiple poller/agent configurations'));
}
public static function nameAlreadyExists(string $name): self
{
return new self(
sprintf(_("The poller/agent configuration name '%s' already exists"), $name),
self::CODE_CONFLICT
);
}
public static function typeChangeNotAllowed(): self
{
return new self(
_('Changing the type of an existing poller/agent configuration is not allowed'),
self::CODE_CONFLICT
);
}
public static function invalidFilename(string $name, string $value): self
{
return new self(
sprintf(_("File path or format '%s' (%s) is invalid"), $value, $name),
self::CODE_CONFLICT
);
}
public static function onlyOnePoller(int $pollerId, int $acId): self
{
return new self(
sprintf(_('Poller ID #%d is the only one linked to poller/agent configuration ID #%d'), $pollerId, $acId),
self::CODE_CONFLICT
);
}
public static function invalidToken(string $name, int $creatorId): self
{
return new self(
sprintf(_('Token with name "%s" and creator ID "%d" is not valid'), $name, $creatorId),
self::CODE_CONFLICT
);
}
public static function tokensAreMandatory(): self
{
return new self(_('Tokens are mandatory'), self::CODE_CONFLICT);
}
public static function invalidHostId(int $hostId): self
{
return new self(sprintf(_('Host ID #%d is invalid'), $hostId));
}
public static function atLeastOneConnectionModeIsRequired(): self
{
return new self('At least one connection mode (agent initiated or poller initiated) must be set to true', self::CODE_CONFLICT);
}
public static function portIsMandatory(): self
{
return new self('Port is mandatory', self::CODE_CONFLICT);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/AgentConfiguration/Application/Repository/WriteAgentConfigurationRepositoryInterface.php | centreon/src/Core/AgentConfiguration/Application/Repository/WriteAgentConfigurationRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AgentConfiguration\Application\Repository;
use Core\AgentConfiguration\Domain\Model\AgentConfiguration;
use Core\AgentConfiguration\Domain\Model\NewAgentConfiguration;
use Core\Common\Domain\Exception\RepositoryException;
/**
* Interface
*
* @class WriteAgentConfigurationRepositoryInterface
* @package Core\AgentConfiguration\Application\Repository
*/
interface WriteAgentConfigurationRepositoryInterface
{
/**
* Create a new agent configuration (AC).
*
* @param NewAgentConfiguration $agentConfiguration
*
* @throws RepositoryException
*
* @return int
*/
public function add(NewAgentConfiguration $agentConfiguration): int;
/**
* Update an agent configuration (AC).
*
* @param AgentConfiguration $agentConfiguration
*
* @throws RepositoryException
*/
public function update(AgentConfiguration $agentConfiguration): void;
/**
* Delete an agent configuration.
*
* @param int $id
*
* @throws RepositoryException
*/
public function delete(int $id): void;
/**
* Link listed poller to the agent configuration (AC).
*
* @param int $agentConfigurationId
* @param int[] $pollerIds
*
* @throws RepositoryException
*/
public function linkToPollers(int $agentConfigurationId, array $pollerIds): void;
/**
* Unlink all pollers from the agent configuration (AC).
*
* @param int $agentConfigurationId
*
* @throws RepositoryException
*/
public function removePollers(int $agentConfigurationId): void;
/**
* Unlink a specific poller from the agent configuration (AC).
*
* @param int $agentConfigurationId
* @param int $pollerId
*
* @throws RepositoryException
*/
public function removePoller(int $agentConfigurationId, int $pollerId): void;
/**
* Add the broker directive to pollers engine configurations.
*
* @param string $module
* @param int[] $pollerIds
*
* @throws RepositoryException
*/
public function addBrokerDirective(string $module, array $pollerIds): 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/AgentConfiguration/Application/Repository/ReadAgentConfigurationRepositoryInterface.php | centreon/src/Core/AgentConfiguration/Application/Repository/ReadAgentConfigurationRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AgentConfiguration\Application\Repository;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\AgentConfiguration\Domain\Model\AgentConfiguration;
use Core\AgentConfiguration\Domain\Model\Poller;
use Core\AgentConfiguration\Domain\Model\Type;
use Core\Common\Domain\TrimmedString;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
interface ReadAgentConfigurationRepositoryInterface
{
/**
* Determine if an Agent Configuration (AC) exists by its name.
*
* @param TrimmedString $name
*
* @throws \Throwable
*
* @return bool
*/
public function existsByName(TrimmedString $name): bool;
/**
* Find an Agent Configuration (AC).
*
* @param int $agentConfigurationId
*
* @throws \Throwable
*
* @return ?AgentConfiguration
*/
public function find(int $agentConfigurationId): ?AgentConfiguration;
/**
* Find all the pollers associated with any AC of the specified type.
*
* @param Type $type
*
* @throws \Throwable
*
* @return Poller[]
*/
public function findPollersByType(Type $type): array;
/**
* Find all the pollers associated with an AC ID.
*
* @param int $agentConfigurationId
*
* @throws \Throwable
*
* @return Poller[]
*/
public function findPollersByAcId(int $agentConfigurationId): array;
/**
* Return poller IDs that have the specified broker directive defined in their engine configuration.
*
* @param string $module
*
* @throws \Throwable
*
* @return int[]
*/
public function findPollersWithBrokerDirective(string $module): array;
/**
* Return all the agent configurations.
*
* @param RequestParametersInterface $requestParameters
*
* @throws \Throwable
*
* @return AgentConfiguration[]
*/
public function findAllByRequestParameters(RequestParametersInterface $requestParameters): array;
/**
* Return all the agent configurations based on request parameters and ACL.
*
* @param RequestParametersInterface $requestParameters
* @param AccessGroup[] $accessGroups
*
* @throws \Throwable
*
* @return AgentConfiguration[]
*/
public function findAllByRequestParametersAndAccessGroups(
RequestParametersInterface $requestParameters,
array $accessGroups,
): array;
/**
* Finds Agent Configurations by a given poller ID.
*
* @param int $pollerId The ID of the poller to find entities for
*
* @throws \Throwable
*
* @return AgentConfiguration|null Agent Configurations found by the given poller ID
*/
public function findByPollerId(int $pollerId): ?AgentConfiguration;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/AgentConfiguration/Application/Factory/AgentConfigurationFactory.php | centreon/src/Core/AgentConfiguration/Application/Factory/AgentConfigurationFactory.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AgentConfiguration\Application\Factory;
use Assert\AssertionFailedException;
use Core\AgentConfiguration\Domain\Model\AgentConfiguration;
use Core\AgentConfiguration\Domain\Model\ConfigurationParameters\CmaConfigurationParameters;
use Core\AgentConfiguration\Domain\Model\ConfigurationParameters\TelegrafConfigurationParameters;
use Core\AgentConfiguration\Domain\Model\ConnectionModeEnum;
use Core\AgentConfiguration\Domain\Model\NewAgentConfiguration;
use Core\AgentConfiguration\Domain\Model\Type;
class AgentConfigurationFactory
{
/**
* @param string $name
* @param Type $type
* @param ConnectionModeEnum $connectionMode
* @param array<string,mixed> $parameters
*
* @throws AssertionFailedException
*
* @return NewAgentConfiguration
*/
public static function createNewAgentConfiguration(
string $name,
Type $type,
ConnectionModeEnum $connectionMode,
array $parameters,
): NewAgentConfiguration {
return new NewAgentConfiguration(
name: $name,
type: $type,
connectionMode: $connectionMode,
configuration: match ($type) {
Type::TELEGRAF => new TelegrafConfigurationParameters($parameters),
Type::CMA => new CmaConfigurationParameters($parameters),
}
);
}
/**
* @param int $id
* @param string $name
* @param Type $type
* @param array<string,mixed> $parameters
* @param ConnectionModeEnum $connectionMode
*
* @throws AssertionFailedException
*
* @return AgentConfiguration
*/
public static function createAgentConfiguration(
int $id,
string $name,
Type $type,
array $parameters,
ConnectionModeEnum $connectionMode,
): AgentConfiguration {
return new AgentConfiguration(
id: $id,
name: $name,
type: $type,
connectionMode: $connectionMode,
configuration: match ($type) {
Type::TELEGRAF => new TelegrafConfigurationParameters($parameters),
Type::CMA => new CmaConfigurationParameters($parameters),
}
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/AgentConfiguration/Domain/Model/ConfigurationParametersInterface.php | centreon/src/Core/AgentConfiguration/Domain/Model/ConfigurationParametersInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AgentConfiguration\Domain\Model;
interface ConfigurationParametersInterface
{
/**
* @return array<string,mixed>
*/
public function getData(): array;
/**
* Retrieves the broker directive.
*
* @return ?string
*/
public function getBrokerDirective(): ?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/AgentConfiguration/Domain/Model/AgentConfiguration.php | centreon/src/Core/AgentConfiguration/Domain/Model/AgentConfiguration.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\AgentConfiguration\Domain\Model;
use Assert\AssertionFailedException;
use Centreon\Domain\Common\Assertion\Assertion;
/**
* @immutable
*/
class AgentConfiguration
{
public const MAX_NAME_LENGTH = 255;
public const DEFAULT_HOST = '0.0.0.0';
public const DEFAULT_PORT = 4317;
private string $name = '';
/**
* @param int $id
* @param string $name
* @param Type $type
* @param ConnectionModeEnum $connectionMode
* @param ConfigurationParametersInterface $configuration
*
* @throws AssertionFailedException
*/
public function __construct(
private readonly int $id,
string $name,
private readonly Type $type,
private readonly ConnectionModeEnum $connectionMode,
private readonly ConfigurationParametersInterface $configuration,
) {
$shortName = (new \ReflectionClass($this))->getShortName();
$this->name = trim($name);
Assertion::maxLength($this->name, self::MAX_NAME_LENGTH, $shortName . '::name');
Assertion::notEmptyString($this->name, $shortName . '::name');
}
public function getId(): int
{
return $this->id;
}
public function getName(): string
{
return $this->name;
}
public function getType(): Type
{
return $this->type;
}
public function getConnectionMode(): ConnectionModeEnum
{
return $this->connectionMode;
}
/**
* @return ConfigurationParametersInterface
*/
public function getConfiguration(): ConfigurationParametersInterface
{
return $this->configuration;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/AgentConfiguration/Domain/Model/Type.php | centreon/src/Core/AgentConfiguration/Domain/Model/Type.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AgentConfiguration\Domain\Model;
enum Type: string
{
case TELEGRAF = 'telegraf';
case CMA = 'centreon-agent';
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/AgentConfiguration/Domain/Model/ConnectionModeEnum.php | centreon/src/Core/AgentConfiguration/Domain/Model/ConnectionModeEnum.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AgentConfiguration\Domain\Model;
enum ConnectionModeEnum
{
case SECURE;
case NO_TLS;
case INSECURE;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/AgentConfiguration/Domain/Model/NewAgentConfiguration.php | centreon/src/Core/AgentConfiguration/Domain/Model/NewAgentConfiguration.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AgentConfiguration\Domain\Model;
use Assert\AssertionFailedException;
use Centreon\Domain\Common\Assertion\Assertion;
/**
* @immutable
*/
class NewAgentConfiguration
{
public const MAX_NAME_LENGTH = 255;
private string $name;
/**
* @param string $name
* @param Type $type
* @param ConnectionModeEnum $connectionMode
* @param ConfigurationParametersInterface $configuration
*
* @throws AssertionFailedException
*/
public function __construct(
string $name,
private readonly Type $type,
private readonly ConnectionModeEnum $connectionMode,
private ConfigurationParametersInterface $configuration,
) {
$shortName = (new \ReflectionClass($this))->getShortName();
$this->name = trim($name);
Assertion::maxLength($this->name, self::MAX_NAME_LENGTH, $shortName . '::name');
Assertion::notEmptyString($this->name, $shortName . '::name');
}
public function getName(): string
{
return $this->name;
}
public function getType(): Type
{
return $this->type;
}
public function getConnectionMode(): ConnectionModeEnum
{
return $this->connectionMode;
}
/**
* @return ConfigurationParametersInterface
*/
public function getConfiguration(): ConfigurationParametersInterface
{
return $this->configuration;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/AgentConfiguration/Domain/Model/Poller.php | centreon/src/Core/AgentConfiguration/Domain/Model/Poller.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AgentConfiguration\Domain\Model;
/**
* @immutable
*/
class Poller
{
public function __construct(
public readonly int $id,
public readonly string $name,
public readonly ?bool $isCentral = null,
) {
}
public function getId(): int
{
return $this->id;
}
public function getName(): string
{
return $this->name;
}
public function isCentral(): ?bool
{
return $this->isCentral;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/AgentConfiguration/Domain/Model/ConfigurationParameters/TelegrafConfigurationParameters.php | centreon/src/Core/AgentConfiguration/Domain/Model/ConfigurationParameters/TelegrafConfigurationParameters.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AgentConfiguration\Domain\Model\ConfigurationParameters;
use Centreon\Domain\Common\Assertion\Assertion;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\AgentConfiguration\Domain\Model\ConfigurationParametersInterface;
/**
* @phpstan-type _TelegrafParameters array{
* otel_public_certificate: ?string,
* otel_ca_certificate: ?string,
* otel_private_key: ?string,
* conf_server_port: int,
* conf_certificate: ?string,
* conf_private_key: ?string
* }
*/
class TelegrafConfigurationParameters implements ConfigurationParametersInterface
{
public const BROKER_DIRECTIVE = '/usr/lib64/centreon-engine/libopentelemetry.so '
. '/etc/centreon-engine/otl_server.json';
public const MAX_LENGTH = 255;
public const CERTIFICATE_BASE_PATH = '/etc/pki/';
/** @var array<string> */
private const FORBIDDEN_DIRECTORIES = [
'/tmp', '/root', '/proc', '/mnt', '/run', '/snap', '/sys', '/boot',
];
/**
* @param array<string,mixed> $parameters
*
* @throws AssertionException
*/
public function __construct(private array $parameters)
{
Assertion::range($this->parameters['conf_server_port'], 0, 65535, 'configuration.conf_server_port');
$this->parameters['otel_public_certificate'] = $this->validateCertificatePath(
$this->parameters['otel_public_certificate'],
'configuration.otel_public_certificate'
);
$this->parameters['otel_private_key'] = $this->validateCertificatePath(
$this->parameters['otel_private_key'],
'configuration.otel_private_key'
);
$this->parameters['conf_certificate'] = $this->validateCertificatePath(
$this->parameters['conf_certificate'],
'configuration.conf_certificate'
);
$this->parameters['conf_private_key'] = $this->validateCertificatePath(
$this->parameters['conf_private_key'],
'configuration.conf_private_key'
);
$this->parameters['otel_ca_certificate'] = $this->validateCertificatePath(
$this->parameters['otel_ca_certificate'],
'configuration.otel_ca_certificate'
);
}
/**
* @inheritDoc
*
* @return _TelegrafParameters
*/
public function getData(): array
{
/** @var _TelegrafParameters */
return $this->parameters;
}
public function getBrokerDirective(): ?string
{
return self::BROKER_DIRECTIVE;
}
/**
* Prepends a prefix to a certificate path if it's a relative path.
*
* @param string $path
*
* @return string
*/
private function prependPrefix(string $path): string
{
if (str_starts_with($path, '/')) {
return $path;
}
return self::CERTIFICATE_BASE_PATH . ltrim($path, '/');
}
private function validateCertificatePath(?string $path, string $field): ?string
{
if ($path === null || $path === '') {
return null;
}
$this->assertPathSecurity($path, $field);
$normalizedPath = $this->prependPrefix($path);
Assertion::maxLength($normalizedPath, self::MAX_LENGTH, $field);
return $normalizedPath;
}
/**
* Validates that a certificate path is safe and not in a forbidden directory.
*
* @param string $path
* @param string $field Used for error reporting
*
* @throws AssertionException
*/
private function assertPathSecurity(string $path, string $field): void
{
// Reject relative path patterns
if (
str_contains($path, '../')
|| str_contains($path, '//')
|| str_contains($path, './')
|| $path === '.'
|| $path === '..'
) {
throw new AssertionException(
sprintf('[%s] The path "%s" contains invalid relative path patterns', $field, $path),
);
}
// Reject hidden directories
if (preg_match('#/\\.#', $path) || (str_starts_with($path, '.') && ! str_starts_with($path, './'))) {
throw new AssertionException(
sprintf('[%s] The path "%s" cannot be in a hidden directory', $field, $path),
);
}
// Reject forbidden directories
foreach (self::FORBIDDEN_DIRECTORIES as $forbiddenDirectory) {
if (str_starts_with($path, $forbiddenDirectory . '/') || $path === $forbiddenDirectory) {
throw new AssertionException(
sprintf('[%s] The path "%s" cannot be in directory %s', $field, $path, $forbiddenDirectory),
);
}
}
// Reject forbidden directories : /etc but not /etc/pki
if (str_starts_with($path, '/etc/')) {
if (! str_starts_with($path, self::CERTIFICATE_BASE_PATH) && $path !== '/etc/pki') {
throw new AssertionException(
sprintf('[%s] The path "%s" can only be in /etc/pki/ directory', $field, $path),
);
}
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/AgentConfiguration/Domain/Model/ConfigurationParameters/CmaConfigurationParameters.php | centreon/src/Core/AgentConfiguration/Domain/Model/ConfigurationParameters/CmaConfigurationParameters.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AgentConfiguration\Domain\Model\ConfigurationParameters;
use Centreon\Domain\Common\Assertion\Assertion;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\AgentConfiguration\Domain\Model\AgentConfiguration;
use Core\AgentConfiguration\Domain\Model\ConfigurationParametersInterface;
/**
* @phpstan-type _CmaParameters array{
* agent_initiated: bool,
* otel_public_certificate: ?string,
* otel_private_key: ?string,
* otel_ca_certificate: ?string,
* tokens: array<array{name:string,creator_id:int}>,
* port: int,
* poller_initiated: bool,
* hosts: array<array{
* id: int,
* address: string,
* port: int,
* poller_ca_certificate: ?string,
* poller_ca_name: ?string,
* token: null|array{name:string,creator_id:int}
* }>
* }
*/
class CmaConfigurationParameters implements ConfigurationParametersInterface
{
public const BROKER_MODULE_DIRECTIVE = '/usr/lib64/centreon-engine/libopentelemetry.so '
. '/etc/centreon-engine/otl_server.json';
public const MAX_LENGTH = 255;
public const DEFAULT_CHECK_INTERVAL = 60;
public const DEFAULT_EXPORT_PERIOD = 60;
public const CERTIFICATE_BASE_PATH = '/etc/pki/';
/** @var array<string> */
private const FORBIDDEN_DIRECTORIES = [
'/tmp', '/root', '/proc', '/mnt', '/run', '/snap', '/sys', '/boot',
];
/**
* @param array<string,mixed> $parameters
* @param bool $fromReadRepository
*
* @throws AssertionException
*/
public function __construct(private array $parameters, private readonly bool $fromReadRepository = false)
{
if ($this->parameters['agent_initiated'] === false) {
$this->parameters['otel_public_certificate'] = null;
$this->parameters['otel_private_key'] = null;
$this->parameters['otel_ca_certificate'] = null;
$this->parameters['tokens'] = [];
} else {
$this->parameters['otel_public_certificate'] = $this->validateCertificatePath(
$this->parameters['otel_public_certificate'],
'configuration.otel_public_certificate'
);
$this->parameters['otel_private_key'] = $this->validateCertificatePath(
$this->parameters['otel_private_key'],
'configuration.otel_private_key'
);
$this->parameters['otel_ca_certificate'] = $this->validateCertificatePath(
$this->parameters['otel_ca_certificate'],
'configuration.otel_ca_certificate'
);
// $fromReadRepository allow configurations created before tokens was mandatoryto be read even without tokens
if (! $this->fromReadRepository) {
Assertion::notEmpty($this->parameters['tokens'], 'configuration.tokens');
foreach ($this->parameters['tokens'] as $token) {
Assertion::notEmptyString($token['name']);
}
}
if (! isset($this->parameters['port'])) {
$this->parameters['port'] = AgentConfiguration::DEFAULT_PORT;
}
Assertion::range($this->parameters['port'] ?? AgentConfiguration::DEFAULT_PORT, 0, 65535, 'configuration.port');
}
if ($this->parameters['poller_initiated'] === false) {
$this->parameters['hosts'] = [];
} else {
foreach ($this->parameters['hosts'] as $key => $host) {
Assertion::positiveInt($host['id'], 'configuration.hosts[].id');
Assertion::ipOrDomain($host['address'], 'configuration.hosts[].address');
Assertion::range($host['port'], 0, 65535, 'configuration.hosts[].port');
$this->parameters['hosts'][$key]['poller_ca_certificate'] = $this->validateCertificatePath(
$host['poller_ca_certificate'],
'configuration.hosts[].poller_ca_certificate'
);
// $fromReadRepository allow configurations created before tokens was mandatoryto be read even without tokens
if (! $this->fromReadRepository) {
Assertion::notNull($host['token'], 'configuration.hosts[].token');
Assertion::notEmptyString($host['token']['name'] ?? '');
Assertion::positiveInt($host['token']['creator_id'] ?? 0);
}
}
}
}
/**
* @inheritDoc
*
* @return _CmaParameters
*/
public function getData(): array
{
/** @var _CmaParameters */
return $this->parameters;
}
/**
* @inheritDoc
*/
public function getBrokerDirective(): ?string
{
return self::BROKER_MODULE_DIRECTIVE;
}
private function validateCertificatePath(?string $path, string $field): ?string
{
if ($path === null || $path === '') {
return null;
}
$this->assertPathSecurity($path, $field);
$normalizedPath = $this->prependPrefix($path);
Assertion::maxLength($normalizedPath, self::MAX_LENGTH, $field);
return $normalizedPath;
}
/**
* Prepends a prefix to a certificate path if it's a relative path.
*
* @param string $path
*
* @return string
*/
private function prependPrefix(string $path): string
{
if (str_starts_with($path, '/')) {
return $path;
}
return self::CERTIFICATE_BASE_PATH . ltrim($path, '/');
}
/**
* Validates that a certificate path is safe and not in a forbidden directory.
*
* @param string $path
* @param string $field Used for error reporting
*
* @throws AssertionException
*/
private function assertPathSecurity(string $path, string $field): void
{
// Reject relative paths
if (
str_contains($path, '../')
|| str_contains($path, '//')
|| str_contains($path, './')
|| $path === '.'
|| $path === '..'
) {
throw new AssertionException(
sprintf('[%s] The path "%s" contains invalid relative path patterns', $field, $path),
);
}
// Reject hidden directories
if (preg_match('#/\\.#', $path) || (str_starts_with($path, '.') && ! str_starts_with($path, './'))) {
throw new AssertionException(
sprintf('[%s] The path "%s" cannot be in a hidden directory', $field, $path),
);
}
// Reject forbidden directories
foreach (self::FORBIDDEN_DIRECTORIES as $forbiddenDirectory) {
if (str_starts_with($path, $forbiddenDirectory . '/') || $path === $forbiddenDirectory) {
throw new AssertionException(
sprintf('[%s] The path "%s" cannot be in directory %s', $field, $path, $forbiddenDirectory),
);
}
}
// Reject forbidden directories : /etc but not /etc/pki
if (str_starts_with($path, '/etc/')) {
if (! str_starts_with($path, '/etc/pki/') && $path !== '/etc/pki') {
throw new AssertionException(
sprintf('[%s] The path "%s" can only be in /etc/pki/ directory', $field, $path),
);
}
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/AgentConfiguration/Infrastructure/Voters/AgentConfigurationVoter.php | centreon/src/Core/AgentConfiguration/Infrastructure/Voters/AgentConfigurationVoter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AgentConfiguration\Infrastructure\Voters;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Core\AgentConfiguration\Application\Repository\ReadAgentConfigurationRepositoryInterface;
use Core\AgentConfiguration\Domain\Model\Poller;
use Core\MonitoringServer\Application\Repository\ReadMonitoringServerRepositoryInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
/**
* @extends Voter<string, mixed>
*/
final class AgentConfigurationVoter extends Voter
{
use LoggerTrait;
public const READ_AC = 'read_agent_configuration';
public const READ_AC_POLLERS = 'read_agent_configuration_pollers';
public function __construct(
private readonly ReadAgentConfigurationRepositoryInterface $readRepository,
private readonly ReadMonitoringServerRepositoryInterface $readMonitoringServerRepository,
private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepository,
) {
}
/**
* {@inheritDoc}
*/
protected function supports(string $attribute, $subject): bool
{
if ($attribute === self::READ_AC) {
return $subject === null;
}
if ($attribute === self::READ_AC_POLLERS) {
return is_numeric($subject);
}
return false;
}
/**
* {@inheritDoc}
*
* @param numeric-string|null $subject
*/
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
$user = $token->getUser();
if (! $user instanceof ContactInterface) {
return false;
}
return match ($attribute) {
self::READ_AC => $this->checkTopologyRole($user),
self::READ_AC_POLLERS => $this->checkAgentConfigurationPollers($user, (int) $subject),
default => throw new \LogicException('Action on agent configuration not handled'),
};
}
/**
* Checks if the user has sufficient rights to access agent configurations.
*
* @param ContactInterface $user
*
* @return bool
*/
private function checkTopologyRole(ContactInterface $user): bool
{
if ($user->hasTopologyRole(Contact::ROLE_CONFIGURATION_POLLERS_AGENT_CONFIGURATIONS_RW)) {
return true;
}
$this->error(
"User doesn't have sufficient rights to access agent configurations",
['user_id' => $user->getId()]
);
return false;
}
/**
* Checks if the user has the correct access groups for the pollers associated with the given agent configuration.
*
* @param ContactInterface $user The user to check
* @param int $agentConfigurationId The ID of the agent configuration
*
* @return bool True if the user has the correct access groups, false otherwise
*/
private function checkAgentConfigurationPollers(ContactInterface $user, int $agentConfigurationId): bool
{
if ($user->isAdmin()) {
return true;
}
$pollers = $this->readRepository->findPollersByAcId($agentConfigurationId);
$pollerIds = array_map(
static fn (Poller $poller): int => $poller->id,
$pollers
);
$validPollerIds = $this->readMonitoringServerRepository->existByAccessGroups(
$pollerIds,
$this->readAccessGroupRepository->findByContact($user)
);
if (array_diff($pollerIds, $validPollerIds) === []) {
return true;
}
$this->debug(
'User does not have the correct access groups for pollers',
[
'user_id' => $user->getId(),
'poller_ids' => array_diff($pollerIds, $validPollerIds),
]
);
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/AgentConfiguration/Infrastructure/Serializer/ConfigurationParametersInterfaceNormalizer.php | centreon/src/Core/AgentConfiguration/Infrastructure/Serializer/ConfigurationParametersInterfaceNormalizer.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AgentConfiguration\Infrastructure\Serializer;
use Core\AgentConfiguration\Domain\Model\ConfigurationParameters\CmaConfigurationParameters;
use Core\AgentConfiguration\Domain\Model\ConfigurationParameters\TelegrafConfigurationParameters;
use Core\AgentConfiguration\Domain\Model\ConfigurationParametersInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
/**
* @phpstan-import-type _TelegrafParameters from TelegrafConfigurationParameters
* @phpstan-import-type _CmaParameters from CmaConfigurationParameters
*/
class ConfigurationParametersInterfaceNormalizer implements NormalizerInterface
{
/**
* {@inheritDoc}
*
* @param ConfigurationParametersInterface $object
* @param string|null $format
* @param array<string, mixed> $context
*
* @return _TelegrafParameters|_CmaParameters|null
*/
public function normalize(
mixed $object,
?string $format = null,
array $context = [],
): float|int|bool|array|string|null {
/** @var array{groups: string[]} $context */
if (in_array('AgentConfiguration:Read', $context['groups'], true)) {
/** @var _TelegrafParameters|_CmaParameters $data */
$data = $object->getData();
}
return $data ?? null;
}
/**
* @param mixed $data
* @param ?string $format
* @param array<string, mixed> $context
*/
public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool
{
return $data instanceof ConfigurationParametersInterface;
}
/**
* @param ?string $format
* @return array<class-string|'*'|'object'|string, bool|null>
*/
public function getSupportedTypes(?string $format): array
{
return [
ConfigurationParametersInterface::class => 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/AgentConfiguration/Infrastructure/Serializer/FindAgentConfigurationResponseNormalizer.php | centreon/src/Core/AgentConfiguration/Infrastructure/Serializer/FindAgentConfigurationResponseNormalizer.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AgentConfiguration\Infrastructure\Serializer;
use Core\AgentConfiguration\Application\UseCase\FindAgentConfiguration\FindAgentConfigurationResponse;
use Core\AgentConfiguration\Domain\Model\Poller;
use Core\AgentConfiguration\Domain\Model\Type;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
class FindAgentConfigurationResponseNormalizer implements NormalizerInterface, NormalizerAwareInterface
{
use NormalizerAwareTrait;
/**
* @param FindAgentConfigurationResponse $object
* @param string|null $format
* @param array<string, mixed> $context
*
* @throws \Throwable
*
* @return array<string, mixed>
*/
public function normalize(
mixed $object,
?string $format = null,
array $context = [],
): array {
/** @var array<string, bool|float|int|string> $data */
$data = $this->normalizer->normalize($object->agentConfiguration, $format, $context);
/** @var array{groups: string[]} $context */
if (in_array('AgentConfiguration:Read', $context['groups'], true)) {
$data['pollers'] = array_map(
fn (Poller $poller) => $this->normalizer->normalize($poller, $format, $context),
$object->pollers
);
/** @var array{
* configuration: array{
* hosts: array<int, array{
* id: int
* }>
* }
* } $data */
if ($object->agentConfiguration->getType() === Type::CMA && $object->hostNamesById !== null) {
foreach ($data['configuration']['hosts'] as $index => $host) {
$data['configuration']['hosts'][$index]['name'] = $object->hostNamesById->getName($host['id']);
}
}
}
return $data;
}
/**
* @param mixed $data
* @param ?string $format
* @param array<string, mixed> $context
*/
public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool
{
return $data instanceof FindAgentConfigurationResponse;
}
/**
* @param ?string $format
* @return array<class-string|'*'|'object'|string, bool|null>
*/
public function getSupportedTypes(?string $format): array
{
return [
FindAgentConfigurationResponse::class => 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/AgentConfiguration/Infrastructure/Serializer/AgentConfigurationNormalizer.php | centreon/src/Core/AgentConfiguration/Infrastructure/Serializer/AgentConfigurationNormalizer.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AgentConfiguration\Infrastructure\Serializer;
use Core\AgentConfiguration\Domain\Model\AgentConfiguration;
use Core\AgentConfiguration\Domain\Model\ConnectionModeEnum;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
class AgentConfigurationNormalizer implements NormalizerInterface
{
public function __construct(
#[Autowire(service: 'serializer.normalizer.object')]
private readonly NormalizerInterface $normalizer,
) {
}
/**
* @param AgentConfiguration $object
* @param string|null $format
* @param array<string, mixed> $context
*
* @throws \Throwable
*
* @return array<string, mixed>
*/
public function normalize(
mixed $object,
?string $format = null,
array $context = [],
): array {
/** @var array<string, bool|float|int|string> $data */
$data = $this->normalizer->normalize($object, $format, $context);
$data['connection_mode'] = match ($object->getConnectionMode()) {
ConnectionModeEnum::SECURE => 'secure',
ConnectionModeEnum::NO_TLS => 'no-tls',
ConnectionModeEnum::INSECURE => 'insecure',
};
return $data;
}
/**
* @param array<string, mixed> $context
* @param mixed $data
* @param ?string $format
*/
public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool
{
return $data instanceof AgentConfiguration;
}
/**
* @param ?string $format
* @return array<class-string|'*'|'object'|string, bool|null>
*/
public function getSupportedTypes(?string $format): array
{
return [
AgentConfiguration::class => 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/AgentConfiguration/Infrastructure/Repository/DbReadAgentConfigurationRepository.php | centreon/src/Core/AgentConfiguration/Infrastructure/Repository/DbReadAgentConfigurationRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AgentConfiguration\Infrastructure\Repository;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Centreon\Infrastructure\DatabaseConnection;
use Centreon\Infrastructure\RequestParameters\SqlRequestParametersTranslator;
use Core\AgentConfiguration\Application\Repository\ReadAgentConfigurationRepositoryInterface;
use Core\AgentConfiguration\Domain\Model\AgentConfiguration;
use Core\AgentConfiguration\Domain\Model\ConfigurationParameters\CmaConfigurationParameters;
use Core\AgentConfiguration\Domain\Model\ConfigurationParameters\TelegrafConfigurationParameters;
use Core\AgentConfiguration\Domain\Model\ConnectionModeEnum;
use Core\AgentConfiguration\Domain\Model\Poller;
use Core\AgentConfiguration\Domain\Model\Type;
use Core\Common\Domain\TrimmedString;
use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB;
use Core\Common\Infrastructure\Repository\RepositoryTrait;
use Core\MonitoringServer\Infrastructure\Repository\MonitoringServerRepositoryTrait;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
use Core\Security\Token\Domain\Model\JwtToken;
/**
* @phpstan-type _AgentConfiguration array{
* id:int,
* type:string,
* name:string,
* connection_mode:string,
* configuration:string,
* tokens?: JwtToken[]
* }
*/
class DbReadAgentConfigurationRepository extends AbstractRepositoryRDB implements ReadAgentConfigurationRepositoryInterface
{
use RepositoryTrait;
use MonitoringServerRepositoryTrait;
public function __construct(
DatabaseConnection $db,
) {
$this->db = $db;
}
/**
* @inheritDoc
*/
public function existsByName(TrimmedString $name): bool
{
$request = $this->translateDbName(
<<<'SQL'
SELECT 1
FROM `:db`.`agent_configuration`
WHERE name = :name
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':name', $name->value, \PDO::PARAM_STR);
$statement->execute();
return (bool) $statement->fetchColumn();
}
/**
* @inheritDoc
*/
public function find(int $agentConfigurationId): ?AgentConfiguration
{
$sql = <<<'SQL'
SELECT *
FROM `:db`.`agent_configuration` ac
WHERE ac.`id` = :id
SQL;
// Prepare SQL + bind values
$statement = $this->db->prepare($this->translateDbName($sql));
$statement->bindValue(':id', $agentConfigurationId, \PDO::PARAM_INT);
$statement->execute();
if ($result = $statement->fetch()) {
/** @var _AgentConfiguration $result */
return $this->createFromArray($result);
}
return null;
}
/**
* @inheritDoc
*/
public function findPollersByType(Type $type): array
{
$sql = <<<'SQL'
SELECT
rel.`poller_id` as id,
ng.`name`
FROM `:db`.`ac_poller_relation` rel
JOIN `:db`.`agent_configuration` ac
ON rel.ac_id = ac.id
JOIN `:db`.`nagios_server` ng
ON rel.poller_id = ng.id
WHERE ac.`type` = :type
SQL;
// Prepare SQL + bind values
$statement = $this->db->prepare($this->translateDbName($sql));
$statement->bindValue(':type', $type->value, \PDO::PARAM_STR);
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$statement->execute();
// Retrieve data
$pollers = [];
foreach ($statement as $result) {
/** @var array{id:int,name:string} $result */
$pollers[] = new Poller($result['id'], $result['name']);
}
return $pollers;
}
/**
* @inheritDoc
*/
public function findPollersByAcId(int $agentConfigurationId): array
{
$statement = $this->db->prepare($this->translateDbName(
<<<'SQL'
SELECT
rel.`poller_id` as id,
ng.`name`,
(ng.`localhost` = '1' AND NOT EXISTS (
SELECT 1 FROM `:db`.`remote_servers` rs WHERE rs.server_id = ng.id
)) as is_central
FROM `:db`.`ac_poller_relation` rel
JOIN `:db`.`nagios_server` ng
ON rel.poller_id = ng.id
WHERE rel.`ac_id` = :id
SQL
));
$statement->bindValue(':id', $agentConfigurationId, \PDO::PARAM_INT);
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$statement->execute();
// Retrieve data
$pollers = [];
foreach ($statement as $result) {
/** @var array{id:int,name:string,is_central:int} $result */
$pollers[] = new Poller($result['id'], $result['name'], $result['is_central'] === 1);
}
return $pollers;
}
/**
* @inheritDoc
*/
public function findPollersWithBrokerDirective(string $module): array
{
$statement = $this->db->prepare($this->translateDbName(
<<<'SQL'
SELECT
`cfg_nagios_id`
FROM `:db`.`cfg_nagios_broker_module`
WHERE `broker_module` = :module
SQL
));
$statement->bindValue(':module', $module, \PDO::PARAM_STR);
$statement->execute();
return $statement->fetchAll(\PDO::FETCH_COLUMN);
}
/**
* @inheritDoc
*/
public function findAllByRequestParameters(RequestParametersInterface $requestParameters): array
{
$sqlTranslator = new SqlRequestParametersTranslator($requestParameters);
$sqlTranslator->setConcordanceArray([
'name' => 'ac.name',
'type' => 'ac.type',
'poller.id' => 'rel.poller_id',
]);
$request = <<<'SQL'
SELECT SQL_CALC_FOUND_ROWS
ac.id,
ac.name,
ac.type,
ac.connection_mode,
ac.configuration
FROM `:db`.`agent_configuration` ac
INNER JOIN `:db`.`ac_poller_relation` rel
ON ac.id = rel.ac_id
SQL;
// Search
$request .= $sqlTranslator->translateSearchParameterToSql();
$request .= ' GROUP BY ac.name';
// Sort
$sortRequest = $sqlTranslator->translateSortParameterToSql();
$request .= ! is_null($sortRequest)
? $sortRequest
: ' ORDER BY ac.id ASC';
// Pagination
$request .= $sqlTranslator->translatePaginationToSql();
$statement = $this->db->prepare($this->translateDbName($request));
foreach ($sqlTranslator->getSearchValues() as $key => $data) {
$type = key($data);
if ($type !== null) {
$value = $data[$type];
$statement->bindValue($key, $value, $type);
}
}
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$statement->execute();
$result = $this->db->query('SELECT FOUND_ROWS()');
if ($result !== false && ($total = $result->fetchColumn()) !== false) {
$sqlTranslator->getRequestParameters()->setTotal((int) $total);
}
$agentConfigurations = [];
foreach ($statement as $result) {
/** @var _AgentConfiguration $result */
$agentConfigurations[] = $this->createFromArray($result);
}
return $agentConfigurations;
}
/**
* @inheritDoc
*/
public function findAllByRequestParametersAndAccessGroups(
RequestParametersInterface $requestParameters,
array $accessGroups,
): array {
if ($accessGroups === []) {
return [];
}
$accessGroupIds = array_map(
static fn (AccessGroup $accessGroup): int => $accessGroup->getId(),
$accessGroups
);
if (! $this->hasRestrictedAccessToMonitoringServers($accessGroupIds)) {
return $this->findAllByRequestParameters($requestParameters);
}
$sqlTranslator = new SqlRequestParametersTranslator($requestParameters);
$sqlTranslator->setConcordanceArray([
'name' => 'ac.name',
'type' => 'ac.type',
'poller.id' => 'rel.poller_id',
]);
[$accessGroupsBindValues, $accessGroupIdsQuery] = $this->createMultipleBindQuery(
array_map(fn (AccessGroup $accessGroup) => $accessGroup->getId(), $accessGroups),
':acl_'
);
$request = <<<SQL
SELECT
ac.id,
ac.name,
ac.type,
ac.connection_mode,
ac.configuration
FROM `:db`.`agent_configuration` ac
INNER JOIN `:db`.`ac_poller_relation` rel
ON ac.id = rel.ac_id
INNER JOIN `:db`.acl_resources_poller_relations arpr
ON rel.poller_id = arpr.poller_id
INNER JOIN `:db`.acl_res_group_relations argr
ON argr.acl_res_id = arpr.acl_res_id
AND argr.acl_group_id IN ({$accessGroupIdsQuery})
SQL;
// Search
$request .= $search = $sqlTranslator->translateSearchParameterToSql();
$request .= $search !== null
? ' AND '
: ' WHERE ';
$request .= ' ac.id NOT IN (
SELECT rel.ac_id
FROM `ac_poller_relation` rel
LEFT JOIN acl_resources_poller_relations arpr ON rel.poller_id = arpr.poller_id
LEFT JOIN acl_res_group_relations argr ON argr.acl_res_id = arpr.acl_res_id
WHERE argr.acl_group_id IS NULL
)';
$request .= ' GROUP BY ac.name';
// Sort
$sortRequest = $sqlTranslator->translateSortParameterToSql();
$request .= ! is_null($sortRequest)
? $sortRequest
: ' ORDER BY ac.id ASC';
// Pagination
$request .= $sqlTranslator->translatePaginationToSql();
$statement = $this->db->prepare($this->translateDbName($request));
foreach ($sqlTranslator->getSearchValues() as $key => $data) {
$type = key($data);
if ($type !== null) {
$value = $data[$type];
$statement->bindValue($key, $value, $type);
}
}
foreach ($accessGroupsBindValues as $bindKey => $hostGroupId) {
$statement->bindValue($bindKey, $hostGroupId, \PDO::PARAM_INT);
}
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$statement->execute();
// Set total
$result = $this->db->query('SELECT FOUND_ROWS()');
if ($result !== false && ($total = $result->fetchColumn()) !== false) {
$sqlTranslator->getRequestParameters()->setTotal((int) $total);
}
$agentConfigurations = [];
foreach ($statement as $result) {
/** @var _AgentConfiguration $result */
$agentConfigurations[] = $this->createFromArray($result);
}
return $agentConfigurations;
}
/**
* @inheritDoc
*/
public function findByPollerId(int $pollerId): ?AgentConfiguration
{
$statement = $this->db->prepare($this->translateDbName(
<<<'SQL'
SELECT
ac.id,
ac.name,
ac.type,
ac.connection_mode,
ac.configuration
FROM `:db`.`agent_configuration` ac
JOIN `:db`.`ac_poller_relation` rel
ON rel.ac_id = ac.id
WHERE rel.poller_id = :id
SQL
));
$statement->bindValue(':id', $pollerId, \PDO::PARAM_INT);
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$statement->execute();
if ($result = $statement->fetch()) {
/** @var _AgentConfiguration $result */
return $this->createFromArray($result);
}
return null;
}
/**
* @param _AgentConfiguration $row
*
* @throws \Throwable
*
* @return AgentConfiguration
*/
private function createFromArray(array $row): AgentConfiguration
{
/** @var array<string,mixed> $configuration */
$configuration = json_decode(
json: $row['configuration'],
associative: true,
depth: JSON_OBJECT_AS_ARRAY | JSON_THROW_ON_ERROR
);
$type = Type::from($row['type']);
$connectionMode = match ($row['connection_mode']) {
'secure' => ConnectionModeEnum::SECURE,
'no-tls' => ConnectionModeEnum::NO_TLS,
'insecure' => ConnectionModeEnum::INSECURE,
default => throw new \InvalidArgumentException('Invalid connection mode'),
};
return new AgentConfiguration(
id: $row['id'],
name: $row['name'],
type: $type,
connectionMode: $connectionMode,
configuration: match ($type->value) {
Type::TELEGRAF->value => new TelegrafConfigurationParameters($configuration),
Type::CMA->value => new CmaConfigurationParameters($configuration, 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/AgentConfiguration/Infrastructure/Repository/DbWriteAgentConfigurationRepository.php | centreon/src/Core/AgentConfiguration/Infrastructure/Repository/DbWriteAgentConfigurationRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AgentConfiguration\Infrastructure\Repository;
use Adaptation\Database\Connection\Collection\QueryParameters;
use Adaptation\Database\Connection\ValueObject\QueryParameter;
use Core\AgentConfiguration\Application\Repository\WriteAgentConfigurationRepositoryInterface;
use Core\AgentConfiguration\Domain\Model\AgentConfiguration;
use Core\AgentConfiguration\Domain\Model\ConnectionModeEnum;
use Core\AgentConfiguration\Domain\Model\NewAgentConfiguration;
use Core\Common\Domain\Exception\RepositoryException;
use Core\Common\Infrastructure\Repository\DatabaseRepository;
use Core\Common\Infrastructure\Repository\RepositoryTrait;
/**
* Class
*
* @class DbWriteAgentConfigurationRepository
* @package Core\AgentConfiguration\Infrastructure\Repository
*/
class DbWriteAgentConfigurationRepository extends DatabaseRepository implements WriteAgentConfigurationRepositoryInterface
{
use RepositoryTrait;
/**
* @inheritDoc
*/
public function add(NewAgentConfiguration $agentConfiguration): int
{
try {
$query = $this->connection->createQueryBuilder()->insert('`:db`.`agent_configuration`')
->values(
[
'type' => ':type',
'name' => ':name',
'connection_mode' => ':connection_mode',
'configuration' => ':configuration',
]
)->getQuery();
$this->connection->insert(
$this->translateDbName($query),
QueryParameters::create([
QueryParameter::string('type', $agentConfiguration->getType()->value),
QueryParameter::string('name', $agentConfiguration->getName()),
QueryParameter::string(
':connection_mode',
match ($agentConfiguration->getConnectionMode()) {
ConnectionModeEnum::NO_TLS => 'no-tls',
ConnectionModeEnum::SECURE => 'secure',
ConnectionModeEnum::INSECURE => 'insecure',
}
),
QueryParameter::string(
'configuration',
json_encode($agentConfiguration->getConfiguration()->getData(), JSON_THROW_ON_ERROR)
),
])
);
return (int) $this->connection->getLastInsertId();
} catch (\Throwable $exception) {
throw new RepositoryException(
message: 'Error while adding agent configuration',
context: ['type' => $agentConfiguration->getType()->value, 'name' => $agentConfiguration->getName()],
previous: $exception
);
}
}
/**
* @inheritDoc
*/
public function update(AgentConfiguration $agentConfiguration): void
{
try {
$queryBuilder = $this->connection->createQueryBuilder();
$query = $queryBuilder->update('`:db`.`agent_configuration`')
->set('name', ':name')
->set('configuration', ':configuration')
->set('connection_mode', ':connection_mode')
->where($queryBuilder->expr()->equal('id', ':id'))
->getQuery();
$this->connection->update(
$this->translateDbName($query),
QueryParameters::create([
QueryParameter::int('id', $agentConfiguration->getId()),
QueryParameter::string('name', $agentConfiguration->getName()),
QueryParameter::string(
'connection_mode',
match ($agentConfiguration->getConnectionMode()) {
ConnectionModeEnum::NO_TLS => 'no-tls',
ConnectionModeEnum::SECURE => 'secure',
ConnectionModeEnum::INSECURE => 'insecure',
}
),
QueryParameter::string(
'configuration',
json_encode($agentConfiguration->getConfiguration()->getData(), JSON_THROW_ON_ERROR)
),
])
);
} catch (\Throwable $exception) {
throw new RepositoryException(
message: 'Error while updating agent configuration',
context: ['id' => $agentConfiguration->getId(), 'name' => $agentConfiguration->getName()],
previous: $exception
);
}
}
/**
* @inheritDoc
*/
public function delete(int $id): void
{
try {
$queryBuilder = $this->connection->createQueryBuilder();
$query = $queryBuilder->delete('`:db`.`agent_configuration`')
->where($queryBuilder->expr()->equal('id', ':id'))
->getQuery();
$this->connection->delete(
$this->translateDbName($query),
QueryParameters::create([QueryParameter::int('id', $id)])
);
} catch (\Throwable $exception) {
throw new RepositoryException(
message: 'Error while deleting agent configuration',
context: ['id' => $id],
previous: $exception
);
}
}
/**
* @inheritDoc
*/
public function linkToPollers(int $agentConfigurationId, array $pollerIds): void
{
try {
$query = $this->connection->createQueryBuilder()->insert('`:db`.`ac_poller_relation`')
->values(
[
'ac_id' => ':ac_id',
'poller_id' => ':poller_id',
]
)->getQuery();
foreach ($pollerIds as $poller) {
$pollerId = $poller;
$this->connection->insert(
$this->translateDbName($query),
QueryParameters::create([
QueryParameter::int('ac_id', $agentConfigurationId),
QueryParameter::int('poller_id', $pollerId),
])
);
}
} catch (\Throwable $exception) {
throw new RepositoryException(
message: 'Error while linking agent configuration with pollers',
context: ['agentConfigurationId' => $agentConfigurationId, 'pollerIds' => $pollerIds],
previous: $exception
);
}
}
/**
* @inheritDoc
*/
public function removePollers(int $agentConfigurationId): void
{
try {
$queryBuilder = $this->connection->createQueryBuilder();
$query = $queryBuilder->delete('`:db`.`ac_poller_relation`')
->where($queryBuilder->expr()->equal('ac_id', ':ac_id'))
->getQuery();
$this->connection->delete(
$this->translateDbName($query),
QueryParameters::create([QueryParameter::int('ac_id', $agentConfigurationId)])
);
} catch (\Throwable $exception) {
throw new RepositoryException(
message: 'Error while removing pollers from agent configuration',
context: ['ac_id' => $agentConfigurationId],
previous: $exception
);
}
}
/**
* @inheritDoc
*/
public function removePoller(int $agentConfigurationId, int $pollerId): void
{
try {
$queryBuilder = $this->connection->createQueryBuilder();
$query = $queryBuilder->delete('`:db`.`ac_poller_relation`')
->where($queryBuilder->expr()->equal('ac_id', ':ac_id'))
->andWhere($queryBuilder->expr()->equal('poller_id', ':poller_id'))
->getQuery();
$this->connection->delete(
$this->translateDbName($query),
QueryParameters::create([
QueryParameter::int('ac_id', $agentConfigurationId),
QueryParameter::int('poller_id', $pollerId),
])
);
} catch (\Throwable $exception) {
throw new RepositoryException(
message: 'Error while removing a poller from agent configuration',
context: ['ac_id' => $agentConfigurationId, 'poller_id' => $pollerId],
previous: $exception
);
}
}
/**
* @inheritDoc
*/
public function addBrokerDirective(string $module, array $pollerIds): void
{
try {
$query = $this->connection->createQueryBuilder()->insert('`:db`.`cfg_nagios_broker_module`')
->values(
[
'bk_mod_id' => ':bk_mod_id',
'cfg_nagios_id' => ':cfg_nagios_id',
'broker_module' => ':broker_module',
]
)->getQuery();
foreach ($pollerIds as $poller) {
$pollerId = $poller;
$this->connection->insert(
$this->translateDbName($query),
QueryParameters::create([
QueryParameter::null('bk_mod_id'),
QueryParameter::int('cfg_nagios_id', $pollerId),
QueryParameter::string('broker_module', $module),
])
);
}
} catch (\Exception $exception) {
throw new RepositoryException(
message: 'Error while adding broker directive in agent configuration',
context: ['pollerIds' => $pollerIds, 'broker_module' => $module],
previous: $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/AgentConfiguration/Infrastructure/API/FindAgentConfiguration/FindAgentConfigurationController.php | centreon/src/Core/AgentConfiguration/Infrastructure/API/FindAgentConfiguration/FindAgentConfigurationController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AgentConfiguration\Infrastructure\API\FindAgentConfiguration;
use Centreon\Application\Controller\AbstractController;
use Core\AgentConfiguration\Application\UseCase\FindAgentConfiguration\FindAgentConfiguration;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Infrastructure\Common\Api\StandardPresenter;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Http\Attribute\IsGranted;
#[IsGranted(
'read_agent_configuration',
null,
'You are not allowed to access poller/agent configurations',
Response::HTTP_FORBIDDEN
)]
#[IsGranted(
'read_agent_configuration_pollers',
'id',
'poller/agent configuration could not be found',
Response::HTTP_NOT_FOUND
)]
final class FindAgentConfigurationController extends AbstractController
{
public function __invoke(
int $id,
FindAgentConfiguration $useCase,
StandardPresenter $presenter,
): Response {
$response = $useCase($id);
if ($response instanceof ResponseStatusInterface) {
return $this->createResponse($response);
}
return JsonResponse::fromJsonString(
$presenter->present($response, ['groups' => ['AgentConfiguration:Read']])
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/AgentConfiguration/Infrastructure/API/UpdateAgentConfiguration/UpdateAgentConfigurationController.php | centreon/src/Core/AgentConfiguration/Infrastructure/API/UpdateAgentConfiguration/UpdateAgentConfigurationController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AgentConfiguration\Infrastructure\API\UpdateAgentConfiguration;
use Centreon\Application\Controller\AbstractController;
use Centreon\Domain\Log\LoggerTrait;
use Core\AgentConfiguration\Application\UseCase\UpdateAgentConfiguration\UpdateAgentConfiguration;
use Core\AgentConfiguration\Application\UseCase\UpdateAgentConfiguration\UpdateAgentConfigurationRequest;
use Core\AgentConfiguration\Domain\Model\ConnectionModeEnum;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\Infrastructure\Common\Api\DefaultPresenter;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
final class UpdateAgentConfigurationController extends AbstractController
{
use LoggerTrait;
public function __invoke(
int $id,
Request $request,
UpdateAgentConfiguration $useCase,
DefaultPresenter $presenter,
): Response {
$this->denyAccessUnlessGrantedForApiConfiguration();
try {
$updateAcRequest = $this->createRequest($id, $request);
$useCase($updateAcRequest, $presenter);
} catch (\InvalidArgumentException $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
$presenter->setResponseStatus(new InvalidArgumentResponse($ex));
} catch (\Throwable $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
$presenter->setResponseStatus(new ErrorResponse($ex));
}
return $presenter->show();
}
/**
* @param int $id
* @param Request $request
*
* @throws \InvalidArgumentException
*
* @return UpdateAgentConfigurationRequest
*/
private function createRequest(int $id, Request $request): UpdateAgentConfigurationRequest
{
/**
* @var array{
* name:string,
* type:string,
* connection_mode:string|null,
* poller_ids:int[],
* configuration:array<string,mixed>
* } $data
*/
$data = $this->validateAndRetrieveDataSent($request, __DIR__ . '/UpdateAgentConfigurationSchema.json');
$schemaFile = match ($data['type']) {
'telegraf' => 'TelegrafConfigurationSchema.json',
'centreon-agent' => 'CmaConfigurationSchema.json',
default => throw new \InvalidArgumentException(sprintf("Unknown parameter type with value '%s'", $data['type'])),
};
$this->validateDataSent($request, __DIR__ . "/../Schema/{$schemaFile}");
$updateRequest = new UpdateAgentConfigurationRequest();
$updateRequest->id = $id;
$updateRequest->type = $data['type'];
$updateRequest->name = $data['name'];
$updateRequest->connectionMode = match ($data['connection_mode']) {
'no-tls' => ConnectionModeEnum::NO_TLS,
'insecure' => ConnectionModeEnum::INSECURE,
'secure' => ConnectionModeEnum::SECURE,
default => ConnectionModeEnum::SECURE,
};
$updateRequest->pollerIds = $data['poller_ids'];
$updateRequest->configuration = $data['configuration'];
return $updateRequest;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/AgentConfiguration/Infrastructure/API/DeleteAgentConfiguration/DeleteAgentConfigurationController.php | centreon/src/Core/AgentConfiguration/Infrastructure/API/DeleteAgentConfiguration/DeleteAgentConfigurationController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AgentConfiguration\Infrastructure\API\DeleteAgentConfiguration;
use Centreon\Application\Controller\AbstractController;
use Centreon\Domain\Log\LoggerTrait;
use Core\AgentConfiguration\Application\UseCase\DeleteAgentConfiguration\DeleteAgentConfiguration;
use Core\Infrastructure\Common\Api\DefaultPresenter;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
final class DeleteAgentConfigurationController extends AbstractController
{
use LoggerTrait;
/**
* @param int $id
* @param DeleteAgentConfiguration $useCase
* @param DefaultPresenter $presenter
*
* @throws AccessDeniedException
*
* @return Response
*/
public function __invoke(
int $id,
DeleteAgentConfiguration $useCase,
DefaultPresenter $presenter,
): Response {
$this->denyAccessUnlessGrantedForApiConfiguration();
$useCase($id, $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/AgentConfiguration/Infrastructure/API/FindAgentConfigurations/FindAgentConfigurationsController.php | centreon/src/Core/AgentConfiguration/Infrastructure/API/FindAgentConfigurations/FindAgentConfigurationsController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AgentConfiguration\Infrastructure\API\FindAgentConfigurations;
use Centreon\Application\Controller\AbstractController;
use Core\AgentConfiguration\Application\UseCase\FindAgentConfigurations\FindAgentConfigurations;
use Symfony\Component\HttpFoundation\Response;
final class FindAgentConfigurationsController extends AbstractController
{
public function __invoke(FindAgentConfigurations $useCase, FindAgentConfigurationsPresenter $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/AgentConfiguration/Infrastructure/API/FindAgentConfigurations/FindAgentConfigurationsPresenter.php | centreon/src/Core/AgentConfiguration/Infrastructure/API/FindAgentConfigurations/FindAgentConfigurationsPresenter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AgentConfiguration\Infrastructure\API\FindAgentConfigurations;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\AgentConfiguration\Application\UseCase\FindAgentConfigurations\{
FindAgentConfigurationsPresenterInterface as PresenterInterface,
FindAgentConfigurationsResponse
};
use Core\Application\Common\UseCase\{
AbstractPresenter,
ResponseStatusInterface
};
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
final class FindAgentConfigurationsPresenter extends AbstractPresenter implements PresenterInterface
{
public function __construct(
protected RequestParametersInterface $requestParameters,
PresenterFormatterInterface $presenterFormatter,
) {
parent::__construct($presenterFormatter);
}
public function presentResponse(FindAgentConfigurationsResponse|ResponseStatusInterface $data): void
{
if ($data instanceof ResponseStatusInterface) {
$this->setResponseStatus($data);
} else {
$result = [];
foreach ($data->agentConfigurations as $agentConfiguration) {
$result[] = [
'id' => $agentConfiguration->id,
'name' => $agentConfiguration->name,
'type' => $agentConfiguration->type->value,
'pollers' => array_map(
fn ($poller) => ['id' => $poller->id, 'name' => $poller->name, 'is_central' => $poller->isCentral],
$agentConfiguration->pollers
),
];
}
$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/AgentConfiguration/Infrastructure/API/DeleteAgentConfigurationPollerLink/DeleteAgentConfigurationPollerLinkController.php | centreon/src/Core/AgentConfiguration/Infrastructure/API/DeleteAgentConfigurationPollerLink/DeleteAgentConfigurationPollerLinkController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AgentConfiguration\Infrastructure\API\DeleteAgentConfigurationPollerLink;
use Centreon\Application\Controller\AbstractController;
use Centreon\Domain\Log\LoggerTrait;
use Core\AgentConfiguration\Application\UseCase\DeleteAgentConfigurationPollerLink\DeleteAgentConfigurationPollerLink;
use Core\Infrastructure\Common\Api\DefaultPresenter;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
final class DeleteAgentConfigurationPollerLinkController extends AbstractController
{
use LoggerTrait;
/**
* @param int $acId
* @param int $pollerId
* @param DeleteAgentConfigurationPollerLink $useCase
* @param DefaultPresenter $presenter
*
* @throws AccessDeniedException
*
* @return Response
*/
public function __invoke(
int $acId,
int $pollerId,
DeleteAgentConfigurationPollerLink $useCase,
DefaultPresenter $presenter,
): Response {
$this->denyAccessUnlessGrantedForApiConfiguration();
$useCase($acId, $pollerId, $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/AgentConfiguration/Infrastructure/API/AddAgentConfiguration/AddAgentConfigurationController.php | centreon/src/Core/AgentConfiguration/Infrastructure/API/AddAgentConfiguration/AddAgentConfigurationController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AgentConfiguration\Infrastructure\API\AddAgentConfiguration;
use Centreon\Application\Controller\AbstractController;
use Centreon\Domain\Log\LoggerTrait;
use Core\AgentConfiguration\Application\UseCase\AddAgentConfiguration\AddAgentConfiguration;
use Core\AgentConfiguration\Application\UseCase\AddAgentConfiguration\AddAgentConfigurationRequest;
use Core\AgentConfiguration\Domain\Model\ConnectionModeEnum;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
final class AddAgentConfigurationController extends AbstractController
{
use LoggerTrait;
public function __invoke(
Request $request,
AddAgentConfiguration $useCase,
AddAgentConfigurationPresenter $presenter,
): Response {
$this->denyAccessUnlessGrantedForApiConfiguration();
try {
$addAcRequest = $this->createRequest($request);
$useCase($addAcRequest, $presenter);
} catch (\InvalidArgumentException $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
$presenter->setResponseStatus(new InvalidArgumentResponse($ex));
} catch (\Throwable $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
$presenter->setResponseStatus(new ErrorResponse($ex));
}
return $presenter->show();
}
/**
* @param Request $request
*
* @throws \InvalidArgumentException
*
* @return AddAgentConfigurationRequest
*/
private function createRequest(Request $request): AddAgentConfigurationRequest
{
/**
* @var array{
* name:string,
* type:string,
* connection_mode:string|null,
* poller_ids:int[],
* configuration:array<string,mixed>
* } $data
*/
$data = $this->validateAndRetrieveDataSent($request, __DIR__ . '/AddAgentConfigurationSchema.json');
$schemaFile = match ($data['type']) {
'telegraf' => 'TelegrafConfigurationSchema.json',
'centreon-agent' => 'CmaConfigurationSchema.json',
default => throw new \InvalidArgumentException(sprintf("Unknown parameter type with value '%s'", $data['type'])),
};
$this->validateDataSent($request, __DIR__ . "/../Schema/{$schemaFile}");
$addRequest = new AddAgentConfigurationRequest();
$addRequest->type = $data['type'];
$addRequest->name = $data['name'];
$addRequest->connectionMode = match ($data['connection_mode']) {
'no-tls' => ConnectionModeEnum::NO_TLS,
'insecure' => ConnectionModeEnum::INSECURE,
'secure' => ConnectionModeEnum::SECURE,
default => ConnectionModeEnum::SECURE,
};
$addRequest->pollerIds = $data['poller_ids'];
$addRequest->configuration = $data['configuration'];
return $addRequest;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/AgentConfiguration/Infrastructure/API/AddAgentConfiguration/AddAgentConfigurationPresenter.php | centreon/src/Core/AgentConfiguration/Infrastructure/API/AddAgentConfiguration/AddAgentConfigurationPresenter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\AgentConfiguration\Infrastructure\API\AddAgentConfiguration;
use Core\AgentConfiguration\Application\UseCase\AddAgentConfiguration\AddAgentConfigurationPresenterInterface;
use Core\AgentConfiguration\Application\UseCase\AddAgentConfiguration\AddAgentConfigurationResponse;
use Core\AgentConfiguration\Domain\Model\ConnectionModeEnum;
use Core\AgentConfiguration\Domain\Model\Poller;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\CreatedResponse;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Infrastructure\Common\Presenter\PresenterTrait;
class AddAgentConfigurationPresenter extends AbstractPresenter implements AddAgentConfigurationPresenterInterface
{
use PresenterTrait;
/**
* @inheritDoc
*/
public function presentResponse(AddAgentConfigurationResponse|ResponseStatusInterface $response): void
{
if ($response instanceof ResponseStatusInterface) {
$this->setResponseStatus($response);
} else {
$this->present(
new CreatedResponse(
$response->id,
[
'id' => $response->id,
'name' => $response->name,
'type' => $response->type->value,
'configuration' => $response->configuration,
'connection_mode' => $this->connectionModeToString($response->connectionMode),
'pollers' => array_map(fn (Poller $poller) => ['id' => $poller->id, 'name' => $poller->name], $response->pollers),
]
)
);
// NOT setting location as required route does not currently exist
}
}
private function ConnectionModeToString(ConnectionModeEnum $connectionMode): string
{
return match ($connectionMode) {
ConnectionModeEnum::SECURE => 'secure',
ConnectionModeEnum::NO_TLS => 'no-tls',
ConnectionModeEnum::INSECURE => 'insecure',
};
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Dashboard/Application/Event/DashboardUpdatedEvent.php | centreon/src/Core/Dashboard/Application/Event/DashboardUpdatedEvent.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Dashboard\Application\Event;
final readonly class DashboardUpdatedEvent
{
/**
* @param int $dashboardId
* @param string $directory
* @param string $content
* @param string $filename
* @param int|null $thumbnailId
*/
public function __construct(
private int $dashboardId,
private string $directory,
private string $content,
private string $filename,
private int|null $thumbnailId = null,
) {
}
/**
* @return string
*/
public function getContent(): string
{
return $this->content;
}
public function getDashboardId(): int
{
return $this->dashboardId;
}
public function getDirectory(): string
{
return $this->directory;
}
public function getFilename(): string
{
return $this->filename;
}
public function getThumbnailId(): int|null
{
return $this->thumbnailId;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Dashboard/Application/UseCase/ShareDashboard/ShareDashboardValidator.php | centreon/src/Core/Dashboard/Application/UseCase/ShareDashboard/ShareDashboardValidator.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Dashboard\Application\UseCase\ShareDashboard;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Core\Contact\Application\Repository\ReadContactGroupRepositoryInterface;
use Core\Contact\Application\Repository\ReadContactRepositoryInterface;
use Core\Dashboard\Application\Exception\DashboardException;
use Core\Dashboard\Application\Repository\ReadDashboardRepositoryInterface;
use Core\Dashboard\Application\Repository\ReadDashboardShareRepositoryInterface;
use Core\Dashboard\Domain\Model\Role\DashboardContactGroupRole;
use Core\Dashboard\Domain\Model\Role\DashboardContactRole;
use Core\Dashboard\Domain\Model\Role\DashboardGlobalRole;
use Core\Dashboard\Domain\Model\Role\DashboardSharingRole;
use Core\Dashboard\Infrastructure\Model\DashboardSharingRoleConverter;
use Utility\Difference\BasicDifference;
class ShareDashboardValidator
{
public function __construct(
private readonly ContactInterface $user,
private readonly ReadDashboardRepositoryInterface $readDashboardRepository,
private readonly ReadDashboardShareRepositoryInterface $readDashboardShareRepository,
private readonly ReadContactRepositoryInterface $contactRepository,
private readonly ReadContactGroupRepositoryInterface $readContactGroupRepository,
) {
}
/**
* @param int $dashboardId
* @param bool $isAdmin
*
* @throws DashboardException|\Throwable
*/
public function validateDashboard(int $dashboardId, bool $isAdmin): void
{
// Validate Dashboard Exists
if ($this->readDashboardRepository->existsOne($dashboardId) === false) {
throw DashboardException::theDashboardDoesNotExist($dashboardId);
}
// Validate Dashboard is shared as editor to the user.
if (
! $isAdmin
&& ! $this->readDashboardShareRepository->existsAsEditor($dashboardId, $this->user)
) {
throw DashboardException::dashboardAccessRightsNotAllowedForWriting($dashboardId);
}
}
/**
* Validate request contacts against the following rules:
* - The contacts should exist
* - The contacts should be unique in the request
* - The contacts should have Dashboard related ACLs
* - The contacts should have sufficient ACLs for their given roles
* (e.g a Viewer in ACLs can not be shared as Editor)
* - If the user executing the request is not an admin, the contacts should be member of his access groups
*
* @param bool $isAdmin
* @param array<array{id: int, role: string}> $contacts
* @param int[] $contactIdsInUserContactGroups
*
* @throws DashboardException|\Throwable
*/
public function validateContactsForCloud(
bool $isAdmin,
array $contacts,
array $contactIdsInUserContactGroups = [],
): void {
$contactIds = array_map(static fn (array $contact): int => $contact['id'], $contacts);
$this->validateContactsExist($contactIds);
$this->validateContactsAreUnique($contactIds);
/**
* Retrieve the contacts which have Dashboard's ACLs.
*/
$dashboardContactRoles = $this->readDashboardShareRepository->findContactsWithAccessRightByContactIds(
$contactIds
);
$this->validateContactsHaveDashboardACLs($dashboardContactRoles, $contactIds);
$contactsByIdAndRole = [];
foreach ($contacts as $contact) {
$contactsByIdAndRole[$contact['id']] = $contact['role'];
}
$this->validateContactsHaveSufficientRightForSharingRole($contactsByIdAndRole, $dashboardContactRoles);
// If the current user is not admin, the shared contacts should be member of his contact groups.
if (! $isAdmin) {
$this->validateContactsAreInTheSameContactGroupThanCurrentUser($contactIds, $contactIdsInUserContactGroups);
}
}
/**
* Validate request contacts against the following rules:
* - The contacts should exist
* - The contacts should be unique in the request
* - The contacts should have Dashboard related ACLs
* - The contacts should have sufficient ACLs for their given roles
* (e.g a Viewer in ACLs can not be shared as Editor)
* - If the user executing the request is not an admin, the contacts should be member of his access groups
*
* @param bool $isAdmin
* @param array<array{id: int, role: string}> $contacts
* @param int[] $contactIdsInUserAccessGroups
*
* @throws DashboardException|\Throwable
*/
public function validateContactsForOnPremise(
bool $isAdmin,
array $contacts,
array $contactIdsInUserAccessGroups = [],
): void {
$contactIds = array_map(static fn (array $contact): int => $contact['id'], $contacts);
$this->validateContactsExist($contactIds);
$this->validateContactsAreUnique($contactIds);
/**
* Retrieve the contacts which have Dashboard's ACLs.
*/
$dashboardContactRoles = $this->readDashboardShareRepository->findContactsWithAccessRightByContactIds(
$contactIds
);
/**
* As the Admins does not have concrete ACLs,
* it is needed to retrieve and add them to the list of users with valid roles.
*/
$adminUsers = $this->contactRepository->findAdminsByIds($contactIds);
foreach ($adminUsers as $adminUser) {
$dashboardContactRoles[] = new DashboardContactRole(
$adminUser->getId(),
$adminUser->getName(),
$adminUser->getEmail(),
[DashboardGlobalRole::Administrator]
);
}
$this->validateContactsHaveDashboardACLs($dashboardContactRoles, $contactIds);
$contactsByIdAndRole = [];
foreach ($contacts as $contact) {
$contactsByIdAndRole[$contact['id']] = $contact['role'];
}
$this->validateContactsHaveSufficientRightForSharingRole($contactsByIdAndRole, $dashboardContactRoles);
// If the current user is not admin, the shared contacts should be member of his access groups.
if (! $isAdmin) {
$this->validateContactsAreInTheSameAccessGroupThanCurrentUser($contactIds, $contactIdsInUserAccessGroups);
}
}
/**
* Validate request contact groups against the following rules:
* - The contact groups should exist
* - The contact groups should be unique in the request
* - The contact groups should have Dashboard related ACLs
* - The contacts should have sufficient ACLs for their given roles
* (e.g a Viewer in ACLs can not be shared as Editor)
* - If the user executing the request is not an admin, the contacts should be member of his contact groups
*
* @param bool $isAdmin
* @param array<array{id: int, role: string}> $contactGroups
* @param int[] $userContactGroupIds
*
* @throws DashboardException|\Throwable
*/
public function validateContactGroupsForOnPremise(
bool $isAdmin,
array $contactGroups,
array $userContactGroupIds = [],
): void {
// Validate contact groups exists
$contactGroupIds = array_map(static fn (array $contactGroup): int => $contactGroup['id'], $contactGroups);
$this->validateContactGroupsExist($contactGroupIds);
$this->validateContactGroupsAreUnique($contactGroupIds);
$dashboardContactGroupRoles = $this->readDashboardShareRepository
->findContactGroupsWithAccessRightByContactGroupIds($contactGroupIds);
$this->validateContactGroupsHaveDashboardACLs($dashboardContactGroupRoles, $contactGroupIds);
$this->validateContactGroupsHaveSufficientRightForSharingRole($contactGroups, $dashboardContactGroupRoles);
if (! $isAdmin) {
$this->validateContactGroupsAreInCurrentUserContactGroups($contactGroupIds, $userContactGroupIds);
}
}
/**
* Validate request contact groups against the following rules:
* - The contact groups should exist
* - The contact groups should be unique in the request
* - If the user executing the request is not an admin, the contactgroups shoul be part of his contact groups
*
* @param bool $isAdmin
* @param array<array{id: int, role: string}> $contactGroups
* @param int[] $userContactGroupIds
*
* @throws DashboardException|\Throwable
*/
public function validateContactGroupsForCloud(
bool $isAdmin,
array $contactGroups,
array $userContactGroupIds = [],
): void {
// Validate contact groups exists
$contactGroupIds = array_map(static fn (array $contactGroup): int => $contactGroup['id'], $contactGroups);
$this->validateContactGroupsExist($contactGroupIds);
$this->validateContactGroupsAreUnique($contactGroupIds);
if (! $isAdmin) {
$this->validateContactGroupsAreInCurrentUserContactGroups($contactGroupIds, $userContactGroupIds);
}
}
/**
* @param int[] $contactIds
*
* @throws DashboardException
*/
private function validateContactsExist(array $contactIds): void
{
if (
! empty(
($nonexistentUsers = array_diff($contactIds, $this->contactRepository->exist($contactIds)))
)
) {
throw DashboardException::theContactsDoNotExist($nonexistentUsers);
}
}
/**
* @param int[] $contactIds
*
* @throws DashboardException
*/
private function validateContactsAreUnique(array $contactIds): void
{
if (count(array_flip($contactIds)) < count($contactIds)) {
throw DashboardException::contactForShareShouldBeUnique();
}
}
/**
* Validate that contacts in the request are contacts with Dashboard ACLs.
*
* A user without Dashboard ACLs can not be shared on a dashboard.
*
* @param DashboardContactRole[] $dashboardContactRoles
* @param int[] $contactIds
*
* @throws DashboardException
*/
private function validateContactsHaveDashboardACLs(array $dashboardContactRoles, array $contactIds): void
{
$dashboardContactRoleIds = array_map(
static fn (DashboardContactRole $dashboardContactRole) => $dashboardContactRole->getContactId(),
$dashboardContactRoles
);
$contactIdsDifference = new BasicDifference($contactIds, $dashboardContactRoleIds);
if ($contactIdsDifference->getRemoved() !== []) {
throw DashboardException::theContactsDoesNotHaveDashboardAccessRights($contactIdsDifference->getRemoved());
}
}
/**
* @param DashboardContactGroupRole[] $dashboardContactGroupRoles
* @param int[] $contactGroupIds
*
* @throws DashboardException
*/
private function validateContactGroupsHaveDashboardACLs(
array $dashboardContactGroupRoles,
array $contactGroupIds,
): void {
$dashboardContactGroupRoleIds = array_map(
static fn (DashboardContactGroupRole $dashboardContactRole) => $dashboardContactRole->getContactGroupId(),
$dashboardContactGroupRoles
);
$contactGroupIdsDifference = new BasicDifference($contactGroupIds, $dashboardContactGroupRoleIds);
if ($contactGroupIdsDifference->getRemoved() !== []) {
throw DashboardException::theContactGroupsDoesNotHaveDashboardAccessRights(
$contactGroupIdsDifference->getRemoved()
);
}
}
/**
* @param array<int, string> $contactsByIdAndRole
* @param DashboardContactRole[] $dashboardContactRoles
*
* @throws DashboardException
*/
private function validateContactsHaveSufficientRightForSharingRole(
array $contactsByIdAndRole,
array $dashboardContactRoles,
): void {
foreach ($dashboardContactRoles as $dashboardContactRole) {
if (
DashboardSharingRoleConverter::fromString($contactsByIdAndRole[$dashboardContactRole->getContactId()])
!== DashboardSharingRole::Viewer
&& $dashboardContactRole->getMostPermissiveRole() === DashboardGlobalRole::Viewer
) {
throw DashboardException::notSufficientAccessRightForUser(
$dashboardContactRole->getContactName(),
$contactsByIdAndRole[$dashboardContactRole->getContactId()]
);
}
}
}
/**
* @param array<array{id:int, role:string}> $contactGroups
* @param DashboardContactGroupRole[] $dashboardContactGroupRoles
*
* @throws DashboardException
*/
private function validateContactGroupsHaveSufficientRightForSharingRole(
array $contactGroups,
array $dashboardContactGroupRoles,
): void {
$contactGroupByIdAndRole = [];
foreach ($contactGroups as $contactGroup) {
$contactGroupByIdAndRole[$contactGroup['id']] = $contactGroup['role'];
}
foreach ($dashboardContactGroupRoles as $dashboardContactGroupRole) {
if (
DashboardSharingRoleConverter::fromString(
$contactGroupByIdAndRole[$dashboardContactGroupRole->getContactGroupId()]
) !== DashboardSharingRole::Viewer
&& $dashboardContactGroupRole->getMostPermissiveRole() === DashboardGlobalRole::Viewer
) {
throw DashboardException::notSufficientAccessRightForContactGroup(
$dashboardContactGroupRole->getContactGroupName(),
$contactGroupByIdAndRole[$dashboardContactGroupRole->getContactGroupId()]
);
}
}
}
/**
* @param int[] $requestContactIds
* @param int[] $contactIdsInUserContactGroups
*
* @throws DashboardException
*/
private function validateContactsAreInTheSameContactGroupThanCurrentUser(
array $requestContactIds,
array $contactIdsInUserContactGroups,
): void {
$contactDifference = new BasicDifference($requestContactIds, $contactIdsInUserContactGroups);
if ($contactDifference->getRemoved() !== []) {
throw DashboardException::userAreNotInContactGroups($contactDifference->getRemoved());
}
}
/**
* @param int[] $requestContactIds
* @param int[] $contactIdsInUserAccessGroups
*
* @throws DashboardException
*/
private function validateContactsAreInTheSameAccessGroupThanCurrentUser(
array $requestContactIds,
array $contactIdsInUserAccessGroups,
): void {
$contactDifference = new BasicDifference($requestContactIds, $contactIdsInUserAccessGroups);
if ($contactDifference->getRemoved() !== []) {
throw DashboardException::userAreNotInAccessGroups($contactDifference->getRemoved());
}
}
/**
* @param int[] $contactGroupIds
* @param int[] $userContactGroupIds
*
* @throws DashboardException
*/
private function validateContactGroupsAreInCurrentUserContactGroups(
array $contactGroupIds,
array $userContactGroupIds,
): void {
$contactGroupIdsDifference = new BasicDifference($contactGroupIds, $userContactGroupIds);
if ($contactGroupIdsDifference->getRemoved() !== []) {
throw DashboardException::contactGroupIsNotInUserContactGroups(
$contactGroupIdsDifference->getRemoved()
);
}
}
/**
* @param int[] $contactGroupIds
*
* @throws DashboardException|\Throwable
*/
private function validateContactGroupsExist(array $contactGroupIds): void
{
if (
! empty(
($nonexistentContactGroups = array_diff(
$contactGroupIds,
$this->readContactGroupRepository->exist($contactGroupIds)
))
)
) {
throw DashboardException::theContactGroupsDoNotExist($nonexistentContactGroups);
}
}
/**
* @param int[] $contactGroupIds
*
* @throws DashboardException
*/
private function validateContactGroupsAreUnique(array $contactGroupIds): void
{
if (count(array_flip($contactGroupIds)) < count($contactGroupIds)) {
throw DashboardException::contactGroupForShareShouldBeUnique();
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Dashboard/Application/UseCase/ShareDashboard/ShareDashboardRequest.php | centreon/src/Core/Dashboard/Application/UseCase/ShareDashboard/ShareDashboardRequest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Dashboard\Application\UseCase\ShareDashboard;
final class ShareDashboardRequest
{
public int $dashboardId = 0;
/**
* @var array<array{
* id: int,
* role: string
* }>
*/
public array $contacts = [];
/**
* @var array<array{
* id: int,
* role: string
* }>
*/
public array $contactGroups = [];
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Dashboard/Application/UseCase/ShareDashboard/ShareDashboardPresenterInterface.php | centreon/src/Core/Dashboard/Application/UseCase/ShareDashboard/ShareDashboardPresenterInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Dashboard\Application\UseCase\ShareDashboard;
use Core\Application\Common\UseCase\ResponseStatusInterface;
interface ShareDashboardPresenterInterface
{
/**
* @param ResponseStatusInterface $response
*/
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/Dashboard/Application/UseCase/ShareDashboard/ShareDashboard.php | centreon/src/Core/Dashboard/Application/UseCase/ShareDashboard/ShareDashboard.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Dashboard\Application\UseCase\ShareDashboard;
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\InvalidArgumentResponse;
use Core\Application\Common\UseCase\NoContentResponse;
use Core\Application\Common\UseCase\NotFoundResponse;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Contact\Application\Repository\ReadContactGroupRepositoryInterface;
use Core\Contact\Application\Repository\ReadContactRepositoryInterface;
use Core\Contact\Domain\Model\ContactGroup;
use Core\Dashboard\Application\Exception\DashboardException;
use Core\Dashboard\Application\Repository\WriteDashboardShareRepositoryInterface;
use Core\Dashboard\Domain\Model\DashboardRights;
use Core\Dashboard\Domain\Model\Role\TinyRole;
use Core\Dashboard\Infrastructure\Model\DashboardSharingRoleConverter;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
/** @package Core\Dashboard\Application\UseCase\ShareDashboard */
final class ShareDashboard
{
use LoggerTrait;
public const AUTHORIZED_ACL_GROUPS = ['customer_admin_acl'];
public function __construct(
private readonly DashboardRights $rights,
private readonly ShareDashboardValidator $validator,
private readonly WriteDashboardShareRepositoryInterface $writeDashboardShareRepository,
private readonly ReadContactRepositoryInterface $readContactRepository,
private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepository,
private readonly ReadContactGroupRepositoryInterface $readContactGroupRepository,
private readonly ContactInterface $user,
private readonly DataStorageEngineInterface $dataStorageEngine,
private readonly bool $isCloudPlatform,
) {
}
public function __invoke(ShareDashboardRequest $request): ResponseStatusInterface
{
try {
$isUserAdmin = $this->isUserAdmin();
$contactIdsRelationsToDelete = [];
$this->validator->validateDashboard(
dashboardId: $request->dashboardId,
isAdmin: $isUserAdmin,
);
if ($isUserAdmin) {
$this->isCloudPlatform
? $this->validator->validateContactsForCloud(isAdmin: true, contacts: $request->contacts)
: $this->validator->validateContactsForOnPremise(isAdmin: true, contacts: $request->contacts);
$this->isCloudPlatform
? $this->validator->validateContactGroupsForCloud(isAdmin: true, contactGroups: $request->contactGroups)
: $this->validator->validateContactGroupsForOnPremise(isAdmin: true, contactGroups: $request->contactGroups);
} else {
$currentUserContactGroupIds = $this->findCurrentUserContactGroupIds();
if ($this->isCloudPlatform) {
$contactIdsInCurrentUserContactGroups = $this->readContactRepository->findContactIdsByContactGroups(
$currentUserContactGroupIds
);
$this->validator->validateContactsForCloud(
isAdmin: false,
contacts: $request->contacts,
contactIdsInUserContactGroups: $contactIdsInCurrentUserContactGroups,
);
$this->validator->validateContactGroupsForCloud(
isAdmin: false,
contactGroups: $request->contactGroups,
userContactGroupIds: $currentUserContactGroupIds,
);
$contactIdsRelationsToDelete = $contactIdsInCurrentUserContactGroups;
} else {
$contactIdsInUserAccessGroups = $this->readContactRepository->findContactIdsByAccessGroups(
$this->findCurrentUserAccessGroupIds()
);
$this->validator->validateContactsForOnPremise(
isAdmin: false,
contacts: $request->contacts,
contactIdsInUserAccessGroups: $contactIdsInUserAccessGroups,
);
$this->validator->validateContactGroupsForOnPremise(
isAdmin: false,
contactGroups: $request->contactGroups,
userContactGroupIds: $currentUserContactGroupIds,
);
$contactIdsRelationsToDelete = $contactIdsInUserAccessGroups;
}
}
$contactRoles = $this->createRolesFromRequest($request->contacts);
$contactGroupRoles = $this->createRolesFromRequest($request->contactGroups);
$isUserAdmin
? $this->updateDashboardSharesAsAdmin(
$request->dashboardId,
$contactRoles,
$contactGroupRoles
)
: $this->updateDashboardSharesAsNonAdmin(
$request->dashboardId,
$contactRoles,
$contactGroupRoles,
$currentUserContactGroupIds,
$contactIdsRelationsToDelete
);
return new NoContentResponse();
} catch (DashboardException $ex) {
$this->error(
"Error while updating dashboard shares : {$ex->getMessage()}",
[
'dashboard_id' => $request->dashboardId,
'contact_id' => $this->user->getId(),
'contacts' => $request->contacts,
'contact_groups' => $request->contactGroups,
'exception' => [
'message' => $ex->getMessage(),
'trace' => (string) $ex,
],
]
);
return match ($ex->getCode()) {
DashboardException::CODE_NOT_FOUND => new NotFoundResponse($ex),
DashboardException::CODE_FORBIDDEN => new ForbiddenResponse($ex),
default => new InvalidArgumentResponse($ex->getMessage()),
};
} catch (\Throwable $ex) {
$this->error(
"Error while updating dashboard shares : {$ex->getMessage()}",
[
'dashboard_id' => $request->dashboardId,
'contact_id' => $this->user->getId(),
'contacts' => $request->contacts,
'contact_groups' => $request->contactGroups,
'exception' => [
'message' => $ex->getMessage(),
'trace' => (string) $ex,
],
]
);
return new ErrorResponse(DashboardException::errorWhileUpdatingDashboardShare()->getMessage());
}
}
/**
* @param array<array{id: int, role: string}> $data
* @return TinyRole[]
*/
private function createRolesFromRequest(array $data): array
{
return array_map(
static fn (array $item): TinyRole => new TinyRole(
$item['id'],
DashboardSharingRoleConverter::fromString($item['role'])
),
$data
);
}
/**
* @throws \Throwable
* @return int[]
*/
private function findCurrentUserContactGroupIds(): array
{
$contactGroups = $this->readContactGroupRepository->findAllByUserId($this->user->getId());
return array_map(
static fn (ContactGroup $contactGroup): int => $contactGroup->getId(),
$contactGroups
);
}
/**
* @throws \Throwable
* @return int[]
*/
private function findCurrentUserAccessGroupIds(): array
{
$accessGroups = $this->readAccessGroupRepository->findByContact($this->user);
return array_map(
static fn (AccessGroup $accessGroup): int => $accessGroup->getId(),
$accessGroups
);
}
/**
* @param int $dashboardId
* @param TinyRole[] $contactRoles
* @param TinyRole[] $contactGroupRoles
*
* @throws \Throwable
*/
private function updateDashboardSharesAsAdmin(int $dashboardId, array $contactRoles, array $contactGroupRoles): void
{
try {
$this->dataStorageEngine->startTransaction();
$this->writeDashboardShareRepository->deleteDashboardShares($dashboardId);
$this->writeDashboardShareRepository->addDashboardContactShares($dashboardId, $contactRoles);
$this->writeDashboardShareRepository->addDashboardContactGroupShares(
$dashboardId,
$contactGroupRoles
);
$this->dataStorageEngine->commitTransaction();
} catch (\Throwable $ex) {
$this->error(
"Error during update dashboard shares transaction, rolling back: {$ex->getMessage()}",
[
'dashboard_id' => $dashboardId,
'exception' => [
'message' => $ex->getMessage(),
'trace' => (string) $ex,
],
]
);
$this->dataStorageEngine->rollbackTransaction();
throw $ex;
}
}
/**
* @param int $dashboardId
* @param TinyRole[] $contactRoles
* @param TinyRole[] $contactGroupRoles
* @param int[] $userContactGroupIds
* @param int[] $contactIdsInUserAccessGroups
*
* @throws \Throwable
*/
private function updateDashboardSharesAsNonAdmin(
int $dashboardId,
array $contactRoles,
array $contactGroupRoles,
array $userContactGroupIds,
array $contactIdsInUserAccessGroups,
): void {
try {
$this->dataStorageEngine->startTransaction();
$this->writeDashboardShareRepository->deleteDashboardSharesByContactIds(
$dashboardId,
$contactIdsInUserAccessGroups
);
$this->writeDashboardShareRepository->deleteDashboardSharesByContactGroupIds(
$dashboardId,
$userContactGroupIds
);
$this->writeDashboardShareRepository->addDashboardContactShares($dashboardId, $contactRoles);
$this->writeDashboardShareRepository->addDashboardContactGroupShares(
$dashboardId,
$contactGroupRoles
);
$this->dataStorageEngine->commitTransaction();
} catch (\Throwable $ex) {
$this->error(
"Error during update dashboard shares transaction, rolling back: {$ex->getMessage()}",
[
'dashboard_id' => $dashboardId,
'exception' => [
'message' => $ex->getMessage(),
'trace' => (string) $ex,
],
]
);
$this->dataStorageEngine->rollbackTransaction();
throw $ex;
}
}
/**
* @throws \Throwable
*
* @return bool
*/
private function isUserAdmin(): bool
{
if ($this->rights->hasAdminRole()) {
return true;
}
$userAccessGroupNames = array_map(
static fn (AccessGroup $accessGroup): string => $accessGroup->getName(),
$this->readAccessGroupRepository->findByContact($this->user)
);
return ! (empty(array_intersect($userAccessGroupNames, self::AUTHORIZED_ACL_GROUPS)))
&& $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/Dashboard/Application/UseCase/DeleteDashboardFromFavorites/DeleteDashboardFromFavorites.php | centreon/src/Core/Dashboard/Application/UseCase/DeleteDashboardFromFavorites/DeleteDashboardFromFavorites.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Dashboard\Application\UseCase\DeleteDashboardFromFavorites;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\NoContentResponse;
use Core\Application\Common\UseCase\NotFoundResponse;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Dashboard\Application\Exception\DashboardException;
use Core\Dashboard\Application\Repository\ReadDashboardRepositoryInterface;
use Core\UserProfile\Application\Repository\ReadUserProfileRepositoryInterface;
use Core\UserProfile\Application\Repository\WriteUserProfileRepositoryInterface;
use Throwable;
final class DeleteDashboardFromFavorites
{
use LoggerTrait;
/**
* @param WriteUserProfileRepositoryInterface $userProfileWriter
* @param ReadUserProfileRepositoryInterface $userProfileReader
* @param ReadDashboardRepositoryInterface $dashboardReader
* @param ContactInterface $user
*/
public function __construct(
private readonly WriteUserProfileRepositoryInterface $userProfileWriter,
private readonly ReadUserProfileRepositoryInterface $userProfileReader,
private readonly ReadDashboardRepositoryInterface $dashboardReader,
private readonly ContactInterface $user,
) {
}
/**
* @param int $dashboardId
* @return ResponseStatusInterface
*/
public function __invoke(int $dashboardId): ResponseStatusInterface
{
try {
$this->assertDashboardId($dashboardId);
$profile = $this->userProfileReader->findByContact($this->user);
if ($profile === null) {
$this->error('Profile not found for user', ['user_id' => $this->user->getId()]);
return new NotFoundResponse('User profile');
}
if (! in_array($dashboardId, $profile->getFavoriteDashboards(), true)) {
$this->error(
'Dashboard is not set as favorite for user',
[
'user_id' => $this->user->getId(),
'dashboard_id' => $dashboardId,
]
);
return new NotFoundResponse('Dashboard');
}
$this->userProfileWriter->removeDashboardFromFavorites($profile->getId(), $dashboardId);
return new NoContentResponse();
} catch (DashboardException $exception) {
$response = match ($exception->getCode()) {
DashboardException::CODE_NOT_FOUND => new NotFoundResponse('Dashboard'),
default => new ErrorResponse($exception),
};
$this->error(
"Error while removing dashboard from user favorite dashboards : {$exception->getMessage()}",
[
'user_id' => $this->user->getId(),
'dashboard_id' => $dashboardId,
'exception' => ['message' => $exception->getMessage(), 'trace' => $exception->getTraceAsString()],
]
);
return $response;
} catch (Throwable $exception) {
$this->error(
"Error while removing dashboard from user favorite dashboards : {$exception->getMessage()}",
[
'user_id' => $this->user->getId(),
'dashboard_id' => $dashboardId,
'exception' => ['message' => $exception->getMessage(), 'trace' => $exception->getTraceAsString()],
]
);
return new ErrorResponse($exception);
}
}
/**
* @param int $dashboardId
*
* @throws Throwable
* @throws DashboardException
*/
private function assertDashboardId(int $dashboardId): void
{
if (! $this->dashboardReader->existsOne($dashboardId)) {
throw DashboardException::theDashboardDoesNotExist($dashboardId);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Dashboard/Application/UseCase/FindDashboards/FindDashboards.php | centreon/src/Core/Dashboard/Application/UseCase/FindDashboards/FindDashboards.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Dashboard\Application\UseCase\FindDashboards;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Contact\Application\Repository\ReadContactRepositoryInterface;
use Core\Dashboard\Application\Exception\DashboardException;
use Core\Dashboard\Application\Repository\ReadDashboardRepositoryInterface;
use Core\Dashboard\Application\Repository\ReadDashboardShareRepositoryInterface;
use Core\Dashboard\Domain\Model\Dashboard;
use Core\Dashboard\Domain\Model\DashboardRights;
use Core\Dashboard\Domain\Model\Role\DashboardSharingRole;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
use Core\UserProfile\Application\Repository\ReadUserProfileRepositoryInterface;
use Throwable;
/** @package Core\Dashboard\Application\UseCase\FindDashboards */
final class FindDashboards
{
use LoggerTrait;
public const AUTHORIZED_ACL_GROUPS = ['customer_admin_acl'];
/** @var int[] */
private array $usersFavoriteDashboards = [];
public function __construct(
private readonly ReadDashboardRepositoryInterface $readDashboardRepository,
private readonly ReadDashboardShareRepositoryInterface $readDashboardShareRepository,
private readonly RequestParametersInterface $requestParameters,
private readonly ReadContactRepositoryInterface $readContactRepository,
private readonly DashboardRights $rights,
private readonly ContactInterface $contact,
private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepository,
private readonly ReadUserProfileRepositoryInterface $userProfileReader,
private readonly bool $isCloudPlatform,
) {
}
public function __invoke(FindDashboardsPresenterInterface $presenter): void
{
try {
$profile = $this->userProfileReader->findByContact($this->contact);
$this->usersFavoriteDashboards = $profile !== null ? $profile->getFavoriteDashboards() : [];
$presenter->presentResponse(
$this->isUserAdmin() ? $this->findDashboardAsAdmin() : $this->findDashboardAsViewer(),
);
$this->info('Find dashboards', ['request' => $this->requestParameters->toArray()]);
} catch (Throwable $ex) {
$this->error(
"Error while searching dashboards : {$ex->getMessage()}",
[
'contact_id' => $this->contact->getId(),
'favorite_dashboards' => $this->usersFavoriteDashboards,
'request_parameters' => $this->requestParameters->toArray(),
'exception' => ['message' => $ex->getMessage(), 'trace' => $ex->getTraceAsString()],
]
);
$presenter->presentResponse(new ErrorResponse(DashboardException::errorWhileSearching()));
}
}
/**
* @throws Throwable
*
* @return FindDashboardsResponse
*/
private function findDashboardAsAdmin(): FindDashboardsResponse
{
$dashboards = $this->readDashboardRepository->findByRequestParameter($this->requestParameters);
$dashboardIds = array_map(
static fn (Dashboard $dashboard): int => $dashboard->getId(),
$dashboards
);
$thumbnails = $this->readDashboardRepository->findThumbnailsByDashboardIds($dashboardIds);
$contactIds = $this->extractAllContactIdsFromDashboards($dashboards);
return FindDashboardsFactory::createResponse(
dashboards: $dashboards,
contactNames: $this->readContactRepository->findNamesByIds(...$contactIds),
sharingRolesList: $this->readDashboardShareRepository->getMultipleSharingRoles($this->contact, ...$dashboards),
contactShares: $this->readDashboardShareRepository->findDashboardsContactShares(...$dashboards),
contactGroupShares: $this->readDashboardShareRepository->findDashboardsContactGroupShares(...$dashboards),
defaultRole: DashboardSharingRole::Editor,
thumbnails: $thumbnails,
favoriteDashboards: $this->usersFavoriteDashboards
);
}
/**
* @throws Throwable
*
* @return FindDashboardsResponse
*/
private function findDashboardAsViewer(): FindDashboardsResponse
{
$dashboards = $this->readDashboardRepository->findByRequestParameterAndContact(
$this->requestParameters,
$this->contact,
);
$dashboardIds = array_map(
static fn (Dashboard $dashboard): int => $dashboard->getId(),
$dashboards
);
$thumbnails = $this->readDashboardRepository->findThumbnailsByDashboardIds($dashboardIds);
$editorIds = $this->extractAllContactIdsFromDashboards($dashboards);
$userAccessGroups = $this->readAccessGroupRepository->findByContact($this->contact);
$accessGroupsIds = array_map(
static fn (AccessGroup $accessGroup): int => $accessGroup->getId(),
$userAccessGroups
);
$userInCurrentUserAccessGroups = $this->readContactRepository->findContactIdsByAccessGroups($accessGroupsIds);
return FindDashboardsFactory::createResponse(
dashboards: $dashboards,
contactNames: $this->readContactRepository->findNamesByIds(...$editorIds),
sharingRolesList: $this->readDashboardShareRepository->getMultipleSharingRoles($this->contact, ...$dashboards),
contactShares: $this->readDashboardShareRepository->findDashboardsContactSharesByContactIds(
$userInCurrentUserAccessGroups,
...$dashboards
),
contactGroupShares: $this->readDashboardShareRepository->findDashboardsContactGroupSharesByContact($this->contact, ...$dashboards),
defaultRole: DashboardSharingRole::Viewer,
thumbnails: $thumbnails,
favoriteDashboards: $this->usersFavoriteDashboards
);
}
/**
* @param list<Dashboard> $dashboards
*
* @return int[]
*/
private function extractAllContactIdsFromDashboards(array $dashboards): array
{
$contactIds = [];
foreach ($dashboards as $dashboard) {
if ($id = $dashboard->getCreatedBy()) {
$contactIds[] = $id;
}
if ($id = $dashboard->getUpdatedBy()) {
$contactIds[] = $id;
}
}
return $contactIds;
}
/**
* @throws Throwable
*
* @return bool
*/
private function isUserAdmin(): bool
{
if ($this->rights->hasAdminRole()) {
return true;
}
$userAccessGroupNames = array_map(
static fn (AccessGroup $accessGroup): string => $accessGroup->getName(),
$this->readAccessGroupRepository->findByContact($this->contact)
);
return ! (empty(array_intersect($userAccessGroupNames, self::AUTHORIZED_ACL_GROUPS)))
&& $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/Dashboard/Application/UseCase/FindDashboards/FindDashboardsPresenterInterface.php | centreon/src/Core/Dashboard/Application/UseCase/FindDashboards/FindDashboardsPresenterInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Dashboard\Application\UseCase\FindDashboards;
use Core\Application\Common\UseCase\ResponseStatusInterface;
interface FindDashboardsPresenterInterface
{
public function presentResponse(FindDashboardsResponse|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/Dashboard/Application/UseCase/FindDashboards/FindDashboardsFactory.php | centreon/src/Core/Dashboard/Application/UseCase/FindDashboards/FindDashboardsFactory.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Dashboard\Application\UseCase\FindDashboards;
use Core\Dashboard\Application\UseCase\FindDashboards\Response\DashboardResponseDto;
use Core\Dashboard\Application\UseCase\FindDashboards\Response\ThumbnailResponseDto;
use Core\Dashboard\Application\UseCase\FindDashboards\Response\UserResponseDto;
use Core\Dashboard\Domain\Model\Dashboard;
use Core\Dashboard\Domain\Model\Role\DashboardSharingRole;
use Core\Dashboard\Domain\Model\Share\DashboardContactGroupShare;
use Core\Dashboard\Domain\Model\Share\DashboardContactShare;
use Core\Dashboard\Domain\Model\Share\DashboardSharingRoles;
use Core\Media\Domain\Model\Media;
final class FindDashboardsFactory
{
/**
* @param list<Dashboard> $dashboards
* @param array<int, array{id: int, name: string}> $contactNames
* @param array<int, DashboardSharingRoles> $sharingRolesList
* @param array<int, array<DashboardContactShare>> $contactShares
* @param array<int, array<DashboardContactGroupShare>> $contactGroupShares
* @param DashboardSharingRole $defaultRole
* @param array<int, Media> $thumbnails
* @param int[] $favoriteDashboards
*
* @return FindDashboardsResponse
*/
public static function createResponse(
array $dashboards,
array $contactNames,
array $sharingRolesList,
array $contactShares,
array $contactGroupShares,
DashboardSharingRole $defaultRole,
array $thumbnails,
array $favoriteDashboards,
): FindDashboardsResponse {
$response = new FindDashboardsResponse();
foreach ($dashboards as $dashboard) {
$sharingRoles = $sharingRolesList[$dashboard->getId()] ?? null;
$ownRole = $defaultRole->getTheMostPermissiveOfBoth($sharingRoles?->getTheMostPermissiveRole());
$thumbnail = $thumbnails[$dashboard->getId()] ?? null;
$dto = new DashboardResponseDto();
$dto->id = $dashboard->getId();
$dto->name = $dashboard->getName();
$dto->description = $dashboard->getDescription();
$dto->createdAt = $dashboard->getCreatedAt();
$dto->updatedAt = $dashboard->getUpdatedAt();
$dto->ownRole = $ownRole;
if (null !== ($contactId = $dashboard->getCreatedBy())) {
$dto->createdBy = new UserResponseDto();
$dto->createdBy->id = $contactId;
$dto->createdBy->name = $contactNames[$contactId]['name'] ?? '';
}
if (null !== ($contactId = $dashboard->getCreatedBy())) {
$dto->updatedBy = new UserResponseDto();
$dto->updatedBy->id = $contactId;
$dto->updatedBy->name = $contactNames[$contactId]['name'] ?? '';
}
// Add shares only if the user if editor, as the viewers should not be able to see shares.
if ($ownRole === DashboardSharingRole::Editor && array_key_exists($dashboard->getId(), $contactShares)) {
$dto->shares['contacts'] = array_map(static fn (DashboardContactShare $contactShare): array => [
'id' => $contactShare->getContactId(),
'name' => $contactShare->getContactName(),
'email' => $contactShare->getContactEmail(),
'role' => $contactShare->getRole(),
], $contactShares[$dashboard->getId()]);
}
if ($ownRole === DashboardSharingRole::Editor && array_key_exists($dashboard->getId(), $contactGroupShares)) {
$dto->shares['contact_groups'] = array_map(
static fn (DashboardContactGroupShare $contactGroupShare): array => [
'id' => $contactGroupShare->getContactGroupId(),
'name' => $contactGroupShare->getContactGroupName(),
'role' => $contactGroupShare->getRole(),
],
$contactGroupShares[$dashboard->getId()]
);
}
if ($thumbnail !== null) {
$dto->thumbnail = new ThumbnailResponseDto(
$thumbnail->getId(),
$thumbnail->getFilename(),
$thumbnail->getDirectory()
);
}
if (in_array($dto->id, $favoriteDashboards, true)) {
$dto->isFavorite = true;
}
$response->dashboards[] = $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/Dashboard/Application/UseCase/FindDashboards/FindDashboardsResponse.php | centreon/src/Core/Dashboard/Application/UseCase/FindDashboards/FindDashboardsResponse.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Dashboard\Application\UseCase\FindDashboards;
use Core\Dashboard\Application\UseCase\FindDashboards\Response\DashboardResponseDto;
final class FindDashboardsResponse
{
/**
* @param DashboardResponseDto[] $dashboards
*/
public function __construct(
public array $dashboards = [],
) {
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Dashboard/Application/UseCase/FindDashboards/Response/ThumbnailResponseDto.php | centreon/src/Core/Dashboard/Application/UseCase/FindDashboards/Response/ThumbnailResponseDto.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Dashboard\Application\UseCase\FindDashboards\Response;
final class ThumbnailResponseDto
{
public function __construct(
public int $id = 0,
public string $name = '',
public string $directory = '',
) {
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Dashboard/Application/UseCase/FindDashboards/Response/UserResponseDto.php | centreon/src/Core/Dashboard/Application/UseCase/FindDashboards/Response/UserResponseDto.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Dashboard\Application\UseCase\FindDashboards\Response;
final class UserResponseDto
{
public function __construct(
public int $id = 0,
public string $name = '',
) {
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Dashboard/Application/UseCase/FindDashboards/Response/DashboardResponseDto.php | centreon/src/Core/Dashboard/Application/UseCase/FindDashboards/Response/DashboardResponseDto.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Dashboard\Application\UseCase\FindDashboards\Response;
use Core\Dashboard\Domain\Model\Role\DashboardSharingRole;
use DateTimeImmutable;
final class DashboardResponseDto
{
/**
* @param int $id
* @param string $name
* @param string|null $description
* @param UserResponseDto|null $createdBy
* @param UserResponseDto|null $updatedBy
* @param DateTimeImmutable $createdAt
* @param DateTimeImmutable $updatedAt
* @param DashboardSharingRole $ownRole
* @param array{
* contacts: array<array{
* id: int,
* name: string,
* email: string,
* role: DashboardSharingRole
* }>,
* contact_groups: array<array{
* id: int,
* name: string,
* role: DashboardSharingRole
* }>
* } $shares
* @param ThumbnailResponseDto $thumbnail
* @param bool $isFavorite
*/
public function __construct(
public int $id = 0,
public string $name = '',
public ?string $description = null,
public ?UserResponseDto $createdBy = null,
public ?UserResponseDto $updatedBy = null,
public DateTimeImmutable $createdAt = new DateTimeImmutable(),
public DateTimeImmutable $updatedAt = new DateTimeImmutable(),
public DashboardSharingRole $ownRole = DashboardSharingRole::Viewer,
public array $shares = ['contacts' => [], 'contact_groups' => []],
public ?ThumbnailResponseDto $thumbnail = null,
public bool $isFavorite = 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/Dashboard/Application/UseCase/FindMetricsTop/FindMetricsTopRequest.php | centreon/src/Core/Dashboard/Application/UseCase/FindMetricsTop/FindMetricsTopRequest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Dashboard\Application\UseCase\FindMetricsTop;
use Symfony\Component\Validator\Constraints as Assert;
final class FindMetricsTopRequest
{
/**
* @param string $metricName
*/
public function __construct(
#[Assert\NotBlank]
public readonly string $metricName,
) {
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Dashboard/Application/UseCase/FindMetricsTop/FindMetricsTopPresenterInterface.php | centreon/src/Core/Dashboard/Application/UseCase/FindMetricsTop/FindMetricsTopPresenterInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Dashboard\Application\UseCase\FindMetricsTop;
use Core\Application\Common\UseCase\ResponseStatusInterface;
interface FindMetricsTopPresenterInterface
{
/**
* @param FindMetricsTopResponse|ResponseStatusInterface $response
*/
public function presentResponse(FindMetricsTopResponse|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/Dashboard/Application/UseCase/FindMetricsTop/FindMetricsTopResponse.php | centreon/src/Core/Dashboard/Application/UseCase/FindMetricsTop/FindMetricsTopResponse.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Dashboard\Application\UseCase\FindMetricsTop;
use Core\Dashboard\Application\UseCase\FindMetricsTop\Response\MetricInformationDto;
final class FindMetricsTopResponse
{
public string $metricName;
public string $metricUnit;
/** @var MetricInformationDto[] */
public array $resourceMetrics;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Dashboard/Application/UseCase/FindMetricsTop/FindMetricsTop.php | centreon/src/Core/Dashboard/Application/UseCase/FindMetricsTop/FindMetricsTop.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Dashboard\Application\UseCase\FindMetricsTop;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
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\Dashboard\Application\Exception\DashboardException;
use Core\Dashboard\Application\Repository\ReadDashboardPerformanceMetricRepositoryInterface;
use Core\Dashboard\Application\UseCase\FindMetricsTop\Response\MetricInformationDto;
use Core\Dashboard\Domain\Model\DashboardRights;
use Core\Dashboard\Domain\Model\Metric\ResourceMetric;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
final readonly class FindMetricsTop
{
public const AUTHORIZED_ACL_GROUPS = ['customer_admin_acl'];
/**
* @param ContactInterface $user
* @param RequestParametersInterface $requestParameters
* @param ReadAccessGroupRepositoryInterface $accessGroupRepository
* @param ReadDashboardPerformanceMetricRepositoryInterface $dashboardMetricRepository
* @param DashboardRights $rights
* @param bool $isCloudPlatform
*/
public function __construct(
private ContactInterface $user,
private RequestParametersInterface $requestParameters,
private ReadAccessGroupRepositoryInterface $accessGroupRepository,
private ReadDashboardPerformanceMetricRepositoryInterface $dashboardMetricRepository,
private DashboardRights $rights,
private bool $isCloudPlatform,
) {
}
/**
* @param FindMetricsTopPresenterInterface $presenter
* @param FindMetricsTopRequest $request
*/
public function __invoke(FindMetricsTopPresenterInterface $presenter, FindMetricsTopRequest $request): void
{
try {
if ($this->isUserAdmin()) {
$resourceMetrics = $this->dashboardMetricRepository->findByRequestParametersAndMetricName(
$this->requestParameters,
$request->metricName
);
} elseif ($this->rights->canAccess()) {
$accessGroups = $this->accessGroupRepository->findByContact($this->user);
$resourceMetrics = $this->dashboardMetricRepository
->findByRequestParametersAndAccessGroupsAndMetricName(
$this->requestParameters,
$accessGroups,
$request->metricName
);
} else {
$presenter->presentResponse(new ForbiddenResponse(
DashboardException::accessNotAllowed()->getMessage()
));
return;
}
if ($resourceMetrics === []) {
$presenter->presentResponse(new NotFoundResponse('metrics'));
return;
}
$presenter->presentResponse($this->createResponse($resourceMetrics));
} catch (RepositoryException $e) {
$presenter->presentResponse(
new ErrorResponse(
message: 'An error occured while retrieving top metrics',
exception: $e,
)
);
return;
}
}
/**
* Create FindMetricsTopResponse DTO.
*
* @param ResourceMetric[] $resourceMetrics
*
* @return FindMetricsTopResponse
*/
private function createResponse(array $resourceMetrics): FindMetricsTopResponse
{
$response = new FindMetricsTopResponse();
$response->metricName = $resourceMetrics[0]->getMetrics()[0]->getName();
$response->metricUnit = $resourceMetrics[0]->getMetrics()[0]->getUnit();
$response->resourceMetrics = array_map(function ($resourceMetric) {
$metricInformation = new MetricInformationDto();
$metric = $resourceMetric->getMetrics()[0];
$metricInformation->serviceId = $resourceMetric->getServiceId();
$metricInformation->resourceName = $resourceMetric->getResourceName();
$metricInformation->parentName = $resourceMetric->getParentName();
$metricInformation->parentId = $resourceMetric->getParentId();
$metricInformation->currentValue = $metric->getCurrentValue();
$metricInformation->warningHighThreshold = $metric->getWarningHighThreshold();
$metricInformation->criticalHighThreshold = $metric->getCriticalHighThreshold();
$metricInformation->warningLowThreshold = $metric->getWarningLowThreshold();
$metricInformation->criticalLowThreshold = $metric->getCriticalLowThreshold();
$metricInformation->minimumValue = $metric->getMinimumValue();
$metricInformation->maximumValue = $metric->getMaximumValue();
return $metricInformation;
}, $resourceMetrics);
return $response;
}
/**
* @throws RepositoryException
*
* @return bool
*/
private function isUserAdmin(): bool
{
if ($this->rights->hasAdminRole()) {
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->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/Dashboard/Application/UseCase/FindMetricsTop/Response/MetricInformationDto.php | centreon/src/Core/Dashboard/Application/UseCase/FindMetricsTop/Response/MetricInformationDto.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Dashboard\Application\UseCase\FindMetricsTop\Response;
class MetricInformationDto
{
public int $serviceId = 0;
public string $resourceName = '';
public string $parentName = '';
public int $parentId = 0;
public ?float $currentValue = null;
public ?float $warningHighThreshold = null;
public ?float $criticalHighThreshold = null;
public ?float $warningLowThreshold = null;
public ?float $criticalLowThreshold = null;
public ?float $minimumValue = null;
public ?float $maximumValue = 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/Dashboard/Application/UseCase/FindSingleMetric/FindSingleMetricResponse.php | centreon/src/Core/Dashboard/Application/UseCase/FindSingleMetric/FindSingleMetricResponse.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Dashboard\Application\UseCase\FindSingleMetric;
final readonly class FindSingleMetricResponse
{
public function __construct(
public int $id,
public string $name,
public ?string $unit = null,
public ?float $currentValue = null,
public ?float $warningHighThreshold = null,
public ?float $warningLowThreshold = null,
public ?float $criticalHighThreshold = null,
public ?float $criticalLowThreshold = 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/Dashboard/Application/UseCase/FindSingleMetric/FindSingleMetric.php | centreon/src/Core/Dashboard/Application/UseCase/FindSingleMetric/FindSingleMetric.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Dashboard\Application\UseCase\FindSingleMetric;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\NotFoundResponse;
use Core\Metric\Application\Repository\ReadMetricRepositoryInterface;
use Core\Metric\Domain\Model\Metric;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Service\Application\Repository\ReadRealTimeServiceRepositoryInterface;
final readonly class FindSingleMetric
{
/**
* @param ContactInterface $user
* @param ReadMetricRepositoryInterface $metricRepository
* @param ReadRealTimeServiceRepositoryInterface $serviceRepository
* @param ReadAccessGroupRepositoryInterface $accessGroupRepository
* @param RequestParametersInterface $requestParameters
*/
public function __construct(
private ContactInterface $user,
private ReadMetricRepositoryInterface $metricRepository,
private ReadRealTimeServiceRepositoryInterface $serviceRepository,
private ReadAccessGroupRepositoryInterface $accessGroupRepository,
private RequestParametersInterface $requestParameters,
) {
}
/**
* @param FindSingleMetricRequest $request
* @param FindSingleMetricPresenterInterface $presenter
*/
public function __invoke(
FindSingleMetricRequest $request,
FindSingleMetricPresenterInterface $presenter,
): void {
try {
if (! $this->serviceRepository->exists($request->serviceId, $request->hostId)) {
$presenter->presentResponse(new NotFoundResponse(
'Service',
[
'host_id' => $request->hostId,
'service_id' => $request->serviceId,
'user_id' => $this->user->getId(),
]
));
return;
}
if ($this->user->isAdmin()) {
$metric = $this->metricRepository->findSingleMetricValue(
$request->hostId,
$request->serviceId,
$request->metricName,
$this->requestParameters
);
} else {
$accessGroups = $this->accessGroupRepository->findByContact($this->user);
$metric = $this->metricRepository->findSingleMetricValue(
$request->hostId,
$request->serviceId,
$request->metricName,
$this->requestParameters,
$accessGroups
);
}
if ($metric !== null) {
$presenter->presentResponse(
$this->createResponse($metric)
);
} else {
$presenter->presentResponse(new NotFoundResponse(
'Metric not found',
[
'host_id' => $request->hostId,
'service_id' => $request->serviceId,
'metric_name' => $request->metricName,
'user_id' => $this->user->getId(),
]
));
}
} catch (\Throwable $exception) {
$presenter->presentResponse(new ErrorResponse(
'Error while retrieving metric : ' . $exception->getMessage(),
[
'host_id' => $request->hostId,
'service_id' => $request->serviceId,
'metric_name' => $request->metricName,
'user_id' => $this->user->getId(),
],
$exception
));
}
}
/**
* Create Response.
*
* @param Metric $metric
*
* @return FindSingleMetricResponse
*/
private function createResponse(Metric $metric): FindSingleMetricResponse
{
return new FindSingleMetricResponse(
id: $metric->getId(),
name: $metric->getName(),
unit: $metric->getUnit(),
currentValue: $metric->getCurrentValue(),
warningHighThreshold: $metric->getWarningHighThreshold(),
warningLowThreshold: $metric->getWarningLowThreshold(),
criticalHighThreshold: $metric->getCriticalHighThreshold(),
criticalLowThreshold: $metric->getCriticalLowThreshold(),
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Dashboard/Application/UseCase/FindSingleMetric/FindSingleMetricRequest.php | centreon/src/Core/Dashboard/Application/UseCase/FindSingleMetric/FindSingleMetricRequest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Dashboard\Application\UseCase\FindSingleMetric;
final readonly class FindSingleMetricRequest
{
/**
* @param int $hostId
* @param int $serviceId
* @param string $metricName
* @throws \InvalidArgumentException
*/
public function __construct(
public int $hostId,
public int $serviceId,
public string $metricName,
) {
if ($hostId <= 0) {
throw new \InvalidArgumentException("hostId must be greater than 0, {$hostId} given");
}
if ($serviceId <= 0) {
throw new \InvalidArgumentException("serviceId must be greater than 0, {$serviceId} given");
}
if (trim($metricName) === '') {
throw new \InvalidArgumentException('metricName cannot be empty');
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Dashboard/Application/UseCase/FindSingleMetric/FindSingleMetricPresenterInterface.php | centreon/src/Core/Dashboard/Application/UseCase/FindSingleMetric/FindSingleMetricPresenterInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Dashboard\Application\UseCase\FindSingleMetric;
use Core\Application\Common\UseCase\ResponseStatusInterface;
interface FindSingleMetricPresenterInterface
{
public function presentResponse(FindSingleMetricResponse|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/Dashboard/Application/UseCase/FindSingleMetaMetric/FindSingleMetaMetricResponse.php | centreon/src/Core/Dashboard/Application/UseCase/FindSingleMetaMetric/FindSingleMetaMetricResponse.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Dashboard\Application\UseCase\FindSingleMetaMetric;
final readonly class FindSingleMetaMetricResponse
{
public function __construct(
public int $id,
public string $name,
public ?string $unit = null,
public ?float $currentValue = null,
public ?float $warningHighThreshold = null,
public ?float $warningLowThreshold = null,
public ?float $criticalHighThreshold = null,
public ?float $criticalLowThreshold = 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/Dashboard/Application/UseCase/FindSingleMetaMetric/FindSingleMetaMetric.php | centreon/src/Core/Dashboard/Application/UseCase/FindSingleMetaMetric/FindSingleMetaMetric.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Dashboard\Application\UseCase\FindSingleMetaMetric;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\NotFoundResponse;
use Core\Metric\Application\Repository\ReadMetricRepositoryInterface;
use Core\Metric\Domain\Model\Metric;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Service\Application\Repository\ReadRealTimeServiceRepositoryInterface;
final readonly class FindSingleMetaMetric
{
/**
* @param ContactInterface $user
* @param ReadMetricRepositoryInterface $metricRepository
* @param ReadRealTimeServiceRepositoryInterface $serviceRepository
* @param ReadAccessGroupRepositoryInterface $accessGroupRepository
* @param RequestParametersInterface $requestParameters
*/
public function __construct(
private ContactInterface $user,
private ReadMetricRepositoryInterface $metricRepository,
private ReadRealTimeServiceRepositoryInterface $serviceRepository,
private ReadAccessGroupRepositoryInterface $accessGroupRepository,
private RequestParametersInterface $requestParameters,
) {
}
/**
* @param FindSingleMetaMetricRequest $request
* @param FindSingleMetaMetricPresenterInterface $presenter
*/
public function __invoke(
FindSingleMetaMetricRequest $request,
FindSingleMetaMetricPresenterInterface $presenter,
): void {
try {
$service = $this->serviceRepository->existsByDescription($request->metaServiceId);
if ($service === false) {
$presenter->presentResponse(new NotFoundResponse(
'MetaService',
[
'metaServiceId' => $request->metaServiceId,
'userId' => $this->user->getId(),
]
));
return;
}
if ($this->user->isAdmin()) {
$metric = $this->metricRepository->findSingleMetaMetricValue(
$service,
$request->metricName,
$this->requestParameters
);
} else {
$accessGroups = $this->accessGroupRepository->findByContact($this->user);
$metric = $this->metricRepository->findSingleMetaMetricValue(
$service,
$request->metricName,
$this->requestParameters,
$accessGroups
);
}
if ($metric !== null) {
$presenter->presentResponse(
$this->createResponse($metric)
);
} else {
$presenter->presentResponse(new NotFoundResponse(
'Metric not found',
[
'metaServiceId' => $request->metaServiceId,
'metricName' => $request->metricName,
'userId' => $this->user->getId(),
]
));
}
} catch (\Throwable $exception) {
$presenter->presentResponse(new ErrorResponse(
'Error while retrieving metric : ' . $exception->getMessage(),
[
'metaServiceId' => $request->metaServiceId,
'metricName' => $request->metricName,
'userId' => $this->user->getId(),
],
$exception
));
}
}
/**
* Create Response.
*
* @param Metric $metric
*
* @return FindSingleMetaMetricResponse
*/
private function createResponse(Metric $metric): FindSingleMetaMetricResponse
{
return new FindSingleMetaMetricResponse(
id: $metric->getId(),
name: $metric->getName(),
unit: $metric->getUnit(),
currentValue: $metric->getCurrentValue(),
warningHighThreshold: $metric->getWarningHighThreshold(),
warningLowThreshold: $metric->getWarningLowThreshold(),
criticalHighThreshold: $metric->getCriticalHighThreshold(),
criticalLowThreshold: $metric->getCriticalLowThreshold(),
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Dashboard/Application/UseCase/FindSingleMetaMetric/FindSingleMetaMetricPresenterInterface.php | centreon/src/Core/Dashboard/Application/UseCase/FindSingleMetaMetric/FindSingleMetaMetricPresenterInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Dashboard\Application\UseCase\FindSingleMetaMetric;
use Core\Application\Common\UseCase\ResponseStatusInterface;
interface FindSingleMetaMetricPresenterInterface
{
public function presentResponse(FindSingleMetaMetricResponse|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/Dashboard/Application/UseCase/FindSingleMetaMetric/FindSingleMetaMetricRequest.php | centreon/src/Core/Dashboard/Application/UseCase/FindSingleMetaMetric/FindSingleMetaMetricRequest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Dashboard\Application\UseCase\FindSingleMetaMetric;
final readonly class FindSingleMetaMetricRequest
{
/**
* @param int $metaServiceId
* @param string $metricName
* @throws \InvalidArgumentException
*/
public function __construct(
public int $metaServiceId,
public string $metricName,
) {
if ($metaServiceId <= 0) {
throw new \InvalidArgumentException("metaServiceId must be greater than 0, {$metaServiceId} given");
}
if (trim($metricName) === '') {
throw new \InvalidArgumentException('metricName cannot be empty');
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Dashboard/Application/UseCase/AddDashboard/AddDashboardRequest.php | centreon/src/Core/Dashboard/Application/UseCase/AddDashboard/AddDashboardRequest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Dashboard\Application\UseCase\AddDashboard;
use Core\Dashboard\Domain\Model\Refresh\RefreshType;
final class AddDashboardRequest
{
public string $name = '';
public ?string $description = null;
/** @var array<PanelRequest> */
public array $panels = [];
/** @var array{type:RefreshType, interval: int|null} */
public array $refresh = [
'type' => RefreshType::Global,
'interval' => null,
];
}
| 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.