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/Service/Infrastructure/API/DeployServices/DeployServicesOnPremPresenter.php | centreon/src/Core/Service/Infrastructure/API/DeployServices/DeployServicesOnPremPresenter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See 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\Service\Infrastructure\API\DeployServices;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\CreatedResponse;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Service\Application\UseCase\DeployServices\DeployServiceDto;
use Core\Service\Application\UseCase\DeployServices\DeployServicesPresenterInterface;
use Core\Service\Application\UseCase\DeployServices\DeployServicesResponse;
use Core\Service\Infrastructure\Model\NotificationTypeConverter;
use Core\Service\Infrastructure\Model\YesNoDefaultConverter;
class DeployServicesOnPremPresenter extends AbstractPresenter implements DeployServicesPresenterInterface
{
/**
* @inheritDoc
*/
public function presentResponse(DeployServicesResponse|ResponseStatusInterface $response): void
{
if ($response instanceof ResponseStatusInterface) {
$this->setResponseStatus($response);
} else {
$this->present(
new CreatedResponse(
null,
[
'services' => array_map(
static fn (DeployServiceDto $service): array => [
'id' => $service->id,
'name' => $service->name,
'host_id' => $service->hostId,
'geo_coords' => $service->geoCoords,
'comment' => $service->comment,
'service_template_id' => $service->serviceTemplateId,
'check_command_id' => $service->commandId,
'check_command_args' => $service->commandArguments,
'check_timeperiod_id' => $service->checkTimePeriodId,
'max_check_attempts' => $service->maxCheckAttempts,
'normal_check_interval' => $service->normalCheckInterval,
'retry_check_interval' => $service->retryCheckInterval,
'active_check_enabled' => YesNoDefaultConverter::toInt($service->activeChecksEnabled),
'passive_check_enabled' => YesNoDefaultConverter::toInt($service->passiveChecksEnabled),
'volatility_enabled' => YesNoDefaultConverter::toInt($service->volatilityEnabled),
'notification_enabled' => YesNoDefaultConverter::toInt($service->notificationsEnabled),
'is_contact_additive_inheritance' => $service->isContactAdditiveInheritance,
'is_contact_group_additive_inheritance' => $service->isContactGroupAdditiveInheritance,
'notification_timeperiod_id' => $service->notificationTimePeriodId,
'notification_type' => NotificationTypeConverter::toBits($service->notificationTypes),
'first_notification_delay' => $service->firstNotificationDelay,
'recovery_notification_delay' => $service->recoveryNotificationDelay,
'acknowledgement_timeout' => $service->acknowledgementTimeout,
'freshness_checked' => YesNoDefaultConverter::toInt($service->checkFreshness),
'freshness_threshold' => $service->freshnessThreshold,
'flap_detection_enabled' => YesNoDefaultConverter::toInt($service->flapDetectionEnabled),
'low_flap_threshold' => $service->lowFlapThreshold,
'high_flap_threshold' => $service->highFlapThreshold,
'event_handler_enabled' => YesNoDefaultConverter::toInt($service->eventHandlerEnabled),
'event_handler_command_id' => $service->eventHandlerCommandId,
'event_handler_command_args' => $service->eventHandlerArguments,
'graph_template_id' => $service->graphTemplateId,
'note' => $service->note,
'note_url' => $service->noteUrl,
'action_url' => $service->actionUrl,
'icon_id' => $service->iconId,
'icon_alternative' => $service->iconAlternative,
'severity_id' => $service->severityId,
'is_activated' => $service->isActivated,
],
$response->services
),
]
)
);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Service/Infrastructure/API/DeleteServices/DeleteServicesRequestTransformer.php | centreon/src/Core/Service/Infrastructure/API/DeleteServices/DeleteServicesRequestTransformer.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See 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\Service\Infrastructure\API\DeleteServices;
use Core\Service\Application\UseCase\DeleteServices\DeleteServicesRequest;
abstract readonly class DeleteServicesRequestTransformer
{
/**
* @param DeleteServicesInput $input
* @return DeleteServicesRequest
*/
public static function transform(DeleteServicesInput $input): DeleteServicesRequest
{
return new DeleteServicesRequest(serviceIds: $input->ids);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Service/Infrastructure/API/DeleteServices/DeleteServicesInput.php | centreon/src/Core/Service/Infrastructure/API/DeleteServices/DeleteServicesInput.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See 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\Service\Infrastructure\API\DeleteServices;
use Symfony\Component\Validator\Constraints as Assert;
final class DeleteServicesInput
{
/**
* @param int[] $ids
*/
public function __construct(
#[Assert\NotNull()]
#[Assert\Type('array')]
#[Assert\All(
new Assert\Type('integer')
)]
public readonly mixed $ids,
) {
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Service/Infrastructure/API/DeleteServices/DeleteServicesController.php | centreon/src/Core/Service/Infrastructure/API/DeleteServices/DeleteServicesController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See 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\Service\Infrastructure\API\DeleteServices;
use Centreon\Application\Controller\AbstractController;
use Core\Infrastructure\Common\Api\StandardPresenter;
use Core\Service\Application\UseCase\DeleteServices\DeleteServices;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Attribute\MapRequestPayload;
use Symfony\Component\Security\Http\Attribute\IsGranted;
#[IsGranted(
'service_delete',
null,
'You are not allowed to delete services',
Response::HTTP_FORBIDDEN
)]
final class DeleteServicesController extends AbstractController
{
public function __invoke(
DeleteServices $useCase,
#[MapRequestPayload()] DeleteServicesInput $request,
StandardPresenter $presenter,
): Response {
$response = $useCase(DeleteServicesRequestTransformer::transform($request));
return JsonResponse::fromJsonString($presenter->present($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/Service/Infrastructure/API/AddService/AddServiceSaasPresenter.php | centreon/src/Core/Service/Infrastructure/API/AddService/AddServiceSaasPresenter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See 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\Service\Infrastructure\API\AddService;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\CreatedResponse;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Service\Application\UseCase\AddService\AddServicePresenterInterface;
use Core\Service\Application\UseCase\AddService\AddServiceResponse;
use Core\Service\Application\UseCase\AddService\MacroDto;
use Core\Service\Infrastructure\Model\YesNoDefaultConverter;
class AddServiceSaasPresenter extends AbstractPresenter implements AddServicePresenterInterface
{
public function __construct(PresenterFormatterInterface $presenterFormatter)
{
parent::__construct($presenterFormatter);
}
public function presentResponse(ResponseStatusInterface|AddServiceResponse $response): void
{
if ($response instanceof ResponseStatusInterface) {
$this->setResponseStatus($response);
} else {
$this->present(
new CreatedResponse(
$response->id,
[
'id' => $response->id,
'name' => $response->name,
'host_id' => $response->hostId,
'service_template_id' => $response->serviceTemplateId,
'check_timeperiod_id' => $response->checkTimePeriodId,
'max_check_attempts' => $response->maxCheckAttempts,
'normal_check_interval' => $response->normalCheckInterval,
'retry_check_interval' => $response->retryCheckInterval,
'note' => $response->note,
'note_url' => $response->noteUrl,
'action_url' => $response->actionUrl,
'geo_coords' => $response->geoCoords,
'icon_id' => $response->iconId,
'severity_id' => $response->severityId,
'check_command_id' => $response->commandId,
'check_command_args' => $response->commandArguments,
'event_handler_enabled' => YesNoDefaultConverter::toInt($response->eventHandlerEnabled),
'event_handler_command_id' => $response->eventHandlerId,
'categories' => array_map(fn ($category): array => [
'id' => $category['id'],
'name' => $category['name'],
], $response->categories),
'groups' => array_map(fn ($group): array => [
'id' => $group['id'],
'name' => $group['name'],
], $response->groups),
'macros' => array_map(fn (MacroDto $macro): array => [
'name' => $macro->name,
'value' => $macro->isPassword ? null : $macro->value,
'is_password' => $macro->isPassword,
'description' => $macro->description,
], $response->macros),
]
)
);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Service/Infrastructure/API/AddService/AddServiceOnPremPresenter.php | centreon/src/Core/Service/Infrastructure/API/AddService/AddServiceOnPremPresenter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See 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\Service\Infrastructure\API\AddService;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\CreatedResponse;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Service\Application\UseCase\AddService\AddServicePresenterInterface;
use Core\Service\Application\UseCase\AddService\AddServiceResponse;
use Core\Service\Application\UseCase\AddService\MacroDto;
use Core\Service\Infrastructure\Model\NotificationTypeConverter;
use Core\Service\Infrastructure\Model\YesNoDefaultConverter;
class AddServiceOnPremPresenter extends AbstractPresenter implements AddServicePresenterInterface
{
public function presentResponse(ResponseStatusInterface|AddServiceResponse $response): void
{
if ($response instanceof ResponseStatusInterface) {
$this->setResponseStatus($response);
} else {
$this->present(
new CreatedResponse(
$response->id,
[
'id' => $response->id,
'name' => $response->name,
'host_id' => $response->hostId,
'comment' => $response->comment,
'service_template_id' => $response->serviceTemplateId,
'check_command_id' => $response->commandId,
'check_command_args' => $response->commandArguments,
'check_timeperiod_id' => $response->checkTimePeriodId,
'max_check_attempts' => $response->maxCheckAttempts,
'normal_check_interval' => $response->normalCheckInterval,
'retry_check_interval' => $response->retryCheckInterval,
'active_check_enabled' => YesNoDefaultConverter::toInt($response->activeChecks),
'passive_check_enabled' => YesNoDefaultConverter::toInt($response->passiveCheck),
'volatility_enabled' => YesNoDefaultConverter::toInt($response->volatility),
'notification_enabled' => YesNoDefaultConverter::toInt($response->notificationsEnabled),
'is_contact_additive_inheritance' => $response->isContactAdditiveInheritance,
'is_contact_group_additive_inheritance' => $response->isContactGroupAdditiveInheritance,
'notification_interval' => $response->notificationInterval,
'notification_timeperiod_id' => $response->notificationTimePeriodId,
'notification_type' => NotificationTypeConverter::toBits($response->notificationTypes),
'first_notification_delay' => $response->firstNotificationDelay,
'recovery_notification_delay' => $response->recoveryNotificationDelay,
'acknowledgement_timeout' => $response->acknowledgementTimeout,
'freshness_checked' => YesNoDefaultConverter::toInt($response->checkFreshness),
'freshness_threshold' => $response->freshnessThreshold,
'flap_detection_enabled' => YesNoDefaultConverter::toInt($response->flapDetectionEnabled),
'low_flap_threshold' => $response->lowFlapThreshold,
'high_flap_threshold' => $response->highFlapThreshold,
'event_handler_enabled' => YesNoDefaultConverter::toInt($response->eventHandlerEnabled),
'event_handler_command_id' => $response->eventHandlerId,
'event_handler_command_args' => $response->eventHandlerArguments,
'graph_template_id' => $response->graphTemplateId,
'note' => $response->note,
'note_url' => $response->noteUrl,
'action_url' => $response->actionUrl,
'icon_id' => $response->iconId,
'icon_alternative' => $response->iconAlternativeText,
'geo_coords' => $response->geoCoords,
'severity_id' => $response->severityId,
'is_activated' => $response->isActivated,
'macros' => array_map(fn (MacroDto $macro): array => [
'name' => $macro->name,
'value' => $macro->isPassword ? null : $macro->value,
'is_password' => $macro->isPassword,
'description' => $macro->description,
], $response->macros),
'categories' => array_map(fn ($category): array => [
'id' => $category['id'],
'name' => $category['name'],
], $response->categories),
'groups' => array_map(fn ($group): array => [
'id' => $group['id'],
'name' => $group['name'],
], $response->groups),
]
)
);
// The location will be implemented when the FindServiceTemplate API endpoint is implemented.
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Service/Infrastructure/API/AddService/AddServiceController.php | centreon/src/Core/Service/Infrastructure/API/AddService/AddServiceController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See 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\Service\Infrastructure\API\AddService;
use Centreon\Application\Controller\AbstractController;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\Common\Domain\YesNoDefault;
use Core\Service\Application\UseCase\AddService\AddService;
use Core\Service\Application\UseCase\AddService\AddServiceRequest;
use Core\Service\Application\UseCase\AddService\MacroDto;
use Core\Service\Infrastructure\Model\YesNoDefaultConverter;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
/**
* @phpstan-type _Service = array{
* name: string,
* host_id: int,
* comment: string|null,
* service_template_id: int|null,
* check_command_id: int|null,
* check_command_args: list<string>|null,
* check_timeperiod_id: int|null,
* max_check_attempts: int|null,
* normal_check_interval: int|null,
* retry_check_interval: int|null,
* active_check_enabled: int|null,
* passive_check_enabled: int|null,
* volatility_enabled: int|null,
* notification_enabled: int|null,
* is_contact_additive_inheritance: boolean|null,
* is_contact_group_additive_inheritance: boolean|null,
* notification_interval: int|null,
* notification_timeperiod_id: int|null,
* notification_type: int|null,
* first_notification_delay: int|null,
* recovery_notification_delay: int|null,
* acknowledgement_timeout: int|null,
* freshness_checked: int|null,
* freshness_threshold: int|null,
* flap_detection_enabled: int|null,
* low_flap_threshold: int|null,
* high_flap_threshold: int|null,
* event_handler_enabled: int|null,
* event_handler_command_id: int|null,
* event_handler_command_args: list<string>|null,
* graph_template_id: int|null,
* note: string|null,
* note_url: string|null,
* action_url: string|null,
* icon_id: int|null,
* icon_alternative: string|null,
* severity_id: int|null,
* is_activated: boolean|null,
* is_locked: boolean|null,
* geo_coords: string|null,
* macros: array<array{name: string, value: string|null, is_password: bool, description: string|null}>,
* service_categories: list<int>|null,
* service_groups: list<int>|null
* }
*/
final class AddServiceController extends AbstractController
{
use LoggerTrait;
/**
* @param AddService $useCase
* @param AddServiceOnPremPresenter $onPremPresenter
* @param AddServiceSaasPresenter $saasPresenter
* @param bool $isCloudPlatform
* @param Request $request
*
* @throws AccessDeniedException
*
* @return Response
*/
public function __invoke(
AddService $useCase,
AddServiceOnPremPresenter $onPremPresenter,
AddServiceSaasPresenter $saasPresenter,
bool $isCloudPlatform,
Request $request,
): Response {
$this->denyAccessUnlessGrantedForApiConfiguration();
$presenter = $isCloudPlatform ? $saasPresenter : $onPremPresenter;
$validationSchema = $isCloudPlatform
? 'AddServiceSaasSchema.json'
: 'AddServiceOnPremSchema.json';
try {
/** @var _Service $data */
$data = $this->validateAndRetrieveDataSent(
$request,
__DIR__ . DIRECTORY_SEPARATOR . $validationSchema
);
$useCase($this->createDto($data), $presenter);
} catch (\InvalidArgumentException $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
$presenter->setResponseStatus(new InvalidArgumentResponse($ex));
}
return $presenter->show();
}
/**
* @param _Service $request
*
* @return AddServiceRequest
*/
private function createDto(array $request): AddServiceRequest
{
$defaultOptionValue = YesNoDefaultConverter::toInt(YesNoDefault::Default);
$dto = new AddServiceRequest();
$dto->name = $request['name'];
$dto->hostId = $request['host_id'];
$dto->comment = $request['comment'] ?? null;
$dto->serviceTemplateParentId = $request['service_template_id'];
$dto->commandId = $request['check_command_id'];
$dto->commandArguments = $request['check_command_args'] ?? [];
$dto->checkTimePeriodId = $request['check_timeperiod_id'];
$dto->maxCheckAttempts = $request['max_check_attempts'] ?? null;
$dto->normalCheckInterval = $request['normal_check_interval'] ?? null;
$dto->retryCheckInterval = $request['retry_check_interval'] ?? null;
$dto->activeChecks = $request['active_check_enabled'] ?? $defaultOptionValue;
$dto->passiveCheck = $request['passive_check_enabled'] ?? $defaultOptionValue;
$dto->volatility = $request['volatility_enabled'] ?? $defaultOptionValue;
$dto->notificationsEnabled = $request['notification_enabled'] ?? $defaultOptionValue;
$dto->isContactAdditiveInheritance = $request['is_contact_additive_inheritance'] ?? false;
$dto->isContactGroupAdditiveInheritance = $request['is_contact_group_additive_inheritance'] ?? false;
$dto->notificationInterval = $request['notification_interval'] ?? null;
$dto->notificationTimePeriodId = $request['notification_timeperiod_id'] ?? null;
$dto->notificationTypes = $request['notification_type'] ?? null;
$dto->firstNotificationDelay = $request['first_notification_delay'] ?? null;
$dto->recoveryNotificationDelay = $request['recovery_notification_delay'] ?? null;
$dto->acknowledgementTimeout = $request['acknowledgement_timeout'] ?? null;
$dto->checkFreshness = $request['freshness_checked'] ?? $defaultOptionValue;
$dto->freshnessThreshold = $request['freshness_threshold'] ?? null;
$dto->flapDetectionEnabled = $request['flap_detection_enabled'] ?? $defaultOptionValue;
$dto->lowFlapThreshold = $request['low_flap_threshold'] ?? null;
$dto->highFlapThreshold = $request['high_flap_threshold'] ?? null;
$dto->eventHandlerEnabled = $request['event_handler_enabled'] ?? $defaultOptionValue;
$dto->eventHandlerId = $request['event_handler_command_id'] ?? null;
$dto->eventHandlerArguments = $request['event_handler_command_args'] ?? [];
$dto->graphTemplateId = $request['graph_template_id'] ?? null;
$dto->note = $request['note'];
$dto->noteUrl = $request['note_url'];
$dto->actionUrl = $request['action_url'];
$dto->iconId = $request['icon_id'] ?? null;
$dto->iconAlternativeText = $request['icon_alternative'] ?? null;
$dto->severityId = $request['severity_id'];
$dto->geoCoords = $request['geo_coords'] ?? '';
$dto->isActivated = $request['is_activated'] ?? true;
$dto->serviceCategories = $request['service_categories'] ?? [];
$dto->serviceGroups = $request['service_groups'] ?? [];
foreach ($request['macros'] as $macro) {
$dto->macros[] = new MacroDto(
$macro['name'],
$macro['value'],
(bool) $macro['is_password'],
$macro['description']
);
}
return $dto;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Proxy/Application/Repository/ReadProxyRepositoryInterface.php | centreon/src/Core/Proxy/Application/Repository/ReadProxyRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See 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\Proxy\Application\Repository;
use Core\Proxy\Domain\Model\Proxy;
interface ReadProxyRepositoryInterface
{
/**
* Return the proxy configuration or null.
*
* @return Proxy|null
*/
public function getProxy(): ?Proxy;
/**
* Return true if a proxy is defined false otherwise.
*
* @return bool
*/
public function hasProxy(): bool;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Proxy/Domain/Model/Proxy.php | centreon/src/Core/Proxy/Domain/Model/Proxy.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Proxy\Domain\Model;
use Assert\AssertionFailedException;
use Centreon\Domain\Common\Assertion\Assertion;
class Proxy implements \Stringable
{
private string $protocol = 'http';
/**
* @param string $url
* @param ?int $port
* @param ?string $login
* @param ?string $password
*
* @throws AssertionFailedException
*/
public function __construct(
private string $url,
readonly private ?int $port = null,
private ?string $login = null,
private ?string $password = null,
) {
$this->url = trim($this->url);
Assertion::notEmptyString($this->url, 'Proxy:url');
$this->defineProtocolFromUrl();
if ($this->port !== null) {
Assertion::min($this->port, 0, 'Proxy:port');
}
if ($this->login !== null) {
$this->login = trim($this->login);
Assertion::notEmptyString($this->login, 'Proxy:login');
}
if ($this->password !== null) {
$this->password = trim($this->password);
Assertion::notEmptyString($this->password, 'Proxy:password');
}
}
/**
* **Available formats:**.
*
* <<procotol>>://<<user>>:<<password>>@<<url>>:<<port>>
*
* <<procotol>>://<<user>>:<<password>>@<<url>>
*
* <<procotol>>://<<url>>:<<port>>
*
* <<procotol>>://<<url>>
*
* @return string
*/
public function __toString()
{
$url = $this->protocol . '://' . $this->url;
if ($this->login !== null) {
$url = $this->protocol . '://' . $this->login . ':' . $this->password . '@' . $this->url;
}
if ($this->port !== null) {
$url .= ':' . $this->port;
}
return $url;
}
public function getUrl(): string
{
return $this->url;
}
public function getLogin(): ?string
{
return $this->login;
}
public function getPassword(): ?string
{
return $this->password;
}
public function getProtocol(): string
{
return $this->protocol;
}
public function getPort(): ?int
{
return $this->port;
}
private function defineProtocolFromUrl(): void
{
if ($index = mb_strpos($this->url, '://')) {
$this->protocol = mb_substr($this->url, 0, $index);
$this->url = mb_substr($this->url, $index + 3);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Proxy/Infrastructure/Repository/DbReadProxyRepository.php | centreon/src/Core/Proxy/Infrastructure/Repository/DbReadProxyRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See 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\Proxy\Infrastructure\Repository;
use Centreon\Infrastructure\DatabaseConnection;
use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB;
use Core\Proxy\Application\Repository\ReadProxyRepositoryInterface;
use Core\Proxy\Domain\Model\Proxy;
class DbReadProxyRepository extends AbstractRepositoryRDB implements ReadProxyRepositoryInterface
{
/**
* @param DatabaseConnection $db
*/
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* @inheritDoc
*/
public function getProxy(): ?Proxy
{
$statement = $this->db->query($this->translateDbName(
<<<'SQL'
SELECT `key`, `value` FROM `:db`.`options` WHERE `key` LIKE 'proxy%';
SQL
));
/**
* @var array{
* proxy_url:string|null,
* proxy_port:string|null,
* proxy_user: string|null,
* proxy_password: string|null
* }|false $proxyInfo
*/
$proxyInfo = $statement === false ? false : $statement->fetchAll(\PDO::FETCH_KEY_PAIR);
if (isset($proxyInfo['proxy_url']) && $proxyInfo['proxy_url'] !== '') {
$port = isset($proxyInfo['proxy_port']) ? (int) $proxyInfo['proxy_port'] : null;
return new Proxy(
$proxyInfo['proxy_url'],
$port,
$proxyInfo['proxy_user'],
$proxyInfo['proxy_password'],
);
}
return null;
}
/**
* @inheritDoc
*/
public function hasProxy(): bool
{
$statement = $this->db->query($this->translateDbName(
<<<'SQL'
SELECT 1 FROM `:db`.`options`
WHERE `key` = 'proxy_url'
SQL
));
return $statement && $statement->fetchColumn();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Command/Application/UseCase/MigrateAllCommands/MigrationErrorDto.php | centreon/src/Core/Command/Application/UseCase/MigrateAllCommands/MigrationErrorDto.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See 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\Command\Application\UseCase\MigrateAllCommands;
class MigrationErrorDto
{
public int $id = 0;
public string $name = '';
public string $reason = '';
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Command/Application/UseCase/MigrateAllCommands/MigrateAllCommandsPresenterInterface.php | centreon/src/Core/Command/Application/UseCase/MigrateAllCommands/MigrateAllCommandsPresenterInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See 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\Command\Application\UseCase\MigrateAllCommands;
use Core\Application\Common\UseCase\ResponseStatusInterface;
interface MigrateAllCommandsPresenterInterface
{
public function presentResponse(MigrateAllCommandsResponse|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/Command/Application/UseCase/MigrateAllCommands/MigrateAllCommands.php | centreon/src/Core/Command/Application/UseCase/MigrateAllCommands/MigrateAllCommands.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See 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\Command\Application\UseCase\MigrateAllCommands;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Command\Application\Repository\ReadCommandRepositoryInterface;
use Core\Command\Application\Repository\WriteCommandRepositoryInterface;
use Core\Command\Domain\Model\Argument;
use Core\Command\Domain\Model\Command;
use Core\Command\Domain\Model\NewCommand;
use Core\CommandMacro\Domain\Model\CommandMacro;
use Core\CommandMacro\Domain\Model\CommandMacroType;
use Psr\Log\LoggerInterface;
final class MigrateAllCommands
{
private MigrateAllCommandsResponse $response;
public function __construct(
readonly private ReadCommandRepositoryInterface $readCommandRepository,
readonly private WriteCommandRepositoryInterface $writeCommandRepository,
readonly private LoggerInterface $logger,
) {
$this->response = new MigrateAllCommandsResponse();
}
public function __invoke(MigrateAllCommandsPresenterInterface $presenter): void
{
try {
$commands = $this->readCommandRepository->findAll();
$this->migrateCommands($commands, $this->response);
$presenter->presentResponse($this->response);
} catch (\Throwable $ex) {
$this->logger->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
$presenter->presentResponse(new ErrorResponse($ex->getMessage()));
}
}
/**
* @param \Iterator<int,Command>&\Countable $commands
* @param MigrateAllCommandsResponse $response
*/
private function migrateCommands(\Iterator&\Countable $commands, MigrateAllCommandsResponse $response): void
{
$response->results = new class (
$commands,
$this->writeCommandRepository,
$this->logger,
) implements \Iterator, \Countable {
/**
* @param \Iterator<int,Command>&\Countable $commands
* @param WriteCommandRepositoryInterface $writeCommandRepository
* @param LoggerInterface $logger
*/
public function __construct(
readonly private \Iterator&\Countable $commands,
readonly private WriteCommandRepositoryInterface $writeCommandRepository,
readonly private LoggerInterface $logger,
) {
}
/**
* @return CommandRecordedDto|MigrationErrorDto
*/
public function current(): CommandRecordedDto|MigrationErrorDto
{
/** @var Command $command */
$command = $this->commands->current();
$this->logger->debug(
'Migrating command',
['command_id' => $command->getId(), 'command_name' => $command->getName()]
);
try {
if ($command->isLocked() || ! $command->isActivated()) {
$this->logger->debug(
'Command disabled or locked, skip migration',
['command_id' => $command->getId()]
);
throw new \Exception('Command disabled or locked');
}
$command = $this->preventErrors($command);
$targetNewCommandId = $this->writeCommandRepository->add(NewCommand::createFromCommand($command));
$status = new CommandRecordedDto();
$status->targetId = $targetNewCommandId;
$status->sourceId = $command->getId();
$status->name = $command->getName();
return $status;
} catch (\Throwable $ex) {
$this->logger->debug((string) $ex);
$status = new MigrationErrorDto();
$status->id = $command->getId();
$status->name = $command->getName();
$status->reason = $ex->getMessage();
return $status;
}
}
public function next(): void
{
$this->commands->next();
}
public function key(): int
{
return $this->commands->key();
}
public function valid(): bool
{
return $this->commands->key() < $this->commands->count();
}
public function rewind(): void
{
$this->commands->rewind();
}
public function count(): int
{
return $this->commands->count();
}
/**
* This method aims to avoid API errors due to corrupted/out-of-date datas in:
* - macro descriptions,
* - argument descritions.
*
* @param Command $command
*/
private function preventErrors(Command $command): Command
{
$this->logger->debug(
'Preventative cleanup of command macro descriptions',
['command_id' => $command->getId(), 'command_name' => $command->getName()]
);
$command->setMacros($this->cleanMacroDescriptions($command));
$this->logger->debug(
'Preventative cleanup of command argument descriptions',
['command_id' => $command->getId(), 'command_name' => $command->getName()]
);
$command->setArguments($this->cleanArgumentDescriptions($command));
return $command;
}
/**
* @param Command $command
*
* @return CommandMacro[]
*/
private function cleanMacroDescriptions(Command $command): array
{
preg_match_all(
'/(\$_HOST(?<macros_h>\w+)\$)|(\$_SERVICE(?<macros_s>\w+)\$)/',
$command->getCommandLine(),
$matches
);
$commandHostMacros = array_unique($matches['macros_h']);
$commandServiceMacros = array_unique($matches['macros_s']);
$updatedMacros = [];
foreach ($command->getMacros() as $macro) {
$cleanedName = str_replace(' :', '', $macro->getName());
if (
(
$macro->getType() === CommandMacroType::Host
&& ! in_array($cleanedName, $commandHostMacros, true)
)
|| (
$macro->getType() === CommandMacroType::Service
&& ! in_array($cleanedName, $commandServiceMacros, true)
)
) {
$this->logger->debug(sprintf(
"Removing command macro description '%s'",
$cleanedName
));
continue;
}
$updatedMacros[] = new CommandMacro(
commandId: $macro->getCommandId(),
type: $macro->getType(),
name: $cleanedName
);
}
return $updatedMacros;
}
/**
* @param Command $command
*
* @return Argument[]
*/
private function cleanArgumentDescriptions(Command $command): array
{
preg_match_all('/\$(?<args>ARG\d+)\$/', $command->getCommandLine(), $matches);
$commandArguments = array_unique($matches['args']);
$arguments = $command->getArguments();
foreach ($arguments as $index => $argument) {
if (! in_array($argument->getName(), $commandArguments, true)) {
$this->logger->debug(sprintf(
"Removing command argument description '%s'",
$argument->getName()
));
unset($arguments[$index]);
}
}
return $arguments;
}
};
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Command/Application/UseCase/MigrateAllCommands/MigrateAllCommandsResponse.php | centreon/src/Core/Command/Application/UseCase/MigrateAllCommands/MigrateAllCommandsResponse.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See 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\Command\Application\UseCase\MigrateAllCommands;
final class MigrateAllCommandsResponse
{
/** @var \Iterator<CommandRecordedDto|MigrationErrorDto> */
public \Iterator $results;
public function __construct()
{
$this->results = new \ArrayIterator([]);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Command/Application/UseCase/MigrateAllCommands/CommandRecordedDto.php | centreon/src/Core/Command/Application/UseCase/MigrateAllCommands/CommandRecordedDto.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See 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\Command\Application\UseCase\MigrateAllCommands;
class CommandRecordedDto
{
public int $sourceId = 0;
public int $targetId = 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/Command/Application/UseCase/AddCommand/AddCommandValidation.php | centreon/src/Core/Command/Application/UseCase/AddCommand/AddCommandValidation.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See 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\Command\Application\UseCase\AddCommand;
use Centreon\Domain\Log\LoggerTrait;
use Core\Command\Application\Exception\CommandException;
use Core\Command\Application\Repository\ReadCommandRepositoryInterface;
use Core\CommandMacro\Domain\Model\CommandMacroType;
use Core\Common\Domain\TrimmedString;
use Core\Connector\Application\Repository\ReadConnectorRepositoryInterface;
use Core\GraphTemplate\Application\Repository\ReadGraphTemplateRepositoryInterface;
class AddCommandValidation
{
use LoggerTrait;
public function __construct(
private readonly ReadCommandRepositoryInterface $readCommandRepository,
private readonly ReadConnectorRepositoryInterface $readConnectorRepository,
private readonly ReadGraphTemplateRepositoryInterface $readGraphTemplateRepository,
) {
}
/**
* @param AddCommandRequest $request
*
* @throws \Throwable
*/
public function assertIsValidName(AddCommandRequest $request): void
{
if ($this->readCommandRepository->existsByName(new TrimmedString($request->name))) {
throw CommandException::nameAlreadyExists($request->name);
}
}
/**
* Assert that the defined arguments are present in the command_line and matching the required pattern ('/\$(?<args>ARG\d+)\$/').
*
* @param AddCommandRequest $request
*
* @throws \Throwable
*/
public function assertAreValidArguments(AddCommandRequest $request): void
{
$argumentNames = array_unique(array_map(fn (ArgumentDto $arg) => $arg->name, $request->arguments));
preg_match_all('/\$(?<args>ARG\d+)\$/', $request->commandLine, $matches);
$commandArguments = array_unique($matches['args']);
$invalidArguments = [];
foreach ($argumentNames as $argumentName) {
if (! in_array($argumentName, $commandArguments, true)) {
$invalidArguments[] = $argumentName;
}
}
if ($invalidArguments !== []) {
throw CommandException::invalidArguments($invalidArguments);
}
}
/**
* Assert the defined macros are present in the command_line in the format required for their defined type.
* '/(\$_HOST(?<macros_h>\w+)\$)/' => for host macros
* '/(\$_SERVICE(?<macros_s>\w+)\$)/' => for service macros.
*
* @param AddCommandRequest $request
*
* @throws \Throwable
*/
public function assertAreValidMacros(AddCommandRequest $request): void
{
preg_match_all(
'/(\$_HOST(?<macros_h>\w+)\$)|(\$_SERVICE(?<macros_s>\w+)\$)/',
$request->commandLine,
$matches
);
$commandHostMacros = array_unique($matches['macros_h']);
$commandServiceMacros = array_unique($matches['macros_s']);
$invalidMacros = [];
foreach ($request->macros as $macro) {
if (
$macro->type === CommandMacroType::Host
&& ! in_array($macro->name, $commandHostMacros, true)
) {
$invalidMacros[] = $macro->name;
}
if (
$macro->type === CommandMacroType::Service
&& ! in_array($macro->name, $commandServiceMacros, true)
) {
$invalidMacros[] = $macro->name;
}
}
if ($invalidMacros !== []) {
throw CommandException::invalidMacros($invalidMacros);
}
}
public function assertIsValidConnector(AddCommandRequest $request): void
{
if (
$request->connectorId !== null
&& ! $this->readConnectorRepository->exists($request->connectorId)
) {
throw CommandException::idDoesNotExist('connectorId', $request->connectorId);
}
}
public function assertIsValidGraphTemplate(AddCommandRequest $request): void
{
if (
$request->graphTemplateId !== null
&& ! $this->readGraphTemplateRepository->exists($request->graphTemplateId)
) {
throw CommandException::idDoesNotExist('graphTemplateId', $request->graphTemplateId);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Command/Application/UseCase/AddCommand/AddCommandPresenterInterface.php | centreon/src/Core/Command/Application/UseCase/AddCommand/AddCommandPresenterInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See 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\Command\Application\UseCase\AddCommand;
use Core\Application\Common\UseCase\ResponseStatusInterface;
interface AddCommandPresenterInterface
{
public function presentResponse(AddCommandResponse|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/Command/Application/UseCase/AddCommand/ArgumentDto.php | centreon/src/Core/Command/Application/UseCase/AddCommand/ArgumentDto.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See 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\Command\Application\UseCase\AddCommand;
class ArgumentDto
{
public function __construct(
public string $name,
public string $description = '',
) {
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Command/Application/UseCase/AddCommand/AddCommandRequest.php | centreon/src/Core/Command/Application/UseCase/AddCommand/AddCommandRequest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See 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\Command\Application\UseCase\AddCommand;
use Core\Command\Domain\Model\CommandType;
final class AddCommandRequest
{
public string $name = '';
public CommandType $type = CommandType::Check;
public string $commandLine = '';
public bool $isShellEnabled = false;
public string $argumentExample = '';
/** @var ArgumentDto[] */
public array $arguments = [];
/** @var MacroDto[] */
public array $macros = [];
public ?int $connectorId = null;
public ?int $graphTemplateId = 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/Command/Application/UseCase/AddCommand/MacroDto.php | centreon/src/Core/Command/Application/UseCase/AddCommand/MacroDto.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See 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\Command\Application\UseCase\AddCommand;
use Core\CommandMacro\Domain\Model\CommandMacroType;
class MacroDto
{
public function __construct(
public string $name,
public CommandMacroType $type = CommandMacroType::Host,
public string $description = '',
) {
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Command/Application/UseCase/AddCommand/AddCommand.php | centreon/src/Core/Command/Application/UseCase/AddCommand/AddCommand.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See 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\Command\Application\UseCase\AddCommand;
use Assert\AssertionFailedException;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\ConflictResponse;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\Command\Application\Exception\CommandException;
use Core\Command\Application\Repository\ReadCommandRepositoryInterface;
use Core\Command\Application\Repository\WriteCommandRepositoryInterface;
use Core\Command\Domain\Model\Argument;
use Core\Command\Domain\Model\Command;
use Core\Command\Domain\Model\CommandType;
use Core\Command\Domain\Model\NewCommand;
use Core\CommandMacro\Domain\Model\CommandMacro;
use Core\CommandMacro\Domain\Model\NewCommandMacro;
use Core\Common\Domain\TrimmedString;
final class AddCommand
{
use LoggerTrait;
/** @var CommandType[] */
private $allowedCommandTypes = [];
public function __construct(
private readonly ReadCommandRepositoryInterface $readCommandRepository,
private readonly WriteCommandRepositoryInterface $writeCommandRepository,
private readonly AddCommandValidation $validation,
private readonly ContactInterface $user,
) {
}
/**
* @param AddCommandRequest $request
* @param AddCommandPresenterInterface $presenter
*/
public function __invoke(AddCommandRequest $request, AddCommandPresenterInterface $presenter): void
{
try {
$this->allowedCommandTypes = $this->getAllowedCommandTypes();
if ($this->allowedCommandTypes === [] || ! in_array($request->type, $this->allowedCommandTypes, true)) {
$this->error(
"User doesn't have sufficient rights to add a command",
['user_id' => $this->user->getId()]
);
$presenter->presentResponse(
new ForbiddenResponse(CommandException::addNotAllowed())
);
return;
}
$this->validation->assertIsValidName($request);
$this->validation->assertAreValidArguments($request);
$this->validation->assertAreValidMacros($request);
$this->validation->assertIsValidConnector($request);
$this->validation->assertIsValidGraphTemplate($request);
$newCommand = $this->createNewCommand($request);
$newCommandId = $this->writeCommandRepository->add($newCommand);
$this->info('New command created', ['command_id' => $newCommandId]);
$command = $this->readCommandRepository->findById($newCommandId);
if (! $command) {
$presenter->presentResponse(
new ErrorResponse(CommandException::errorWhileRetrieving())
);
return;
}
$presenter->presentResponse($this->createResponse($command));
} catch (AssertionFailedException $ex) {
$presenter->presentResponse(new InvalidArgumentResponse($ex));
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
} catch (CommandException $ex) {
$presenter->presentResponse(
match ($ex->getCode()) {
CommandException::CODE_CONFLICT => new ConflictResponse($ex),
default => new ErrorResponse($ex),
}
);
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
} catch (\Throwable $ex) {
$presenter->presentResponse(new ErrorResponse(CommandException::errorWhileAdding($ex)));
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
}
}
/**
* @param AddCommandRequest $request
*
* @throws \Exception
* @throws AssertionFailedException
*
* @return NewCommand
*/
private function createNewCommand(AddCommandRequest $request): NewCommand
{
$arguments = [];
foreach ($request->arguments as $argument) {
$arguments[] = new Argument(
new TrimmedString($argument->name),
new TrimmedString($argument->description ?? '')
);
}
$macros = [];
foreach ($request->macros as $macro) {
$macros[] = new NewCommandMacro(
$macro->type,
$macro->name,
$macro->description
);
}
return new NewCommand(
name: new TrimmedString($request->name),
commandLine: new TrimmedString($request->commandLine),
isShellEnabled: $request->isShellEnabled,
type: $request->type,
argumentExample: new TrimmedString($request->argumentExample),
arguments: $arguments,
macros: $macros,
connectorId: $request->connectorId,
graphTemplateId: $request->graphTemplateId,
);
}
/**
* @param Command $command
*
* @throws \Throwable
*
* @return AddCommandResponse
*/
private function createResponse(Command $command): AddCommandResponse
{
$response = new AddCommandResponse();
$response->id = $command->getId();
$response->name = $command->getName();
$response->type = $command->getType();
$response->commandLine = $command->getCommandLine();
$response->argumentExample = $command->getArgumentExample();
$response->isShellEnabled = $command->isShellEnabled();
$response->isActivated = $command->isActivated();
$response->isLocked = $command->isLocked();
$response->arguments = array_map(
fn (Argument $argument) => [
'name' => $argument->getName(),
'description' => $argument->getDescription(),
],
$command->getArguments(),
);
$response->macros = array_map(
fn (CommandMacro $macro) => [
'name' => $macro->getName(),
'description' => $macro->getDescription(),
'type' => $macro->getType(),
],
$command->getMacros(),
);
$response->connector = $command->getConnector() !== null
? [
'id' => $command->getConnector()->getId(),
'name' => (string) $command->getConnector()->getName(),
]
: null;
$response->graphTemplate = $command->getGraphTemplate() !== null
? [
'id' => $command->getGraphTemplate()->getId(),
'name' => (string) $command->getGraphTemplate()->getName(),
]
: null;
return $response;
}
/**
* @return CommandType[]
*/
private function getAllowedCommandTypes(): array
{
$allowedCommandTypes = [];
if ($this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_COMMANDS_CHECKS_RW)) {
$allowedCommandTypes[] = CommandType::Check;
}
if ($this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_COMMANDS_NOTIFICATIONS_RW)) {
$allowedCommandTypes[] = CommandType::Notification;
}
if ($this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_COMMANDS_MISCELLANEOUS_RW)) {
$allowedCommandTypes[] = CommandType::Miscellaneous;
}
if ($this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_COMMANDS_DISCOVERY_RW)) {
$allowedCommandTypes[] = CommandType::Discovery;
}
return $allowedCommandTypes;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Command/Application/UseCase/AddCommand/AddCommandResponse.php | centreon/src/Core/Command/Application/UseCase/AddCommand/AddCommandResponse.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See 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\Command\Application\UseCase\AddCommand;
use Core\Command\Domain\Model\CommandType;
use Core\CommandMacro\Domain\Model\CommandMacroType;
final class AddCommandResponse
{
public int $id = 0;
public string $name = '';
public CommandType $type = CommandType::Check;
public string $commandLine = '';
public bool $isShellEnabled = false;
public bool $isActivated = true;
public bool $isLocked = false;
public string $argumentExample = '';
/** @var array<array{name:string,description:string}> */
public array $arguments = [];
/** @var array<array{name:string,type:CommandMacroType,description:string}> */
public array $macros = [];
/** @var null|array{id:int,name:string} */
public null|array $connector = null;
/** @var null|array{id:int,name:string} */
public null|array $graphTemplate = 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/Command/Application/UseCase/FindCommands/CommandDto.php | centreon/src/Core/Command/Application/UseCase/FindCommands/CommandDto.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See 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\Command\Application\UseCase\FindCommands;
use Core\Command\Domain\Model\CommandType;
class CommandDto
{
public int $id = 0;
public string $name = '';
public string $commandLine = '';
public CommandType $type = CommandType::Check;
public bool $isShellEnabled = false;
public bool $isActivated = true;
public bool $isLocked = 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/Command/Application/UseCase/FindCommands/FindCommandsResponse.php | centreon/src/Core/Command/Application/UseCase/FindCommands/FindCommandsResponse.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See 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\Command\Application\UseCase\FindCommands;
final class FindCommandsResponse
{
/** @var CommandDto[] */
public array $commands = [];
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Command/Application/UseCase/FindCommands/FindCommands.php | centreon/src/Core/Command/Application/UseCase/FindCommands/FindCommands.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See 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\Command\Application\UseCase\FindCommands;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Centreon\Infrastructure\RequestParameters\RequestParametersTranslatorException;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Command\Application\Exception\CommandException;
use Core\Command\Application\Repository\ReadCommandRepositoryInterface;
use Core\Command\Domain\Model\Command;
use Core\Command\Domain\Model\CommandType;
final class FindCommands
{
use LoggerTrait;
public function __construct(
private readonly RequestParametersInterface $requestParameters,
private readonly ReadCommandRepositoryInterface $readCommandRepository,
private readonly ContactInterface $contact,
) {
}
/**
* @param FindCommandsPresenterInterface $presenter
*/
public function __invoke(FindCommandsPresenterInterface $presenter): void
{
try {
$commandTypes = $this->retrieveCommandTypesBasedOnContactRights();
if ($commandTypes === []) {
$this->error(
"User doesn't have sufficient rights to see commands",
['user_id' => $this->contact->getId()]
);
$presenter->presentResponse(
new ForbiddenResponse(CommandException::accessNotAllowed())
);
return;
}
$commands = $this->readCommandRepository->findByRequestParameterAndTypes(
$this->requestParameters,
$commandTypes
);
$presenter->presentResponse($this->createResponse($commands));
} catch (RequestParametersTranslatorException $ex) {
$presenter->presentResponse(new ErrorResponse($ex->getMessage()));
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
} catch (\Throwable $ex) {
$presenter->presentResponse(new ErrorResponse(CommandException::errorWhileSearching($ex)));
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
}
}
/**
* @param Command[] $commands
*
* @return FindCommandsResponse
*/
private function createResponse(array $commands): FindCommandsResponse
{
$response = new FindCommandsResponse();
foreach ($commands as $command) {
$commandDto = new CommandDto();
$commandDto->id = $command->getId();
$commandDto->name = $command->getName();
$commandDto->type = $command->getType();
$commandDto->commandLine = $command->getCommandLine();
$commandDto->isShellEnabled = $command->isShellEnabled();
$commandDto->isActivated = $command->isActivated();
$commandDto->isLocked = $command->isLocked();
$response->commands[] = $commandDto;
}
return $response;
}
/**
* @return CommandType[]
*/
private function retrieveCommandTypesBasedOnContactRights(): array
{
if ($this->contact->isAdmin()) {
return [
CommandType::Notification,
CommandType::Check,
CommandType::Miscellaneous,
CommandType::Discovery,
];
}
$commandsTypes = [];
if (
$this->contact->hasTopologyRole(Contact::ROLE_CONFIGURATION_COMMANDS_CHECKS_R)
|| $this->contact->hasTopologyRole(Contact::ROLE_CONFIGURATION_COMMANDS_CHECKS_RW)
) {
$commandsTypes[] = CommandType::Check;
}
if (
$this->contact->hasTopologyRole(Contact::ROLE_CONFIGURATION_COMMANDS_NOTIFICATIONS_R)
|| $this->contact->hasTopologyRole(Contact::ROLE_CONFIGURATION_COMMANDS_NOTIFICATIONS_RW)
) {
$commandsTypes[] = CommandType::Notification;
}
if (
$this->contact->hasTopologyRole(Contact::ROLE_CONFIGURATION_COMMANDS_MISCELLANEOUS_R)
|| $this->contact->hasTopologyRole(Contact::ROLE_CONFIGURATION_COMMANDS_MISCELLANEOUS_RW)
) {
$commandsTypes[] = CommandType::Miscellaneous;
}
if (
$this->contact->hasTopologyRole(Contact::ROLE_CONFIGURATION_COMMANDS_DISCOVERY_R)
|| $this->contact->hasTopologyRole(Contact::ROLE_CONFIGURATION_COMMANDS_DISCOVERY_RW)
) {
$commandsTypes[] = CommandType::Discovery;
}
return $commandsTypes;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Command/Application/UseCase/FindCommands/FindCommandsPresenterInterface.php | centreon/src/Core/Command/Application/UseCase/FindCommands/FindCommandsPresenterInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See 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\Command\Application\UseCase\FindCommands;
use Core\Application\Common\UseCase\ResponseStatusInterface;
interface FindCommandsPresenterInterface
{
public function presentResponse(FindCommandsResponse|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/Command/Application/Exception/CommandException.php | centreon/src/Core/Command/Application/Exception/CommandException.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See 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\Command\Application\Exception;
final class CommandException extends \Exception
{
public const CODE_CONFLICT = 1;
/**
* @return self
*/
public static function accessNotAllowed(): self
{
return new self(_('You are not allowed to access commands'));
}
/**
* @param \Throwable $ex
*
* @return self
*/
public static function errorWhileSearching(\Throwable $ex): self
{
return new self(_('Error while searching for commands'), 0, $ex);
}
/**
* @param string $name
*
* @return CommandException
*/
public static function nameAlreadyExists(string $name): self
{
return new self(
sprintf(_("The '%s' command name already exists"), $name),
self::CODE_CONFLICT
);
}
/**
* @param int $type
*
* @return CommandException
*/
public static function invalidCommandType(int $type): self
{
return new self(
sprintf(_("'%d' is not a valid command type"), $type),
self::CODE_CONFLICT
);
}
/**
* @param string[] $arguments
*
* @return CommandException
*/
public static function invalidArguments(array $arguments): self
{
return new self(
sprintf(_('The following arguments are not valid: %s'), implode(', ', $arguments)),
self::CODE_CONFLICT
);
}
/**
* @param string[] $macros
*
* @return CommandException
*/
public static function invalidMacros(array $macros): self
{
return new self(
sprintf(_('The following macros are not valid: %s'), implode(', ', $macros)),
self::CODE_CONFLICT
);
}
/**
* @return self
*/
public static function addNotAllowed(): self
{
return new self(_('You are not allowed to add a command'));
}
/**
* @param \Throwable $ex
*
* @return self
*/
public static function errorWhileAdding(\Throwable $ex): self
{
return new self(_('Error while adding the command'), 0, $ex);
}
/**
* @return self
*/
public static function errorWhileRetrieving(): self
{
return new self(_('Error while retrieving a command'));
}
/**
* @param string $propertyName
* @param int $propertyValue
*
* @return self
*/
public static function idDoesNotExist(string $propertyName, int $propertyValue): self
{
return new self(
sprintf(
_("The %s with value '%d' does not exist"),
$propertyName,
$propertyValue
),
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/Command/Application/Repository/WriteCommandRepositoryInterface.php | centreon/src/Core/Command/Application/Repository/WriteCommandRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See 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\Command\Application\Repository;
use Core\Command\Domain\Model\NewCommand;
interface WriteCommandRepositoryInterface
{
/**
* Add a command.
*
* @param NewCommand $command
*
* @throws \Throwable
*
* @return int
*/
public function add(NewCommand $command): int;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Command/Application/Repository/ReadCommandRepositoryInterface.php | centreon/src/Core/Command/Application/Repository/ReadCommandRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See 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\Command\Application\Repository;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Command\Domain\Model\Command;
use Core\Command\Domain\Model\CommandType;
use Core\Common\Domain\TrimmedString;
interface ReadCommandRepositoryInterface
{
/**
* Determine if a command exists by its ID.
*
* @param int $commandId
*
* @throws \Throwable
*
* @return bool
*/
public function exists(int $commandId): bool;
/**
* Determine if a command exists by its ID and type.
*
* @param int $commandId
* @param CommandType $commandType
*
* @throws \Throwable
*
* @return bool
*/
public function existsByIdAndCommandType(int $commandId, CommandType $commandType): bool;
/**
* Determine if a command exists by its name.
*
* @param TrimmedString $name
*
* @throws \Throwable
*
* @return bool
*/
public function existsByName(TrimmedString $name): bool;
/**
* Retrieve a command by its ID.
*
* @param int $commandId
*
* @throws \Throwable
*
* @return Command|null
*/
public function findById(int $commandId): ?Command;
/**
* Retrieve commands by their IDs.
* The array key is the command ID.
*
* @param int[] $commandIds
*
* @throws \Throwable
*
* @return Command[]
*/
public function findByIds(array $commandIds): array;
/**
* Search for all commands based on request parameters and command types.
*
* @param RequestParametersInterface $requestParameters
* @param CommandType[] $commandTypes
*
* @throws \Throwable
*
* @return Command[]
*/
public function findByRequestParameterAndTypes(
RequestParametersInterface $requestParameters,
array $commandTypes,
): array;
/**
* Find all commands.
*
* @throws \Throwable
*
* @return \Iterator<int,Command>&\Countable
*/
public function findAll(): \Iterator&\Countable;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Command/Domain/Model/CommandType.php | centreon/src/Core/Command/Domain/Model/CommandType.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See 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\Command\Domain\Model;
enum CommandType
{
case Notification;
case Check;
case Miscellaneous;
case Discovery;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Command/Domain/Model/Command.php | centreon/src/Core/Command/Domain/Model/Command.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Command\Domain\Model;
use Assert\AssertionFailedException;
use Centreon\Domain\Common\Assertion\Assertion;
use Core\CommandMacro\Domain\Model\CommandMacro;
use Core\Common\Domain\SimpleEntity;
use Core\MonitoringServer\Model\MonitoringServer;
class Command
{
public const COMMAND_MAX_LENGTH = NewCommand::COMMAND_MAX_LENGTH;
public const EXAMPLE_MAX_LENGTH = NewCommand::EXAMPLE_MAX_LENGTH;
public const NAME_MAX_LENGTH = NewCommand::NAME_MAX_LENGTH;
/**
* @param int $id
* @param string $name
* @param string $commandLine
* @param bool $isShellEnabled
* @param bool $isActivated
* @param string $argumentExample
* @param Argument[] $arguments
* @param CommandMacro[] $macros
* @param null|SimpleEntity $connector
* @param null|SimpleEntity $graphTemplate
* @param CommandType $type
* @param bool $isLocked
*
* @throws AssertionFailedException
*/
public function __construct(
private readonly int $id,
private string $name,
private string $commandLine,
private bool $isShellEnabled = false,
private bool $isActivated = true,
private string $argumentExample = '',
private array $arguments = [],
private array $macros = [],
private ?SimpleEntity $connector = null,
private ?SimpleEntity $graphTemplate = null,
private readonly CommandType $type = CommandType::Check,
private readonly bool $isLocked = false,
) {
Assertion::positiveInt($id, 'Command::id');
Assertion::notEmptyString($name, 'Command::name');
Assertion::maxLength($name, self::NAME_MAX_LENGTH, 'Command::name');
Assertion::unauthorizedCharacters(
$name,
MonitoringServer::ILLEGAL_CHARACTERS,
'Command::name'
);
Assertion::notEmptyString($commandLine, 'Command::commandLine');
Assertion::maxLength($commandLine, self::COMMAND_MAX_LENGTH, 'Command::commandLine');
Assertion::maxLength($argumentExample, self::EXAMPLE_MAX_LENGTH, 'Command::argumentExample');
}
public function getId(): int
{
return $this->id;
}
public function getName(): string
{
return $this->name;
}
public function getCommandLine(): string
{
return $this->commandLine;
}
public function getType(): CommandType
{
return $this->type;
}
public function isShellEnabled(): bool
{
return $this->isShellEnabled;
}
public function isActivated(): bool
{
return $this->isActivated;
}
public function isLocked(): bool
{
return $this->isLocked;
}
public function getArgumentExample(): string
{
return $this->argumentExample;
}
/**
* @return Argument[]
*/
public function getArguments(): array
{
return $this->arguments;
}
/**
* @return CommandMacro[]
*/
public function getMacros(): array
{
return $this->macros;
}
public function getConnector(): ?SimpleEntity
{
return $this->connector;
}
public function getGraphTemplate(): ?SimpleEntity
{
return $this->graphTemplate;
}
/**
* @param Argument[] $arguments
*/
public function setArguments(array $arguments): void
{
$this->arguments = $arguments;
}
/**
* @param CommandMacro[] $macros
*/
public function setMacros(array $macros): void
{
$this->macros = $macros;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Command/Domain/Model/NewCommand.php | centreon/src/Core/Command/Domain/Model/NewCommand.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See 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\Command\Domain\Model;
use Assert\AssertionFailedException;
use Centreon\Domain\Common\Assertion\Assertion;
use Core\CommandMacro\Domain\Model\CommandMacro;
use Core\CommandMacro\Domain\Model\NewCommandMacro;
use Core\Common\Domain\TrimmedString;
use Core\MonitoringServer\Model\MonitoringServer;
class NewCommand
{
public const COMMAND_MAX_LENGTH = 65535;
public const EXAMPLE_MAX_LENGTH = 255;
public const NAME_MAX_LENGTH = 200;
/**
* @param TrimmedString $name
* @param TrimmedString $commandLine
* @param bool $isShellEnabled
* @param CommandType $type
* @param TrimmedString $argumentExample
* @param Argument[] $arguments
* @param NewCommandMacro[] $macros
* @param null|int $connectorId
* @param null|int $graphTemplateId
*
* @throws AssertionFailedException
*/
public function __construct(
private readonly TrimmedString $name,
private readonly TrimmedString $commandLine,
private readonly bool $isShellEnabled = false,
private readonly CommandType $type = CommandType::Check,
private readonly TrimmedString $argumentExample = new TrimmedString(''),
private readonly array $arguments = [],
private readonly array $macros = [],
private readonly ?int $connectorId = null,
private readonly ?int $graphTemplateId = null,
) {
Assertion::notEmptyString($name->value, 'NewCommand::name');
Assertion::maxLength($name->value, self::NAME_MAX_LENGTH, 'NewCommand::name');
Assertion::unauthorizedCharacters(
$name->value,
MonitoringServer::ILLEGAL_CHARACTERS,
'NewCommand::name'
);
Assertion::notEmptyString($commandLine->value, 'NewCommand::commandLine');
Assertion::maxLength($commandLine->value, self::COMMAND_MAX_LENGTH, 'NewCommand::commandLine');
Assertion::maxLength($argumentExample->value, self::EXAMPLE_MAX_LENGTH, 'NewCommand::argumentExample');
if ($connectorId !== null) {
Assertion::positiveInt($connectorId, 'NewCommand::connectorId');
}
if ($graphTemplateId !== null) {
Assertion::positiveInt($graphTemplateId, 'NewCommand::graphTemplateId');
}
}
public function getName(): string
{
return $this->name->value;
}
public function getCommandLine(): string
{
return $this->commandLine->value;
}
public function getType(): CommandType
{
return $this->type;
}
public function isShellEnabled(): bool
{
return $this->isShellEnabled;
}
public function getArgumentExample(): string
{
return $this->argumentExample->value;
}
/**
* @return Argument[]
*/
public function getArguments(): array
{
return $this->arguments;
}
/**
* @return NewCommandMacro[]
*/
public function getMacros(): array
{
return $this->macros;
}
public function getConnectorId(): ?int
{
return $this->connectorId;
}
public function getGraphTemplateId(): ?int
{
return $this->graphTemplateId;
}
/**
* @param Command $command
*
* @throws AssertionFailedException
*
* @return NewCommand
*/
public static function createFromCommand(Command $command): self
{
return new self(
name: new TrimmedString($command->getName()),
commandLine: new TrimmedString($command->getCommandLine()),
isShellEnabled: $command->isShellEnabled(),
type: $command->getType(),
argumentExample: new TrimmedString($command->getArgumentExample()),
arguments: $command->getArguments(),
macros: array_map(
fn (CommandMacro $macro) => NewCommandMacro::createFromMacro($macro),
$command->getMacros()
),
connectorId: $command->getConnector()?->getId(),
graphTemplateId: $command->getGraphTemplate()?->getId(),
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Command/Domain/Model/Argument.php | centreon/src/Core/Command/Domain/Model/Argument.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See 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\Command\Domain\Model;
use Assert\AssertionFailedException;
use Centreon\Domain\Common\Assertion\Assertion;
use Core\Common\Domain\TrimmedString;
class Argument
{
public const NAME_MAX_LENGTH = 255;
public const DESCRIPTION_MAX_LENGTH = 255;
/**
* @param TrimmedString $name
* @param TrimmedString $description
*
* @throws AssertionFailedException
*/
public function __construct(
private readonly TrimmedString $name,
private readonly TrimmedString $description,
) {
Assertion::notEmptyString($name->value, 'Argument::name');
Assertion::maxLength($name->value, self::NAME_MAX_LENGTH, 'Argument::name');
Assertion::regex($name->value, '/^ARG\d+$/', 'Argument::name');
Assertion::maxLength($description->value, self::DESCRIPTION_MAX_LENGTH, 'Argument::description');
}
public function getName(): string
{
return $this->name->value;
}
public function getDescription(): string
{
return $this->description->value;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Command/Infrastructure/Model/CommandTypeConverter.php | centreon/src/Core/Command/Infrastructure/Model/CommandTypeConverter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See 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\Command\Infrastructure\Model;
use Core\Command\Domain\Model\CommandType;
final class CommandTypeConverter
{
/**
* @param CommandType $commandType
*
* @return int
*/
public static function toInt(CommandType $commandType): int
{
return match ($commandType) {
CommandType::Notification => 1,
CommandType::Check => 2,
CommandType::Miscellaneous => 3,
CommandType::Discovery => 4,
};
}
/**
* @param int $commandType
*
* @throws \RangeException
*
* @return CommandType
*/
public static function fromInt(int $commandType): CommandType
{
return match ($commandType) {
1 => CommandType::Notification,
2 => CommandType::Check,
3 => CommandType::Miscellaneous,
4 => CommandType::Discovery,
default => throw new \RangeException('Command type must be between 1 and 4'),
};
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Command/Infrastructure/Repository/DbWriteCommandRepository.php | centreon/src/Core/Command/Infrastructure/Repository/DbWriteCommandRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See 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\Command\Infrastructure\Repository;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Infrastructure\DatabaseConnection;
use Core\Command\Application\Repository\WriteCommandRepositoryInterface;
use Core\Command\Domain\Model\NewCommand;
use Core\Command\Infrastructure\Model\CommandTypeConverter;
use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB;
use Core\Common\Infrastructure\Repository\RepositoryTrait;
use Core\Common\Infrastructure\RequestParameters\Normalizer\BoolToEnumNormalizer;
class DbWriteCommandRepository extends AbstractRepositoryRDB implements WriteCommandRepositoryInterface
{
use LoggerTrait;
use RepositoryTrait;
/**
* @param DatabaseConnection $db
*/
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* @inheritDoc
*/
public function add(NewCommand $command): int
{
$alreadyInTransaction = $this->db->inTransaction();
if (! $alreadyInTransaction) {
$this->db->beginTransaction();
}
try {
$commandId = $this->addCommand($command);
$this->addArguments($commandId, $command);
$this->addMacros($commandId, $command);
if (! $alreadyInTransaction) {
$this->db->commit();
}
return $commandId;
} catch (\Throwable $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
if (! $alreadyInTransaction) {
$this->db->rollBack();
}
throw $ex;
}
}
/**
* @param NewCommand $command
*
* @throws \Throwable
*
* @return int
*/
private function addCommand(NewCommand $command): int
{
$request = $this->translateDbName(
<<<'SQL'
INSERT INTO `:db`.command
(
command_name,
command_line,
command_example,
command_type,
graph_id,
connector_id,
enable_shell
) VALUES
(
:command_name,
:command_line,
:argument_example,
:command_type,
:graph_id,
:connector_id,
:enable_shell
)
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':command_name', $command->getName(), \PDO::PARAM_STR);
$statement->bindValue(':command_type', CommandTypeConverter::toInt($command->getType()), \PDO::PARAM_STR);
$statement->bindValue(':command_line', $command->getCommandLine(), \PDO::PARAM_STR);
$statement->bindValue(':argument_example', $command->getArgumentExample(), \PDO::PARAM_STR);
$statement->bindValue(':graph_id', $command->getGraphTemplateId(), \PDO::PARAM_INT);
$statement->bindValue(':connector_id', $command->getConnectorId(), \PDO::PARAM_INT);
$statement->bindValue(
':enable_shell',
(new BoolToEnumNormalizer())->normalize($command->isShellEnabled()),
\PDO::PARAM_INT
);
$statement->execute();
return (int) $this->db->lastInsertId();
}
/**
* @param int $commandId
* @param NewCommand $command
*
* @throws \Throwable
*/
private function addArguments(int $commandId, NewCommand $command): void
{
if ($command->getArguments() === []) {
$this->debug("No argument for command {$commandId}");
return;
}
$request = <<<'SQL'
INSERT INTO `:db`.command_arg_description
(
cmd_id,
macro_name,
macro_description
) VALUES
SQL;
foreach ($command->getArguments() as $key => $argument) {
$request .= $key > 0 ? ', ' : '';
$request .= <<<SQL
(
:commandId,
:argName_{$key},
:argDescription_{$key}
)
SQL;
}
$statement = $this->db->prepare($this->translateDbName($request));
foreach ($command->getArguments() as $key => $argument) {
$statement->bindValue(":argName_{$key}", $argument->getName(), \PDO::PARAM_STR);
$statement->bindValue(":argDescription_{$key}", $argument->getDescription(), \PDO::PARAM_STR);
}
$statement->bindValue(':commandId', $commandId, \PDO::PARAM_STR);
$statement->execute();
}
/**
* @param int $commandId
* @param NewCommand $command
*
* @throws \Throwable
*/
private function addMacros(int $commandId, NewCommand $command): void
{
if ($command->getMacros() === []) {
$this->debug("No macro for command {$commandId}");
return;
}
$request = <<<'SQL'
INSERT INTO `:db`.on_demand_macro_command
(
command_macro_name,
command_macro_desciption,
command_command_id,
command_macro_type
) VALUES
SQL;
foreach ($command->getMacros() as $key => $macro) {
$request .= $key > 0 ? ', ' : '';
$request .= <<<SQL
(
:macroName_{$key},
:macroDescription_{$key},
:commandId,
:macroType_{$key}
)
SQL;
}
$statement = $this->db->prepare($this->translateDbName($request));
foreach ($command->getMacros() as $key => $macro) {
$statement->bindValue(":macroName_{$key}", $macro->getName(), \PDO::PARAM_STR);
$statement->bindValue(":macroDescription_{$key}", $macro->getDescription(), \PDO::PARAM_STR);
$statement->bindValue(":macroType_{$key}", $macro->getType()->value, \PDO::PARAM_STR);
}
$statement->bindValue(':commandId', $commandId, \PDO::PARAM_STR);
$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/Command/Infrastructure/Repository/DbReadCommandRepository.php | centreon/src/Core/Command/Infrastructure/Repository/DbReadCommandRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See 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\Command\Infrastructure\Repository;
use Assert\AssertionFailedException;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Centreon\Domain\RequestParameters\RequestParameters;
use Centreon\Infrastructure\DatabaseConnection;
use Centreon\Infrastructure\RequestParameters\SqlRequestParametersTranslator;
use Core\Command\Application\Repository\ReadCommandRepositoryInterface;
use Core\Command\Domain\Model\Argument;
use Core\Command\Domain\Model\Command;
use Core\Command\Domain\Model\CommandType;
use Core\Command\Infrastructure\Model\CommandTypeConverter;
use Core\CommandMacro\Domain\Model\CommandMacro;
use Core\CommandMacro\Domain\Model\CommandMacroType;
use Core\Common\Domain\SimpleEntity;
use Core\Common\Domain\TrimmedString;
use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB;
use Core\Common\Infrastructure\RequestParameters\Normalizer\BoolToIntegerNormalizer;
use Psr\Log\LoggerInterface;
use Utility\SqlConcatenator;
/**
* @phpstan-type _Command array{
* command_id: int,
* command_name: string,
* command_line: string,
* command_example?: string|null,
* command_type: int,
* enable_shell: int,
* command_activate: string,
* command_locked: int,
* connector_id?: int|null,
* connector_name?: string|null,
* graph_template_id?: int|null,
* graph_template_name?: string|null,
* }
*/
class DbReadCommandRepository extends AbstractRepositoryRDB implements ReadCommandRepositoryInterface
{
private const MAX_ITEMS_BY_REQUEST = 100;
/**
* @param DatabaseConnection $db
* @param LoggerInterface $logger
*/
public function __construct(DatabaseConnection $db, readonly private LoggerInterface $logger)
{
$this->db = $db;
}
/**
* @inheritDoc
*/
public function exists(int $commandId): bool
{
$this->logger->info(sprintf('Check existence of command with ID #%d', $commandId));
$request = $this->translateDbName(
<<<'SQL'
SELECT 1
FROM `:db`.command
WHERE command_id = :commandId
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':commandId', $commandId, \PDO::PARAM_INT);
$statement->execute();
return (bool) $statement->fetchColumn();
}
/**
* @inheritDoc
*/
public function existsByIdAndCommandType(int $commandId, CommandType $commandType): bool
{
$this->logger->info(
sprintf(
'Check existence of command with ID #%d and type %s',
$commandId,
CommandTypeConverter::toInt($commandType)
)
);
$request = $this->translateDbName(
<<<'SQL'
SELECT 1
FROM `:db`.command
WHERE command_id = :commandId
AND command_type = :commandType
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':commandId', $commandId, \PDO::PARAM_INT);
$statement->bindValue(':commandType', CommandTypeConverter::toInt($commandType), \PDO::PARAM_INT);
$statement->execute();
return (bool) $statement->fetchColumn();
}
/**
* @inheritDoc
*/
public function existsByName(TrimmedString $name): bool
{
$request = $this->translateDbName(
<<<'SQL'
SELECT 1
FROM `:db`.command
WHERE command_name = :commandName
SQL
);
$statement = $this->db->prepare($request);
$statement->bindValue(':commandName', $name->value, \PDO::PARAM_STR);
$statement->execute();
return (bool) $statement->fetchColumn();
}
/**
* @inheritDoc
*/
public function findById(int $commandId): ?Command
{
$request = <<<'SQL'
SELECT
command.command_id,
command.command_name,
command.command_line,
command.command_example,
command.command_type,
command.enable_shell,
command.command_activate,
command.command_locked,
command.connector_id,
connector.name as connector_name,
command.graph_id as graph_template_id,
giv_graphs_template.name as graph_template_name
FROM `:db`.command
LEFT JOIN `:db`.connector
ON command.connector_id = connector.id
LEFT JOIN `:db`.giv_graphs_template
ON command.graph_id = giv_graphs_template.graph_id
WHERE command.command_id = :commandId
SQL;
$statement = $this->db->prepare($this->translateDbName($request));
$statement->bindValue(':commandId', $commandId, \PDO::PARAM_INT);
$statement->execute();
if (! ($result = $statement->fetch(\PDO::FETCH_ASSOC))) {
return null;
}
/** @var _Command $result */
$command = $this->createCommand($result);
$command->setArguments($this->findArgumentsByCommandId($commandId));
$command->setMacros($this->findMacrosByCommandId($commandId));
return $command;
}
/**
* @inheritDoc
*/
public function findByIds(array $commandIds): array
{
$sqlConcatenator = new SqlConcatenator();
$sqlConcatenator->defineSelect(
<<<'SQL'
SELECT
command.command_id,
command.command_name,
command.command_line,
command.command_example,
command.command_type,
command.enable_shell,
command.command_activate,
command.command_locked,
command.connector_id,
connector.name as connector_name,
command.graph_id as graph_template_id,
giv_graphs_template.name as graph_template_name
FROM `:db`.command
LEFT JOIN `:db`.connector
ON command.connector_id = connector.id
LEFT JOIN `:db`.giv_graphs_template
ON command.graph_id = giv_graphs_template.graph_id
SQL
);
$sqlConcatenator->appendWhere('command_id IN (:command_ids)');
$sqlConcatenator->storeBindValueMultiple(
':command_ids',
$commandIds,
\PDO::PARAM_INT
);
$statement = $this->db->prepare($this->translateDbName((string) $sqlConcatenator));
$sqlConcatenator->bindValuesToStatement($statement);
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$statement->execute();
$commands = [];
foreach ($statement as $result) {
/** @var _Command $result */
$command = $this->createCommand($result);
$commands[$command->getId()] = $command;
}
return $commands;
}
/**
* @inheritDoc
*/
public function findByRequestParameterAndTypes(
RequestParametersInterface $requestParameters,
array $commandTypes,
): array {
$commands = [];
if ($commandTypes === []) {
return $commands;
}
$sqlTranslator = new SqlRequestParametersTranslator($requestParameters);
$sqlTranslator->getRequestParameters()->setConcordanceStrictMode(RequestParameters::CONCORDANCE_MODE_STRICT);
$sqlTranslator->setConcordanceArray([
'id' => 'command_id',
'name' => 'command_name',
'type' => 'command_type',
'is_locked' => 'command_locked',
]);
$sqlTranslator->addNormalizer('is_locked', new BoolToIntegerNormalizer());
$request = <<<'SQL'
SELECT
command_id,
command_name,
command_line,
command_type,
enable_shell,
command_activate,
command_locked
FROM `:db`.command
SQL;
$sqlConcatenator = new SqlConcatenator();
$sqlConcatenator->defineSelect($request);
$sqlConcatenator->appendWhere('command_type IN (:command_type)');
$sqlConcatenator->storeBindValueMultiple(
':command_type',
array_map(
fn (CommandType $commandType): int => CommandTypeConverter::toInt($commandType),
$commandTypes
),
\PDO::PARAM_INT
);
$sqlTranslator->translateForConcatenator($sqlConcatenator);
$statement = $this->db->prepare($this->translateDbName((string) $sqlConcatenator));
$sqlTranslator->bindSearchValues($statement);
$sqlConcatenator->bindValuesToStatement($statement);
$statement->execute();
$sqlTranslator->calculateNumberOfRows($this->db);
while ($result = $statement->fetch(\PDO::FETCH_ASSOC)) {
/** @var _Command $result */
$commands[] = $this->createCommand($result);
}
return $commands;
}
/**
* @inheritDoc
*/
public function findAll(): \Iterator&\Countable
{
$this->logger->debug(sprintf('Loading commands in blocks of %d elements', self::MAX_ITEMS_BY_REQUEST));
return new class ($this->db, self::MAX_ITEMS_BY_REQUEST, $this->createCommand(...), $this->findArgumentsByCommandId(...), $this->findMacrosByCommandId(...), $this->logger) extends AbstractRepositoryRDB implements \Iterator, \Countable {
/** @var callable */
protected $createCommand;
/** @var callable */
protected $findArguments;
/** @var callable */
protected $findMacros;
private int $position = 0;
private int $requestIndex = 0;
private int $totalItems = 0;
private false|\PDOStatement $statement = false;
/**
* @var false|array{
* command_id: int,
* command_name: string,
* command_line: string,
* command_example?: string|null,
* command_type: int,
* enable_shell: int,
* command_activate: string,
* command_locked: int,
* connector_id?: int|null,
* connector_name?: string|null,
* graph_template_id?: int|null,
* graph_template_name?: string|null,
* }
*/
private false|array $currentItem;
public function __construct(
DatabaseConnection $db,
readonly private int $maxItemByRequest,
callable $createCommand,
callable $findArguments,
callable $findMacros,
readonly private LoggerInterface $logger,
) {
$this->db = $db;
$this->createCommand = $createCommand;
$this->findArguments = $findArguments;
$this->findMacros = $findMacros;
}
public function current(): Command
{
return $this->createCommandWithArgumentsAndMacros();
}
public function next(): void
{
$this->position++;
if (! $this->statement || ($nextItem = $this->statement->fetch()) === false) {
if ($this->valid()) {
// There are still items to be retrieved
$this->requestIndex += $this->maxItemByRequest;
$this->loadDatabase();
}
} else {
/**
* @var array{
* command_id: int,
* command_name: string,
* command_line: string,
* command_example?: string|null,
* command_type: int,
* enable_shell: int,
* command_activate: string,
* command_locked: int,
* connector_id?: int|null,
* connector_name?: string|null,
* graph_template_id?: int|null,
* graph_template_name?: string|null,
* } $nextItem
*/
$this->currentItem = $nextItem;
}
}
public function key(): int
{
return $this->position;
}
public function valid(): bool
{
return $this->position < $this->totalItems;
}
public function rewind(): void
{
$this->position = 0;
$this->requestIndex = 0;
$this->totalItems = 0;
$this->loadDatabase();
}
public function count(): int
{
if (! $this->statement) {
$request = <<<'SQL'
SELECT COUNT(*)
FROM `:db`.command
SQL;
$this->statement = $this->db->query($this->translateDbName($request))
?: throw new \Exception('Impossible to retrieve a PDO Statement');
$this->totalItems = (int) $this->statement->fetchColumn();
}
return $this->totalItems;
}
private function loadDatabase(): void
{
$this->logger->debug(
sprintf(
'Loading commands from %d/%d',
$this->requestIndex,
($this->requestIndex + $this->maxItemByRequest)
)
);
$request = <<<'SQL_WRAP'
SELECT SQL_CALC_FOUND_ROWS
command_id,
command_name,
command_line,
command_type,
enable_shell,
command_activate,
command_locked
FROM `:db`.command
WHERE command_type != :excludedCommandType
ORDER BY command_id
LIMIT :from, :max_item_by_request
SQL_WRAP;
$this->statement = $this->db->prepare($this->translateDbName($request));
$this->statement->bindValue(
':excludedCommandType',
CommandTypeConverter::toInt(CommandType::Notification),
\PDO::PARAM_INT
);
$this->statement->bindValue(':from', $this->requestIndex, \PDO::PARAM_INT);
$this->statement->bindValue(':max_item_by_request', $this->maxItemByRequest, \PDO::PARAM_INT);
$this->statement->setFetchMode(\PDO::FETCH_ASSOC);
$this->statement->execute();
$result = $this->db->query('SELECT FOUND_ROWS()');
if ($result !== false && ($total = $result->fetchColumn()) !== false) {
$this->totalItems = (int) $total;
}
/**
* @var false|array{
* command_id: int,
* command_name: string,
* command_line: string,
* command_example?: string|null,
* command_type: int,
* enable_shell: int,
* command_activate: string,
* command_locked: int,
* connector_id?: int|null,
* connector_name?: string|null,
* graph_template_id?: int|null,
* graph_template_name?: string|null,
* } $result
*/
$result = $this->statement->fetch();
$this->currentItem = $result;
}
private function createCommandWithArgumentsAndMacros(): Command
{
$command = ($this->createCommand)($this->currentItem);
$command->setArguments(($this->findArguments)($command->getId()));
$command->setMacros(($this->findMacros)($command->getId()));
return $command;
}
};
}
/**
* @param _Command $data
*
* @throws AssertionFailedException
*
* @return Command
*/
private function createCommand(array $data): Command
{
return new Command(
id: (int) $data['command_id'],
name: $data['command_name'],
commandLine: html_entity_decode($data['command_line']),
type: CommandTypeConverter::fromInt((int) $data['command_type']),
isShellEnabled: (bool) $data['enable_shell'],
isActivated: $data['command_activate'] === '1',
isLocked: (bool) $data['command_locked'],
argumentExample: $data['command_example'] ?? '',
connector: isset($data['connector_id']) && isset($data['connector_name'])
? new SimpleEntity(
id: $data['connector_id'],
name: new TrimmedString($data['connector_name']),
objectName: 'Connector'
)
: null,
graphTemplate: isset($data['graph_template_id']) && isset($data['graph_template_name'])
? new SimpleEntity(
id: $data['graph_template_id'],
name: new TrimmedString($data['graph_template_name']),
objectName: 'GraphTemplate'
)
: null,
);
}
/**
* @param int $commandId
*
* @throws \Throwable
*
* @return Argument[]
*/
private function findArgumentsByCommandId(int $commandId): array
{
$statement = $this->db->prepare($this->translateDbName(
<<<'SQL'
SELECT macro_name, macro_description
FROM command_arg_description
WHERE cmd_id = :commandId
SQL
));
$statement->bindValue(':commandId', $commandId, \PDO::PARAM_INT);
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$statement->execute();
$arguments = [];
/** @var array{
* macro_name: string,
* macro_description: string|null
* } $result
*/
foreach ($statement as $result) {
$arguments[] = new Argument(
name: new TrimmedString(str_replace(':', '', $result['macro_name'])),
description: new TrimmedString($result['macro_description'] ?? '')
);
}
return $arguments;
}
/**
* @param int $commandId
*
* @throws \Throwable
*
* @return CommandMacro[]
*/
private function findMacrosByCommandId(int $commandId): array
{
$statement = $this->db->prepare($this->translateDbName(
<<<'SQL'
SELECT command_macro_name, command_macro_desciption, command_macro_type
FROM on_demand_macro_command
WHERE command_command_id = :commandId
SQL
));
$statement->bindValue(':commandId', $commandId, \PDO::PARAM_INT);
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$statement->execute();
$macros = [];
/** @var array{
* command_macro_name: string,
* command_macro_desciption: string|null,
* command_macro_type: string
* } $result
*/
foreach ($statement as $result) {
$macro = new CommandMacro(
commandId: $commandId,
type: CommandMacroType::from($result['command_macro_type']),
name: $result['command_macro_name']
);
$macro->setDescription($result['command_macro_desciption'] ?? '');
$macros[] = $macro;
}
return $macros;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Command/Infrastructure/Repository/ApiWriteCommandRepository.php | centreon/src/Core/Command/Infrastructure/Repository/ApiWriteCommandRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See 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\Command\Infrastructure\Repository;
use Centreon\Domain\Log\LoggerTrait;
use Core\Command\Application\Repository\WriteCommandRepositoryInterface;
use Core\Command\Domain\Model\Argument;
use Core\Command\Domain\Model\NewCommand;
use Core\Command\Infrastructure\Model\CommandTypeConverter;
use Core\CommandMacro\Domain\Model\NewCommandMacro;
use Core\Common\Infrastructure\Repository\ApiRepositoryTrait;
use Core\Common\Infrastructure\Repository\RepositoryTrait;
use Symfony\Contracts\HttpClient\HttpClientInterface;
class ApiWriteCommandRepository implements WriteCommandRepositoryInterface
{
use LoggerTrait;
use RepositoryTrait;
use ApiRepositoryTrait;
public function __construct(readonly private HttpClientInterface $httpClient)
{
}
/**
* @inheritDoc
*/
public function add(NewCommand $command): int
{
$apiEndpoint = $this->url . '/api/latest/configuration/commands';
$options = [
'verify_peer' => true,
'verify_host' => true,
'timeout' => $this->timeout,
];
if ($this->proxy !== null) {
$options['proxy'] = $this->proxy;
$this->debug('Adding command using proxy');
}
$options['headers'] = [
'Content-Type: application/json',
'X-AUTH-TOKEN: ' . $this->authenticationToken,
];
$options['body'] = json_encode([
'name' => $command->getName(),
'type' => CommandTypeConverter::toInt($command->getType()),
'command_line' => $command->getCommandLine(),
'is_shell' => $command->isShellEnabled(),
'argument_example' => $this->emptyStringAsNull($command->getArgumentExample()),
'arguments' => array_map(
fn (Argument $arg) => [
'name' => $arg->getName(),
'description' => $this->emptyStringAsNull($arg->getDescription()),
],
$command->getArguments(),
),
'macros' => array_map(
fn (NewCommandMacro $cmd) => [
'name' => $cmd->getName(),
'type' => (int) $cmd->getType()->value,
'description' => $this->emptyStringAsNull($cmd->getDescription()),
],
$command->getMacros(),
),
'connector_id' => $command->getConnectorId(),
'graph_template_id' => $command->getGraphTemplateId(),
]);
if ($options['body'] === false) {
$this->debug('Error when encoding request body');
throw new \Exception('Request error: unable to encode body');
}
$response = $this->httpClient->request('POST', $apiEndpoint, $options);
if ($response->getStatusCode() !== 201) {
try {
/** @var array{message:string} $content */
$content = $response->toArray(false);
} catch (\Throwable $ex) {
$this->debug('Error when retrieving response content', [
'http_code' => $response->getStatusCode(),
'exception' => (string) $ex,
'response_content' => $response->getContent(false),
]);
throw new \Exception(
sprintf(
'Request error: {"code":%d,"message":"Error when retrieving response content (see logs for more details)"',
$response->getStatusCode()
),
$response->getStatusCode()
);
}
$this->debug('API error', [
'http_code' => $response->getStatusCode(),
'message' => $content['message'],
]);
throw new \Exception(sprintf('Request error: %s', $content['message']), $response->getStatusCode());
}
return (int) $response->toArray()['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/Command/Infrastructure/Repository/DbWriteCommandActionLogRepository.php | centreon/src/Core/Command/Infrastructure/Repository/DbWriteCommandActionLogRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See 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\Command\Infrastructure\Repository;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\Repository\RepositoryException;
use Centreon\Infrastructure\DatabaseConnection;
use Core\ActionLog\Application\Repository\WriteActionLogRepositoryInterface;
use Core\ActionLog\Domain\Model\ActionLog;
use Core\Command\Application\Repository\WriteCommandRepositoryInterface;
use Core\Command\Domain\Model\Argument;
use Core\Command\Domain\Model\CommandType;
use Core\Command\Domain\Model\NewCommand;
use Core\Command\Infrastructure\Model\CommandTypeConverter;
use Core\CommandMacro\Domain\Model\CommandMacroType;
use Core\CommandMacro\Domain\Model\NewCommandMacro;
use Core\Common\Domain\TrimmedString;
use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB;
class DbWriteCommandActionLogRepository extends AbstractRepositoryRDB implements WriteCommandRepositoryInterface
{
use LoggerTrait;
private const COMMAND_PROPERTIES_MAP = [
'name' => 'command_name',
'commandLine' => 'command_line',
'isShellEnabled' => 'enable_shell',
'type' => 'command_type',
'argumentExample' => 'argument_example',
'arguments' => 'arguments',
'macros' => 'macros',
'connectorId' => 'connectors',
'graphTemplateId' => 'graph_id',
];
public function __construct(
private readonly WriteCommandRepositoryInterface $writeCommandRepository,
private readonly WriteActionLogRepositoryInterface $writeActionLogRepository,
private readonly ContactInterface $contact,
DatabaseConnection $db,
) {
$this->db = $db;
}
public function add(NewCommand $command): int
{
try {
$commandId = $this->writeCommandRepository->add($command);
if ($commandId === 0) {
throw new RepositoryException('Command ID cannot be 0');
}
$actionLog = new ActionLog(
objectType: ActionLog::OBJECT_TYPE_COMMAND,
objectId: $commandId,
objectName: $command->getName(),
actionType: ActionLog::ACTION_TYPE_ADD,
contactId: $this->contact->getId()
);
$actionLogId = $this->writeActionLogRepository->addAction($actionLog);
if ($actionLogId === 0) {
throw new RepositoryException('Action Log ID cannot be 0');
}
$actionLog->setId($actionLogId);
$this->writeActionLogRepository->addActionDetails($actionLog, $this->getCommandAsArray($command));
return $commandId;
} catch (\Throwable $ex) {
$this->error(
'Error while adding a Command',
['command' => $command->getName(), 'trace' => $ex->getTraceAsString()]
);
throw $ex;
}
}
/**
* @param NewCommand $command
*
* @return array<string, int|string>
*/
private function getCommandAsArray(NewCommand $command): array
{
$reflection = new \ReflectionClass($command);
$properties = $reflection->getProperties();
$commandAsArray = [];
foreach ($properties as $property) {
$property->setAccessible(true);
$propertyName = $property->getName();
$propertyValue = $property->getValue($command);
$commandAsArray[self::COMMAND_PROPERTIES_MAP[$propertyName]] = match ($propertyName) {
'name', 'commandLine', 'argumentExample' => $propertyValue instanceof TrimmedString
? (string) $propertyValue
: '',
'isShellEnabled' => $propertyValue ? '1' : '0',
'type' => $propertyValue instanceof CommandType ? CommandTypeConverter::toInt($propertyValue) : '',
'arguments' => is_array($propertyValue) ? $this->getArgumentsAsString($propertyValue) : '',
'macros' => is_array($propertyValue) ? $this->getMacrosAsString($propertyValue) : '',
'connectorId', 'graphTemplateId' => is_int($propertyValue) ? $propertyValue : '',
default => '',
};
}
return $commandAsArray;
}
/**
* @param Argument[] $arguments
*
* @return string
*/
private function getArgumentsAsString(array $arguments): string
{
$arguments = array_map(
fn ($argument) => $argument->getName() . ' : ' . $argument->getDescription(),
$arguments
);
$argumentsAsString = '';
if ($arguments !== []) {
$argumentsAsString = implode(' ', $arguments);
}
return $argumentsAsString;
}
/**
* @param NewCommandMacro[] $macros
*
* @return string
*/
private function getMacrosAsString(array $macros): string
{
$macros = array_map(
function (NewCommandMacro $macro): string {
$resourceType = $macro->getType() === CommandMacroType::Host
? 'HOST'
: 'SERVICE';
return 'MACRO (' . $resourceType . ') ' . $macro->getName() . ' : '
. $macro->getDescription();
},
$macros
);
$macrosAsString = '';
if ($macros !== []) {
$macrosAsString = implode(' ', $macros);
}
return $macrosAsString;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Command/Infrastructure/API/AddCommand/AddCommandPresenter.php | centreon/src/Core/Command/Infrastructure/API/AddCommand/AddCommandPresenter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See 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\Command\Infrastructure\API\AddCommand;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\CreatedResponse;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Command\Application\UseCase\AddCommand\AddCommandPresenterInterface;
use Core\Command\Application\UseCase\AddCommand\AddCommandResponse;
use Core\Command\Infrastructure\Model\CommandTypeConverter;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Infrastructure\Common\Presenter\PresenterTrait;
class AddCommandPresenter extends AbstractPresenter implements AddCommandPresenterInterface
{
use PresenterTrait;
public function __construct(PresenterFormatterInterface $presenterFormatter)
{
parent::__construct($presenterFormatter);
}
public function presentResponse(ResponseStatusInterface|AddCommandResponse $response): void
{
if ($response instanceof ResponseStatusInterface) {
$this->setResponseStatus($response);
} else {
$this->present(
new CreatedResponse(
$response->id,
[
'id' => $response->id,
'name' => $response->name,
'type' => CommandTypeConverter::toInt($response->type),
'command_line' => $response->commandLine,
'is_shell' => $response->isShellEnabled,
'is_activated' => $response->isActivated,
'is_locked' => $response->isLocked,
'argument_example' => $this->emptyStringAsNull($response->argumentExample),
'arguments' => array_map(fn (array $argument): array => [
'name' => $argument['name'],
'description' => $this->emptyStringAsNull($argument['description']),
], $response->arguments),
'macros' => array_map(fn (array $macro): array => [
'name' => $macro['name'],
'type' => $macro['type']->value,
'description' => $this->emptyStringAsNull($macro['description']),
], $response->macros),
'connector' => $response->connector
? ['id' => $response->connector['id'], 'name' => $response->connector['name']]
: null,
'grap_template' => $response->graphTemplate
? ['id' => $response->graphTemplate['id'], 'name' => $response->graphTemplate['name']]
: 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/Command/Infrastructure/API/AddCommand/AddCommandController.php | centreon/src/Core/Command/Infrastructure/API/AddCommand/AddCommandController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See 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\Command\Infrastructure\API\AddCommand;
use Centreon\Application\Controller\AbstractController;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\Command\Application\UseCase\AddCommand\AddCommand;
use Core\Command\Application\UseCase\AddCommand\AddCommandRequest;
use Core\Command\Application\UseCase\AddCommand\ArgumentDto;
use Core\Command\Application\UseCase\AddCommand\MacroDto;
use Core\Command\Infrastructure\Model\CommandTypeConverter;
use Core\CommandMacro\Domain\Model\CommandMacroType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
/**
* @phpstan-type _CommandTemplate = array{
* name: string,
* type: integer,
* command_line: string,
* is_shell?: bool,
* argument_example?: null|string,
* arguments?: array<array{name:string,description:null|string}>,
* macros?: array<array{name:string,type:int,description:null|string}>,
* connector_id?: null|integer,
* graph_template_id?: null|integer,
* }
*/
final class AddCommandController extends AbstractController
{
use LoggerTrait;
/**
* @param AddCommand $useCase
* @param AddCommandPresenter $presenter
* @param Request $request
*
* @throws AccessDeniedException
*
* @return Response
*/
public function __invoke(
AddCommand $useCase,
AddCommandPresenter $presenter,
Request $request,
): Response {
$this->denyAccessUnlessGrantedForApiConfiguration();
try {
/** @var _CommandTemplate $data */
$data = $this->validateAndRetrieveDataSent(
$request,
__DIR__ . '/AddCommandSchema.json'
);
$useCase($this->createDto($data), $presenter);
} catch (\InvalidArgumentException $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
$presenter->setResponseStatus(new InvalidArgumentResponse($ex));
}
return $presenter->show();
}
/**
* @param _CommandTemplate $request
*
* @return AddCommandRequest
*/
private function createDto(array $request): AddCommandRequest
{
$dto = new AddCommandRequest();
$dto->name = $request['name'];
$dto->type = CommandTypeConverter::fromInt($request['type']);
$dto->commandLine = $request['command_line'];
$dto->isShellEnabled = $request['is_shell'] ?? false;
$dto->argumentExample = $request['argument_example'] ?? '';
$dto->connectorId = $request['connector_id'] ?? null;
$dto->graphTemplateId = $request['graph_template_id'] ?? null;
foreach ($request['macros'] ?? [] as $macro) {
$dto->macros[] = new MacroDto(
$macro['name'],
CommandMacroType::from((string) $macro['type']),
$macro['description'] ?? ''
);
}
foreach ($request['arguments'] ?? [] as $argument) {
$dto->arguments[] = new ArgumentDto(
$argument['name'],
$argument['description'] ?? ''
);
}
return $dto;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Command/Infrastructure/API/FindCommands/FindCommandsPresenter.php | centreon/src/Core/Command/Infrastructure/API/FindCommands/FindCommandsPresenter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See 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\Command\Infrastructure\API\FindCommands;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Command\Application\UseCase\FindCommands\FindCommandsPresenterInterface;
use Core\Command\Application\UseCase\FindCommands\FindCommandsResponse;
use Core\Command\Infrastructure\Model\CommandTypeConverter;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Infrastructure\Common\Presenter\PresenterTrait;
class FindCommandsPresenter extends AbstractPresenter implements FindCommandsPresenterInterface
{
use PresenterTrait;
public function __construct(
private readonly RequestParametersInterface $requestParameters,
protected PresenterFormatterInterface $presenterFormatter,
) {
parent::__construct($presenterFormatter);
}
public function presentResponse(ResponseStatusInterface|FindCommandsResponse $response): void
{
if ($response instanceof ResponseStatusInterface) {
$this->setResponseStatus($response);
} else {
$result = [];
foreach ($response->commands as $command) {
$result[] = [
'id' => $command->id,
'name' => $command->name,
'type' => CommandTypeConverter::toInt($command->type),
'command_line' => $command->commandLine,
'is_shell' => $command->isShellEnabled,
'is_locked' => $command->isLocked,
'is_activated' => $command->isActivated,
];
}
$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/Command/Infrastructure/API/FindCommands/FindCommandsController.php | centreon/src/Core/Command/Infrastructure/API/FindCommands/FindCommandsController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See 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\Command\Infrastructure\API\FindCommands;
use Centreon\Application\Controller\AbstractController;
use Core\Command\Application\UseCase\FindCommands\FindCommands;
use Core\Command\Application\UseCase\FindCommands\FindCommandsPresenterInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
final class FindCommandsController extends AbstractController
{
/**
* @param FindCommands $useCase
* @param FindCommandsPresenter $presenter
*
* @throws AccessDeniedException
*
* @return Response
*/
public function __invoke(FindCommands $useCase, FindCommandsPresenterInterface $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/Command/Infrastructure/Command/MigrateAllCommands/MigrateAllCommandsCommand.php | centreon/src/Core/Command/Infrastructure/Command/MigrateAllCommands/MigrateAllCommandsCommand.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See 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\Command\Infrastructure\Command\MigrateAllCommands;
use Centreon\Domain\Log\LoggerTrait;
use Core\Command\Application\UseCase\MigrateAllCommands\MigrateAllCommands;
use Core\Command\Infrastructure\Repository\ApiWriteCommandRepository;
use Core\Common\Infrastructure\Command\AbstractMigrationCommand;
use Core\Proxy\Application\Repository\ReadProxyRepositoryInterface;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
#[AsCommand(
name: 'command:all',
description: 'Migrate all commands from the current platform to the defined target platform'
)]
class MigrateAllCommandsCommand extends AbstractMigrationCommand
{
use LoggerTrait;
public function __construct(
ReadProxyRepositoryInterface $readProxyRepository,
readonly private ApiWriteCommandRepository $apiWriteCommandRepository,
readonly private MigrateAllCommands $useCase,
private readonly int $curlTimeout,
) {
parent::__construct($readProxyRepository);
}
protected function configure(): void
{
$this->addArgument(
'target-url',
InputArgument::REQUIRED,
"The target platform base url to connect to the API (ex: 'http://localhost/centreon')"
);
$this->setHelp(
"Migrates all commands to the target platform.\r\n"
. 'However the commands migration command will not replace commands that already exists on the target platform.'
);
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
try {
$this->setStyle($output);
$this->apiWriteCommandRepository->setTimeout($this->curlTimeout);
$proxy = $this->getProxy();
if ($proxy !== null && $proxy !== '') {
$this->apiWriteCommandRepository->setProxy($proxy);
}
if (is_string($target = $input->getArgument('target-url'))) {
$this->apiWriteCommandRepository->setUrl($target);
} else {
// Theoretically it should never happen
throw new \InvalidArgumentException('target-url is not a string');
}
$token = $this->askAuthenticationToken(self::TARGET_PLATFORM, $input, $output);
$this->apiWriteCommandRepository->setAuthenticationToken($token);
($this->useCase)(new MigrateAllCommandsPresenter($output));
} catch (\Throwable $ex) {
$this->writeError($ex->getMessage(), $output);
return self::FAILURE;
}
return self::SUCCESS;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Command/Infrastructure/Command/MigrateAllCommands/MigrateAllCommandsPresenter.php | centreon/src/Core/Command/Infrastructure/Command/MigrateAllCommands/MigrateAllCommandsPresenter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See 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\Command\Infrastructure\Command\MigrateAllCommands;
use Core\Application\Common\UseCase\CliAbstractPresenter;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Command\Application\UseCase\MigrateAllCommands\CommandRecordedDto;
use Core\Command\Application\UseCase\MigrateAllCommands\MigrateAllCommandsPresenterInterface;
use Core\Command\Application\UseCase\MigrateAllCommands\MigrateAllCommandsResponse;
use Core\Command\Application\UseCase\MigrateAllCommands\MigrationErrorDto;
class MigrateAllCommandsPresenter extends CliAbstractPresenter implements MigrateAllCommandsPresenterInterface
{
public function presentResponse(MigrateAllCommandsResponse|ResponseStatusInterface $response): void
{
if ($response instanceof ResponseStatusInterface) {
$this->error($response->getMessage());
} else {
foreach ($response->results as $result) {
if ($result instanceof CommandRecordedDto) {
$this->write("<ok> OK</> {$result->name} => source:{$result->sourceId} / target:{$result->targetId}");
} elseif ($result instanceof MigrationErrorDto) {
$this->write("<error>ERROR</> {$result->name}/{$result->id} ({$result->reason})");
}
}
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Command/Infrastructure/Command/Exception/CommandMigrationCommandException.php | centreon/src/Core/Command/Infrastructure/Command/Exception/CommandMigrationCommandException.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See 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\Command\Infrastructure\Command\Exception;
class CommandMigrationCommandException extends \Exception
{
/**
* @return self
*/
public static function contactNotFound(): self
{
return new self(_('Contact not found'));
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/PollerMacro/Application/Repository/ReadPollerMacroRepositoryInterface.php | centreon/src/Core/PollerMacro/Application/Repository/ReadPollerMacroRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See 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\PollerMacro\Application\Repository;
use Core\PollerMacro\Domain\Model\PollerMacro;
interface ReadPollerMacroRepositoryInterface
{
/**
* Find all poller macros of type password.
*
* @throws \Throwable
*
* @return PollerMacro[]
*/
public function findPasswords(): 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/PollerMacro/Application/Repository/WritePollerMacroRepositoryInterface.php | centreon/src/Core/PollerMacro/Application/Repository/WritePollerMacroRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See 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\PollerMacro\Application\Repository;
use Core\PollerMacro\Domain\Model\PollerMacro;
interface WritePollerMacroRepositoryInterface
{
/**
* Update a poller macro.
*
* @param PollerMacro $macro
*
* @throws \Throwable
*/
public function update(PollerMacro $macro): 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/PollerMacro/Domain/Model/PollerMacro.php | centreon/src/Core/PollerMacro/Domain/Model/PollerMacro.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See 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\PollerMacro\Domain\Model;
class PollerMacro
{
public function __construct(
private readonly int $id,
private string $name,
private string $value,
private ?string $comment,
private bool $isActive,
private bool $isPassword,
) {
}
public function getId(): int
{
return $this->id;
}
public function getName(): string
{
return $this->name;
}
public function getValue(): string
{
return $this->value;
}
public function getComment(): ?string
{
return $this->comment;
}
public function isActive(): bool
{
return $this->isActive;
}
public function isPassword(): bool
{
return $this->isPassword;
}
public function setValue(string $value): void
{
$this->value = $value;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/PollerMacro/Infrastructure/Repository/DbWritePollerMacroRepository.php | centreon/src/Core/PollerMacro/Infrastructure/Repository/DbWritePollerMacroRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See 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\PollerMacro\Infrastructure\Repository;
use Centreon\Infrastructure\DatabaseConnection;
use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB;
use Core\PollerMacro\Application\Repository\WritePollerMacroRepositoryInterface;
use Core\PollerMacro\Domain\Model\PollerMacro;
/**
* @phpstan-type _Macro array{
* resource_id:int,
* resource_name:string,
* resource_line:string,
* resource_comment:string|null,
* resource_activate:string,
* is_password:int,
* }
*/
class DbWritePollerMacroRepository extends AbstractRepositoryRDB implements WritePollerMacroRepositoryInterface
{
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* @inheritDoc
*/
public function update(PollerMacro $macro): void
{
$statement = $this->db->prepare($this->translateDbName(
<<<'SQL'
UPDATE `:db`.`cfg_resource` SET
resource_name = :name,
resource_line = :value,
resource_comment = :comment,
resource_activate = :isActive,
is_password = :isPassword
WHERE resource_id = :id
SQL
));
$statement->bindValue(':name', $macro->getName(), \PDO::PARAM_STR);
$statement->bindValue(':value', $macro->getValue(), \PDO::PARAM_STR);
$statement->bindValue(':comment', $macro->getComment(), \PDO::PARAM_STR);
$statement->bindValue(':isActive', $macro->isActive(), \PDO::PARAM_STR);
$statement->bindValue(':isPassword', $macro->isPassword(), \PDO::PARAM_INT);
$statement->bindValue(':id', $macro->getId(), \PDO::PARAM_INT);
$statement->execute();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/PollerMacro/Infrastructure/Repository/DbReadPollerMacroRepository.php | centreon/src/Core/PollerMacro/Infrastructure/Repository/DbReadPollerMacroRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See 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\PollerMacro\Infrastructure\Repository;
use Centreon\Infrastructure\DatabaseConnection;
use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB;
use Core\PollerMacro\Application\Repository\ReadPollerMacroRepositoryInterface;
use Core\PollerMacro\Domain\Model\PollerMacro;
/**
* @phpstan-type _Macro array{
* resource_id:int,
* resource_name:string,
* resource_line:string,
* resource_comment:string|null,
* resource_activate:string,
* is_password:int,
* }
*/
class DbReadPollerMacroRepository extends AbstractRepositoryRDB implements ReadPollerMacroRepositoryInterface
{
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* @inheritDoc
*/
public function findPasswords(): array
{
$statement = $this->db->prepare($this->translateDbName(
<<<'SQL'
SELECT * FROM `:db`.`cfg_resource`
WHERE `is_password` = 1
SQL
));
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$statement->execute();
$macros = [];
foreach ($statement as $row) {
/** @var _Macro $row */
$macros[] = $this->createFromArray($row);
}
return $macros;
}
/**
* @param _Macro $data
*
* @return PollerMacro
*/
private function createFromArray(array $data): PollerMacro
{
return new PollerMacro(
id: $data['resource_id'],
name: $data['resource_name'],
value: $data['resource_line'],
comment: $data['resource_comment'],
isActive: $data['resource_activate'] === '1' ? true : false,
isPassword: (bool) $data['is_password'],
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonModule/ServiceProvider.php | centreon/src/CentreonModule/ServiceProvider.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonModule;
use Centreon\Infrastructure\Provider\AutoloadServiceProviderInterface;
use CentreonModule\Application\Webservice;
use CentreonModule\Infrastructure\Service;
use Pimple\Container;
use Pimple\Psr11\ServiceLocator;
class ServiceProvider implements AutoloadServiceProviderInterface
{
public const CENTREON_MODULE = 'centreon.module';
/**
* Register services.
*
* @param Container $pimple
*/
public function register(Container $pimple): void
{
$pimple[\Centreon\ServiceProvider::CENTREON_WEBSERVICE]
->add(Webservice\CentreonModuleWebservice::class);
// alias of CentreonModuleWebservice need for back compatibility and it's deprecated for using
$pimple[\Centreon\ServiceProvider::CENTREON_WEBSERVICE]
->add(Webservice\CentreonModulesWebservice::class);
$pimple[static::CENTREON_MODULE] = function (Container $container): Service\CentreonModuleService {
$services = [
'finder',
'configuration',
\Centreon\ServiceProvider::CENTREON_DB_MANAGER,
\CentreonLegacy\ServiceProvider::CENTREON_LEGACY_MODULE_LICENSE,
\CentreonLegacy\ServiceProvider::CENTREON_LEGACY_MODULE_INSTALLER,
\CentreonLegacy\ServiceProvider::CENTREON_LEGACY_MODULE_UPGRADER,
\CentreonLegacy\ServiceProvider::CENTREON_LEGACY_MODULE_REMOVER,
\CentreonLegacy\ServiceProvider::CENTREON_LEGACY_WIDGET_INSTALLER,
\CentreonLegacy\ServiceProvider::CENTREON_LEGACY_WIDGET_UPGRADER,
\CentreonLegacy\ServiceProvider::CENTREON_LEGACY_WIDGET_REMOVER,
];
$locator = new ServiceLocator($container, $services);
return new Service\CentreonModuleService($locator);
};
}
public static function order(): int
{
return 5;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonModule/Application/DataRepresenter/ModuleEntity.php | centreon/src/CentreonModule/Application/DataRepresenter/ModuleEntity.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonModule\Application\DataRepresenter;
use CentreonModule\Infrastructure\Entity\Module;
use JsonSerializable;
class ModuleEntity implements JsonSerializable
{
/** @var Module */
private $entity;
/**
* Construct.
*
* @param Module|null $entity
*/
public function __construct(?Module $entity)
{
$this->entity = $entity;
}
/**
* @OA\Schema(
* schema="ModuleEntity",
*
* @OA\Property(property="id", type="integer"),
* @OA\Property(property="type", type="string", enum={"module","widget"}),
* @OA\Property(property="description", type="string"),
* @OA\Property(property="label", type="string"),
* @OA\Property(property="version", type="object",
* @OA\Property(property="current", type="string"),
* @OA\Property(property="available", type="string"),
* @OA\Property(property="outdated", type="boolean"),
* @OA\Property(property="installed", type="boolean")
* ),
* @OA\Property(property="license", type="string")
* )
*
* JSON serialization of entity
*
* @return array<string,mixed>
*/
public function jsonSerialize(): mixed
{
$outdated = ! $this->entity->isInternal() && $this->entity->isInstalled() && ! $this->entity->isUpdated();
return [
'id' => $this->entity->getId(),
'type' => $this->entity->getType(),
'description' => $this->entity->getName(),
'label' => $this->entity->getAuthor(),
'version' => [
'current' => $this->entity->getVersionCurrent(),
'available' => $this->entity->getVersion(),
'outdated' => $outdated,
'installed' => $this->entity->isInstalled(),
],
'is_internal' => $this->entity->isInternal(),
'license' => $this->entity->getLicense(),
];
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonModule/Application/DataRepresenter/ModuleDetailEntity.php | centreon/src/CentreonModule/Application/DataRepresenter/ModuleDetailEntity.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonModule\Application\DataRepresenter;
use CentreonModule\Infrastructure\Entity\Module;
use JsonSerializable;
class ModuleDetailEntity implements JsonSerializable
{
/** @var Module */
private $entity;
/**
* Construct.
*
* @param Module $entity
*/
public function __construct(Module $entity)
{
$this->entity = $entity;
}
/**
* @OA\Schema(
* schema="ModuleDetailEntity",
*
* @OA\Property(property="id", type="integer"),
* @OA\Property(property="type", type="string", enum={"module","widget"}),
* @OA\Property(property="title", type="string"),
* @OA\Property(property="description", type="string"),
* @OA\Property(property="label", type="string"),
* @OA\Property(property="stability", type="string"),
* @OA\Property(property="version", type="object",
* @OA\Property(property="current", type="string"),
* @OA\Property(property="available", type="string"),
* @OA\Property(property="outdated", type="boolean"),
* @OA\Property(property="installed", type="boolean")
* ),
* @OA\Property(property="is_internal", type="boolean"),
* @OA\Property(property="license", type="string"),
* @OA\Property(property="images", type="array", items={"string"}),
* @OA\Property(property="last_update", type="string"),
* @OA\Property(property="release_note", type="string")
* )
*
* JSON serialization of entity
*
* @return array<string,mixed>
*/
public function jsonSerialize(): mixed
{
$outdated = ! $this->entity->isInternal() && $this->entity->isInstalled() && ! $this->entity->isUpdated();
return [
'id' => $this->entity->getId(),
'type' => $this->entity->getType(),
'title' => $this->entity->getName(),
'description' => $this->entity->getDescription(),
'label' => $this->entity->getAuthor(),
'stability' => $this->entity->getStability(),
'version' => [
'current' => $this->entity->getVersionCurrent(),
'available' => $this->entity->getVersion(),
'outdated' => $outdated,
'installed' => $this->entity->isInstalled(),
],
'is_internal' => $this->entity->isInternal(),
'license' => $this->entity->getLicense(),
'images' => $this->entity->getImages(),
'last_update' => $this->entity->getLastUpdate(),
'release_note' => $this->entity->getReleaseNote(),
];
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonModule/Application/DataRepresenter/UpdateAction.php | centreon/src/CentreonModule/Application/DataRepresenter/UpdateAction.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonModule\Application\DataRepresenter;
use CentreonModule\Infrastructure\Entity\Module;
use JsonSerializable;
class UpdateAction implements JsonSerializable
{
/** @var Module */
private $entity;
/** @var string|null */
private $message;
/**
* Construct.
*
* @param Module $entity
* @param Module|null $entity
* @param string $message
*/
public function __construct(?Module $entity = null, ?string $message = null)
{
$this->entity = $entity;
$this->message = $message;
}
/**
* @OA\Schema(
* schema="UpdateAction",
*
* @OA\Property(property="entity", ref="#/components/schemas/ModuleEntity"),
* @OA\Property(property="message", type="string")
* )
*
* JSON serialization of entity
*
* @return array{entity:ModuleEntity|string|null, message:string|null}
*/
public function jsonSerialize(): mixed
{
$entity = null;
if ($this->entity !== null) {
$entity = new ModuleEntity($this->entity);
}
return [
'entity' => $entity,
'message' => $this->message,
];
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonModule/Application/Webservice/CentreonModulesWebservice.php | centreon/src/CentreonModule/Application/Webservice/CentreonModulesWebservice.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonModule\Application\Webservice;
use CentreonRemote\Application\Webservice\CentreonWebServiceAbstract;
/**
* @OA\Tag(name="centreon_modules_webservice", description="Resource for external public access")
*/
class CentreonModulesWebservice extends CentreonWebServiceAbstract
{
/**
* @OA\Post(
* path="/external.php?object=centreon_modules_webservice&action=getBamModuleInfo",
* description="Get list of modules and widgets",
* tags={"centreon_modules_webservice"},
*
* @OA\Parameter(
* in="query",
* name="object",
* description="the name of the API object class",
* required=true,
*
* @OA\Schema(
* type="string",
* enum={"centreon_modules_webservice"}
* )
* ),
*
* @OA\Parameter(
* in="query",
* name="action",
* description="the name of the action in the API class",
* required=true,
*
* @OA\Schema(
* type="string",
* enum={"getBamModuleInfo"}
* )
* ),
*
* @OA\Response(
* response="200",
* description="JSON with BAM module info",
*
* @OA\JsonContent(
*
* @OA\Property(property="enabled", type="boolean"),
* @OA\Property(property="status", type="boolean")
* )
* )
* )
*
* Get info for BAM module
*
* @return array<string,bool>
*/
public function postGetBamModuleInfo(): array
{
$moduleInfoObj = $this->getDi()[\CentreonLegacy\ServiceProvider::CENTREON_LEGACY_MODULE_INFORMATION];
$modules = $moduleInfoObj->getList();
if (
array_key_exists('centreon-bam-server', $modules)
&& $modules['centreon-bam-server']['is_installed']
) {
return ['enabled' => true];
}
return ['enabled' => false];
}
/**
* Authorize to access to the action.
*
* @param string $action The action name
* @param \CentreonUser $user The current user
* @param bool $isInternal If the api is call in internal
*
* @return bool If the user has access to the action
*/
public function authorize($action, $user, $isInternal = false): bool
{
return true;
}
/**
* Name of web service object.
*
* @return string
*/
public static function getName(): string
{
return 'centreon_modules_webservice';
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonModule/Application/Webservice/CentreonModuleWebservice.php | centreon/src/CentreonModule/Application/Webservice/CentreonModuleWebservice.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonModule\Application\Webservice;
use Centreon\Application\DataRepresenter\Bulk;
use Centreon\Application\DataRepresenter\Response;
use Centreon\Infrastructure\Webservice;
use CentreonModule\Application\DataRepresenter\ModuleDetailEntity;
use CentreonModule\Application\DataRepresenter\ModuleEntity;
use CentreonModule\Application\DataRepresenter\UpdateAction;
use CentreonModule\Infrastructure\Service\CentreonModuleService;
use CentreonModule\ServiceProvider;
/**
* @OA\Tag(name="centreon_module", description="Resource for authorized access")
*/
class CentreonModuleWebservice extends Webservice\WebServiceAbstract implements Webservice\WebserviceAutorizeRestApiInterface
{
/**
* Authorize to access to the action.
*
* @param string $action The action name
* @param \CentreonUser $user The current user
* @param bool $isInternal If the api is call in internal
*
* @return bool If the user has access to the action
*/
public function authorize($action, $user, $isInternal = false)
{
return ! (! $user->admin && $user->access->page('50709') === 0);
}
/**
* @OA\Get(
* path="/internal.php?object=centreon_module&action=list",
* description="Get list of modules and widgets",
* tags={"centreon_module"},
* security={{"Session": {}}},
*
* @OA\Parameter(
* in="query",
* name="object",
*
* @OA\Schema(
* type="string",
* enum={"centreon_module"},
* default="centreon_module"
* ),
* description="the name of the API object class",
* required=true
* ),
*
* @OA\Parameter(
* in="query",
* name="action",
*
* @OA\Schema(
* type="string",
* enum={"list"},
* default="list"
* ),
* description="the name of the action in the API class",
* required=true
* ),
*
* @OA\Parameter(
* in="query",
* name="search",
*
* @OA\Schema(
* type="string"
* ),
* description="filter the result by name and keywords",
* required=false
* ),
*
* @OA\Parameter(
* in="query",
* name="installed",
*
* @OA\Schema(
* type="boolean"
* ),
* description="filter the result by installed or non-installed modules",
* required=false
* ),
*
* @OA\Parameter(
* in="query",
* name="updated",
*
* @OA\Schema(
* type="boolean"
* ),
* description="filter the result by updated or non-installed modules",
* required=false
* ),
*
* @OA\Parameter(
* in="query",
* name="types",
*
* @OA\Schema(
* type="array",
* items={"type": "string", "enum": {"module", "widget"}}
* ),
* description="filter the result by type",
* required=false
* ),
*
* @OA\Response(
* response="200",
* description="OK",
*
* @OA\MediaType(
* mediaType="application/json",
*
* @OA\Schema(
*
* @OA\Property(property="module",
* @OA\Property(
* property="entities",
* type="array",
*
* @OA\Items(ref="#/components/schemas/ModuleEntity")
* ),
*
* @OA\Property(
* property="pagination",
* ref="#/components/schemas/Pagination"
* )
* ),
* @OA\Property(property="widget", type="object",
* @OA\Property(
* property="entities",
* type="array",
*
* @OA\Items(ref="#/components/schemas/ModuleEntity")
* ),
*
* @OA\Property(
* property="pagination",
* ref="#/components/schemas/Pagination"
* )
* ),
* @OA\Property(property="status", type="boolean")
* )
* )
* )
* )
*
* Get list of modules and widgets
*
* @throws \RestBadRequestException
*
* @return Response
*/
public function getList()
{
// extract post payload
$request = $this->query();
$search = isset($request['search']) && $request['search'] ? $request['search'] : null;
$installed = $request['installed'] ?? null;
$updated = $request['updated'] ?? null;
$typeList = isset($request['types']) ? (array) $request['types'] : null;
if ($installed && strtolower($installed) === 'true') {
$installed = true;
} elseif ($installed && strtolower($installed) === 'false') {
$installed = false;
} elseif ($installed) {
$installed = null;
}
if ($updated && strtolower($updated) === 'true') {
$updated = true;
} elseif ($updated && strtolower($updated) === 'false') {
$updated = false;
} elseif ($updated) {
$updated = null;
}
$list = $this->getDi()[ServiceProvider::CENTREON_MODULE]
->getList($search, $installed, $updated, $typeList);
$result = new Bulk($list, null, null, null, ModuleEntity::class);
return new Response($result);
}
/**
* @OA\Get(
* path="/internal.php?object=centreon_module&action=details",
* description="Get details of modules and widgets",
* tags={"centreon_module"},
*
* @OA\Parameter(
* in="query",
* name="object",
*
* @OA\Schema(
* type="string",
* enum={"centreon_module"},
* default="centreon_module"
* ),
* description="the name of the API object class",
* required=true
* ),
*
* @OA\Parameter(
* in="query",
* name="action",
*
* @OA\Schema(
* type="string",
* enum={"details"},
* default="details"
* ),
* description="the name of the action in the API class",
* required=true
* ),
*
* @OA\Parameter(
* in="query",
* name="id",
*
* @OA\Schema(
* type="string"
* ),
* description="ID of a module or a widget",
* required=true
* ),
*
* @OA\Parameter(
* in="query",
* name="type",
*
* @OA\Schema(
* type="string",
* enum={
* "module",
* "widget"
* }
* ),
* description="type of object",
* required=true
* ),
*
* @OA\Response(
* response="200",
* description="OK",
*
* @OA\MediaType(
* mediaType="application/json",
*
* @OA\Schema(
*
* @OA\Property(property="result", ref="#/components/schemas/ModuleDetailEntity"),
* @OA\Property(property="status", type="boolean")
* )
* )
* )
* )
*
* Get details of module/widget
*
* @throws \RestBadRequestException
*
* @return Response
*/
public function getDetails()
{
// extract post payload
$request = $this->query();
$id = isset($request['id']) && $request['id'] ? $request['id'] : null;
$type = $request['type'] ?? null;
$detail = $this->getDi()[ServiceProvider::CENTREON_MODULE]
->getDetail($id, $type);
$result = null;
$status = false;
if ($detail !== null) {
$result = new ModuleDetailEntity($detail);
$status = true;
}
return new Response($result, $status);
}
/**
* @OA\Post(
* path="/internal.php?object=centreon_module&action=install",
* summary="Install module or widget",
* tags={"centreon_module"},
*
* @OA\Parameter(
* in="query",
* name="object",
*
* @OA\Schema(
* type="string",
* enum={"centreon_module"},
* default="centreon_module"
* ),
* description="the name of the API object class",
* required=true
* ),
*
* @OA\Parameter(
* in="query",
* name="action",
*
* @OA\Schema(
* type="string",
* enum={"install"},
* default="install"
* ),
* description="the name of the action in the API class",
* required=true
* ),
*
* @OA\Parameter(
* in="query",
* name="id",
*
* @OA\Schema(
* type="string"
* ),
* description="ID of a module or a widget",
* required=true
* ),
*
* @OA\Parameter(
* in="query",
* name="type",
*
* @OA\Schema(
* type="string",
* enum={
* "module",
* "widget"
* }
* ),
* description="type of object",
* required=true
* ),
*
* @OA\Response(
* response="200",
* description="OK",
*
* @OA\JsonContent(
*
* @OA\Property(property="result", ref="#/components/schemas/UpdateAction"),
* @OA\Property(property="status", type="boolean")
* )
* )
* )
*
* Install module or widget
*
* @throws \RestBadRequestException
*
* @return Response
*/
public function postInstall()
{
// extract post payload
$request = $this->query();
$id = isset($request['id']) && $request['id'] ? $request['id'] : '';
$type = $request['type'] ?? '';
$status = false;
$result = null;
$entity = null;
/**
* @var CentreonModuleService
*/
$moduleService = $this->getDi()[ServiceProvider::CENTREON_MODULE];
try {
$entity = $moduleService->install($id, $type);
} catch (\Exception $e) {
$result = new UpdateAction(null, $e->getMessage());
}
if ($entity !== null) {
$result = new UpdateAction($entity);
$status = true;
}
return new Response($result, $status);
}
/**
* @OA\Post(
* path="/internal.php?object=centreon_module&action=update",
* summary="Update module or widget",
* tags={"centreon_module"},
*
* @OA\Parameter(
* in="query",
* name="object",
*
* @OA\Schema(
* type="string",
* enum={"centreon_module"},
* default="centreon_module"
* ),
* description="the name of the API object class",
* required=true
* ),
*
* @OA\Parameter(
* in="query",
* name="action",
*
* @OA\Schema(
* type="string",
* enum={"update"},
* default="update"
* ),
* description="the name of the action in the API class",
* required=true
* ),
*
* @OA\Parameter(
* in="query",
* name="id",
*
* @OA\Schema(
* type="string"
* ),
* description="ID of a module or a widget",
* required=true
* ),
*
* @OA\Parameter(
* in="query",
* name="type",
*
* @OA\Schema(
* type="string",
* enum={
* "module",
* "widget"
* }
* ),
* description="type of object",
* required=true
* ),
*
* @OA\Response(
* response="200",
* description="OK",
*
* @OA\JsonContent(
*
* @OA\Property(property="result", ref="#/components/schemas/UpdateAction"),
* @OA\Property(property="status", type="boolean")
* )
* )
* )
*
* Update module or widget
*
* @throws \RestBadRequestException
*
* @return Response
*/
public function postUpdate()
{
// extract post payload
$request = $this->query();
$id = isset($request['id']) && $request['id'] ? $request['id'] : '';
$type = $request['type'] ?? '';
$status = false;
$result = null;
$entity = null;
try {
$entity = $this->getDi()[ServiceProvider::CENTREON_MODULE]
->update($id, $type);
} catch (\Exception $e) {
$result = new UpdateAction(null, $e->getMessage());
}
if ($entity !== null) {
$result = new UpdateAction($entity);
$status = true;
}
return new Response($result, $status);
}
/**
* @OA\Delete(
* path="/internal.php?object=centreon_module&action=remove",
* summary="Remove module or widget",
* tags={"centreon_module"},
*
* @OA\Parameter(
* in="query",
* name="object",
*
* @OA\Schema(
* type="string",
* enum={"centreon_module"},
* default="centreon_module"
* ),
* description="the name of the API object class",
* required=true
* ),
*
* @OA\Parameter(
* in="query",
* name="action",
*
* @OA\Schema(
* type="string",
* enum={"remove"},
* default="remove"
* ),
* description="the name of the action in the API class",
* required=true
* ),
*
* @OA\Parameter(
* in="query",
* name="id",
*
* @OA\Schema(
* type="string"
* ),
* description="ID of a module or a widget",
* required=true
* ),
*
* @OA\Parameter(
* in="query",
* name="type",
*
* @OA\Schema(
* type="string",
* enum={
* "module",
* "widget"
* }
* ),
* description="type of object",
* required=true
* ),
*
* @OA\Response(
* response="200",
* description="OK",
*
* @OA\JsonContent(
*
* @OA\Property(property="result", type="string"),
* @OA\Property(property="status", type="boolean")
* )
* )
* )
*
* Remove module or widget
*
* @throws \RestBadRequestException
*
* @return Response
*/
public function deleteRemove()
{
// extract post payload
$request = $this->query();
$id = isset($request['id']) && $request['id'] ? $request['id'] : '';
$type = $request['type'] ?? '';
$status = false;
$result = null;
try {
$this->getDi()[ServiceProvider::CENTREON_MODULE]
->remove($id, $type);
$status = true;
} catch (\Exception $e) {
$result = $e->getMessage();
}
return new Response($result, $status);
}
/**
* Name of web service object.
*
* @return string
*/
public static function getName(): string
{
return 'centreon_module';
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonModule/Domain/Repository/ModulesInformationsRepository.php | centreon/src/CentreonModule/Domain/Repository/ModulesInformationsRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonModule\Domain\Repository;
use Centreon\Infrastructure\CentreonLegacyDB\ServiceEntityRepository;
class ModulesInformationsRepository extends ServiceEntityRepository
{
/**
* Get an associative array of all modules vs versions.
*
* @return string[]
*/
public function getAllModuleVsVersion(): array
{
$sql = 'SELECT `name` AS `id`, `mod_release` AS `version` FROM `modules_informations`';
$stmt = $this->db->prepare($sql);
$stmt->execute();
$result = [];
while ($row = $stmt->fetch()) {
$result[$row['id']] = $row['version'];
}
return $result;
}
/**
* Get id by name.
*
* @param string $name
*
* @return int|null
*/
public function findIdByName($name): ?int
{
$sql = 'SELECT `id` FROM `modules_informations` WHERE `name` = :name LIMIT 0, 1';
$stmt = $this->db->prepare($sql);
$stmt->bindValue('name', $name);
$stmt->execute();
while ($row = $stmt->fetch()) {
return intval($row['id']);
}
return null;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonModule/Domain/Repository/WidgetModelsRepository.php | centreon/src/CentreonModule/Domain/Repository/WidgetModelsRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonModule\Domain\Repository;
use Centreon\Infrastructure\CentreonLegacyDB\ServiceEntityRepository;
class WidgetModelsRepository extends ServiceEntityRepository
{
/**
* Get an associative array of all widgets vs versions.
*
* @return string[]
*/
public function getAllWidgetsVersion(): array
{
$sql = 'SELECT `directory` AS `id`, `version` FROM `widget_models`';
$stmt = $this->db->prepare($sql);
$stmt->execute();
$result = [];
while ($row = $stmt->fetch()) {
$result[$row['id']] = $row['version'];
}
return $result;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonModule/Infrastructure/Entity/Module.php | centreon/src/CentreonModule/Infrastructure/Entity/Module.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonModule\Infrastructure\Entity;
use CentreonModule\Infrastructure\Source\SourceDataInterface;
class Module implements SourceDataInterface
{
/** @var string */
protected $lastUpdate;
/** @var string */
protected $releaseNote;
/** @var string */
private $id;
/** @var string */
private $type;
/** @var string */
private $name;
/** @var string */
private $description;
/** @var array<int,string> */
private $images = [];
/** @var string */
private $author;
/** @var string|null */
private $version;
/** @var string|null */
private $versionCurrent;
/** @var bool */
private $isInternal = false;
/** @var string */
private $path;
/** @var string */
private $stability = 'stable';
/** @var string */
private $keywords;
/** @var array<string,string|bool> */
private $license;
/** @var bool */
private $isInstalled = false;
/** @var bool */
private $isUpdated = false;
/**
* @var string[] names of the module's dependencies
*
* @example ['centreon-license-manager']
*/
private array $dependencies = [];
/**
* @return string
*/
public function getId(): string
{
return $this->id;
}
/**
* @param string $id
*/
public function setId(string $id): void
{
$this->id = $id;
}
/**
* @return string
*/
public function getType(): string
{
return $this->type;
}
/**
* @param string $type
*/
public function setType(string $type): void
{
$this->type = $type;
}
/**
* @return string
*/
public function getName(): string
{
return $this->name;
}
/**
* @param string $name
*/
public function setName(string $name): void
{
$this->name = $name;
}
/**
* @return string|null
*/
public function getDescription(): ?string
{
return $this->description;
}
/**
* @param string $description
*/
public function setDescription(string $description): void
{
$this->description = $description;
}
/**
* @return array<int,string>
*/
public function getImages(): array
{
return $this->images;
}
/**
* @param string $image
*/
public function addImage(string $image): void
{
$this->images[] = $image;
}
/**
* @return string
*/
public function getAuthor(): string
{
return $this->author;
}
/**
* @param string $author
*/
public function setAuthor(string $author): void
{
$this->author = $author;
}
/**
* @return string|null
*/
public function getVersion(): ?string
{
return $this->version;
}
/**
* @param string|null $version
*/
public function setVersion(?string $version): void
{
$this->version = $version;
}
/**
* @return string|null
*/
public function getVersionCurrent(): ?string
{
return $this->versionCurrent;
}
/**
* @param string|null $versionCurrent
*/
public function setVersionCurrent(?string $versionCurrent): void
{
$this->versionCurrent = $versionCurrent;
}
/**
* @return bool
*/
public function isInternal(): bool
{
return $this->isInternal;
}
/**
* @param bool $isInternal
*/
public function setInternal(bool $isInternal): void
{
$this->isInternal = $isInternal;
}
/**
* @return string
*/
public function getPath(): string
{
return $this->path;
}
/**
* @param string $path
*/
public function setPath(string $path): void
{
$this->path = $path;
}
/**
* @return string
*/
public function getStability(): string
{
return $this->stability;
}
/**
* @param string $stability
*/
public function setStability(string $stability): void
{
$this->stability = $stability;
}
/**
* @return string
*/
public function getKeywords(): string
{
return $this->keywords;
}
/**
* @param string $keywords
*/
public function setKeywords(string $keywords): void
{
$this->keywords = $keywords;
}
/**
* @return array<string,string|bool>|null
*/
public function getLicense(): ?array
{
return $this->license;
}
/**
* @param array<mixed>|null $license
*/
public function setLicense(?array $license = null): void
{
$this->license = $license;
}
/**
* @return string|null
*/
public function getLastUpdate(): ?string
{
return $this->lastUpdate;
}
/**
* @param string $lastUpdate
*/
public function setLastUpdate(string $lastUpdate): void
{
$this->lastUpdate = $lastUpdate;
}
/**
* @return string|null
*/
public function getReleaseNote(): ?string
{
return $this->releaseNote;
}
/**
* @param string $releaseNote
*/
public function setReleaseNote(string $releaseNote): void
{
$this->releaseNote = $releaseNote;
}
/**
* @return bool
*/
public function isInstalled(): bool
{
return $this->isInstalled;
}
/**
* @param bool $value
*/
public function setInstalled(bool $value): void
{
$this->isInstalled = $value;
}
public function isUpdated(): bool
{
return $this->isUpdated;
}
/**
* @param bool $value
*/
public function setUpdated(bool $value): void
{
$this->isUpdated = $value;
}
/**
* @return string[]
*/
public function getDependencies(): array
{
return $this->dependencies;
}
/**
* @param string $dependency
*/
public function addDependency(string $dependency): void
{
$this->dependencies[] = $dependency;
}
/**
* @param string[] $dependencies
*/
public function setDependencies(array $dependencies): void
{
$this->dependencies = [];
foreach ($dependencies as $dependency) {
$this->addDependency($dependency);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonModule/Infrastructure/Source/ModuleSource.php | centreon/src/CentreonModule/Infrastructure/Source/ModuleSource.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace CentreonModule\Infrastructure\Source;
use CentreonLegacy\ServiceProvider as ServiceProviderLegacy;
use CentreonModule\Domain\Repository\ModulesInformationsRepository;
use CentreonModule\Infrastructure\Entity\Module;
use Psr\Container\ContainerInterface;
class ModuleSource extends SourceAbstract
{
public const TYPE = 'module';
public const PATH = 'www/modules/';
public const PATH_WEB = 'modules/';
public const CONFIG_FILE = 'conf.php';
/** @var array<string,mixed> */
protected $info;
/**
* Construct.
*
* @param ContainerInterface $services
*/
public function __construct(ContainerInterface $services)
{
$this->installer = $services->get(ServiceProviderLegacy::CENTREON_LEGACY_MODULE_INSTALLER);
$this->upgrader = $services->get(ServiceProviderLegacy::CENTREON_LEGACY_MODULE_UPGRADER);
$this->remover = $services->get(ServiceProviderLegacy::CENTREON_LEGACY_MODULE_REMOVER);
$this->license = $services->get(ServiceProviderLegacy::CENTREON_LEGACY_MODULE_LICENSE);
parent::__construct($services);
}
public function initInfo(): void
{
$this->info = $this->db
->getRepository(ModulesInformationsRepository::class)
->getAllModuleVsVersion();
}
/**
* {@inheritDoc}
*
* Install module
*
* @throws ModuleException
*/
public function install(string $id): ?Module
{
/**
* Do not try to install the module if the package is not installed (deb or rpm).
*/
if (($module = $this->getDetail($id)) === null) {
throw ModuleException::cannotFindModuleDetails($id);
}
/**
* Check if the module has dependencies
* if it does, then check if those dependencies are installed or need updates
* if not installed -> install the dependency
* if not up to date -> update the dependency.
*/
$this->installOrUpdateDependencies($id);
/**
* Do not execute the install process for the module if it is already installed.
*/
return $module->isInstalled() === false ? parent::install($id) : $module;
}
/**
* {@inheritDoc}
*
* Remove module
*
* @throws ModuleException
*/
public function remove(string $id): void
{
$this->validateRemovalRequirementsOrFail($id);
$recordId = $this->db
->getRepository(ModulesInformationsRepository::class)
->findIdByName($id);
($this->remover)($id, $recordId)->remove();
}
/**
* {@inheritDoc}
*
* Update module
*
* @throws ModuleException
*/
public function update(string $id): ?Module
{
$this->installOrUpdateDependencies($id);
$recordId = $this->db
->getRepository(ModulesInformationsRepository::class)
->findIdByName($id);
($this->upgrader)($id, $recordId)->upgrade();
$this->initInfo();
return $this->getDetail($id);
}
/**
* @param string|null $search
* @param bool|null $installed
* @param bool|null $updated
*
* @return array<int,Module>
*/
public function getList(?string $search = null, ?bool $installed = null, ?bool $updated = null): array
{
$files = ($this->finder::create())
->files()
->name(static::CONFIG_FILE)
->depth('== 1')
->sortByName()
->in($this->getPath());
$result = [];
foreach ($files as $file) {
$entity = $this->createEntityFromConfig($file->getPathName());
if (! $this->isEligible($entity, $search, $installed, $updated)) {
continue;
}
$result[] = $entity;
}
return $result;
}
/**
* @param string $id
*
* @return Module|null
*/
public function getDetail(string $id): ?Module
{
$result = null;
$path = $this->getPath() . $id;
if (file_exists($path) === false) {
return $result;
}
$files = ($this->finder::create())
->files()
->name(static::CONFIG_FILE)
->depth('== 0')
->sortByName()
->in($path);
foreach ($files as $file) {
$result = $this->createEntityFromConfig($file->getPathName());
}
return $result;
}
/**
* @param string $configFile
*
* @return Module
*/
public function createEntityFromConfig(string $configFile): Module
{
$module_conf = [];
$module_conf = $this->getModuleConf($configFile);
$info = current($module_conf);
$entity = new Module();
$entity->setId(basename(dirname($configFile)));
$entity->setPath(dirname($configFile));
$entity->setType(static::TYPE);
$entity->setName($info['rname']);
$entity->setAuthor($info['author']);
$entity->setVersion($info['mod_release']);
$entity->setDescription($info['infos']);
$entity->setKeywords($entity->getId());
$entity->setLicense($this->getLicenseInformationForModule($entity->getId(), $info));
if (array_key_exists('stability', $info) && $info['stability']) {
$entity->setStability($info['stability']);
}
if (array_key_exists('last_update', $info) && $info['last_update']) {
$entity->setLastUpdate($info['last_update']);
}
if (array_key_exists('release_note', $info) && $info['release_note']) {
$entity->setReleaseNote($info['release_note']);
}
if (array_key_exists('images', $info) && $info['images']) {
if (is_string($info['images'])) {
$info['images'] = [$info['images']];
}
foreach ($info['images'] as $image) {
$entity->addImage(static::PATH_WEB . $entity->getId() . '/' . $image);
}
}
if (array_key_exists('dependencies', $info) && is_array($info['dependencies'])) {
$entity->setDependencies($info['dependencies']);
}
// load information about installed modules/widgets
if ($this->info === null) {
$this->initInfo();
}
if (array_key_exists($entity->getId(), $this->info)) {
$entity->setVersionCurrent($this->info[$entity->getId()]);
$entity->setInstalled(true);
$isUpdated = $this->isUpdated($this->info[$entity->getId()], $entity->getVersion());
$entity->setUpdated($isUpdated);
}
return $entity;
}
/**
* @codeCoverageIgnore
*
* @param string $configFile
*
* @return array<mixed>
*/
protected function getModuleConf(string $configFile): array
{
$module_conf = [];
require $configFile;
return $module_conf;
}
/**
* Process license check and return license information.
*
* @param string $slug the module id (slug)
* @param array<string,mixed> $information the information of the module from conf.php
*
* @return array<string,mixed> the license information
*/
protected function getLicenseInformationForModule(string $slug, array $information): array
{
if (empty($information['require_license'])) {
return ['required' => false];
}
// if module requires a license, use License Manager to get information
$dependencyInjector = \Centreon\LegacyContainer::getInstance();
$license = $dependencyInjector['lm.license'];
$license->setProductForModule($slug);
$licenseInFileData = $license->getData();
return [
'required' => true,
'expiration_date' => $this->license->getLicenseExpiration($slug),
'host_usage' => $this->getHostUsage(),
'is_valid' => $license->validate(),
'host_limit' => $licenseInFileData['licensing']['hosts'] ?? -1,
];
}
/**
* @codeCoverageIgnore
*
* @return string
*/
protected function getPath(): string
{
return $this->path . static::PATH;
}
/**
* Return the number actively used.
*
* @return int|null
*/
private function getHostUsage(): ?int
{
$database = new \CentreonDB();
$request = <<<'SQL'
SELECT COUNT(*) AS `num` FROM host WHERE host_register = "1"
SQL;
$statement = $database->query($request);
if ($record = $statement->fetch(\PDO::FETCH_ASSOC)) {
return (int) $record['num'];
}
return null;
}
/**
* Install or update module dependencies when needed.
*
* @param string $moduleId
*
* @throws ModuleException
*/
private function installOrUpdateDependencies(string $moduleId): void
{
$sortedDependencies = $this->getSortedDependencies($moduleId);
foreach ($sortedDependencies as $dependency) {
$dependencyDetails = $this->getDetail($dependency);
if ($dependencyDetails === null) {
throw ModuleException::cannotFindModuleDetails($dependency);
}
if (! $dependencyDetails->isInstalled()) {
$this->install($dependency);
} elseif (! $dependencyDetails->isUpdated()) {
$this->update($dependency);
}
}
}
/**
* Sort module dependencies.
*
* @param string $moduleId (example: centreon-license-manager)
* @param string[] $alreadyProcessed
*
* @throws ModuleException
*
* @return string[]
*/
private function getSortedDependencies(
string $moduleId,
array $alreadyProcessed = [],
) {
$dependencies = [];
if (in_array($moduleId, $alreadyProcessed, true)) {
return $dependencies;
}
$alreadyProcessed[] = $moduleId;
$moduleDetails = $this->getDetail($moduleId);
if ($moduleDetails === null) {
throw ModuleException::moduleIsMissing($moduleId);
}
foreach ($moduleDetails->getDependencies() as $dependency) {
$dependencies[] = $dependency;
$dependencyDetails = $this->getDetail($dependency);
if (! $dependencyDetails) {
throw ModuleException::moduleIsMissing($dependency);
}
$dependencies = array_unique([
...$this->getSortedDependencies($dependencyDetails->getId(), $alreadyProcessed),
...$dependencies,
]);
}
return $dependencies;
}
/**
* Validate requirements before remove (dependencies).
*
* @param string $moduleId (example: centreon-license-manager)
*
* @throws ModuleException
*/
private function validateRemovalRequirementsOrFail(string $moduleId): void
{
$dependenciesToRemove = [];
$modules = $this->getList();
foreach ($modules as $module) {
if ($module->isInstalled() && in_array($moduleId, $module->getDependencies(), true)) {
$dependenciesToRemove[] = $module->getName();
}
}
if ($dependenciesToRemove !== []) {
throw ModuleException::modulesNeedToBeRemovedFirst($dependenciesToRemove);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonModule/Infrastructure/Source/WidgetSource.php | centreon/src/CentreonModule/Infrastructure/Source/WidgetSource.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonModule\Infrastructure\Source;
use CentreonLegacy\ServiceProvider as ServiceProviderLegacy;
use CentreonModule\Domain\Repository\WidgetModelsRepository;
use CentreonModule\Infrastructure\Entity\Module;
use Psr\Container\ContainerInterface;
class WidgetSource extends SourceAbstract
{
public const TYPE = 'widget';
public const PATH = 'www/widgets/';
public const CONFIG_FILE = 'configs.xml';
/** @var string[] */
private $info;
/**
* Construct.
*
* @param ContainerInterface $services
*/
public function __construct(ContainerInterface $services)
{
$this->installer = $services->get(ServiceProviderLegacy::CENTREON_LEGACY_WIDGET_INSTALLER);
$this->upgrader = $services->get(ServiceProviderLegacy::CENTREON_LEGACY_WIDGET_UPGRADER);
$this->remover = $services->get(ServiceProviderLegacy::CENTREON_LEGACY_WIDGET_REMOVER);
parent::__construct($services);
}
public function initInfo(): void
{
$this->info = $this->db
->getRepository(WidgetModelsRepository::class)
->getAllWidgetsVersion();
}
/**
* @param string|null $search
* @param bool|null $installed
* @param bool|null $updated
*
* @return array<int,Module>
*/
public function getList(?string $search = null, ?bool $installed = null, ?bool $updated = null): array
{
$files = $this->finder
->files()
->name(static::CONFIG_FILE)
->depth('== 1')
->sortByName()
->in($this->getPath());
$result = [];
foreach ($files as $file) {
$entity = $this->createEntityFromConfig($file->getPathName());
if (! $this->isEligible($entity, $search, $installed, $updated)) {
continue;
}
$result[] = $entity;
}
return $result;
}
/**
* @param string $id
*
* @return Module|null
*/
public function getDetail(string $id): ?Module
{
$result = null;
$path = $this->getPath() . $id;
if (file_exists($path) === false) {
return $result;
}
$files = $this->finder
->files()
->name(static::CONFIG_FILE)
->depth('== 0')
->sortByName()
->in($path);
foreach ($files as $file) {
$result = $this->createEntityFromConfig($file->getPathName());
}
return $result;
}
/**
* @param string $configFile
*
* @return Module
*/
public function createEntityFromConfig(string $configFile): Module
{
// force linux path format
$configFile = str_replace(DIRECTORY_SEPARATOR, '/', $configFile);
$xml = simplexml_load_file($configFile);
$entity = new Module();
$entity->setId(basename(dirname($configFile)));
$entity->setPath(dirname($configFile));
$entity->setType(static::TYPE);
$entity->setName($xml->title->__toString());
$entity->setDescription($xml->description->__toString());
$entity->setAuthor($xml->author->__toString());
$entity->setVersion($xml->version ? $xml->version->__toString() : null);
$entity->setInternal($xml->version ? false : true);
$entity->setKeywords($xml->keywords->__toString());
if ($xml->stability) {
$entity->setStability($xml->stability->__toString());
}
if ($xml->last_update) {
$entity->setLastUpdate($xml->last_update->__toString());
}
if ($xml->release_note) {
$entity->setReleaseNote($xml->release_note->__toString());
}
if ($xml->screenshot) {
foreach ($xml->screenshot as $image) {
if (! empty($image->__toString())) {
$entity->addImage($image->__toString());
}
}
unset($image);
}
if ($xml->screenshots) {
foreach ($xml->screenshots as $image) {
if (! empty($image->screenshot['src']->__toString())) {
$entity->addImage($image->screenshot['src']->__toString());
}
}
unset($image);
}
// load information about installed modules/widgets
if ($this->info === null) {
$this->initInfo();
}
if (array_key_exists($entity->getId(), $this->info)) {
$entity->setVersionCurrent($this->info[$entity->getId()]);
$entity->setInstalled(true);
$isUpdated
= $entity->isInternal() || $this->isUpdated($this->info[$entity->getId()], $entity->getVersion());
$entity->setUpdated($isUpdated);
}
return $entity;
}
/**
* @codeCoverageIgnore
*
* @return string
*/
protected function getPath(): string
{
return $this->path . static::PATH;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonModule/Infrastructure/Source/SourceInterface.php | centreon/src/CentreonModule/Infrastructure/Source/SourceInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonModule\Infrastructure\Source;
use CentreonModule\Infrastructure\Entity\Module;
interface SourceInterface
{
public function initInfo(): void;
/**
* @param string|null $search
* @param bool|null $installed
* @param bool|null $updated
*
* @return array<int,Module>
*/
public function getList(?string $search = null, ?bool $installed = null, ?bool $updated = null): array;
public function getDetail(string $id): ?Module;
public function install(string $id): ?Module;
public function update(string $id): ?Module;
public function remove(string $id): void;
public function createEntityFromConfig(string $configFile): Module;
public function isEligible(
Module $entity,
?string $search = null,
?bool $installed = null,
?bool $updated = null,
): bool;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonModule/Infrastructure/Source/SourceDataInterface.php | centreon/src/CentreonModule/Infrastructure/Source/SourceDataInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonModule\Infrastructure\Source;
interface SourceDataInterface
{
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonModule/Infrastructure/Source/ModuleException.php | centreon/src/CentreonModule/Infrastructure/Source/ModuleException.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace CentreonModule\Infrastructure\Source;
class ModuleException extends \Exception
{
/**
* @param string[] $modules
*
* @return self
*/
public static function modulesNeedToBeRemovedFirst(array $modules): self
{
return new self(
sprintf(_('Following modules need to be removed first: %s'), implode(', ', $modules)),
);
}
/**
* @param string $module
*
* @return self
*/
public static function moduleIsMissing(string $module): self
{
return new self(
sprintf(_('Module "%s" is missing'), $module),
);
}
/**
* @param string $module
*
* @return self
*/
public static function cannotFindModuleDetails(string $module): self
{
return new self(
sprintf(_('An error occured while retrieving details of module "%s"'), $module),
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonModule/Infrastructure/Source/SourceAbstract.php | centreon/src/CentreonModule/Infrastructure/Source/SourceAbstract.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonModule\Infrastructure\Source;
use CentreonLegacy\Core\Configuration\Configuration;
use CentreonModule\Infrastructure\Entity\Module;
use Psr\Container\ContainerInterface;
abstract class SourceAbstract implements SourceInterface
{
/** @var \Centreon\Infrastructure\Service\CentreonDBManagerService */
protected $db;
/** @var \Symfony\Component\Finder\Finder */
protected $finder;
/** @var string */
protected $path;
/** @var \CentreonLegacy\Core\Widget\Upgrader|\CentreonLegacy\Core\Module\Upgrader */
protected $upgrader;
/** @var \CentreonLegacy\Core\Module\License */
protected $license;
/** @var \CentreonLegacy\Core\Widget\Remover|\CentreonLegacy\Core\Module\Remover */
protected $remover;
/** @var \CentreonLegacy\Core\Widget\Installer|\CentreonLegacy\Core\Module\Installer */
protected $installer;
/**
* Construct.
*
* @param ContainerInterface $services
*/
public function __construct(ContainerInterface $services)
{
$this->db = $services->get(\Centreon\ServiceProvider::CENTREON_DB_MANAGER);
$this->finder = $services->get('finder');
$this->path = $services->get('configuration')
->get(Configuration::CENTREON_PATH);
}
/**
* Install module or widget.
*
* @param string $id
*
* @return Module|null
*/
public function install(string $id): ?Module
{
($this->installer)($id)->install();
$this->initInfo();
return $this->getDetail($id);
}
/**
* Update module or widget.
*
* @param string $id
*
* @return Module|null
*/
public function update(string $id): ?Module
{
($this->upgrader)($id)->upgrade();
$this->initInfo();
return $this->getDetail($id);
}
/**
* Remove module or widget.
*
* @param string $id
*/
public function remove(string $id): void
{
($this->remover)($id)->remove();
}
public function isEligible(
Module $entity,
?string $search = null,
?bool $installed = null,
?bool $updated = null,
): bool {
if ($search !== null && stripos($entity->getKeywords() . $entity->getName(), $search) === false) {
return false;
}
if ($installed !== null && $entity->isInstalled() !== $installed) {
return false;
}
return ! ($updated !== null && ($entity->isInstalled() !== true || $entity->isUpdated() !== $updated));
}
/**
* @param string $installedVersion
* @param string $codeVersion
*
* @return bool
*/
public function isUpdated($installedVersion, $codeVersion): bool
{
$result = false;
$installedVersion = trim(strtolower($installedVersion));
$codeVersion = trim(strtolower($codeVersion));
if ($installedVersion == $codeVersion) {
$result = true;
}
return $result;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonModule/Infrastructure/Service/CentreonModuleService.php | centreon/src/CentreonModule/Infrastructure/Service/CentreonModuleService.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonModule\Infrastructure\Service;
use CentreonModule\Infrastructure\Entity\Module;
use CentreonModule\Infrastructure\Source;
use Psr\Container\ContainerInterface;
class CentreonModuleService
{
/** @var array<string,mixed> */
protected $sources = [];
/**
* Construct.
*
* @param ContainerInterface $services
*/
public function __construct(ContainerInterface $services)
{
$this->initSources($services);
}
/**
* @param string|null $search
* @param bool|null $installed
* @param bool|null $updated
* @param array<mixed>|null $typeList
*
* @return array<string|int,Module[]>
*/
public function getList(
?string $search = null,
?bool $installed = null,
?bool $updated = null,
?array $typeList = null,
): array {
$result = [];
if ($typeList !== null && $typeList) {
$sources = [];
foreach ($this->sources as $type => $source) {
if (! in_array($type, $typeList) && ! $installed) {
continue;
}
$sources[$type] = $source;
}
} else {
$sources = $this->sources;
}
foreach ($sources as $type => $source) {
$list = $source->getList($search, $installed, $updated);
$result[$type] = $this->sortList($list);
}
return $result;
}
/**
* @param string $id
* @param string $type
*
* @return Module|null
*/
public function getDetail(string $id, string $type): ?Module
{
if (! array_key_exists($type, $this->sources)) {
return null;
}
return $this->sources[$type]->getDetail($id);
}
/**
* @param string $id
* @param string $type
*
* @return Module|null
*/
public function install(string $id, string $type): ?Module
{
if (! array_key_exists($type, $this->sources)) {
return null;
}
return $this->sources[$type]->install($id);
}
/**
* @param string $id
* @param string $type
*
* @return Module|null
*/
public function update(string $id, string $type): ?Module
{
if (! array_key_exists($type, $this->sources)) {
return null;
}
return $this->sources[$type]->update($id);
}
/**
* @param string $id
* @param string $type
*
* @return bool|null
*/
public function remove(string $id, string $type): ?bool
{
if (! array_key_exists($type, $this->sources)) {
return null;
}
$this->sources[$type]->remove($id);
return true;
}
/**
* Init list of sources.
*
* @param ContainerInterface $services
*/
protected function initSources(ContainerInterface $services): void
{
$this->sources = [
Source\ModuleSource::TYPE => new Source\ModuleSource($services),
Source\WidgetSource::TYPE => new Source\WidgetSource($services),
];
}
/**
* Sort list by:.
*
* - To update (then by name)
* - To install (then by name)
* - Installed (then by name)
*
* @param Module[] $list
*
* @return Module[]
*/
protected function sortList(array $list): array
{
usort($list, function ($a, $b) {
$aVal = $a->getName();
$bVal = $b->getName();
if ($aVal === $bVal) {
return 0;
}
return ($aVal < $bVal) ? -1 : 1;
});
usort($list, function ($a, $b) {
$sortByName = function ($a, $b) {
$aVal = $a->isInstalled();
$bVal = $b->isInstalled();
if ($aVal === $bVal) {
return 0;
}
return ($aVal < $bVal) ? -1 : 1;
};
$aVal = $a->isInstalled() && ! $a->isUpdated();
$bVal = $b->isInstalled() && ! $b->isUpdated();
if ($aVal === $bVal) {
return $sortByName($a, $b);
}
return ($aVal === true) ? -1 : 1;
});
return $list;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/LegacyContainer.php | centreon/src/Centreon/LegacyContainer.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Centreon;
use Pimple\Container;
/**
* This class is designed to create a single instance of the Pimple container.
* This factory will later be used by Symfony to create a service for this container.
*
* @package Centreon
*/
class LegacyContainer
{
/** @var Container */
private static $container;
/**
* Return a unique instance of the Pimple container.
*
* @return Container
*/
public static function getInstance(): Container
{
if (self::$container === null) {
self::$container = new Container();
}
return self::$container;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/ServiceProvider.php | centreon/src/Centreon/ServiceProvider.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace Centreon;
use Centreon\Application\Validation;
use Centreon\Application\Webservice;
use Centreon\Domain\Repository\CfgCentreonBrokerInfoRepository;
use Centreon\Domain\Repository\CfgCentreonBrokerRepository;
use Centreon\Domain\Service\BrokerConfigurationService;
use Centreon\Domain\Service\FrontendComponentService;
use Centreon\Domain\Service\I18nService;
use Centreon\Infrastructure\Event;
use Centreon\Infrastructure\Provider\AutoloadServiceProviderInterface;
use Centreon\Infrastructure\Service;
use Centreon\Infrastructure\Service\CentcoreConfigService;
use Centreon\Infrastructure\Service\CentreonClapiService;
use Centreon\Infrastructure\Service\CentreonDBManagerService;
use Centreon\Infrastructure\Service\CentreonWebserviceService;
use CentreonACL as CACL;
use CentreonClapi\CentreonACL;
use CentreonLegacy\ServiceProvider as LegacyServiceProvider;
use Pimple\Container;
use Pimple\Psr11\ServiceLocator;
use Symfony\Component\PropertyInfo\Extractor\ReflectionExtractor;
use Symfony\Component\Serializer;
use Symfony\Component\Validator;
use Symfony\Component\Validator\Constraints;
class ServiceProvider implements AutoloadServiceProviderInterface
{
// webservices
public const CENTREON_WEBSERVICE = 'centreon.webservice';
public const MENU_WEBSERVICE = 'centreon.menu.webservice';
// services
public const CENTREON_PAGINATION = 'centreon.pagination';
public const CENTREON_I18N_SERVICE = 'centreon.i18n_service';
public const CENTREON_FRONTEND_COMPONENT_SERVICE = 'centreon.frontend_component_service';
public const CENTREON_BROKER_CONFIGURATION_SERVICE = 'centreon.broker_configuration_service';
// repositories
public const CENTREON_BROKER_REPOSITORY = 'centreon.broker_repository';
public const CENTREON_BROKER_INFO_REPOSITORY = 'centreon.broker_info_repository';
// managers and infrastructure services
public const CENTREON_DB_MANAGER = 'centreon.db-manager';
public const CENTREON_CLAPI = 'centreon.clapi';
public const UPLOAD_MANGER = 'upload.manager';
public const CENTREON_EVENT_DISPATCHER = 'centreon.event_dispatcher';
public const CENTREON_USER = 'centreon.user';
public const YML_CONFIG = 'yml.config';
public const CENTREON_VALIDATOR_FACTORY = 'centreon.validator_factory';
public const CENTREON_VALIDATOR_TRANSLATOR = 'centreon.validator_translator';
public const VALIDATOR = 'validator';
public const VALIDATOR_EXPRESSION = 'validator.expression';
public const SERIALIZER = 'serializer';
public const SERIALIZER_OBJECT_NORMALIZER = 'serializer.object.normalizer';
public const CENTREON_ACL = 'centreon.acl';
public const CENTREON_GLOBAL_ACL = 'centreon.global.acl';
/**
* {@inheritDoc}
*/
public function register(Container $pimple): void
{
// init global yml config from src/Centreon
$pimple[static::YML_CONFIG] = function (Container $pimple) {
return $pimple[LegacyServiceProvider::CONFIGURATION]->getModuleConfig(__DIR__);
};
$pimple[static::CENTREON_WEBSERVICE] = function (Container $container): CentreonWebserviceService {
return new CentreonWebserviceService();
};
$pimple[static::CENTREON_WEBSERVICE]
->add(Webservice\TopologyWebservice::class)
->add(Webservice\ContactGroupsWebservice::class)
->add(Webservice\ImagesWebservice::class)
->add(Webservice\AclGroupWebservice::class)
// add webservice to get translation from centreon and its extensions
->add(Webservice\CentreonI18n::class)
// add webservice to get frontend hooks and pages installed by modules and widgets
->add(Webservice\CentreonFrontendComponent::class);
$pimple[static::CENTREON_I18N_SERVICE] = function (Container $pimple): I18nService {
$phpstan_needs_this_variable = $pimple['translator']; // bind lang
return new I18nService(
$pimple[LegacyServiceProvider::CENTREON_LEGACY_MODULE_INFORMATION],
$pimple['finder'],
$pimple['filesystem']
);
};
$pimple[static::CENTREON_FRONTEND_COMPONENT_SERVICE] = function (Container $pimple): FrontendComponentService {
return new FrontendComponentService(
new ServiceLocator(
$pimple,
FrontendComponentService::dependencies()
)
);
};
$pimple[static::CENTREON_CLAPI] = function (Container $container): CentreonClapiService {
return new CentreonClapiService();
};
$pimple[static::CENTREON_DB_MANAGER] = function (Container $container): CentreonDBManagerService {
$services = [
'realtime_db',
'configuration_db',
];
$locator = new ServiceLocator($container, $services);
return new CentreonDBManagerService($locator);
};
$pimple[static::CENTREON_PAGINATION] = function (Container $container): Service\CentreonPaginationService {
return new Service\CentreonPaginationService(
new ServiceLocator(
$container,
Service\CentreonPaginationService::dependencies()
)
);
};
$pimple['centreon.user'] = function (Container $container): ?\CentreonUser {
// @codeCoverageIgnoreStart
if (! empty($GLOBALS['centreon']->user) && $GLOBALS['centreon']->user instanceof \CentreonUser) {
return $GLOBALS['centreon']->user;
}
if (php_sapi_name() !== 'cli' && session_status() == PHP_SESSION_NONE) {
session_start();
}
return $_SESSION['centreon']->user; // @codeCoverageIgnoreEnd
};
$pimple[static::CENTREON_ACL] = function (Container $container): CentreonACL {
return new CentreonACL($container);
};
$pimple[static::CENTREON_GLOBAL_ACL] = function (): CACL {
$service = new CACL($_SESSION['centreon']->user->user_id, $_SESSION['centreon']->user->admin);
return $service;
};
$pimple['centreon.config'] = function (): CentcoreConfigService {
return new CentcoreConfigService();
};
/**
* Repositories
*/
// @todo class is available via centreon.db-manager
$pimple[static::CENTREON_BROKER_REPOSITORY] = function (Container $container): CfgCentreonBrokerRepository {
return new CfgCentreonBrokerRepository($container['configuration_db']);
};
// @todo class is available via centreon.db-manager
$pimple[static::CENTREON_BROKER_INFO_REPOSITORY]
= function (Container $container): CfgCentreonBrokerInfoRepository {
return new CfgCentreonBrokerInfoRepository($container['configuration_db']);
};
/**
* Services
*/
$pimple[static::CENTREON_BROKER_CONFIGURATION_SERVICE]
= function (Container $container): BrokerConfigurationService {
$service = new BrokerConfigurationService();
$service->setBrokerInfoRepository($container[ServiceProvider::CENTREON_BROKER_INFO_REPOSITORY]);
return $service;
};
$pimple[static::UPLOAD_MANGER] = function (Container $pimple): Service\UploadFileService {
$services = [];
$locator = new ServiceLocator($pimple, $services);
$service = new Service\UploadFileService($locator, $_FILES);
return $service;
};
$pimple[static::CENTREON_EVENT_DISPATCHER] = function (): Event\EventDispatcher {
$eventDispatcher = new Event\EventDispatcher();
$eventDispatcher->setDispatcherLoader(
new Event\FileLoader(
__DIR__ . '/../../www/modules/',
'custom-module-form.php'
)
);
return $eventDispatcher;
};
$this->registerValidator($pimple);
$pimple[static::SERIALIZER_OBJECT_NORMALIZER] = function (): Serializer\Normalizer\ObjectNormalizer {
$classMetadataFactory = new Serializer\Mapping\Factory\ClassMetadataFactory(
new Serializer\Mapping\Loader\AttributeLoader()
);
return new Serializer\Normalizer\ObjectNormalizer(
$classMetadataFactory,
new Serializer\NameConverter\MetadataAwareNameConverter($classMetadataFactory),
null,
new ReflectionExtractor()
);
};
$pimple[static::SERIALIZER] = function ($container): Serializer\Serializer {
return new Serializer\Serializer([
$container[static::SERIALIZER_OBJECT_NORMALIZER],
new Serializer\Normalizer\ArrayDenormalizer(),
], [
new Serializer\Encoder\JsonEncoder(),
]);
};
}
/**
* Register services related with validation
*
* @param Container $pimple
*/
public function registerValidator(Container $pimple): void
{
$pimple[static::VALIDATOR] = function (Container $container): Validator\Validator\ValidatorInterface {
return Validator\Validation::createValidatorBuilder()
->addMethodMapping('loadValidatorMetadata')
->setConstraintValidatorFactory($container[ServiceProvider::CENTREON_VALIDATOR_FACTORY])
->setTranslator($container[ServiceProvider::CENTREON_VALIDATOR_TRANSLATOR])
->getValidator();
};
$pimple[static::CENTREON_VALIDATOR_FACTORY]
= function (Container $container): Validation\CentreonValidatorFactory {
return new Validation\CentreonValidatorFactory($container);
};
$pimple[static::CENTREON_VALIDATOR_TRANSLATOR]
= function (Container $container): Validation\CentreonValidatorTranslator {
return new Validation\CentreonValidatorTranslator($container['centreon.user']);
};
$pimple[static::VALIDATOR_EXPRESSION] = function (): Constraints\ExpressionValidator {
return new Constraints\ExpressionValidator();
};
}
/**
* {@inheritDoc}
*/
public static function order(): int
{
return 1;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Application/ApiPlatform.php | centreon/src/Centreon/Application/ApiPlatform.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Centreon\Application;
/**
* Used to get API parameters
*/
class ApiPlatform
{
/** @var string */
private $version;
/**
* Get the API version
*
* @return string
*/
public function getVersion(): string
{
return $this->version;
}
/**
* Set the API version
*
* @param string $version
* @return $this
*/
public function setVersion(string $version): self
{
$this->version = $version;
return $this;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Application/DataRepresenter/Entity.php | centreon/src/Centreon/Application/DataRepresenter/Entity.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace Centreon\Application\DataRepresenter;
use JsonSerializable;
use ReflectionClass;
class Entity implements JsonSerializable
{
/** @var mixed */
private $entity;
/**
* Construct
*
* @param mixed $entity
*/
public function __construct($entity)
{
$this->entity = $entity;
}
/**
* JSON serialization of entity
*
* @return mixed[]
*/
public function jsonSerialize(): mixed
{
return is_object($this->entity) ? static::dismount($this->entity) : (array) $this->entity;
}
/**
* @param object $object
* @throws \ReflectionException
* @return array<mixed>
*/
public static function dismount(object $object): array
{
$reflectionClass = new ReflectionClass($object::class);
$array = [];
foreach ($reflectionClass->getProperties() as $property) {
$property->setAccessible(true);
$array[$property->getName()] = $property->getValue($object);
$property->setAccessible(false);
}
return $array;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Application/DataRepresenter/Response.php | centreon/src/Centreon/Application/DataRepresenter/Response.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace Centreon\Application\DataRepresenter;
use JsonSerializable;
/**
* Unification of API response
*/
class Response implements JsonSerializable
{
/** @var bool */
private $status;
/** @var mixed */
private $result;
/**
* Construct
*
* @param mixed $result
* @param bool $status
*/
public function __construct($result, bool $status = true)
{
$this->status = $status;
$this->result = $result;
}
/**
* JSON serialization of response
*
* @return array{status: bool, result: mixed}
*/
public function jsonSerialize(): mixed
{
return [
'status' => $this->status,
'result' => $this->result,
];
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Application/DataRepresenter/Listing.php | centreon/src/Centreon/Application/DataRepresenter/Listing.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace Centreon\Application\DataRepresenter;
use JsonSerializable;
/**
* @OA\Schema(
* schema="Pagination",
* allOf={
* @OA\Schema(
* @OA\Property(property="total", type="integer"),
* @OA\Property(property="offset", type="integer"),
* @OA\Property(property="limit", type="integer")
* )
* }
* )
*/
class Listing implements JsonSerializable
{
/** @var array */
private $entities;
/** @var int|null */
private $offset;
/** @var int */
private $limit;
/** @var int */
private $total;
/** @var string */
private $entityClass;
/**
* Construct
*
* @param mixed $entities
* @param string $entityClass Entity JSON wrap class
* @param int $total
* @param int $offset
* @param int $limit
* @param string $entityClass
*/
public function __construct(
$entities,
?int $total = null,
?int $offset = null,
?int $limit = null,
?string $entityClass = null,
) {
$this->entities = $entities ?? [];
$this->total = $total ?: count($this->entities);
$this->offset = $offset;
$this->limit = $limit ?? $this->total;
$this->entityClass = $entityClass ?? Entity::class;
}
/**
* JSON serialization of list
*
* @return array<string,mixed>
*/
public function jsonSerialize(): mixed
{
$result = [
'pagination' => [
'total' => $this->total,
'offset' => $this->offset ?? 0,
'limit' => $this->limit,
],
'entities' => [],
];
foreach ($this->entities as $entity) {
$result['entities'][] = new $this->entityClass($entity);
}
return $result;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Application/DataRepresenter/ValidatorErrorList.php | centreon/src/Centreon/Application/DataRepresenter/ValidatorErrorList.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace Centreon\Application\DataRepresenter;
use JsonSerializable;
use Symfony\Component\Validator\ConstraintViolationList;
class ValidatorErrorList implements JsonSerializable
{
/** @var ConstraintViolationList */
private $errors;
/**
* Construct
*
* @param ConstraintViolationList $errors
*/
public function __construct(ConstraintViolationList $errors)
{
$this->errors = $errors;
}
/**
* @OA\Schema(
* schema="ValidatorErrorList",
* @OA\Property(property="field", type="string"),
* @OA\Property(property="messages", type="array", items={"string"})
* )
*
* JSON serialization of errors
*
* @return array<array{field: string, messages: string}>
*/
public function jsonSerialize(): mixed
{
$result = [];
foreach ($this->errors as $error) {
$result[] = [
'field' => $error->getPropertyPath(),
'messages' => $error->getMessage(),
];
}
return $result;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Application/DataRepresenter/Bulk.php | centreon/src/Centreon/Application/DataRepresenter/Bulk.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace Centreon\Application\DataRepresenter;
use JsonSerializable;
class Bulk implements JsonSerializable
{
/** @var array */
private $lists;
/** @var int */
private $offset;
/** @var int */
private $limit;
/** @var string */
private $listingClass;
/** @var string */
private $entityClass;
/**
* Construct
*
* @param array $lists
* @param string $listingClass
* @param string $entityClass
*/
public function __construct(
array $lists,
?int $offset = null,
?int $limit = null,
?string $listingClass = null,
?string $entityClass = null,
) {
$this->lists = $lists;
$this->offset = $offset;
$this->limit = $limit;
$this->listingClass = $listingClass ?? Listing::class;
$this->entityClass = $entityClass ?? Entity::class;
}
/**
* JSON serialization of several lists
*
* @return mixed[]
*/
public function jsonSerialize(): mixed
{
$result = [];
foreach ($this->lists as $name => $entities) {
$result[$name] = new $this->listingClass(
$entities,
null,
$this->offset,
$this->limit,
$this->entityClass
);
}
return $result;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Application/DataRepresenter/Topology/NavigationList.php | centreon/src/Centreon/Application/DataRepresenter/Topology/NavigationList.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Centreon\Application\DataRepresenter\Topology;
use Centreon\Domain\Entity\Topology;
use JsonSerializable;
class NavigationList implements JsonSerializable
{
/** @var array<Topology> */
private array $entities;
/**
* Configurations from navigation.yml.
*
* @var array<array{name: string, color: string, icon: string}>
*/
private array $navConfig;
/** @var array<string> */
private array $enabledFeatureFlags;
/**
* @param array<Topology> $entities
* @param array<array{name: string, color: string, icon: string}> $navConfig
* @param array<string> $enabledFeatureFlags
*/
public function __construct(array $entities, array $navConfig = [], array $enabledFeatureFlags = [])
{
$this->navConfig = $navConfig;
$this->entities = $entities;
$this->enabledFeatureFlags = $enabledFeatureFlags;
}
/**
* @return array<array{name: string, color: string, icon: string}>
*/
public function getNavConfig(): array
{
return $this->navConfig;
}
/**
* JSON serialization of entity.
*
* @return array<mixed>
*/
public function jsonSerialize(): array
{
$groups = $this->extractGroups($this->entities);
$tree = $this->generateTreeLevels($this->entities, $groups);
return $this->removeKeysFromArray($tree);
}
/**
* Get navigation items color for page.
*
* @param int|string $pageId The page id
*
* @return string color
*/
protected function getColor(int|string $pageId): string
{
return $this->getNavConfig()[$pageId]['color']
?? $this->getNavConfig()['default']['color'];
}
/**
* Get navigation items icons per page.
*
* @param int|string $pageId The page id
*
* @return string icon name
*/
protected function getIcon(int|string $pageId): string
{
return $this->getNavConfig()[$pageId]['icon']
?? $this->getNavConfig()['default']['icon'];
}
/**
* Extract groups from full array of topologies.
*
* @param array<Topology> $entities array of topologies
*
* @return array<mixed> of topologies
*/
private function extractGroups(array $entities): array
{
$groups = [];
foreach ($entities as $entity) {
if ($entity->getTopologyPage() === null && $entity->getIsReact() === '0') {
$groups[$entity->getTopologyParent()][$entity->getTopologyGroup()] = [
'name' => $entity->getTopologyName(),
];
}
}
return $groups;
}
/**
* Tells whether the Topology entity should be excluded because of feature flags.
*
* @param Topology $entity
*/
private function isFeatureFlagExcluded(Topology $entity): bool
{
$flag = (string) $entity->getTopologyFeatureFlag();
if ($flag === '') {
return false;
}
return ! in_array($flag, $this->enabledFeatureFlags, true);
}
/**
* Generate level list of menu.
*
* @param array<Topology> $entities
* @param array<mixed> $groups
*
* @return array<mixed>
*/
private function generateTreeLevels(array $entities, array $groups): array
{
$tree = [];
foreach ($entities as $entity) {
if (
null === ($topologyPage = $entity->getTopologyPage())
|| $this->isFeatureFlagExcluded($entity)
) {
continue;
}
if (
preg_match('/^(\d)$/', $topologyPage, $matches)
) {
// LEVEL 1 (specific case where topology_id = topology_page)
$tree[$matches[1]] = [
'page' => $topologyPage,
'label' => $entity->getTopologyName(),
'menu_id' => $entity->getTopologyName(),
'url' => $entity->getTopologyUrl(),
'color' => $this->getColor($topologyPage),
'icon' => $this->getIcon($topologyPage),
'children' => [],
'options' => $entity->getTopologyUrlOpt(),
'is_react' => (bool) $entity->getIsReact(),
'show' => (bool) $entity->getTopologyShow(),
];
} elseif (
preg_match('/^(\d)\d\d$/', $topologyPage, $matches)
&& ! empty($tree[$matches[1]])
) {
// LEVEL 2
$tree[$matches[1]]['children'][$topologyPage] = [
'page' => $topologyPage,
'label' => $entity->getTopologyName(),
'url' => $entity->getTopologyUrl(),
'groups' => [],
'options' => $entity->getTopologyUrlOpt(),
'is_react' => (bool) $entity->getIsReact(),
'show' => (bool) $entity->getTopologyShow(),
];
} elseif (
preg_match('/^(\d)(\d\d)\d\d$/', $topologyPage, $matches)
&& ! empty($tree[$matches[1]]['children'][$matches[1] . $matches[2]])
) {
// LEVEL 3
$levelOne = $matches[1];
$levelTwo = $matches[1] . $matches[2];
// generate the array for the item
$levelThree = [
'page' => $topologyPage,
'label' => $entity->getTopologyName(),
'url' => $entity->getTopologyUrl(),
'options' => $entity->getTopologyUrlOpt(),
'is_react' => (bool) $entity->getIsReact(),
'show' => (bool) $entity->getTopologyShow(),
];
// check if topology has group index
$topologyGroup = $entity->getTopologyGroup();
if (
$topologyGroup !== null
&& isset($groups[$levelTwo][$topologyGroup])
) {
if (! isset($tree[$levelOne]['children'][$levelTwo]['groups'][$topologyGroup])) {
$tree[$levelOne]['children'][$levelTwo]['groups'][$topologyGroup] = [
'label' => $groups[$levelTwo][$topologyGroup]['name'],
'children' => [],
];
}
$tree[$levelOne]['children'][$levelTwo]['groups'][$topologyGroup]['children'][] = $levelThree;
} else {
if (! isset($tree[$levelOne]['children'][$levelTwo]['groups']['default'])) {
$tree[$levelOne]['children'][$levelTwo]['groups']['default'] = [
'label' => 'Main Menu',
'children' => [],
];
}
$tree[$levelOne]['children'][$levelTwo]['groups']['default']['children'][] = $levelThree;
}
}
}
return $tree;
}
/**
* Extract the array without keys to avoid serialization into objects.
*
* @param array<mixed> $tree
*
* @return array<mixed>
*/
private function removeKeysFromArray(array $tree): array
{
foreach ($tree as &$value) {
if (! empty($value['children'])) {
foreach ($value['children'] as &$c) {
if (! empty($c['groups'])) {
$c['groups'] = array_values($c['groups']);
}
}
$value['children'] = array_values($value['children']);
}
}
return array_values($tree);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Application/Controller/PlatformController.php | centreon/src/Centreon/Application/Controller/PlatformController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Centreon\Application\Controller;
use Centreon\Domain\Platform\Interfaces\PlatformServiceInterface;
use Centreon\Domain\Platform\PlatformException;
use Centreon\Domain\PlatformInformation\Exception\PlatformInformationException;
use Centreon\Domain\PlatformInformation\Model\PlatformInformationDtoValidator;
use Centreon\Domain\PlatformInformation\UseCase\V20\UpdatePartiallyPlatformInformation;
use Centreon\Domain\VersionHelper;
use FOS\RestBundle\View\View;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
/**
* This controller is designed to manage API requests concerning the versions of the different modules, widgets on the
* Centreon platform.
*/
class PlatformController extends AbstractController
{
public function __construct(
private readonly PlatformServiceInterface $informationService,
) {
}
/**
* Retrieves the version of modules, widgets, remote pollers from the Centreon Platform.
*
* @throws PlatformException
*
* @return Response
*/
public function getVersions(): Response
{
$webVersion = $this->informationService->getWebVersion();
$modulesVersion = $this->informationService->getModulesVersion();
$widgetsVersion = $this->informationService->getWidgetsVersion($webVersion);
return new JsonResponse(
[
'web' => (object) $this->extractVersion($webVersion),
'modules' => (object) array_map($this->extractVersion(...), $modulesVersion),
'widgets' => (object) array_map($this->extractVersion(...), $widgetsVersion),
]
);
}
/**
* Update the platform.
*
* @param Request $request
* @param UpdatePartiallyPlatformInformation $updatePartiallyPlatformInformation
*
* @throws \Throwable
*
* @return View
*/
public function updatePlatform(
Request $request,
UpdatePartiallyPlatformInformation $updatePartiallyPlatformInformation,
): View {
$this->denyAccessUnlessGrantedForApiConfiguration();
$updatePartiallyPlatformInformation->addValidators(
[
new PlatformInformationDtoValidator(
$this->getParameter('centreon_path')
. 'config/json_validator/latest/Centreon/PlatformInformation/Update.json'
),
]
);
$request = json_decode((string) $request->getContent(), true);
if (! \is_array($request)) {
throw new BadRequestHttpException(_('Error when decoding sent data'));
}
try {
$updatePartiallyPlatformInformation->execute($request);
} catch (PlatformInformationException $ex) {
return match ($ex->getCode()) {
PlatformInformationException::CODE_FORBIDDEN => $this->view(null, Response::HTTP_FORBIDDEN),
default => $this->view(null, Response::HTTP_BAD_REQUEST),
};
} catch (\Throwable $th) {
$this->view(null, Response::HTTP_INTERNAL_SERVER_ERROR);
}
return $this->view(null, Response::HTTP_NO_CONTENT);
}
/**
* Extract the major, minor and fix number from the version.
*
* @param string $version Version to analyse (ex: 1.2.09)
*
* @return array{
* version: string,
* major: string,
* minor: string,
* fix: string
* } (ex: [ 'version' => '1.2.09', 'major' => '1', 'minor' => '2', 'fix' => '09'])
*/
private function extractVersion(string $version): array
{
[$major, $minor, $fix] = explode(
'.',
VersionHelper::regularizeDepthVersion($version),
3
);
return compact('version', 'major', 'minor', 'fix');
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Application/Controller/AcknowledgementController.php | centreon/src/Centreon/Application/Controller/AcknowledgementController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Centreon\Application\Controller;
use Centreon\Domain\Acknowledgement\Acknowledgement;
use Centreon\Domain\Acknowledgement\AcknowledgementService;
use Centreon\Domain\Acknowledgement\Interfaces\AcknowledgementServiceInterface;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Entity\EntityValidator;
use Centreon\Domain\Exception\EntityNotFoundException;
use Centreon\Domain\Monitoring\Resource as ResourceEntity;
use Centreon\Domain\Option\Interfaces\OptionServiceInterface;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use FOS\RestBundle\Context\Context;
use FOS\RestBundle\View\View;
use JMS\Serializer\Exception\ValidationFailedException;
use JMS\Serializer\SerializerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* Used to manage all requests of hosts acknowledgements.
*/
class AcknowledgementController extends AbstractController
{
private const ACKNOWLEDGE_RESOURCES_PAYLOAD_VALIDATION_FILE
= __DIR__ . '/../../../../config/json_validator/latest/Centreon/Acknowledgement/AcknowledgeResources.json';
private const DISACKNOWLEDGE_RESOURCES_PAYLOAD_VALIDATION_FILE
= __DIR__ . '/../../../../config/json_validator/latest/Centreon/Acknowledgement/DisacknowledgeResources.json';
private const
DEFAULT_ACKNOWLEDGEMENT_STICKY = 'monitoring_ack_sticky';
private const
DEFAULT_ACKNOWLEDGEMENT_PERSISTENT = 'monitoring_ack_persistent';
private const
DEFAULT_ACKNOWLEDGEMENT_NOTIFY = 'monitoring_ack_notify';
private const
DEFAULT_ACKNOWLEDGEMENT_WITH_SERVICES = 'monitoring_ack_svc';
private const
DEFAULT_ACKNOWLEDGEMENT_FORCE_ACTIVE_CHECKS = 'monitoring_ack_active_checks';
public function __construct(
private AcknowledgementServiceInterface $acknowledgementService,
private ReadAccessGroupRepositoryInterface $readAccessGroupRepository,
private OptionServiceInterface $optionService,
) {
}
/**
* Entry point to find the hosts acknowledgements.
*
* @param RequestParametersInterface $requestParameters
*
* @throws \Exception
*
* @return View
*/
public function findHostsAcknowledgements(RequestParametersInterface $requestParameters): View
{
$this->denyAccessUnlessGrantedForApiRealtime();
$hostsAcknowledgements = $this->acknowledgementService
->filterByContact($this->getUser())
->findHostsAcknowledgements();
$context = (new Context())->setGroups(Acknowledgement::SERIALIZER_GROUPS_HOST);
return $this->view(
[
'result' => $hostsAcknowledgements,
'meta' => $requestParameters->toArray(),
]
)->setContext($context);
}
/**
* Entry point to find acknowledgements linked to a host.
*
* @param RequestParametersInterface $requestParameters
* @param int $hostId
*
* @throws \Exception
*
* @return View
*/
public function findAcknowledgementsByHost(
RequestParametersInterface $requestParameters,
int $hostId,
): View {
$this->denyAccessUnlessGrantedForApiRealtime();
$hostsAcknowledgements = $this->acknowledgementService
->filterByContact($this->getUser())
->findAcknowledgementsByHost($hostId);
$context = (new Context())->setGroups(Acknowledgement::SERIALIZER_GROUPS_HOST);
return $this->view(
[
'result' => $hostsAcknowledgements,
'meta' => $requestParameters->toArray(),
]
)->setContext($context);
}
/**
* Entry point to find the services acknowledgements.
*
* @param RequestParametersInterface $requestParameters
*
* @throws \Exception
*
* @return View
*/
public function findServicesAcknowledgements(RequestParametersInterface $requestParameters): View
{
$this->denyAccessUnlessGrantedForApiRealtime();
$servicesAcknowledgements = $this->acknowledgementService
->filterByContact($this->getUser())
->findServicesAcknowledgements();
$context = (new Context())->setGroups(Acknowledgement::SERIALIZER_GROUPS_SERVICE);
return $this->view(
[
'result' => $servicesAcknowledgements,
'meta' => $requestParameters->toArray(),
]
)->setContext($context);
}
/**
* Entry point to find acknowledgements linked to a service.
*
* @param RequestParametersInterface $requestParameters
* @param int $hostId
* @param int $serviceId
*
* @throws \Exception
*
* @return View
*/
public function findAcknowledgementsByService(
RequestParametersInterface $requestParameters,
int $hostId,
int $serviceId,
): View {
$this->denyAccessUnlessGrantedForApiRealtime();
$servicesAcknowledgements = $this->acknowledgementService
->filterByContact($this->getUser())
->findAcknowledgementsByService($hostId, $serviceId);
$context = (new Context())->setGroups(Acknowledgement::SERIALIZER_GROUPS_SERVICE);
return $this->view(
[
'result' => $servicesAcknowledgements,
'meta' => $requestParameters->toArray(),
]
)->setContext($context);
}
/**
* Entry point to find acknowledgements linked to a meta service.
*
* @param RequestParametersInterface $requestParameters
* @param int $metaId
*
* @throws \Exception
*
* @return View
*/
public function findAcknowledgementsByMetaService(
RequestParametersInterface $requestParameters,
int $metaId,
): View {
$this->denyAccessUnlessGrantedForApiRealtime();
$metaServicesAcknowledgements = $this->acknowledgementService
->filterByContact($this->getUser())
->findAcknowledgementsByMetaService($metaId);
$context = (new Context())->setGroups(Acknowledgement::SERIALIZER_GROUPS_SERVICE);
return $this->view(
[
'result' => $metaServicesAcknowledgements,
'meta' => $requestParameters->toArray(),
]
)->setContext($context);
}
/**
* Entry point to add multiple host acknowledgements.
*
* @param Request $request
* @param EntityValidator $entityValidator
* @param SerializerInterface $serializer
*
* @throws \Exception
*
* @return View
*/
public function addHostAcknowledgements(
Request $request,
EntityValidator $entityValidator,
SerializerInterface $serializer,
): View {
$this->denyAccessUnlessGrantedForApiRealtime();
/**
* @var Contact $contact
*/
$contact = $this->getUser();
if (! $contact->isAdmin() && ! $contact->hasRole(Contact::ROLE_HOST_ACKNOWLEDGEMENT)) {
return $this->view(null, Response::HTTP_UNAUTHORIZED);
}
/**
* @var Acknowledgement[] $acknowledgements
*/
$acknowledgements = $serializer->deserialize(
(string) $request->getContent(),
'array<' . Acknowledgement::class . '>',
'json'
);
$this->acknowledgementService->filterByContact($contact);
foreach ($acknowledgements as $acknowledgement) {
$errors = $entityValidator->validate(
$acknowledgement,
null,
AcknowledgementService::VALIDATION_GROUPS_ADD_HOST_ACKS
);
if ($errors->count() > 0) {
throw new ValidationFailedException($errors);
}
try {
$this->acknowledgementService->addHostAcknowledgement($acknowledgement);
} catch (EntityNotFoundException $e) {
continue;
}
}
return $this->view();
}
/**
* Entry point to add multiple service acknowledgements.
*
* @param Request $request
* @param EntityValidator $entityValidator
* @param SerializerInterface $serializer
*
* @throws \Exception
*
* @return View
*/
public function addServiceAcknowledgements(
Request $request,
EntityValidator $entityValidator,
SerializerInterface $serializer,
): View {
$this->denyAccessUnlessGrantedForApiRealtime();
/**
* @var Contact $contact
*/
$contact = $this->getUser();
if (! $contact->isAdmin() && ! $contact->hasRole(Contact::ROLE_SERVICE_ACKNOWLEDGEMENT)) {
return $this->view(null, Response::HTTP_UNAUTHORIZED);
}
/**
* @var Acknowledgement[] $acknowledgements
*/
$acknowledgements = $serializer->deserialize(
(string) $request->getContent(),
'array<' . Acknowledgement::class . '>',
'json'
);
$this->acknowledgementService->filterByContact($contact);
foreach ($acknowledgements as $acknowledgement) {
$errors = $entityValidator->validate(
$acknowledgement,
null,
AcknowledgementService::VALIDATION_GROUPS_ADD_SERVICE_ACKS
);
if ($errors->count() > 0) {
throw new ValidationFailedException($errors);
}
try {
$this->acknowledgementService->addServiceAcknowledgement($acknowledgement);
} catch (EntityNotFoundException $e) {
continue;
}
}
return $this->view();
}
/**
* Entry point to add a host acknowledgement.
*
* @param Request $request
* @param EntityValidator $entityValidator
* @param SerializerInterface $serializer
* @param int $hostId
*
* @throws \Exception
*
* @return View
*/
public function addHostAcknowledgement(
Request $request,
EntityValidator $entityValidator,
SerializerInterface $serializer,
int $hostId,
): View {
$this->denyAccessUnlessGrantedForApiRealtime();
/**
* @var Contact $contact
*/
$contact = $this->getUser();
if (! $contact->isAdmin() && ! $contact->hasRole(Contact::ROLE_HOST_ACKNOWLEDGEMENT)) {
return $this->view(null, Response::HTTP_UNAUTHORIZED);
}
$payload = json_decode((string) $request->getContent(), true);
if (! is_array($payload)) {
throw new \InvalidArgumentException('Error when decoding your sent data');
}
$errors = $entityValidator->validateEntity(
Acknowledgement::class,
$payload,
AcknowledgementService::VALIDATION_GROUPS_ADD_HOST_ACK,
false // To avoid error message for missing fields
);
if ($errors->count() > 0) {
throw new ValidationFailedException($errors);
}
/**
* @var Acknowledgement $acknowledgement
*/
$acknowledgement = $serializer->deserialize(
(string) $request->getContent(),
Acknowledgement::class,
'json'
);
$acknowledgement->setResourceId($hostId);
$this->acknowledgementService
->filterByContact($contact)
->addHostAcknowledgement($acknowledgement);
return $this->view();
}
/**
* Entry point to add a service acknowledgement.
*
* @param Request $request
* @param EntityValidator $entityValidator
* @param SerializerInterface $serializer
* @param int $hostId
* @param int $serviceId
*
* @throws \Exception
*
* @return View
*/
public function addServiceAcknowledgement(
Request $request,
EntityValidator $entityValidator,
SerializerInterface $serializer,
int $hostId,
int $serviceId,
): View {
$this->denyAccessUnlessGrantedForApiRealtime();
/**
* @var Contact $contact
*/
$contact = $this->getUser();
if (! $contact->isAdmin() && ! $contact->hasRole(Contact::ROLE_SERVICE_ACKNOWLEDGEMENT)) {
return $this->view(null, Response::HTTP_UNAUTHORIZED);
}
$payload = json_decode((string) $request->getContent(), true);
if (! is_array($payload)) {
throw new \InvalidArgumentException('Error when decoding your sent data');
}
$errors = $entityValidator->validateEntity(
Acknowledgement::class,
$payload,
AcknowledgementService::VALIDATION_GROUPS_ADD_SERVICE_ACK,
false // To show errors on not expected fields
);
if ($errors->count() > 0) {
throw new ValidationFailedException($errors);
}
/**
* @var Acknowledgement $acknowledgement
*/
$acknowledgement = $serializer->deserialize(
(string) $request->getContent(),
Acknowledgement::class,
'json'
);
$acknowledgement
->setParentResourceId($hostId)
->setResourceId($serviceId);
$this->acknowledgementService
->filterByContact($contact)
->addServiceAcknowledgement($acknowledgement);
return $this->view();
}
/**
* Entry point to add a service acknowledgement.
*
* @param Request $request
* @param EntityValidator $entityValidator
* @param SerializerInterface $serializer
* @param int $metaId
*
* @throws \Exception
*
* @return View
*/
public function addMetaServiceAcknowledgement(
Request $request,
EntityValidator $entityValidator,
SerializerInterface $serializer,
int $metaId,
): View {
$this->denyAccessUnlessGrantedForApiRealtime();
/**
* @var Contact $contact
*/
$contact = $this->getUser();
if (! $contact->isAdmin() && ! $contact->hasRole(Contact::ROLE_SERVICE_ACKNOWLEDGEMENT)) {
return $this->view(null, Response::HTTP_UNAUTHORIZED);
}
$payload = json_decode((string) $request->getContent(), true);
if (! is_array($payload)) {
throw new \InvalidArgumentException('Error when decoding your sent data');
}
$errors = $entityValidator->validateEntity(
Acknowledgement::class,
$payload,
AcknowledgementService::VALIDATION_GROUPS_ADD_SERVICE_ACK,
false // To show errors on not expected fields
);
if ($errors->count() > 0) {
throw new ValidationFailedException($errors);
}
/**
* @var Acknowledgement $acknowledgement
*/
$acknowledgement = $serializer->deserialize(
(string) $request->getContent(),
Acknowledgement::class,
'json'
);
$acknowledgement
->setResourceId($metaId);
$this->acknowledgementService
->filterByContact($contact)
->addMetaServiceAcknowledgement($acknowledgement);
return $this->view();
}
/**
* Entry point to disacknowledge an acknowledgement.
*
* @param int $hostId Host id for which we want to cancel the acknowledgement
*
* @throws \Exception
*
* @return View
*/
public function disacknowledgeHost(int $hostId): View
{
$this->denyAccessUnlessGrantedForApiRealtime();
/**
* @var Contact $contact
*/
$contact = $this->getUser();
if (! $contact->isAdmin() && ! $contact->hasRole(Contact::ROLE_HOST_DISACKNOWLEDGEMENT)) {
return $this->view(null, Response::HTTP_UNAUTHORIZED);
}
$this->acknowledgementService
->filterByContact($contact)
->disacknowledgeHost($hostId);
return $this->view();
}
/**
* Entry point to remove a service acknowledgement.
*
* @param int $hostId Host id linked to service
* @param int $serviceId Service Id for which we want to cancel the acknowledgement
*
* @throws \Exception
*
* @return View
*/
public function disacknowledgeService(int $hostId, int $serviceId): View
{
$this->denyAccessUnlessGrantedForApiRealtime();
/**
* @var Contact $contact
*/
$contact = $this->getUser();
if (! $contact->isAdmin() && ! $contact->hasRole(Contact::ROLE_SERVICE_DISACKNOWLEDGEMENT)) {
return $this->view(null, Response::HTTP_UNAUTHORIZED);
}
$this->acknowledgementService
->filterByContact($contact)
->disacknowledgeService($hostId, $serviceId);
return $this->view();
}
/**
* Entry point to remove a metaservice acknowledgement.
*
* @param int $metaId ID of the metaservice
*
* @throws \Exception
*
* @return View
*/
public function disacknowledgeMetaService(int $metaId): View
{
$this->denyAccessUnlessGrantedForApiRealtime();
/**
* @var Contact $contact
*/
$contact = $this->getUser();
if (! $contact->isAdmin() && ! $contact->hasRole(Contact::ROLE_SERVICE_DISACKNOWLEDGEMENT)) {
return $this->view(null, Response::HTTP_UNAUTHORIZED);
}
$this->acknowledgementService
->filterByContact($contact)
->disacknowledgeMetaService($metaId);
return $this->view();
}
/**
* Entry point to find one acknowledgement.
*
* @param int $acknowledgementId Acknowledgement id to find
*
* @throws \Exception
*
* @return View
*/
public function findOneAcknowledgement(int $acknowledgementId): View
{
$this->denyAccessUnlessGrantedForApiRealtime();
$acknowledgement = $this->acknowledgementService
->filterByContact($this->getUser())
->findOneAcknowledgement($acknowledgementId);
if ($acknowledgement !== null) {
$context = (new Context())
->setGroups(Acknowledgement::SERIALIZER_GROUPS_SERVICE)
->enableMaxDepth();
return $this->view($acknowledgement)->setContext($context);
}
return View::create(null, Response::HTTP_NOT_FOUND, []);
}
/**
* Entry point to find all acknowledgements.
*
* @param RequestParametersInterface $requestParameters
*
* @throws \Exception
*
* @return View
*/
public function findAcknowledgements(RequestParametersInterface $requestParameters): View
{
$this->denyAccessUnlessGrantedForApiRealtime();
/** @var Contact $user */
$user = $this->getUser();
if ($user->isAdmin() === false) {
$accessGroups = $this->readAccessGroupRepository->findByContact($user);
$accessGroupIds = array_map(
fn ($accessGroup) => $accessGroup->getId(),
$accessGroups
);
if ($this->readAccessGroupRepository->hasAccessToResources($accessGroupIds) === false) {
return $this->view(null, Response::HTTP_FORBIDDEN);
}
}
$acknowledgements = $this->acknowledgementService
->filterByContact($this->getUser())
->findAcknowledgements();
$context = (new Context())->setGroups(Acknowledgement::SERIALIZER_GROUPS_SERVICE);
return $this->view(
[
'result' => $acknowledgements,
'meta' => $requestParameters->toArray(),
]
)->setContext($context);
}
/**
* Entry point to bulk disacknowledge resources (hosts and services).
*
* @param Request $request
*
* @return View
*/
public function massDisacknowledgeResources(Request $request): View
{
$this->denyAccessUnlessGrantedForApiRealtime();
/** @var Contact $contact */
$contact = $this->getUser();
if ($contact->isAdmin() === false) {
$accessGroups = $this->readAccessGroupRepository->findByContact($contact);
$accessGroupIds = array_map(
fn ($accessGroup) => $accessGroup->getId(),
$accessGroups
);
if ($this->readAccessGroupRepository->hasAccessToResources($accessGroupIds) === false) {
return $this->view(null, Response::HTTP_FORBIDDEN);
}
}
/**
* Validate POST data for disacknowledge resources.
*/
$payload = $this->validateAndRetrieveDataSent($request, self::DISACKNOWLEDGE_RESOURCES_PAYLOAD_VALIDATION_FILE);
$this->acknowledgementService->filterByContact($contact);
$disacknowledgement = $this->createDisacknowledgementFromPayload($payload);
foreach ($payload['resources'] as $resourcePayload) {
$resource = $this->createResourceFromPayload($resourcePayload);
// start disacknowledgement process
try {
if ($this->hasDisackRightsForResource($contact, $resource)) {
if (! $contact->isAdmin() && ! $contact->hasRole(Contact::ROLE_SERVICE_DISACKNOWLEDGEMENT)) {
$disacknowledgement->setWithServices(false);
}
$this->acknowledgementService->disacknowledgeResource(
$resource,
$disacknowledgement
);
}
} catch (EntityNotFoundException $e) {
// don't stop process if a resource is not found
continue;
}
}
return $this->view(null, Response::HTTP_NO_CONTENT);
}
/**
* Entry point to bulk acknowledge resources (hosts and services).
*
* @param Request $request
*
* @throws \Exception
*
* @return View
*/
public function massAcknowledgeResources(Request $request): View
{
$this->denyAccessUnlessGrantedForApiRealtime();
/** @var Contact $contact */
$contact = $this->getUser();
if ($contact->isAdmin() === false) {
$accessGroups = $this->readAccessGroupRepository->findByContact($contact);
$accessGroupIds = array_map(
fn ($accessGroup) => $accessGroup->getId(),
$accessGroups
);
if ($this->readAccessGroupRepository->hasAccessToResources($accessGroupIds) === false) {
return $this->view(null, Response::HTTP_FORBIDDEN);
}
}
/**
* Validate POST data for acknowledge resources.
*/
$payload = $this->validateAndRetrieveDataSent($request, self::ACKNOWLEDGE_RESOURCES_PAYLOAD_VALIDATION_FILE);
$acknowledgement = $this->createAcknowledgementFromPayload($payload);
$this->acknowledgementService->filterByContact($contact);
foreach ($payload['resources'] as $resourcePayload) {
$resource = $this->createResourceFromPayload($resourcePayload);
// start acknowledgement process
try {
if ($this->hasAckRightsForResource($contact, $resource)) {
if (! $contact->isAdmin() && ! $contact->hasRole(Contact::ROLE_SERVICE_ACKNOWLEDGEMENT)) {
$acknowledgement->setWithServices(false);
}
$this->acknowledgementService->acknowledgeResource(
$resource,
$acknowledgement
);
}
} catch (\Exception $e) {
continue;
}
}
return $this->view(null, Response::HTTP_NO_CONTENT);
}
/**
* Creates a ResourceEntity with payload sent.
*
* @param array<string, mixed> $payload
*
* @return ResourceEntity
*/
private function createResourceFromPayload(array $payload): ResourceEntity
{
$resource = (new ResourceEntity())
->setType($payload['type'])
->setId($payload['id']);
if ($payload['parent'] !== null) {
$resource->setParent(
(new ResourceEntity())
->setId($payload['parent']['id'])
->setType(ResourceEntity::TYPE_HOST)
);
}
return $resource;
}
/**
* @param array<string, mixed> $payload
*
* @return Acknowledgement
*/
private function createAcknowledgementFromPayload(array $payload): Acknowledgement
{
$acknowledgement = new Acknowledgement();
if (isset($payload['acknowledgement']['comment'])) {
$acknowledgement->setComment($payload['acknowledgement']['comment']);
}
$options = $this->optionService->findSelectedOptions([
self::DEFAULT_ACKNOWLEDGEMENT_PERSISTENT,
self::DEFAULT_ACKNOWLEDGEMENT_STICKY,
self::DEFAULT_ACKNOWLEDGEMENT_NOTIFY,
self::DEFAULT_ACKNOWLEDGEMENT_WITH_SERVICES,
self::DEFAULT_ACKNOWLEDGEMENT_FORCE_ACTIVE_CHECKS,
]);
$isAcknowledgementPersistent = $acknowledgement->isPersistentComment();
$isAcknowledgementSticky = $acknowledgement->isSticky();
$isAcknowledgementNotify = $acknowledgement->isNotifyContacts();
$isAcknowledgementWithServices = $acknowledgement->isWithServices();
$isAcknowledgementForceActiveChecks = $acknowledgement->doesForceActiveChecks();
foreach ($options as $option) {
switch ($option->getName()) {
case self::DEFAULT_ACKNOWLEDGEMENT_PERSISTENT:
$isAcknowledgementPersistent = (int) $option->getValue() === 1;
break;
case self::DEFAULT_ACKNOWLEDGEMENT_STICKY:
$isAcknowledgementSticky = (int) $option->getValue() === 1;
break;
case self::DEFAULT_ACKNOWLEDGEMENT_NOTIFY:
$isAcknowledgementNotify = (int) $option->getValue() === 1;
break;
case self::DEFAULT_ACKNOWLEDGEMENT_WITH_SERVICES:
$isAcknowledgementWithServices = (int) $option->getValue() === 1;
break;
case self::DEFAULT_ACKNOWLEDGEMENT_FORCE_ACTIVE_CHECKS:
$isAcknowledgementForceActiveChecks = (int) $option->getValue() === 1;
break;
default:
break;
}
}
isset($payload['acknowledgement']['with_services'])
? $acknowledgement->setWithServices($payload['acknowledgement']['with_services'])
: $acknowledgement->setWithServices($isAcknowledgementWithServices);
isset($payload['acknowledgement']['force_active_checks'])
? $acknowledgement->setForceActiveChecks($payload['acknowledgement']['force_active_checks'])
: $acknowledgement->setForceActiveChecks($isAcknowledgementForceActiveChecks);
isset($payload['acknowledgement']['is_notify_contacts'])
? $acknowledgement->setNotifyContacts($payload['acknowledgement']['is_notify_contacts'])
: $acknowledgement->setNotifyContacts($isAcknowledgementNotify);
isset($payload['acknowledgement']['is_persistent_comment'])
? $acknowledgement->setPersistentComment($payload['acknowledgement']['is_persistent_comment'])
: $acknowledgement->setPersistentComment($isAcknowledgementPersistent);
isset($payload['acknowledgement']['is_sticky'])
? $acknowledgement->setSticky($payload['acknowledgement']['is_sticky'])
: $acknowledgement->setSticky($isAcknowledgementSticky);
return $acknowledgement;
}
/**
* @param array<string, mixed> $payload
*
* @return Acknowledgement
*/
private function createDisacknowledgementFromPayload(array $payload): Acknowledgement
{
$disacknowledgement = new Acknowledgement();
if (isset($payload['disacknowledgement']['with_services'])) {
$disacknowledgement->setWithServices($payload['disacknowledgement']['with_services']);
}
return $disacknowledgement;
}
/**
* Check if the resource can be acknowledged.
*
* @param Contact $contact
* @param ResourceEntity $resource
*
* @return bool
*/
private function hasAckRightsForResource(Contact $contact, ResourceEntity $resource): bool
{
if ($contact->isAdmin()) {
return true;
}
$hasRights = false;
switch ($resource->getType()) {
case ResourceEntity::TYPE_HOST:
$hasRights = $contact->hasRole(Contact::ROLE_HOST_ACKNOWLEDGEMENT);
break;
case ResourceEntity::TYPE_SERVICE:
case ResourceEntity::TYPE_META:
$hasRights = $contact->hasRole(Contact::ROLE_SERVICE_ACKNOWLEDGEMENT);
break;
}
return $hasRights;
}
/**
* Check if the resource can be disacknowledged.
*
* @param Contact $contact
* @param ResourceEntity $resource
*
* @return bool
*/
private function hasDisackRightsForResource(Contact $contact, ResourceEntity $resource): bool
{
if ($contact->isAdmin()) {
return true;
}
$hasRights = false;
switch ($resource->getType()) {
case ResourceEntity::TYPE_HOST:
$hasRights = $contact->hasRole(Contact::ROLE_HOST_DISACKNOWLEDGEMENT);
break;
case ResourceEntity::TYPE_SERVICE:
case ResourceEntity::TYPE_META:
$hasRights = $contact->hasRole(Contact::ROLE_SERVICE_DISACKNOWLEDGEMENT);
break;
}
return $hasRights;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Application/Controller/MetaServiceConfigurationController.php | centreon/src/Centreon/Application/Controller/MetaServiceConfigurationController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Centreon\Application\Controller;
use Centreon\Domain\MetaServiceConfiguration\Exception\MetaServiceConfigurationException;
use Centreon\Domain\MetaServiceConfiguration\UseCase\V2110\FindMetaServicesConfigurations;
use Centreon\Domain\MetaServiceConfiguration\UseCase\V2110\FindOneMetaServiceConfiguration;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Centreon\Infrastructure\MetaServiceConfiguration\API\Model\MetaServiceConfigurationV2110Factory;
use FOS\RestBundle\View\View;
/**
* This class is designed to provide APIs for the context of meta service configuration.
*
* @package Centreon\Application\Controller
*/
class MetaServiceConfigurationController extends AbstractController
{
/**
* @param RequestParametersInterface $requestParameters
* @param FindOneMetaServiceConfiguration $findMetaServiceConfiguration
* @param int $metaId
* @throws MetaServiceConfigurationException
* @return View
*/
public function findOneMetaServiceConfiguration(
RequestParametersInterface $requestParameters,
FindOneMetaServiceConfiguration $findMetaServiceConfiguration,
int $metaId,
): View {
$this->denyAccessUnlessGrantedForApiConfiguration();
$response = $findMetaServiceConfiguration->execute($metaId);
return $this->view(
[
'result' => MetaServiceConfigurationV2110Factory::createOneFromResponse($response),
'meta' => $requestParameters->toArray(),
]
);
}
/**
* @param RequestParametersInterface $requestParameters
* @param FindMetaServicesConfigurations $findMetasServicesConfigurations
* @throws MetaServiceConfigurationException
* @return View
*/
public function findMetaServicesConfigurations(
RequestParametersInterface $requestParameters,
FindMetaServicesConfigurations $findMetasServicesConfigurations,
): View {
$this->denyAccessUnlessGrantedForApiConfiguration();
$response = $findMetasServicesConfigurations->execute();
return $this->view(
[
'result' => MetaServiceConfigurationV2110Factory::createAllFromResponse($response),
'meta' => $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/Centreon/Application/Controller/AuthenticationController.php | centreon/src/Centreon/Application/Controller/AuthenticationController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Centreon\Application\Controller;
use Centreon\Domain\Authentication\UseCase\AuthenticateApi;
use Centreon\Domain\Authentication\UseCase\AuthenticateApiRequest;
use Centreon\Domain\Authentication\UseCase\AuthenticateApiResponse;
use Centreon\Domain\Authentication\UseCase\Logout;
use Centreon\Domain\Authentication\UseCase\LogoutRequest;
use Core\Security\Authentication\Domain\Exception\AuthenticationException;
use FOS\RestBundle\View\View;
use Security\Infrastructure\Authentication\API\Model_2110\ApiAuthenticationFactory;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* @package Centreon\Application\Controller
*/
class AuthenticationController extends AbstractController
{
private const INVALID_CREDENTIALS_MESSAGE = 'Authentication failed';
/**
* Entry point used to identify yourself and retrieve an authentication token.
* (If view_response_listener = true, we need to write the following
* annotation Rest\View(populateDefaultVars=false), otherwise it's not
* necessary).
*
* @param Request $request
* @param AuthenticateApi $authenticate
* @param AuthenticateApiResponse $response
* @return View
*/
public function login(Request $request, AuthenticateApi $authenticate, AuthenticateApiResponse $response): View
{
$contentBody = json_decode((string) $request->getContent(), true);
$login = $contentBody['security']['credentials']['login'] ?? '';
$password = $contentBody['security']['credentials']['password'] ?? '';
$request = new AuthenticateApiRequest($login, $password);
try {
$authenticate->execute($request, $response);
} catch (AuthenticationException $e) {
return $this->view(
[
'code' => Response::HTTP_UNAUTHORIZED,
'message' => _(self::INVALID_CREDENTIALS_MESSAGE),
],
Response::HTTP_UNAUTHORIZED
);
}
return $this->view(ApiAuthenticationFactory::createFromResponse($response));
}
/**
* Entry point used to delete an existing authentication token.
*
* @param Request $request
* @param Logout $logout
* @throws \RestException
* @return View
*/
public function logout(Request $request, Logout $logout): View
{
$token = $request->headers->get('X-AUTH-TOKEN');
if ($token === null) {
return $this->view([
'code' => Response::HTTP_UNAUTHORIZED,
'message' => _(self::INVALID_CREDENTIALS_MESSAGE),
], Response::HTTP_UNAUTHORIZED);
}
$request = new LogoutRequest($token);
$logout->execute($request);
return $this->view([
'message' => 'Successful logout',
]);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Application/Controller/PlatformTopologyController.php | centreon/src/Centreon/Application/Controller/PlatformTopologyController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Centreon\Application\Controller;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Exception\EntityNotFoundException;
use Centreon\Domain\PlatformTopology\Exception\PlatformTopologyException;
use Centreon\Domain\PlatformTopology\Interfaces\PlatformTopologyServiceInterface;
use Centreon\Domain\PlatformTopology\Model\PlatformPending;
use Centreon\Infrastructure\PlatformTopology\Repository\Model\PlatformJsonGraph;
use FOS\RestBundle\Context\Context;
use FOS\RestBundle\View\View;
use JsonSchema\Constraints\Constraint;
use JsonSchema\Validator;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* This controller is designed to manage platform topology API requests and register new servers.
*
* @package Centreon\Application\Controller
*/
class PlatformTopologyController extends AbstractController
{
public const SERIALIZER_GROUP_JSON_GRAPH = ['platform_topology_json_graph'];
/** @var PlatformTopologyServiceInterface */
private $platformTopologyService;
/**
* PlatformTopologyController constructor.
*
* @param PlatformTopologyServiceInterface $platformTopologyService
*/
public function __construct(
PlatformTopologyServiceInterface $platformTopologyService,
) {
$this->platformTopologyService = $platformTopologyService;
}
/**
* Entry point to register a new server.
*
* @param Request $request
*
* @throws PlatformTopologyException
*
* @return View
*/
public function addPlatformToTopology(Request $request): View
{
// check user rights
$this->denyAccessUnlessGrantedForApiConfiguration();
/** @var Contact $contact */
$contact = $this->getUser();
// Check Topology access to Configuration > Pollers page
if (
! $contact->isAdmin()
&& ! (
$contact->hasTopologyRole(Contact::ROLE_CONFIGURATION_MONITORING_SERVER_READ_WRITE)
&& $contact->hasRole(Contact::ROLE_CREATE_EDIT_POLLER_CFG)
)
) {
return $this->view(null, Response::HTTP_FORBIDDEN);
}
// get http request content
$platformToAdd = json_decode((string) $request->getContent(), true);
if (! is_array($platformToAdd)) {
throw new PlatformTopologyException(
_('Error when decoding sent data'),
Response::HTTP_BAD_REQUEST
);
}
/**
* @var string $centreonPath
*/
$centreonPath = $this->getParameter('centreon_path');
// validate request payload consistency
$this->validatePlatformTopologySchema(
$platformToAdd,
$centreonPath . 'config/json_validator/latest/Centreon/PlatformTopology/Register.json'
);
try {
$platformTopology = (new PlatformPending())
->setName($platformToAdd['name'])
->setAddress($platformToAdd['address'])
->setType($platformToAdd['type'])
->setParentAddress($platformToAdd['parent_address']);
if (isset($platformToAdd['hostname'])) {
$platformTopology->setHostname($platformToAdd['hostname']);
}
$this->platformTopologyService->addPendingPlatformToTopology($platformTopology);
return $this->view(null, Response::HTTP_CREATED);
} catch (EntityNotFoundException $ex) {
return $this->view(['message' => $ex->getMessage()], Response::HTTP_NOT_FOUND);
} catch (\Throwable $ex) {
return $this->view(['message' => $ex->getMessage()], Response::HTTP_BAD_REQUEST);
}
}
/**
* Get the Topology of a platform with an adapted Json Graph Format.
*
* @throws PlatformTopologyException
*
* @return View
*/
public function getPlatformJsonGraph(): View
{
$this->denyAccessUnlessGrantedForApiConfiguration();
// Check Topology access to Configuration > Pollers page
/** @var Contact $user */
$user = $this->getUser();
if (
! $user->hasTopologyRole(Contact::ROLE_CONFIGURATION_MONITORING_SERVER_READ)
&& ! $user->hasTopologyRole(Contact::ROLE_CONFIGURATION_MONITORING_SERVER_READ_WRITE)
) {
return $this->view(null, Response::HTTP_FORBIDDEN);
}
try {
if ($user->isAdmin()) {
$platformTopology = $this->platformTopologyService->getPlatformTopology();
} else {
$platformTopology = $this->platformTopologyService->getPlatformTopologyForUser($user);
}
$edges = [];
$nodes = [];
// Format the PlatformTopology into a Json Graph Format
foreach ($platformTopology as $platform) {
$topologyJsonGraph = new PlatformJsonGraph($platform);
if (! empty($topologyJsonGraph->getRelation())) {
$edges[] = $topologyJsonGraph->getRelation();
}
$nodes[$topologyJsonGraph->getId()] = $topologyJsonGraph;
}
$context = (new Context())->setGroups(self::SERIALIZER_GROUP_JSON_GRAPH);
return $this->view(
[
'graph' => [
'label' => 'centreon-topology',
'metadata' => [
'version' => '1.0.0',
],
'nodes' => $nodes,
'edges' => $edges,
],
],
Response::HTTP_OK
)->setContext($context);
} catch (EntityNotFoundException $e) {
return $this->view(['message' => $e->getMessage()], Response::HTTP_NOT_FOUND);
}
}
/**
* Delete a platform from the topology.
*
* @param int $platformId
*
* @return View
*/
public function deletePlatform(int $platformId): View
{
$this->denyAccessUnlessGrantedForApiConfiguration();
// Check Topology access to Configuration > Pollers page
/** @var Contact $contact */
$contact = $this->getUser();
if (
! $this->platformTopologyService->isValidPlatform($contact, $platformId)
|| ! (
$contact->isAdmin()
|| (
$contact->hasTopologyRole(Contact::ROLE_CONFIGURATION_MONITORING_SERVER_READ_WRITE)
&& $contact->hasRole(Contact::ROLE_DELETE_POLLER_CFG)
)
)
) {
return $this->view(null, Response::HTTP_FORBIDDEN);
}
try {
$this->platformTopologyService->deletePlatformAndReallocateChildren($platformId);
return $this->view(null, Response::HTTP_NO_CONTENT);
} catch (EntityNotFoundException $ex) {
return $this->view(['message' => $ex->getMessage()], Response::HTTP_NOT_FOUND);
} catch (\Exception $ex) {
return $this->view(['message' => $ex->getMessage()], Response::HTTP_BAD_REQUEST);
}
}
/**
* Validate platform topology data according to json schema
*
* @param array<mixed> $platformToAdd data sent in json
* @param string $schemaPath
*
* @throws PlatformTopologyException
*/
private function validatePlatformTopologySchema(array $platformToAdd, string $schemaPath): void
{
$platformTopologySchemaToValidate = Validator::arrayToObjectRecursive($platformToAdd);
$validator = new Validator();
$validator->validate(
$platformTopologySchemaToValidate,
(object) ['$ref' => 'file://' . $schemaPath],
Constraint::CHECK_MODE_VALIDATE_SCHEMA
);
if (! $validator->isValid()) {
$message = '';
foreach ($validator->getErrors() as $error) {
$message .= sprintf("[%s] %s\n", $error['property'], $error['message']);
}
throw new PlatformTopologyException($message);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Application/Controller/DowntimeController.php | centreon/src/Centreon/Application/Controller/DowntimeController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Centreon\Application\Controller;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Downtime\Downtime;
use Centreon\Domain\Downtime\Interfaces\DowntimeServiceInterface;
use Centreon\Domain\Exception\EntityNotFoundException;
use Centreon\Domain\Monitoring\Interfaces\MonitoringServiceInterface;
use Centreon\Domain\Monitoring\Resource as ResourceEntity;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use FOS\RestBundle\Context\Context;
use FOS\RestBundle\View\View;
use JMS\Serializer\SerializerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* This class is design to manage all API REST about downtime requests.
*/
class DowntimeController extends AbstractController
{
// Groups for serialization
public const SERIALIZER_GROUPS_HOST = ['downtime_host'];
public const SERIALIZER_GROUPS_SERVICE = ['downtime_service'];
private const VALIDATION_SCHEME_FOR_A_DOWNTIME
= __DIR__ . '/../../../../config/json_validator/latest/Centreon/Downtime/Downtime.json';
private const VALIDATION_SCHEME_FOR_SEVERAL_DOWNTIMES
= __DIR__ . '/../../../../config/json_validator/latest/Centreon/Downtime/Downtimes.json';
private const DOWNTIME_ON_RESOURCES_PAYLOAD_VALIDATION_FILE
= __DIR__ . '/../../../../config/json_validator/latest/Centreon/Downtime/DowntimeResources.json';
/** @var DowntimeServiceInterface */
private DowntimeServiceInterface $downtimeService;
/** @var MonitoringServiceInterface */
private MonitoringServiceInterface $monitoringService;
/**
* DowntimeController constructor.
*
* @param DowntimeServiceInterface $downtimeService
* @param MonitoringServiceInterface $monitoringService
*/
public function __construct(
DowntimeServiceInterface $downtimeService,
MonitoringServiceInterface $monitoringService,
) {
$this->downtimeService = $downtimeService;
$this->monitoringService = $monitoringService;
}
/**
* Entry point to add multiple host downtimes.
*
* @param Request $request
* @param SerializerInterface $serializer
*
* @throws \Exception
*
* @return View
*/
public function addHostDowntimes(Request $request, SerializerInterface $serializer): View
{
$this->denyAccessUnlessGrantedForApiRealtime();
/**
* @var Contact $contact
*/
$contact = $this->getUser();
if (! $contact->isAdmin() && ! $contact->hasRole(Contact::ROLE_ADD_HOST_DOWNTIME)) {
return $this->view(null, Response::HTTP_UNAUTHORIZED);
}
// Validate the content of the request against the JSON schema validator
$this->validateDataSent($request, self::VALIDATION_SCHEME_FOR_SEVERAL_DOWNTIMES);
/**
* @var Downtime[] $downtimes
*/
$downtimes = $serializer->deserialize(
(string) $request->getContent(),
'array<' . Downtime::class . '>',
'json'
);
$this->monitoringService->filterByContact($contact);
$this->downtimeService->filterByContact($contact);
foreach ($downtimes as $downtime) {
try {
$host = $this->monitoringService->findOneHost($downtime->getResourceId());
if ($host === null) {
throw new EntityNotFoundException(
sprintf(_('Host %d not found'), $downtime->getResourceId())
);
}
$this->downtimeService->addHostDowntime($downtime, $host);
} catch (EntityNotFoundException $e) {
continue;
}
}
return $this->view();
}
/**
* Entry point to add multiple service downtimes.
*
* @param Request $request
* @param SerializerInterface $serializer
*
* @throws \Exception
*
* @return View
*/
public function addServiceDowntimes(Request $request, SerializerInterface $serializer): View
{
$this->denyAccessUnlessGrantedForApiRealtime();
/**
* @var Contact $contact
*/
$contact = $this->getUser();
if (! $contact->isAdmin() && ! $contact->hasRole(Contact::ROLE_ADD_SERVICE_DOWNTIME)) {
return $this->view(null, Response::HTTP_UNAUTHORIZED);
}
$this->validateDataSent($request, self::VALIDATION_SCHEME_FOR_SEVERAL_DOWNTIMES);
$this->monitoringService->filterByContact($contact);
$this->downtimeService->filterByContact($contact);
/**
* @var Downtime[] $downtimes
*/
$downtimes = $serializer->deserialize(
(string) $request->getContent(),
'array<' . Downtime::class . '>',
'json'
);
foreach ($downtimes as $downtime) {
try {
$serviceId = $downtime->getResourceId();
$hostId = $downtime->getParentResourceId();
if ($hostId === null) {
throw new \InvalidArgumentException('Parent resource Id can not be null');
}
$service = $this->monitoringService->findOneService($hostId, $serviceId);
if ($service === null) {
throw new EntityNotFoundException(
sprintf(
_('Service %d on host %d not found'),
$downtime->getResourceId(),
$downtime->getParentResourceId()
)
);
}
$host = $this->monitoringService->findOneHost($hostId);
$service->setHost($host);
$this->downtimeService->addServiceDowntime($downtime, $service);
} catch (EntityNotFoundException $e) {
continue;
}
}
return $this->view();
}
/**
* Entry point to add a host downtime.
*
* @param Request $request
* @param SerializerInterface $serializer
* @param int $hostId Host id for which we want to add a downtime
*
* @throws \Exception
*
* @return View
*/
public function addHostDowntime(Request $request, SerializerInterface $serializer, int $hostId): View
{
$this->denyAccessUnlessGrantedForApiRealtime();
/**
* @var Contact $contact
*/
$contact = $this->getUser();
if (! $contact->isAdmin() && ! $contact->hasRole(Contact::ROLE_ADD_HOST_DOWNTIME)) {
return $this->view(null, Response::HTTP_UNAUTHORIZED);
}
// Validate the content of the request against the JSON schema validator
$this->validateDataSent($request, self::VALIDATION_SCHEME_FOR_A_DOWNTIME);
/**
* @var Downtime $downtime
*/
$downtime = $serializer->deserialize(
(string) $request->getContent(),
Downtime::class,
'json'
);
$this->monitoringService->filterByContact($contact);
$host = $this->monitoringService->findOneHost($hostId);
if ($host === null) {
throw new EntityNotFoundException(
sprintf(_('Host %d not found'), $hostId)
);
}
$this->downtimeService->filterByContact($contact);
$this->downtimeService->addHostDowntime($downtime, $host);
return $this->view();
}
/**
* Entry point to add a service downtime.
*
* @param Request $request
* @param SerializerInterface $serializer
* @param int $hostId Host id linked to the service
* @param int $serviceId Service id for which we want to add a downtime
*
* @throws \Exception
*
* @return View
*/
public function addServiceDowntime(
Request $request,
SerializerInterface $serializer,
int $hostId,
int $serviceId,
): View {
$this->denyAccessUnlessGrantedForApiRealtime();
/**
* @var Contact $contact
*/
$contact = $this->getUser();
if (! $contact->isAdmin() && ! $contact->hasRole(Contact::ROLE_ADD_SERVICE_DOWNTIME)) {
return $this->view(null, Response::HTTP_UNAUTHORIZED);
}
// Validate the content of the request against the JSON schema validator
$this->validateDataSent($request, self::VALIDATION_SCHEME_FOR_A_DOWNTIME);
/**
* @var Downtime $downtime
*/
$downtime = $serializer->deserialize((string) $request->getContent(), Downtime::class, 'json');
$this->monitoringService->filterByContact($contact);
$service = $this->monitoringService->findOneService($hostId, $serviceId);
if ($service === null) {
throw new EntityNotFoundException(
sprintf(_('Service %d on host %d not found'), $serviceId, $hostId)
);
}
$host = $this->monitoringService->findOneHost($hostId);
$service->setHost($host);
$this->downtimeService
->filterByContact($contact)
->addServiceDowntime($downtime, $service);
return $this->view();
}
/**
* Entry point to add a service downtime.
*
* @param Request $request
* @param SerializerInterface $serializer
* @param int $metaId ID of the Meta Service
*
* @throws \Exception
*
* @return View
*/
public function addMetaServiceDowntime(Request $request, SerializerInterface $serializer, int $metaId): View
{
$this->denyAccessUnlessGrantedForApiRealtime();
/**
* @var Contact $contact
*/
$contact = $this->getUser();
if (! $contact->isAdmin() && ! $contact->hasRole(Contact::ROLE_ADD_SERVICE_DOWNTIME)) {
return $this->view(null, Response::HTTP_UNAUTHORIZED);
}
$this->validateDataSent($request, self::VALIDATION_SCHEME_FOR_A_DOWNTIME);
/**
* @var Downtime $downtime
*/
$downtime = $serializer->deserialize(
(string) $request->getContent(),
Downtime::class,
'json'
);
$this->monitoringService->filterByContact($contact);
$service = $this->monitoringService->findOneServiceByDescription('meta_' . $metaId);
if (is_null($service)) {
throw new EntityNotFoundException(
sprintf(_('Meta Service linked to service %d not found'), $metaId)
);
}
$hostId = $service->getHost()?->getId();
if ($hostId === null) {
throw new EntityNotFoundException(
sprintf(_('Host meta for meta %d not found'), $metaId)
);
}
$host = $this->monitoringService->findOneHost($hostId);
if ($host === null) {
throw new EntityNotFoundException(
sprintf(_('Host meta for meta %d not found'), $metaId)
);
}
$service->setHost($host);
$this->downtimeService
->filterByContact($contact)
->addServiceDowntime($downtime, $service);
return $this->view();
}
/**
* Entry point to find the last hosts downtimes.
*
* @param RequestParametersInterface $requestParameters
*
* @throws \Exception
*
* @return View
*/
public function findHostDowntimes(RequestParametersInterface $requestParameters): View
{
$this->denyAccessUnlessGrantedForApiRealtime();
/**
* @var Contact $contact
*/
$contact = $this->getUser();
$hostsDowntime = $this->downtimeService
->filterByContact($contact)
->findHostDowntimes();
$context = (new Context())->setGroups(Downtime::SERIALIZER_GROUPS_MAIN);
return $this->view(
[
'result' => $hostsDowntime,
'meta' => $requestParameters->toArray(),
]
)->setContext($context);
}
/**
* Entry point to find the last services downtimes.
*
* @param RequestParametersInterface $requestParameters
*
* @throws \Exception
*
* @return View
*/
public function findServiceDowntimes(RequestParametersInterface $requestParameters): View
{
$this->denyAccessUnlessGrantedForApiRealtime();
/**
* @var Contact $contact
*/
$contact = $this->getUser();
$servicesDowntimes = $this->downtimeService
->filterByContact($contact)
->findServicesDowntimes();
$context = (new Context())->setGroups(Downtime::SERIALIZER_GROUPS_SERVICE);
return $this->view(
[
'result' => $servicesDowntimes,
'meta' => $requestParameters->toArray(),
]
)->setContext($context);
}
/**
* Entry point to find the last downtimes linked to a service.
*
* @param RequestParametersInterface $requestParameters
* @param int $hostId Host id linked to this service
* @param int $serviceId Service id for which we want to find downtimes
*
* @throws \Exception
*
* @return View
*/
public function findDowntimesByService(
RequestParametersInterface $requestParameters,
int $hostId,
int $serviceId,
): View {
$this->denyAccessUnlessGrantedForApiRealtime();
/**
* @var Contact $contact
*/
$contact = $this->getUser();
$this->monitoringService->filterByContact($contact);
if ($this->monitoringService->isHostExists($hostId)) {
$downtimesByHost = $this->downtimeService
->filterByContact($contact)
->findDowntimesByService($hostId, $serviceId);
$context = (new Context())->setGroups(Downtime::SERIALIZER_GROUPS_SERVICE);
return $this->view(
[
'result' => $downtimesByHost,
'meta' => $requestParameters->toArray(),
]
)->setContext($context);
}
return View::create(null, Response::HTTP_NOT_FOUND, []);
}
/**
* Entry point to find the last downtimes linked to a service.
*
* @param RequestParametersInterface $requestParameters
* @param int $metaId ID of the metaservice
*
* @throws \Exception
*
* @return View
*/
public function findDowntimesByMetaService(RequestParametersInterface $requestParameters, int $metaId): View
{
$this->denyAccessUnlessGrantedForApiRealtime();
/**
* @var Contact $contact
*/
$contact = $this->getUser();
$this->monitoringService->filterByContact($contact);
$downtimesByHost = $this->downtimeService
->filterByContact($contact)
->findDowntimesByMetaService($metaId);
$context = (new Context())->setGroups(Downtime::SERIALIZER_GROUPS_SERVICE);
return $this->view(
[
'result' => $downtimesByHost,
'meta' => $requestParameters->toArray(),
]
)->setContext($context);
}
/**
* Entry point to find one host downtime.
*
* @param int $downtimeId Downtime id to find
*
* @throws \Exception
*
* @return View
*/
public function findOneDowntime(int $downtimeId): View
{
$this->denyAccessUnlessGrantedForApiRealtime();
/**
* @var Contact $contact
*/
$contact = $this->getUser();
$downtime = $this->downtimeService
->filterByContact($contact)
->findOneDowntime($downtimeId);
if ($downtime !== null) {
$context = (new Context())
->setGroups(Downtime::SERIALIZER_GROUPS_SERVICE)
->enableMaxDepth();
return $this->view($downtime)->setContext($context);
}
return View::create(null, Response::HTTP_NOT_FOUND, []);
}
/**
* Entry point to find the last downtimes.
*
* @param RequestParametersInterface $requestParameters
*
* @throws \Exception
*
* @return View
*/
public function findDowntimes(RequestParametersInterface $requestParameters): View
{
$this->denyAccessUnlessGrantedForApiRealtime();
/**
* @var Contact $contact
*/
$contact = $this->getUser();
$hostsDowntime = $this->downtimeService
->filterByContact($contact)
->findDowntimes();
$context = (new Context())->setGroups(Downtime::SERIALIZER_GROUPS_SERVICE);
return $this->view(
[
'result' => $hostsDowntime,
'meta' => $requestParameters->toArray(),
]
)->setContext($context);
}
/**
* Entry point to find the last downtimes linked to a host.
*
* @param RequestParametersInterface $requestParameters
* @param int $hostId Host id for which we want to find downtimes
*
* @throws \Exception
*
* @return View
*/
public function findDowntimesByHost(RequestParametersInterface $requestParameters, int $hostId): View
{
$this->denyAccessUnlessGrantedForApiRealtime();
/**
* @var Contact $contact
*/
$contact = $this->getUser();
$this->monitoringService->filterByContact($contact);
$withServices = $requestParameters->getExtraParameter('with_services') === 'true';
if ($this->monitoringService->isHostExists($hostId)) {
$downtimesByHost = $this->downtimeService
->filterByContact($contact)
->findDowntimesByHost($hostId, $withServices);
$contextGroups = $withServices
? Downtime::SERIALIZER_GROUPS_SERVICE
: Downtime::SERIALIZER_GROUPS_MAIN;
$context = (new Context())->setGroups($contextGroups)->enableMaxDepth();
return $this->view(
[
'result' => $downtimesByHost,
'meta' => $requestParameters->toArray(),
]
)->setContext($context);
}
return View::create(null, Response::HTTP_NOT_FOUND, []);
}
/**
* Entry point to cancel one downtime.
*
* @param int $downtimeId Downtime id to cancel
*
* @throws \Exception
*
* @return View
*/
public function cancelOneDowntime(int $downtimeId): View
{
$this->denyAccessUnlessGrantedForApiRealtime();
/**
* @var Contact $contact
*/
$contact = $this->getUser();
$downtime = $this->downtimeService
->filterByContact($contact)
->findOneDowntime($downtimeId);
if ($downtime === null) {
return View::create(null, Response::HTTP_NOT_FOUND, []);
}
$host = $this->monitoringService
->filterByContact($contact)
->findOneHost($downtime->getHostId());
if ($host === null) {
return View::create(null, Response::HTTP_NOT_FOUND, []);
}
if (! $contact->isAdmin()) {
$isServiceDowntime = $downtime->getServiceId() !== null;
$svcCancel = $contact->hasRole(Contact::ROLE_CANCEL_SERVICE_DOWNTIME);
$hostCancel = $contact->hasRole(Contact::ROLE_CANCEL_HOST_DOWNTIME);
if (($isServiceDowntime && ! $svcCancel) || (! $isServiceDowntime && ! $hostCancel)) {
return $this->view(null, Response::HTTP_UNAUTHORIZED);
}
}
$this->downtimeService->cancelDowntime($downtimeId, $host);
return $this->view();
}
/**
* Entry point to bulk set downtime for resources (hosts and services).
*
* @param Request $request
*
* @throws \Exception
*
* @return View
*/
public function massDowntimeResources(Request $request): View
{
$this->denyAccessUnlessGrantedForApiRealtime();
/**
* @var Contact $contact
*/
$contact = $this->getUser();
/**
* Validate POST data for downtime on resources.
*/
$payload = $this->validateAndRetrieveDataSent($request, self::DOWNTIME_ON_RESOURCES_PAYLOAD_VALIDATION_FILE);
$downtime = $this->createDowntimeFromPayload($payload);
$this->downtimeService->filterByContact($contact);
foreach ($payload['resources'] as $resourcePayload) {
$resource = $this->createResourceFromPayload($resourcePayload);
// start applying downtime process
try {
if ($this->hasDtRightsForResource($contact, $resource)) {
if (! $contact->isAdmin() && ! $contact->hasRole(Contact::ROLE_ADD_SERVICE_DOWNTIME)) {
$downtime->setWithServices(false);
}
$this->downtimeService->addResourceDowntime($resource, $downtime);
}
} catch (\Exception $e) {
throw $e;
}
}
return $this->view();
}
/**
* @param array<string, mixed> $payload
*
* @return Downtime
*/
private function createDowntimeFromPayload(array $payload): Downtime
{
$downtime = new Downtime();
if (isset($payload['downtime']['comment'])) {
$downtime->setComment($payload['downtime']['comment']);
}
if (isset($payload['downtime']['duration'])) {
$downtime->setDuration($payload['downtime']['duration']);
}
if (isset($payload['downtime']['with_services'])) {
$downtime->setWithServices($payload['downtime']['with_services']);
}
if (isset($payload['downtime']['end_time'])) {
$endTime = new \DateTime($payload['downtime']['end_time']);
$downtime->setEndTime($endTime);
}
if (isset($payload['downtime']['start_time'])) {
$startTime = new \DateTime($payload['downtime']['start_time']);
$downtime->setStartTime($startTime);
}
if (isset($payload['downtime']['is_fixed'])) {
$downtime->setFixed($payload['downtime']['is_fixed']);
}
return $downtime;
}
/**
* Creates a ResourceEntity with payload sent.
*
* @param array<string, mixed> $payload
*
* @return ResourceEntity
*/
private function createResourceFromPayload(array $payload): ResourceEntity
{
$resource = (new ResourceEntity())
->setType($payload['type'])
->setId($payload['id']);
if ($payload['parent'] !== null) {
$resource->setParent(
(new ResourceEntity())
->setId($payload['parent']['id'])
->setType(ResourceEntity::TYPE_HOST)
);
}
return $resource;
}
/**
* @param Contact $contact
* @param ResourceEntity $resouce
*
* @return bool
*/
private function hasDtRightsForResource(Contact $contact, ResourceEntity $resouce): bool
{
$hasRights = false;
if ($resouce->getType() === ResourceEntity::TYPE_HOST) {
$hasRights = $contact->isAdmin() || $contact->hasRole(Contact::ROLE_ADD_HOST_DOWNTIME);
} elseif ($resouce->getType() === ResourceEntity::TYPE_SERVICE) {
$hasRights = $contact->isAdmin() || $contact->hasRole(Contact::ROLE_ADD_SERVICE_DOWNTIME);
} elseif ($resouce->getType() === ResourceEntity::TYPE_META) {
$hasRights = $contact->isAdmin() || $contact->hasRole(Contact::ROLE_ADD_SERVICE_DOWNTIME);
}
return $hasRights;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Application/Controller/UserController.php | centreon/src/Centreon/Application/Controller/UserController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Centreon\Application\Controller;
use Centreon\Domain\Contact\Contact;
use FOS\RestBundle\View\View;
/**
* Used to manage allowed actions of the current user
*
* @package Centreon\Application\Controller
*/
class UserController extends AbstractController
{
/**
* Entry point to get acl actions of the current user.
*
* @return View
*/
public function getActionsAuthorization(): View
{
$actions = [
'host' => [
'check' => $this->getAuthorizationForRole(Contact::ROLE_HOST_CHECK),
'forced_check' => $this->getAuthorizationForRole(Contact::ROLE_HOST_FORCED_CHECK),
'acknowledgement' => $this->getAuthorizationForRole(Contact::ROLE_HOST_ACKNOWLEDGEMENT),
'disacknowledgement' => $this->getAuthorizationForRole(Contact::ROLE_HOST_DISACKNOWLEDGEMENT),
'downtime' => $this->getAuthorizationForRole(Contact::ROLE_ADD_HOST_DOWNTIME),
'submit_status' => $this->getAuthorizationForRole(Contact::ROLE_HOST_SUBMIT_RESULT),
'comment' => $this->getAuthorizationForRole(Contact::ROLE_HOST_ADD_COMMENT),
],
'service' => [
'check' => $this->getAuthorizationForRole(Contact::ROLE_SERVICE_CHECK),
'forced_check' => $this->getAuthorizationForRole(Contact::ROLE_SERVICE_FORCED_CHECK),
'acknowledgement' => $this->getAuthorizationForRole(Contact::ROLE_SERVICE_ACKNOWLEDGEMENT),
'disacknowledgement' => $this->getAuthorizationForRole(Contact::ROLE_SERVICE_DISACKNOWLEDGEMENT),
'downtime' => $this->getAuthorizationForRole(Contact::ROLE_ADD_SERVICE_DOWNTIME),
'submit_status' => $this->getAuthorizationForRole(Contact::ROLE_SERVICE_SUBMIT_RESULT),
'comment' => $this->getAuthorizationForRole(Contact::ROLE_SERVICE_ADD_COMMENT),
],
'metaservice' => [
'check' => $this->getAuthorizationForRole(Contact::ROLE_SERVICE_CHECK),
'forced_check' => $this->getAuthorizationForRole(Contact::ROLE_SERVICE_FORCED_CHECK),
'acknowledgement' => $this->getAuthorizationForRole(Contact::ROLE_SERVICE_ACKNOWLEDGEMENT),
'disacknowledgement' => $this->getAuthorizationForRole(Contact::ROLE_SERVICE_DISACKNOWLEDGEMENT),
'downtime' => $this->getAuthorizationForRole(Contact::ROLE_ADD_SERVICE_DOWNTIME),
'submit_status' => $this->getAuthorizationForRole(Contact::ROLE_SERVICE_SUBMIT_RESULT),
'comment' => $this->getAuthorizationForRole(Contact::ROLE_SERVICE_ADD_COMMENT),
],
];
return $this->view($actions);
}
/**
* Get authorization for a specific role of the current user
*
* @param string $role
* @return bool
*/
private function getAuthorizationForRole(string $role): bool
{
/**
* @var Contact|null $contact
*/
$contact = $this->getUser();
if ($contact === null) {
return false;
}
return $contact->isAdmin() || $contact->hasRole($role);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Application/Controller/CheckController.php | centreon/src/Centreon/Application/Controller/CheckController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Centreon\Application\Controller;
use Centreon\Domain\Check\Check;
use Centreon\Domain\Check\CheckException;
use Centreon\Domain\Check\Interfaces\CheckServiceInterface;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Entity\EntityValidator;
use Centreon\Domain\Exception\EntityNotFoundException;
use Centreon\Domain\Monitoring\Resource as ResourceEntity;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use FOS\RestBundle\View\View;
use JMS\Serializer\DeserializationContext;
use JMS\Serializer\Exception\ValidationFailedException;
use JMS\Serializer\SerializerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* Used to manage all requests to schedule checks on hosts and services.
*/
class CheckController extends AbstractController
{
// Groups for serialization
public const CHECK_RESOURCES_PAYLOAD_VALIDATION_FILE
= __DIR__ . '/../../../../config/json_validator/latest/Centreon/Check/AddChecks.json';
public const SERIALIZER_GROUPS_HOST = ['check_host'];
public const SERIALIZER_GROUPS_SERVICE = ['check_service'];
public const SERIALIZER_GROUPS_HOST_ADD = ['check_host', 'check_host_add'];
/**
* CheckController constructor.
*
* @param CheckServiceInterface $checkService
*/
public function __construct(
private CheckServiceInterface $checkService,
private ReadAccessGroupRepositoryInterface $readAccessGroupRepository,
) {
}
/**
* Entry point to check multiple hosts.
*
* @param Request $request
* @param EntityValidator $entityValidator
* @param SerializerInterface $serializer
*
* @throws \Exception
*
* @return View
*/
public function checkHosts(
Request $request,
EntityValidator $entityValidator,
SerializerInterface $serializer,
): View {
$this->denyAccessUnlessGrantedForApiRealtime();
/**
* @var Contact $contact
*/
$contact = $this->getUser();
if (! $contact->isAdmin() && ! $contact->hasRole(Contact::ROLE_HOST_CHECK)) {
return $this->view(null, Response::HTTP_UNAUTHORIZED);
}
$context = DeserializationContext::create()->setGroups(self::SERIALIZER_GROUPS_HOST_ADD);
/**
* @var Check[] $checks
*/
$checks = $serializer->deserialize(
(string) $request->getContent(),
'array<' . Check::class . '>',
'json',
$context
);
$this->checkService->filterByContact($contact);
$checkTime = new \DateTime();
foreach ($checks as $check) {
$check->setCheckTime($checkTime);
$errors = $entityValidator->validate(
$check,
null,
Check::VALIDATION_GROUPS_HOST_CHECK
);
if ($errors->count() > 0) {
throw new ValidationFailedException($errors);
}
try {
$this->checkService->checkHost($check);
} catch (EntityNotFoundException $e) {
continue;
}
}
return $this->view();
}
/**
* Entry point to check multiple services.
*
* @param Request $request
* @param EntityValidator $entityValidator
* @param SerializerInterface $serializer
*
* @throws \Exception
*
* @return View
*/
public function checkServices(
Request $request,
EntityValidator $entityValidator,
SerializerInterface $serializer,
): View {
$this->denyAccessUnlessGrantedForApiRealtime();
/**
* @var Contact $contact
*/
$contact = $this->getUser();
if (! $contact->isAdmin() && ! $contact->hasRole(Contact::ROLE_SERVICE_CHECK)) {
return $this->view(null, Response::HTTP_UNAUTHORIZED);
}
$context = DeserializationContext::create()->setGroups(self::SERIALIZER_GROUPS_SERVICE);
/**
* @var Check[] $checks
*/
$checks = $serializer->deserialize(
(string) $request->getContent(),
'array<' . Check::class . '>',
'json',
$context
);
$this->checkService->filterByContact($contact);
$checkTime = new \DateTime();
foreach ($checks as $check) {
$check->setCheckTime($checkTime);
$errors = $entityValidator->validate(
$check,
null,
Check::VALIDATION_GROUPS_SERVICE_CHECK
);
if ($errors->count() > 0) {
throw new ValidationFailedException($errors);
}
try {
$this->checkService->checkService($check);
} catch (EntityNotFoundException $e) {
continue;
}
}
return $this->view();
}
/**
* Entry point to check a host.
*
* @param Request $request
* @param EntityValidator $entityValidator
* @param SerializerInterface $serializer
* @param int $hostId
*
* @throws \Exception
*
* @return View
*/
public function checkHost(
Request $request,
EntityValidator $entityValidator,
SerializerInterface $serializer,
int $hostId,
): View {
$this->denyAccessUnlessGrantedForApiRealtime();
/**
* @var Contact $contact
*/
$contact = $this->getUser();
if (! $contact->isAdmin() && ! $contact->hasRole(Contact::ROLE_HOST_CHECK)) {
return $this->view(null, Response::HTTP_UNAUTHORIZED);
}
$context = DeserializationContext::create()->setGroups(self::SERIALIZER_GROUPS_HOST_ADD);
/**
* @var Check $check
*/
$check = $serializer->deserialize(
(string) $request->getContent(),
Check::class,
'json',
$context
);
$check
->setResourceId($hostId)
->setCheckTime(new \DateTime());
$errors = $entityValidator->validate(
$check,
null,
Check::VALIDATION_GROUPS_HOST_CHECK
);
if ($errors->count() > 0) {
throw new ValidationFailedException($errors);
}
$this->checkService
->filterByContact($contact)
->checkHost($check);
return $this->view();
}
/**
* Entry point to check a service.
*
* @param Request $request
* @param EntityValidator $entityValidator
* @param SerializerInterface $serializer
* @param int $hostId
* @param int $serviceId
*
* @throws \Exception
*
* @return View
*/
public function checkService(
Request $request,
EntityValidator $entityValidator,
SerializerInterface $serializer,
int $hostId,
int $serviceId,
): View {
$this->denyAccessUnlessGrantedForApiRealtime();
/**
* @var Contact $contact
*/
$contact = $this->getUser();
if (
! $contact->isAdmin()
&& ! $contact->hasRole(Contact::ROLE_SERVICE_CHECK)
) {
return $this->view(null, Response::HTTP_UNAUTHORIZED);
}
$context = DeserializationContext::create()->setGroups(self::SERIALIZER_GROUPS_SERVICE);
/**
* @var Check $check
*/
$check = $serializer->deserialize(
(string) $request->getContent(),
Check::class,
'json',
$context
);
$check
->setParentResourceId($hostId)
->setResourceId($serviceId)
->setCheckTime(new \DateTime());
$errors = $entityValidator->validate(
$check,
null,
Check::VALIDATION_GROUPS_SERVICE_CHECK
);
if ($errors->count() > 0) {
throw new ValidationFailedException($errors);
}
$this->checkService
->filterByContact($contact)
->checkService($check);
return $this->view();
}
/**
* Entry point to check a meta service.
*
* @param Request $request
* @param EntityValidator $entityValidator
* @param SerializerInterface $serializer
* @param int $metaId
*
* @throws \Exception
*
* @return View
*/
public function checkMetaService(
Request $request,
EntityValidator $entityValidator,
SerializerInterface $serializer,
int $metaId,
): View {
$this->denyAccessUnlessGrantedForApiRealtime();
/**
* @var Contact $contact
*/
$contact = $this->getUser();
if (! $contact->isAdmin() && ! $contact->hasRole(Contact::ROLE_SERVICE_CHECK)) {
return $this->view(null, Response::HTTP_UNAUTHORIZED);
}
$context = DeserializationContext::create()->setGroups(self::SERIALIZER_GROUPS_SERVICE);
/**
* @var Check $check
*/
$check = $serializer->deserialize(
(string) $request->getContent(),
Check::class,
'json',
$context
);
$check
->setResourceId($metaId)
->setCheckTime(new \DateTime());
$errors = $entityValidator->validate(
$check,
null,
Check::VALIDATION_GROUPS_META_SERVICE_CHECK
);
if ($errors->count() > 0) {
throw new ValidationFailedException($errors);
}
$this->checkService
->filterByContact($contact)
->checkMetaService($check);
return $this->view();
}
/**
* Entry point to check resources.
*
* @param Request $request
*
* @throws \Exception
* @throws CheckException
*
* @return View
*/
public function checkResources(Request $request): View
{
$this->denyAccessUnlessGrantedForApiRealtime();
/**
* @var Contact $user
*/
$user = $this->getUser();
if ($user->isAdmin() === false) {
$accessGroups = $this->readAccessGroupRepository->findByContact($user);
$accessGroupIds = array_map(
fn ($accessGroup) => $accessGroup->getId(),
$accessGroups
);
if ($this->readAccessGroupRepository->hasAccessToResources($accessGroupIds) === false) {
return $this->view(null, Response::HTTP_FORBIDDEN);
}
}
$payload = $this->validateAndRetrieveDataSent($request, self::CHECK_RESOURCES_PAYLOAD_VALIDATION_FILE);
$check = $this->createCheckFromPayload($payload);
foreach ($payload['resources'] as $resourcePayload) {
$resource = $this->createResourceFromPayload($resourcePayload);
// start check process
try {
if ($this->hasCheckRightsForResource($user, $resource)) {
$this->checkService
->filterByContact($user)
->checkResource($check, $resource);
}
} catch (EntityNotFoundException $e) {
continue;
}
}
return $this->view();
}
/**
* Check if the resource can be checked by the current user.
*
* @param Contact $contact
* @param ResourceEntity $resource
*
* @return bool
*/
private function hasCheckRightsForResource(Contact $contact, ResourceEntity $resource): bool
{
if ($contact->isAdmin()) {
return true;
}
$hasRights = false;
switch ($resource->getType()) {
case ResourceEntity::TYPE_HOST:
$hasRights = $contact->hasRole(Contact::ROLE_HOST_CHECK);
break;
case ResourceEntity::TYPE_SERVICE:
case ResourceEntity::TYPE_META:
$hasRights = $contact->hasRole(Contact::ROLE_SERVICE_CHECK);
break;
}
return $hasRights;
}
/**
* @param array<string, mixed> $payload
*
* @return Check
*/
private function createCheckFromPayload(array $payload): Check
{
$check = new Check();
if (isset($payload['check']['is_forced'])) {
$check->setForced($payload['check']['is_forced']);
}
$check->setCheckTime(new \DateTime());
return $check;
}
/**
* Creates a ResourceEntity with payload sent.
*
* @param array<string, mixed> $payload
*
* @return ResourceEntity
*/
private function createResourceFromPayload(array $payload): ResourceEntity
{
$resource = (new ResourceEntity())
->setType($payload['type'])
->setId($payload['id']);
if ($payload['parent'] !== null) {
$resource->setParent(
(new ResourceEntity())
->setId($payload['parent']['id'])
->setType(ResourceEntity::TYPE_HOST)
);
}
return $resource;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Application/Controller/FilterController.php | centreon/src/Centreon/Application/Controller/FilterController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Centreon\Application\Controller;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Exception\EntityNotFoundException;
use Centreon\Domain\Filter\Filter;
use Centreon\Domain\Filter\FilterCriteria;
use Centreon\Domain\Filter\FilterException;
use Centreon\Domain\Filter\Interfaces\FilterServiceInterface;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use FOS\RestBundle\Context\Context;
use FOS\RestBundle\View\View;
use JsonSchema\Constraints\Constraint;
use JsonSchema\Validator;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* Used to manage filters of the current user
*
* @package Centreon\Application\Controller
*/
class FilterController extends AbstractController
{
public const SERIALIZER_GROUPS_MAIN = ['filter_main'];
/** @var FilterServiceInterface */
private $filterService;
/**
* PollerController constructor.
* @param FilterServiceInterface $filterService
*/
public function __construct(FilterServiceInterface $filterService)
{
$this->filterService = $filterService;
}
/**
* Entry point to save a filter for a user.
*
* @param Request $request
* @param string $pageName
* @throws FilterException
* @return View
*/
public function addFilter(Request $request, string $pageName): View
{
$this->denyAccessUnlessGrantedForApiConfiguration();
$this->validatePageNameOrFail($pageName);
/**
* @var Contact $user
*/
$user = $this->getUser();
$this->userHasAccessToResourceStatusOrFail($user);
$payload = $this->validateAndRetrieveDataSent(
$request,
$this->getParameter('centreon_path') . 'config/json_validator/latest/Centreon/Filter/AddOrUpdate.json'
);
/**
* @var FilterCriteria[] $filterCriterias
*/
$filterCriterias = $this->createFilterCriterias($payload);
$filter = (new Filter())
->setPageName($pageName)
->setUserId($user->getId())
->setName($payload['name'])
->setCriterias($filterCriterias);
$filterId = $this->filterService->addFilter($filter);
$filter = $this->filterService->findFilterByUserId($user->getId(), $pageName, $filterId);
$context = (new Context())->setGroups(self::SERIALIZER_GROUPS_MAIN);
return $this->view($filter)->setContext($context);
}
/**
* Entry point to update a filter for a user.
*
* @param Request $request
* @param string $pageName
* @param int $filterId
* @throws EntityNotFoundException
* @throws FilterException
* @return View
*/
public function updateFilter(
Request $request,
string $pageName,
int $filterId,
): View {
$this->denyAccessUnlessGrantedForApiConfiguration();
$this->validatePageNameOrFail($pageName);
/**
* @var Contact $user
*/
$user = $this->getUser();
$this->userHasAccessToResourceStatusOrFail($user);
$this->filterService->filterByContact($user);
$payload = $this->validateAndRetrieveDataSent(
$request,
$this->getParameter('centreon_path') . 'config/json_validator/latest/Centreon/Filter/AddOrUpdate.json'
);
/**
* @var FilterCriteria[] $filterCriterias
*/
$filterCriterias = $this->createFilterCriterias($payload);
$filter = $this->filterService->findFilterByUserId($user->getId(), $pageName, $filterId);
if ($filter === null) {
throw new EntityNotFoundException(
sprintf(_('Filter id %d not found'), $filterId)
);
}
$filter
->setName($payload['name'])
->setCriterias($filterCriterias)
->setOrder($filter->getOrder());
$this->filterService->updateFilter($filter);
$filter = $this->filterService->findFilterByUserId($user->getId(), $pageName, $filterId);
$context = (new Context())->setGroups(self::SERIALIZER_GROUPS_MAIN);
return $this->view($filter)->setContext($context);
}
/**
* Entry point to patch a filter for a user.
*
* @param Request $request
* @param string $pageName
* @param int $filterId
* @throws EntityNotFoundException
* @throws FilterException
* @return View
*/
public function patchFilter(Request $request, string $pageName, int $filterId): View
{
$this->denyAccessUnlessGrantedForApiConfiguration();
$this->validatePageNameOrFail($pageName);
/**
* @var Contact $user
*/
$user = $this->getUser();
$this->userHasAccessToResourceStatusOrFail($user);
$this->filterService->filterByContact($user);
$propertyToPatch = json_decode((string) $request->getContent(), true);
if (! is_array($propertyToPatch)) {
throw new FilterException(_('Error when decoding sent data'));
}
$this->validateFilterSchema(
$propertyToPatch,
$this->getParameter('centreon_path') . 'config/json_validator/latest/Centreon/Filter/Patch.json'
);
$filter = $this->filterService->findFilterByUserId($user->getId(), $pageName, $filterId);
if ($filter === null) {
throw new EntityNotFoundException(
sprintf(_('Filter id %d not found'), $filterId)
);
}
$filter->setOrder($propertyToPatch['order']);
$this->filterService->updateFilter($filter);
$filter = $this->filterService->findFilterByUserId($user->getId(), $pageName, $filterId);
$context = (new Context())->setGroups(self::SERIALIZER_GROUPS_MAIN);
return $this->view($filter)->setContext($context);
}
/**
* Entry point to delete a filter for a user.
*
* @param string $pageName
* @param int $filterId
* @throws EntityNotFoundException
* @return View
*/
public function deleteFilter(string $pageName, int $filterId): View
{
$this->denyAccessUnlessGrantedForApiConfiguration();
$this->validatePageNameOrFail($pageName);
/**
* @var Contact $user
*/
$user = $this->getUser();
$this->userHasAccessToResourceStatusOrFail($user);
$filter = $this->filterService->findFilterByUserId($user->getId(), $pageName, $filterId);
if ($filter === null) {
throw new EntityNotFoundException(
sprintf(_('Filter id %d not found'), $filterId)
);
}
$this->filterService->deleteFilter($filter);
return View::create(null, Response::HTTP_NO_CONTENT, []);
}
/**
* Entry point to get filters saved by the user.
*
* @param RequestParametersInterface $requestParameters
* @param string $pageName
* @return View
*/
public function getFilters(RequestParametersInterface $requestParameters, string $pageName): View
{
$this->denyAccessUnlessGrantedForApiConfiguration();
$this->validatePageNameOrFail($pageName);
/**
* @var Contact $user
*/
$user = $this->getUser();
$this->userHasAccessToResourceStatusOrFail($user);
$filters = $this->filterService->findFiltersByUserId($user->getId(), $pageName);
$context = (new Context())->setGroups(self::SERIALIZER_GROUPS_MAIN);
return $this->view([
'result' => $filters,
'meta' => $requestParameters->toArray(),
])->setContext($context);
}
/**
* Entry point to get filter details by id.
*
* @param string $pageName
* @param int $filterId
* @throws EntityNotFoundException
* @return View
*/
public function getFilter(string $pageName, int $filterId): View
{
$this->denyAccessUnlessGrantedForApiConfiguration();
$this->validatePageNameOrFail($pageName);
/**
* @var Contact $user
*/
$user = $this->getUser();
$this->userHasAccessToResourceStatusOrFail($user);
$filter = $this->filterService->findFilterByUserId($user->getId(), $pageName, $filterId);
if ($filter === null) {
throw new EntityNotFoundException(
sprintf(_('Filter id %d not found'), $filterId)
);
}
$context = (new Context())->setGroups(self::SERIALIZER_GROUPS_MAIN);
return $this->view($filter)->setContext($context);
}
/**
* validate filter data according to json schema
*
* @param array<mixed> $filter sent json
* @throws FilterException
* @return void
*/
private function validateFilterSchema(array $filter, string $schemaPath): void
{
$filterToValidate = Validator::arrayToObjectRecursive($filter);
$validator = new Validator();
$validator->validate(
$filterToValidate,
(object) ['$ref' => 'file://' . $schemaPath],
Constraint::CHECK_MODE_VALIDATE_SCHEMA
);
if (! $validator->isValid()) {
$message = '';
foreach ($validator->getErrors() as $error) {
$message .= sprintf("[%s] %s\n", $error['property'], $error['message']);
}
throw new FilterException($message);
}
}
/**
* @param array<mixed> $data
* @return FilterCriteria[]
*/
private function createFilterCriterias(array $data): array
{
$filterCriterias = [];
foreach ($data['criterias'] as $criteria) {
$filterCriterias[] = (new FilterCriteria())
->setName($criteria['name'])
->setType($criteria['type'])
->setValue($criteria['value'])
->setObjectType($criteria['object_type'] ?? null)
->setSearchData($criteria['search_data'] ?? null);
}
return $filterCriterias;
}
/**
* @param string $pageName
*
* @throws \InvalidArgumentException
*/
private function validatePageNameOrFail(string $pageName): void
{
$pageNames = ['events-view'];
if (! in_array($pageName, $pageNames, true)) {
throw new FilterException(
sprintf(_('Invalid page name. Valid page names are: %s'), implode(', ', $pageNames))
);
}
}
/**
* @param Contact $user
*
* @throws \RestForbiddenException
*/
private function userHasAccessToResourceStatusOrFail(Contact $user): void
{
if (! $user->hasTopologyRole(Contact::ROLE_MONITORING_RESOURCES_STATUS_RW)) {
throw new FilterException(_('You are not allowed to access the Resources Status page'), 403);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Application/Controller/AbstractController.php | centreon/src/Centreon/Application/Controller/AbstractController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Centreon\Application\Controller;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\ConflictResponse;
use Core\Application\Common\UseCase\CreatedResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\Application\Common\UseCase\MultiStatusResponse;
use Core\Application\Common\UseCase\NoContentResponse;
use Core\Application\Common\UseCase\NotFoundResponse;
use Core\Application\Common\UseCase\NotModifiedResponse;
use Core\Application\Common\UseCase\PaymentRequiredResponse;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Application\Common\UseCase\UnauthorizedResponse;
use FOS\RestBundle\Controller\AbstractFOSRestController;
use JsonSchema\Constraints\Constraint;
use JsonSchema\Validator;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
/**
* Abstraction over the FOSRestController.
*/
abstract class AbstractController extends AbstractFOSRestController
{
use LoggerTrait;
public const ROLE_API_REALTIME = 'ROLE_API_REALTIME';
public const ROLE_API_REALTIME_EXCEPTION_MESSAGE = 'You are not authorized to access this resource';
public const ROLE_API_CONFIGURATION = 'ROLE_API_CONFIGURATION';
public const ROLE_API_CONFIGURATION_EXCEPTION_MESSAGE = 'You are not authorized to access this resource';
/**
* @param ResponseStatusInterface $response
*
* @return Response
*/
public function createResponse(ResponseStatusInterface $response): Response
{
$statusCode = match(true) {
$response instanceof ConflictResponse => Response::HTTP_CONFLICT,
$response instanceof CreatedResponse => Response::HTTP_CREATED,
$response instanceof ForbiddenResponse => Response::HTTP_FORBIDDEN,
$response instanceof InvalidArgumentResponse => Response::HTTP_BAD_REQUEST,
$response instanceof MultiStatusResponse => Response::HTTP_MULTI_STATUS,
$response instanceof NoContentResponse => Response::HTTP_NO_CONTENT,
$response instanceof NotFoundResponse => Response::HTTP_NOT_FOUND,
$response instanceof NotModifiedResponse => Response::HTTP_NOT_MODIFIED,
$response instanceof PaymentRequiredResponse => Response::HTTP_PAYMENT_REQUIRED,
$response instanceof UnauthorizedResponse => Response::HTTP_UNAUTHORIZED,
default => Response::HTTP_INTERNAL_SERVER_ERROR,
};
return match($statusCode) {
Response::HTTP_CREATED, Response::HTTP_NO_CONTENT, Response::HTTP_NOT_MODIFIED => new JsonResponse(null, $statusCode),
default => new JsonResponse([
'code' => $statusCode,
'message' => $response->getMessage(),
], $statusCode),
};
}
/**
* @throws AccessDeniedException
*/
public function denyAccessUnlessGrantedForApiConfiguration(): void
{
parent::denyAccessUnlessGranted(
static::ROLE_API_CONFIGURATION,
null,
static::ROLE_API_CONFIGURATION_EXCEPTION_MESSAGE
);
}
/**
* @throws AccessDeniedException
*/
public function denyAccessUnlessGrantedForApiRealtime(): void
{
parent::denyAccessUnlessGranted(
static::ROLE_API_REALTIME,
null,
static::ROLE_API_REALTIME_EXCEPTION_MESSAGE
);
}
/**
* Get current base uri.
*
* @return string
*/
protected function getBaseUri(): string
{
$baseUri = '';
if (
isset($_SERVER['REQUEST_URI'])
&& preg_match(
'/^(.+)\/((api|widgets|modules|include|authentication)\/|main(\.get)?\.php).+/',
$_SERVER['REQUEST_URI'],
$matches
)
) {
$baseUri = $matches[1];
}
return $baseUri;
}
/**
* Validate the data sent.
*
* @param Request $request Request sent by client
* @param string $jsonValidationFile Json validation file
*
* @throws \InvalidArgumentException
*/
protected function validateDataSent(Request $request, string $jsonValidationFile): void
{
// We want to enforce the decoding as possible objects.
$receivedData = json_decode((string) $request->getContent(), false);
if (! is_array($receivedData) && ! ($receivedData instanceof \stdClass)) {
throw new \InvalidArgumentException('Error when decoding your sent data');
}
$validator = new Validator();
$validator->validate(
$receivedData,
(object) [
'$ref' => 'file://' . realpath(
$jsonValidationFile
),
],
Constraint::CHECK_MODE_VALIDATE_SCHEMA
);
if (! $validator->isValid()) {
$message = '';
$this->error('Invalid request body');
foreach ($validator->getErrors() as $error) {
$message .= ! empty($error['property'])
? sprintf("[%s] %s\n", $error['property'], $error['message'])
: sprintf("%s\n", $error['message']);
}
throw new \InvalidArgumentException($message);
}
}
/**
* Validate the data sent and retrieve it.
*
* @param Request $request Request sent by client
* @param string $jsonValidationFile Json validation file
*
* @throws \InvalidArgumentException
*
* @return array<string, mixed>
*/
protected function validateAndRetrieveDataSent(Request $request, string $jsonValidationFile): array
{
$this->validateDataSent($request, $jsonValidationFile);
return json_decode((string) $request->getContent(), true);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Application/Controller/GorgoneController.php | centreon/src/Centreon/Application/Controller/GorgoneController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Centreon\Application\Controller;
use Centreon\Domain\Gorgone\Command\Thumbprint;
use Centreon\Domain\Gorgone\GorgoneException;
use Centreon\Domain\Gorgone\Interfaces\CommandInterface;
use Centreon\Domain\Gorgone\Interfaces\GorgoneServiceInterface;
use FOS\RestBundle\Controller\AbstractFOSRestController;
use FOS\RestBundle\View\View;
use JsonSchema\Constraints\Constraint;
use JsonSchema\Validator;
use Symfony\Component\HttpFoundation\Request;
/**
* This class is designed to provide a single communication interface to interact with the Gorgone system.
*
* @package Centreon\Application\Controller
*/
class GorgoneController extends AbstractFOSRestController
{
/** @var GorgoneServiceInterface */
private $gorgoneService;
/**
* GorgoneController constructor.
*
* @param GorgoneServiceInterface $gorgoneService
*/
public function __construct(GorgoneServiceInterface $gorgoneService)
{
$this->gorgoneService = $gorgoneService;
}
/**
* Entry point to send a command to a specific command
*
* @param int $pollerId Id of the poller for which this command is intended
*
* @param string $commandName Name of the Gorgone command
* @param Request $request
* @throws \Exception
* @return View
*/
public function sendCommand(int $pollerId, string $commandName, Request $request): View
{
$requestBody = json_decode((string) $request->getContent(), false);
if (! empty($requestBody)) {
$validationFile = $this->findValidationFileByCommandName($commandName);
if ($validationFile !== null) {
$validator = new Validator();
$validator->validate(
$requestBody,
(object) ['$ref' => $validationFile],
Constraint::CHECK_MODE_VALIDATE_SCHEMA
);
if (! $validator->isValid()) {
$message = '';
foreach ($validator->getErrors() as $error) {
$message .= sprintf("[%s] %s\n", $error['property'], $error['message']);
}
throw new GorgoneException($message);
}
}
}
$command = $this->createFromName(
$commandName,
$pollerId,
! empty($request->getContent()) ? (string) $request->getContent() : null
);
$gorgoneResponse = $this->gorgoneService->send($command);
return $this->view([
'token' => $gorgoneResponse->getCommand() !== null
? $gorgoneResponse->getCommand()->getToken()
: null,
]);
}
/**
* Entry point to get the response to a specific command
*
* @param int $pollerId Id of the poller for which the command is intended
* @param string $token Token of the command attributed by the Gorgone server
*
* @return View
*/
public function getResponses(int $pollerId, string $token): View
{
$gorgoneResponse = $this->gorgoneService->getResponseFromToken($pollerId, $token);
// We force a call to read the Gorgon Server API responses
$gorgoneResponse->getLastActionLog();
$responseTemplate = ($gorgoneResponse->getError() !== null)
? ['error' => $gorgoneResponse->getError()]
: [];
return $this->view(array_merge($responseTemplate, [
'message' => $gorgoneResponse->getMessage(),
'token' => $gorgoneResponse->getToken(),
'data' => $gorgoneResponse->getActionLogs(),
]));
}
/**
* Check whether the command type exists or not.
*
* @param string $commandType Type of the command (ex: thumbprint, ...)
* @param int $pollerId Id of the poller for which the command is intended
* @param string|null $requestBody Request body to send in the command
* @return CommandInterface
*/
private function createFromName(string $commandType, int $pollerId, ?string $requestBody): CommandInterface
{
switch ($commandType) {
case 'thumbprint':
return new Thumbprint($pollerId);
default:
throw new \LogicException('Unrecognized Command');
}
}
/**
* Find the validation file based on the command name.
*
* Will be implemented with the future commands of Gorgone server.
*
* @param string $commandName Command name
* @throws GorgoneException
* @return string|null Return the path of the validation file or null if not found
*/
private function findValidationFileByCommandName(string $commandName): ?string
{
throw new GorgoneException('Commands containing a request body are not allowed at the moment');
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Application/Controller/MonitoringResourceController.php | centreon/src/Centreon/Application/Controller/MonitoringResourceController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Centreon\Application\Controller;
use Centreon\Domain\Monitoring\Exception\ResourceException;
use Centreon\Domain\Monitoring\Resource as ResourceEntity;
use Core\Infrastructure\RealTime\Hypermedia\HypermediaProviderInterface;
/**
* Resource APIs for the Unified View page
*
* @package Centreon\Application\Controller
*/
class MonitoringResourceController extends AbstractController
{
public const TAB_DETAILS_NAME = 'details';
public const TAB_GRAPH_NAME = 'graph';
public const TAB_SERVICES_NAME = 'services';
public const TAB_TIMELINE_NAME = 'timeline';
public const TAB_SHORTCUTS_NAME = 'shortcuts';
private const RESOURCE_LISTING_URI = '/monitoring/resources';
private const ALLOWED_TABS = [
self::TAB_DETAILS_NAME,
self::TAB_GRAPH_NAME,
self::TAB_SERVICES_NAME,
self::TAB_TIMELINE_NAME,
self::TAB_SHORTCUTS_NAME,
];
// @var HypermediaProviderInterface[]
private array $hyperMediaProviders = [];
/**
* @param \Traversable<HypermediaProviderInterface> $hyperMediaProviders
*/
public function __construct(
\Traversable $hyperMediaProviders,
) {
$this->hasProviders($hyperMediaProviders);
$this->hyperMediaProviders = iterator_to_array($hyperMediaProviders);
}
/**
* Build uri to access host panel with details tab
*
* @param int $hostId
* @return string
*/
public function buildHostDetailsUri(int $hostId): string
{
return $this->buildResourceDetailsUri(
ResourceEntity::TYPE_HOST,
$hostId,
['hostId' => $hostId]
);
}
/**
* Build uri to access host panel
*
* @param int $hostId
* @param string $tab tab name
* @return string
*/
public function buildHostUri(int $hostId, string $tab = self::TAB_DETAILS_NAME): string
{
if (! in_array($tab, self::ALLOWED_TABS)) {
throw new ResourceException(sprintf(_('Cannot build uri to unknown tab : %s'), $tab));
}
$parameters = ['hostId' => $hostId];
return $this->buildListingUri([
'details' => json_encode([
'resourcesDetailsEndpoint' => $this->getBaseUri() . $this->generateResourceDetailsEndpoint($parameters, 'host'),
'type' => ResourceEntity::TYPE_HOST,
'id' => $hostId,
'tab' => $tab,
'uuid' => 'h' . $hostId,
], JSON_UNESCAPED_SLASHES),
]);
}
/**
* Build uri to access service service panel with details tab
*
* @param int $hostId
* @param int $serviceId
* @return string
*/
public function buildServiceDetailsUri(int $hostId, int $serviceId): string
{
return $this->buildResourceDetailsUri(
ResourceEntity::TYPE_SERVICE,
$serviceId,
[
'hostId' => $hostId,
'serviceId' => $serviceId,
]
);
}
/**
* Build uri to access service panel
*
* @param int $hostId
* @param int $serviceId
* @param string $tab tab name
* @return string
*/
public function buildServiceUri(int $hostId, int $serviceId, string $tab = self::TAB_DETAILS_NAME): string
{
if (! in_array($tab, self::ALLOWED_TABS)) {
throw new ResourceException(sprintf(_('Cannot build uri to unknown tab : %s'), $tab));
}
$parameters = ['hostId' => $hostId, 'serviceId' => $serviceId];
return $this->buildListingUri([
'details' => json_encode([
'resourcesDetailsEndpoint' => $this->getBaseUri() . $this->generateResourceDetailsEndpoint($parameters, 'service'),
'id' => $serviceId,
'tab' => $tab,
'uuid' => 'h' . $hostId . '-s' . $serviceId,
], JSON_UNESCAPED_SLASHES),
]);
}
/**
* Build uri to access meta service panel
*
* @param int $metaId
* @return string
*/
public function buildMetaServiceDetailsUri(int $metaId): string
{
return $this->buildResourceDetailsUri(
ResourceEntity::TYPE_META,
$metaId,
[
'metaId' => $metaId,
]
);
}
/**
* Build uri to access listing page of resources with specific parameters
*
* @param string[] $parameters
* @return string
*/
public function buildListingUri(array $parameters): string
{
$baseListingUri = $this->getBaseUri() . self::RESOURCE_LISTING_URI;
if ($parameters !== []) {
$baseListingUri .= '?' . http_build_query($parameters);
}
return $baseListingUri;
}
/**
* @param \Traversable<mixed> $providers
* @return void
*/
private function hasProviders(\Traversable $providers): void
{
if ($providers instanceof \Countable && count($providers) === 0) {
throw new \InvalidArgumentException(
_('You must add at least one provider')
);
}
}
/**
* Generates a resource details endpoint
*
* @param array<string, int> $urlParameters
* @param string $resourceType
* @return string
*/
private function generateResourceDetailsEndpoint(array $urlParameters, string $resourceType): string
{
$resourceDetailsEndpoint = null;
foreach ($this->hyperMediaProviders as $hyperMediaProvider) {
if ($hyperMediaProvider->isValidFor($resourceType)) {
$resourceDetailsEndpoint = $hyperMediaProvider->generateResourceDetailsUri($urlParameters);
}
}
return $resourceDetailsEndpoint;
}
/**
* Generates a resource details redirection link
*
* @param string $resourceType
* @param int $resourceId
* @param array<string, int> $parameters
* @return string
*/
private function buildResourceDetailsUri(string $resourceType, int $resourceId, array $parameters): string
{
return $this->buildListingUri([
'details' => json_encode([
'id' => $resourceId,
'tab' => self::TAB_DETAILS_NAME,
'resourcesDetailsEndpoint' => $this->getBaseUri() . $this->generateResourceDetailsEndpoint($parameters, $resourceType),
]),
]);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Application/Controller/MonitoringHostsController.php | centreon/src/Centreon/Application/Controller/MonitoringHostsController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Centreon\Application\Controller;
use Centreon\Domain\Acknowledgement\Acknowledgement;
use Centreon\Domain\Downtime\Downtime;
use Centreon\Domain\Monitoring\Host;
use Centreon\Domain\Monitoring\HostGroup;
use Centreon\Domain\Monitoring\Interfaces\MonitoringServiceInterface;
use Centreon\Domain\Monitoring\Service;
use Centreon\Domain\Monitoring\ServiceGroup;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use FOS\RestBundle\Context\Context;
use FOS\RestBundle\View\View;
use Symfony\Component\HttpFoundation\Response;
class MonitoringHostsController extends AbstractController
{
/** @var MonitoringServiceInterface */
private $monitoring;
/**
* MonitoringController constructor.
*
* @param MonitoringServiceInterface $monitoringService
*/
public function __construct(MonitoringServiceInterface $monitoringService)
{
$this->monitoring = $monitoringService;
}
/**
* Entry point to get a real time service.
*
* @param int $serviceId Service id
* @param int $hostId Host id
*
* @throws \Exception
*
* @return View
*/
public function getOneService(int $serviceId, int $hostId): View
{
$service = $this->monitoring
->filterByContact($this->getUser())
->findOneService($hostId, $serviceId);
if ($service === null) {
return View::create(null, Response::HTTP_NOT_FOUND, []);
}
try {
if ($service->getCommandLine() !== null) {
$this->monitoring->hidePasswordInServiceCommandLine($service);
}
} catch (\Throwable $ex) {
$service->setCommandLine(sprintf('Unable to hide passwords in command (Reason: %s)', $ex->getMessage()));
}
$groups = [
Service::SERIALIZER_GROUP_FULL,
Acknowledgement::SERIALIZER_GROUP_FULL,
];
$context = (new Context())
->setGroups(array_merge($groups, Downtime::SERIALIZER_GROUPS_SERVICE))
->enableMaxDepth();
return $this->view($service)->setContext($context);
}
/**
* Entry point to get all real time services.
*
* @param RequestParametersInterface $requestParameters Request parameters used to filter the request
*
* @throws \Exception
*
* @return View
*/
public function getServices(RequestParametersInterface $requestParameters): View
{
$this->denyAccessUnlessGrantedForApiRealtime();
$services = $this->monitoring
->filterByContact($this->getUser())
->findServices();
$context = (new Context())
->setGroups([
Service::SERIALIZER_GROUP_MAIN,
Service::SERIALIZER_GROUP_WITH_HOST,
Host::SERIALIZER_GROUP_MIN,
])
->enableMaxDepth();
return $this->view([
'result' => $services,
'meta' => $requestParameters->toArray(),
])->setContext($context);
}
/**
* Entry point to get all real time services based on a service group.
*
* @param RequestParametersInterface $requestParameters Request parameters used to filter the request
*
* @throws \Exception
*
* @return View
*/
public function getServicesByServiceGroups(RequestParametersInterface $requestParameters): View
{
$this->denyAccessUnlessGrantedForApiRealtime();
$withHost = $requestParameters->getExtraParameter('show_host') === 'true';
$withServices = $requestParameters->getExtraParameter('show_service') === 'true';
$contexts = [
ServiceGroup::SERIALIZER_GROUP_MAIN,
];
if ($withServices) {
$withHost = true;
$contexts = array_merge($contexts, [
Host::SERIALIZER_GROUP_WITH_SERVICES,
Service::SERIALIZER_GROUP_MIN,
]);
}
if ($withHost) {
$contexts = array_merge($contexts, [
ServiceGroup::SERIALIZER_GROUP_WITH_HOST,
Host::SERIALIZER_GROUP_MIN,
]);
}
$servicesByServiceGroups = $this->monitoring
->filterByContact($this->getUser())
->findServiceGroups($withHost, $withServices);
$context = (new Context())
->setGroups($contexts)
->enableMaxDepth();
return $this->view([
'result' => $servicesByServiceGroups,
'meta' => $requestParameters->toArray(),
])->setContext($context);
}
/**
* Entry point to get all real time services based on a host group.
*
* @param RequestParametersInterface $requestParameters Request parameters used to filter the request
*
* @throws \Exception
*
* @return View
*/
public function getHostGroups(RequestParametersInterface $requestParameters)
{
$this->denyAccessUnlessGrantedForApiRealtime();
$withHost = $requestParameters->getExtraParameter('show_host') === 'true';
$withServices = $requestParameters->getExtraParameter('show_service') === 'true';
$contexts = [
HostGroup::SERIALIZER_GROUP_MAIN,
];
if ($withServices) {
$withHost = true;
$contexts = array_merge($contexts, [
Host::SERIALIZER_GROUP_WITH_SERVICES,
Service::SERIALIZER_GROUP_MIN,
]);
}
if ($withHost) {
$contexts = array_merge($contexts, [
HostGroup::SERIALIZER_GROUP_WITH_HOST,
Host::SERIALIZER_GROUP_MIN,
]);
}
$hostGroups = $this->monitoring
->filterByContact($this->getUser())
->findHostGroups($withHost, $withServices);
$context = (new Context())
->setGroups($contexts)
->enableMaxDepth();
return $this->view([
'result' => $hostGroups,
'meta' => $requestParameters->toArray(),
])->setContext($context);
}
/**
* Entry point to get all real time hosts.
*
* @param RequestParametersInterface $requestParameters Request parameters used to filter the request
*
* @throws \Exception
*
* @return View
*/
public function getHosts(RequestParametersInterface $requestParameters)
{
$this->denyAccessUnlessGrantedForApiRealtime();
$withServices = $requestParameters->getExtraParameter('show_service') === 'true';
$hosts = $this->monitoring
->filterByContact($this->getUser())
->findHosts($withServices);
$contexts = [
Host::SERIALIZER_GROUP_MAIN,
];
if ($withServices) {
$contexts = array_merge($contexts, [
Host::SERIALIZER_GROUP_WITH_SERVICES,
Service::SERIALIZER_GROUP_MIN,
]);
}
return $this->view([
'result' => $hosts,
'meta' => $requestParameters->toArray(),
])->setContext((new Context())->setGroups($contexts));
}
/**
* Entry point to get a real time host.
*
* @param int $hostId Host id
*
* @throws \Exception
*
* @return View
*/
public function getOneHost(int $hostId)
{
$this->denyAccessUnlessGrantedForApiRealtime();
$host = $this->monitoring
->filterByContact($this->getUser())
->findOneHost($hostId);
if ($host === null) {
return View::create(null, Response::HTTP_NOT_FOUND, []);
}
$groups = [
Host::SERIALIZER_GROUP_FULL,
Service::SERIALIZER_GROUP_MIN,
Acknowledgement::SERIALIZER_GROUP_FULL,
];
$context = (new Context())
->setGroups(
array_merge(
$groups,
Downtime::SERIALIZER_GROUPS_MAIN
)
)
->enableMaxDepth();
return $this->view($host)->setContext($context);
}
/**
* Entry point to get all real time services based on a host.
*
* @param int $hostId Host id for which we want to get all services
* @param RequestParametersInterface $requestParameters Request parameters used to filter the request
*
* @throws \Exception
*
* @return View
*/
public function getServicesByHost(int $hostId, RequestParametersInterface $requestParameters)
{
$this->denyAccessUnlessGrantedForApiRealtime();
$this->monitoring->filterByContact($this->getUser());
if (! $this->monitoring->isHostExists($hostId)) {
return View::create(null, Response::HTTP_NOT_FOUND, []);
}
$context = (new Context())
->setGroups([
Service::SERIALIZER_GROUP_MAIN,
])
->enableMaxDepth();
return $this->view([
'result' => $this->monitoring->findServicesByHost($hostId),
'meta' => $requestParameters->toArray(),
])->setContext($context);
}
/**
* Entry point to get all hostgroups.
*
* @param int $hostId Id of host to search hostgroups for
* @param RequestParametersInterface $requestParameters Request parameters used to filter the request
*
* @throws \Exception
*
* @return View
*/
public function getHostGroupsByHost(int $hostId, RequestParametersInterface $requestParameters)
{
$this->denyAccessUnlessGrantedForApiRealtime();
$this->monitoring->filterByContact($this->getUser());
if (! $this->monitoring->isHostExists($hostId)) {
return View::create(null, Response::HTTP_NOT_FOUND, []);
}
$contexts = [
HostGroup::SERIALIZER_GROUP_MAIN,
];
$hostGroups = $this->monitoring
->filterByContact($this->getUser())
->findHostGroups(true, false, $hostId);
$context = (new Context())
->setGroups($contexts)
->enableMaxDepth();
return $this->view([
'result' => $hostGroups,
'meta' => $requestParameters->toArray(),
])->setContext($context);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Application/Controller/MonitoringServicesController.php | centreon/src/Centreon/Application/Controller/MonitoringServicesController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Centreon\Application\Controller;
use Centreon\Domain\Monitoring\Host;
use Centreon\Domain\Monitoring\Interfaces\MonitoringServiceInterface;
use Centreon\Domain\Monitoring\Service;
use Centreon\Domain\Monitoring\ServiceGroup;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use FOS\RestBundle\Context\Context;
use FOS\RestBundle\View\View;
use Symfony\Component\HttpFoundation\Response;
/**
* Responsible for all routes under /monitoring/services/
* @package Centreon\Application\Controller
*/
class MonitoringServicesController extends AbstractController
{
/** @var MonitoringServiceInterface */
private $monitoring;
/**
* MonitoringController constructor.
*
* @param MonitoringServiceInterface $monitoringService
*/
public function __construct(MonitoringServiceInterface $monitoringService)
{
$this->monitoring = $monitoringService;
}
/**
* Entry point to get all real time services.
* @param RequestParametersInterface $requestParameters Request parameters used to filter the request
* @throws \Exception
* @return View
*/
public function getServices(RequestParametersInterface $requestParameters): View
{
$services = $this->monitoring
->filterByContact($this->getUser())
->findServices();
$context = (new Context())
->setGroups([
Service::SERIALIZER_GROUP_MAIN,
Service::SERIALIZER_GROUP_WITH_HOST,
Host::SERIALIZER_GROUP_MIN,
])
->enableMaxDepth();
return $this->view(
[
'result' => $services,
'meta' => $requestParameters->toArray(),
]
)->setContext($context);
}
/**
* Entry point to get all real time services based on a service group
* @param RequestParametersInterface $requestParameters Request parameters used to filter the request
* @throws \Exception
* @return View
*/
public function getServicesByServiceGroups(RequestParametersInterface $requestParameters): View
{
$withHost = $requestParameters->getExtraParameter('show_host') === 'true';
$withServices = $requestParameters->getExtraParameter('show_service') === 'true';
$contexts = [ServiceGroup::SERIALIZER_GROUP_MAIN];
$contextsWithHosts = [ServiceGroup::SERIALIZER_GROUP_WITH_HOST, Host::SERIALIZER_GROUP_MIN];
$contextsWithService = [Host::SERIALIZER_GROUP_WITH_SERVICES, Service::SERIALIZER_GROUP_MIN];
if ($withServices) {
$withHost = true;
$contexts = array_merge($contexts, $contextsWithService);
}
if ($withHost) {
$contexts = array_merge($contexts, $contextsWithHosts);
}
$servicesByServiceGroups = $this->monitoring
->filterByContact($this->getUser())
->findServiceGroups($withHost, $withServices);
$context = (new Context())
->setGroups($contexts)
->enableMaxDepth();
return $this->view(
[
'result' => $servicesByServiceGroups,
'meta' => $requestParameters->toArray(),
]
)->setContext($context);
}
/**
* Entry point to get all servicegroups attached to host-service
*
* @param RequestParametersInterface $requestParameters Request parameters used to filter the request
* @throws \Exception
* @return View
*/
public function getServiceGroupsByHostAndService(
int $hostId,
int $serviceId,
RequestParametersInterface $requestParameters,
): View {
$this->monitoring->filterByContact($this->getUser());
if ($this->monitoring->isServiceExists($hostId, $serviceId)) {
$serviceGroups = $this->monitoring->findServiceGroupsByHostAndService($hostId, $serviceId);
$context = (new Context())
->setGroups([ServiceGroup::SERIALIZER_GROUP_MAIN])
->enableMaxDepth();
return $this->view(
[
'result' => $serviceGroups,
'meta' => $requestParameters->toArray(),
]
)->setContext($context);
}
return View::create(null, Response::HTTP_NOT_FOUND, []);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Application/Controller/Configuration/MonitoringServerController.php | centreon/src/Centreon/Application/Controller/Configuration/MonitoringServerController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Centreon\Application\Controller\Configuration;
use Centreon\Application\Controller\AbstractController;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Exception\EntityNotFoundException;
use Centreon\Domain\Exception\TimeoutException;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\MonitoringServer\Exception\MonitoringServerException;
use Centreon\Domain\MonitoringServer\Interfaces\MonitoringServerServiceInterface;
use Centreon\Domain\MonitoringServer\MonitoringServer;
use Centreon\Domain\MonitoringServer\UseCase\GenerateAllConfigurations;
use Centreon\Domain\MonitoringServer\UseCase\GenerateConfiguration;
use Centreon\Domain\MonitoringServer\UseCase\ReloadAllConfigurations;
use Centreon\Domain\MonitoringServer\UseCase\ReloadConfiguration;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use FOS\RestBundle\Context\Context;
use FOS\RestBundle\View\View;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
/**
* This class is designed to manage all requests concerning monitoring servers
*
* @package Centreon\Application\Controller
*/
class MonitoringServerController extends AbstractController
{
use LoggerTrait;
/**
* @param MonitoringServerServiceInterface $monitoringServerService
* @param bool $isCloudPlatform
*/
public function __construct(
private readonly MonitoringServerServiceInterface $monitoringServerService,
private readonly bool $isCloudPlatform,
) {
}
/**
* Entry point to find a monitoring server
*
* @param RequestParametersInterface $requestParameters
*
* @throws \Exception
*
* @return View
*/
public function findServers(RequestParametersInterface $requestParameters): View
{
$this->denyAccessUnlessGrantedForApiConfiguration();
$context = (new Context())->setGroups([
MonitoringServer::SERIALIZER_GROUP_MAIN,
]);
$servers = $this->monitoringServerService->findServers();
/**
* @var Contact $user
*/
$user = $this->getUser();
if ($this->isCloudPlatform && ! $user->isAdmin()) {
$excludeCentral = $requestParameters->getExtraParameter('exclude_central');
if (in_array($excludeCentral, [true, 'true', 1], true)) {
$remoteServers = $this->monitoringServerService->findRemoteServersIps();
$servers = array_values(array_filter($servers, function ($server) use ($remoteServers) {
return ! ($server->isLocalhost() && ! in_array($server->getAddress(), $remoteServers, true));
}));
$requestParameters->setTotal(count($servers));
}
}
return $this->view(
[
'result' => $servers,
'meta' => $requestParameters->toArray(),
]
)->setContext($context);
}
/**
* @param GenerateConfiguration $generateConfiguration
* @param int $monitoringServerId
* @throws EntityNotFoundException
* @throws MonitoringServerException
* @return View
*/
public function generateConfiguration(GenerateConfiguration $generateConfiguration, int $monitoringServerId): View
{
$this->denyAccessUnlessGrantedForApiConfiguration();
$this->execute(
function () use ($generateConfiguration, $monitoringServerId): void {
$generateConfiguration->execute($monitoringServerId);
}
);
return $this->view(null, Response::HTTP_NO_CONTENT);
}
/**
* @param GenerateAllConfigurations $generateAllConfigurations
* @throws EntityNotFoundException
* @throws MonitoringServerException
* @return View
*/
public function generateAllConfigurations(GenerateAllConfigurations $generateAllConfigurations): View
{
$this->denyAccessUnlessGrantedForApiConfiguration();
$this->execute(
function () use ($generateAllConfigurations): void {
$generateAllConfigurations->execute();
}
);
return $this->view(null, Response::HTTP_NO_CONTENT);
}
/**
* @param ReloadConfiguration $reloadConfiguration
* @param int $monitoringServerId
* @throws EntityNotFoundException
* @throws MonitoringServerException
* @return View
*/
public function reloadConfiguration(ReloadConfiguration $reloadConfiguration, int $monitoringServerId): View
{
$this->denyAccessUnlessGrantedForApiConfiguration();
$this->execute(
function () use ($reloadConfiguration, $monitoringServerId): void {
$reloadConfiguration->execute($monitoringServerId);
}
);
return $this->view(null, Response::HTTP_NO_CONTENT);
}
/**
* @param ReloadAllConfigurations $reloadAllConfigurations
* @throws EntityNotFoundException
* @throws MonitoringServerException
* @return View
*/
public function reloadAllConfigurations(ReloadAllConfigurations $reloadAllConfigurations): View
{
$this->denyAccessUnlessGrantedForApiConfiguration();
$this->execute(
function () use ($reloadAllConfigurations): void {
$reloadAllConfigurations->execute();
}
);
return $this->view(null, Response::HTTP_NO_CONTENT);
}
/**
* Generate and reload the configuration of a monitoring server.
*
* @param GenerateConfiguration $generateConfiguration
* @param ReloadConfiguration $reloadConfiguration
* @param int $monitoringServerId
* @throws EntityNotFoundException
* @throws MonitoringServerException
* @return View
*/
public function generateAndReloadConfiguration(
GenerateConfiguration $generateConfiguration,
ReloadConfiguration $reloadConfiguration,
int $monitoringServerId,
): View {
$this->denyAccessUnlessGrantedForApiConfiguration();
$this->execute(
function () use ($generateConfiguration, $reloadConfiguration, $monitoringServerId): void {
$generateConfiguration->execute($monitoringServerId);
$reloadConfiguration->execute($monitoringServerId);
}
);
return $this->view(null, Response::HTTP_NO_CONTENT);
}
/**
* Generate and reload all monitoring servers configurations.
*
* @param GenerateAllConfigurations $generateAllConfigurations
* @param ReloadAllConfigurations $reloadAllConfigurations
* @throws EntityNotFoundException
* @throws MonitoringServerException
* @return View
*/
public function generateAndReloadAllConfigurations(
GenerateAllConfigurations $generateAllConfigurations,
ReloadAllConfigurations $reloadAllConfigurations,
): View {
$this->denyAccessUnlessGrantedForApiConfiguration();
$this->execute(
function () use ($generateAllConfigurations, $reloadAllConfigurations): void {
$generateAllConfigurations->execute();
$reloadAllConfigurations->execute();
}
);
return $this->view(null, Response::HTTP_NO_CONTENT);
}
/**
* @param callable $callable
* @throws EntityNotFoundException
* @throws MonitoringServerException
*/
private function execute(callable $callable): void
{
/**
* @var Contact $user
*/
$user = $this->getUser();
try {
if (! $user->isAdmin() && ! $user->hasRole(Contact::ROLE_GENERATE_CONFIGURATION)) {
throw new AccessDeniedException('Insufficient rights (required: ROLE_GENERATE_CONFIGURATION)');
}
$callable();
} catch (TimeoutException $ex) {
$this->error($ex->getMessage());
throw new MonitoringServerException(
'The operation timed out - please use the legacy export menu to workaround this problem'
);
} catch (EntityNotFoundException|AccessDeniedException $ex) {
$this->error($ex->getMessage());
throw $ex;
} catch (\Exception $ex) {
$this->error($ex->getMessage());
throw new MonitoringServerException(
'There was an consistency error in the exported files - please use the legacy export menu to troubleshoot',
previous: $ex,
);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Application/Controller/Configuration/IconController.php | centreon/src/Centreon/Application/Controller/Configuration/IconController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Centreon\Application\Controller\Configuration;
use Centreon\Application\Controller\AbstractController;
use Centreon\Domain\Configuration\Icon\Interfaces\IconServiceInterface;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use FOS\RestBundle\Context\Context;
use FOS\RestBundle\View\View;
/**
* This class is design to manage all API REST requests concerning the icons configuration.
*
* @package Centreon\Application\Controller\Configuration
*/
class IconController extends AbstractController
{
// Groups for serializing
public const SERIALIZER_GROUPS_MAIN = ['icon_main'];
/** @var IconServiceInterface */
private $iconService;
public function __construct(IconServiceInterface $iconService)
{
$this->iconService = $iconService;
}
/**
* Get list of icons
*
* @param RequestParametersInterface $requestParameters
* @throws \Exception
* @return View
*/
public function getIcons(RequestParametersInterface $requestParameters): View
{
$this->denyAccessUnlessGrantedForApiConfiguration();
$icons = $this->iconService->getIcons();
foreach ($icons as $icon) {
if (isset($_SERVER['REQUEST_URI']) && preg_match('/^(.+)\/api\/.+/', $_SERVER['REQUEST_URI'], $matches)) {
$icon->setUrl($matches[1] . '/img/media/' . $icon->getUrl());
}
}
$context = (new Context())
->setGroups(self::SERIALIZER_GROUPS_MAIN);
return $this->view([
'result' => $icons,
'meta' => $requestParameters->toArray(),
])->setContext($context);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Application/Controller/Configuration/ProxyController.php | centreon/src/Centreon/Application/Controller/Configuration/ProxyController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Centreon\Application\Controller\Configuration;
use Centreon\Application\Controller\AbstractController;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Entity\EntityValidator;
use Centreon\Domain\Proxy\Interfaces\ProxyServiceInterface;
use Centreon\Domain\Proxy\Proxy;
use FOS\RestBundle\View\View;
use JMS\Serializer\Exception\ValidationFailedException;
use JMS\Serializer\SerializerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;
/**
* This class is design to manage all API REST requests concerning the proxy configuration.
*
* @package Centreon\Application\Controller\Configuration
*/
class ProxyController extends AbstractController
{
/** @var ProxyServiceInterface */
private $proxyService;
/**
* ProxyController constructor.
*
* @param ProxyServiceInterface $proxyService
*/
public function __construct(ProxyServiceInterface $proxyService)
{
$this->proxyService = $proxyService;
}
/**
* @throws \Exception
* @return View
*/
public function getProxy(): View
{
$this->denyAccessUnlessGrantedForApiConfiguration();
/**
* @var Contact $contact
*/
$contact = $this->getUser();
if (! $contact->isAdmin() && ! $this->isGranted('ROLE_ADMINISTRATION_PARAMETERS_CENTREON_UI_RW')) {
return $this->view(null, Response::HTTP_FORBIDDEN);
}
return $this->view($this->proxyService->getProxy());
}
/**
* @param Request $request
* @param EntityValidator $entityValidator
* @param SerializerInterface $serializer
* @throws \Exception
* @return View
*/
public function updateProxy(
Request $request,
EntityValidator $entityValidator,
SerializerInterface $serializer,
): View {
$this->denyAccessUnlessGrantedForApiConfiguration();
/**
* @var ContactInterface $user
*/
$user = $this->getUser();
if (! $user->isAdmin() && ! $this->isGranted('ROLE_ADMINISTRATION_PARAMETERS_CENTREON_UI_RW')) {
return $this->view(null, Response::HTTP_FORBIDDEN);
}
$data = json_decode((string) $request->getContent(), true);
if ($data === null) {
throw new HttpException(
Response::HTTP_UNPROCESSABLE_ENTITY,
_('Invalid json message received'),
);
}
$errors = $entityValidator->validateEntity(
Proxy::class,
json_decode((string) $request->getContent(), true),
['proxy_main'],
false // We don't allow extra fields
);
if ($errors->count() > 0) {
throw new ValidationFailedException($errors);
}
/**
* @var Proxy $proxy
*/
$proxy = $serializer->deserialize(
(string) $request->getContent(),
Proxy::class,
'json'
);
$this->proxyService->updateProxy($proxy);
return $this->view();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Application/Controller/Monitoring/MetricController.php | centreon/src/Centreon/Application/Controller/Monitoring/MetricController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Centreon\Application\Controller\Monitoring;
use Centreon\Application\Controller\AbstractController;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Exception\EntityNotFoundException;
use Centreon\Domain\Monitoring\Interfaces\MonitoringServiceInterface;
use Centreon\Domain\Monitoring\Metric\Interfaces\MetricServiceInterface;
use Centreon\Domain\Monitoring\Service;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use FOS\RestBundle\View\View;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
/**
* This class is design to manage all API REST about metric requests
*
* @package Centreon\Application\Controller\Metric\Controller
*/
class MetricController extends AbstractController
{
/** @var MetricServiceInterface */
private $metricService;
/** @var MonitoringServiceInterface */
private $monitoringService;
/**
* MetricController constructor.
*
* @param MetricServiceInterface $metricService
* @param MonitoringServiceInterface $monitoringService
*/
public function __construct(
MetricServiceInterface $metricService,
MonitoringServiceInterface $monitoringService,
) {
$this->metricService = $metricService;
$this->monitoringService = $monitoringService;
}
/**
* Entry point to get service metrics
*
* @param int $hostId
* @param int $serviceId
* @param \DateTime $start
* @param \DateTime $end
* @throws \Exception
* @return View
*/
public function getServiceMetrics(
int $hostId,
int $serviceId,
\DateTime $start,
\DateTime $end,
): View {
$this->denyAccessUnlessGrantedForApiRealtime();
/**
* @var Contact $contact
*/
$contact = $this->getUser();
$service = $this->findService($hostId, $serviceId);
$metrics = $this->metricService
->filterByContact($contact)
->findMetricsByService($service, $start, $end);
return $this->view($metrics);
}
/**
* Entry point to get service status
*
* @param int $hostId
* @param int $serviceId
* @param \DateTime $start
* @param \DateTime $end
* @throws \Exception
* @return View
*/
public function getServiceStatus(
int $hostId,
int $serviceId,
\DateTime $start,
\DateTime $end,
): View {
$this->denyAccessUnlessGrantedForApiRealtime();
/**
* @var Contact $contact
*/
$contact = $this->getUser();
$service = $this->findService($hostId, $serviceId);
$status = $this->metricService
->filterByContact($contact)
->findStatusByService($service, $start, $end);
return $this->view($status);
}
/**
* Entry point to get service performance metrics
*
* @param int $hostId
* @param int $serviceId
* @throws \Exception
* @return View
*/
public function getServicePerformanceMetrics(
RequestParametersInterface $requestParameters,
int $hostId,
int $serviceId,
): View {
$this->denyAccessUnlessGrantedForApiRealtime();
[$start, $end] = $this->extractDatesFromRequestParameters($requestParameters);
/**
* @var Contact $contact
*/
$contact = $this->getUser();
$service = $this->findService($hostId, $serviceId);
$metrics = $this->metricService
->filterByContact($contact)
->findMetricsByService($service, $start, $end);
$metrics = $this->normalizePerformanceMetricsDates($metrics);
return $this->view($metrics);
}
/**
* Entry point to get service status metrics
*
* @param int $hostId
* @param int $serviceId
* @throws \Exception
* @return View
*/
public function getServiceStatusMetrics(
RequestParametersInterface $requestParameters,
int $hostId,
int $serviceId,
): View {
$this->denyAccessUnlessGrantedForApiRealtime();
[$start, $end] = $this->extractDatesFromRequestParameters($requestParameters);
/**
* @var Contact $contact
*/
$contact = $this->getUser();
$service = $this->findService($hostId, $serviceId);
$status = $this->metricService
->filterByContact($contact)
->findStatusByService($service, $start, $end);
return $this->view($status);
}
/**
* Entry point to get meta service performance metrics
*
* @param int $metaId
* @throws \Exception
* @return View
*/
public function getMetaServicePerformanceMetrics(
RequestParametersInterface $requestParameters,
int $metaId,
): View {
$this->denyAccessUnlessGrantedForApiRealtime();
[$start, $end] = $this->extractDatesFromRequestParameters($requestParameters);
/**
* @var Contact $contact
*/
$contact = $this->getUser();
$service = $this->monitoringService
->filterByContact($contact)
->findOneServiceByDescription('meta_' . $metaId);
if ($service === null) {
throw new EntityNotFoundException(
sprintf(_('Meta Service linked to service %d not found'), $metaId)
);
}
$metrics = $this->metricService
->filterByContact($contact)
->findMetricsByService($service, $start, $end);
$metrics = $this->normalizePerformanceMetricsDates($metrics);
return $this->view($metrics);
}
/**
* Entry point to get metaservice status metrics
*
* @param int $metaId
* @throws \Exception
* @return View
*/
public function getMetaServiceStatusMetrics(
RequestParametersInterface $requestParameters,
int $metaId,
): View {
$this->denyAccessUnlessGrantedForApiRealtime();
[$start, $end] = $this->extractDatesFromRequestParameters($requestParameters);
/**
* @var Contact $contact
*/
$contact = $this->getUser();
$service = $this->monitoringService
->filterByContact($contact)
->findOneServiceByDescription('meta_' . $metaId);
if ($service === null) {
throw new EntityNotFoundException(
sprintf(_('Meta Service linked to service %d not found'), $metaId)
);
}
$status = $this->metricService
->filterByContact($contact)
->findStatusByService($service, $start, $end);
return $this->view($status);
}
/**
* find a service from host id and service id
*
* @throws EntityNotFoundException if the host or service is not found
* @return Service if the service is found
*/
private function findService(int $hostId, int $serviceId): Service
{
/**
* @var Contact $contact
*/
$contact = $this->getUser();
$this->monitoringService->filterByContact($contact);
$host = $this->monitoringService->findOneHost($hostId);
if (is_null($host)) {
throw new EntityNotFoundException(
sprintf(_('Host %d not found'), $hostId)
);
}
$service = $this->monitoringService->findOneService($hostId, $serviceId);
if (is_null($service)) {
throw new EntityNotFoundException(
sprintf(_('Service %d not found'), $serviceId)
);
}
$service->setHost($host);
return $service;
}
/**
* convert timestamp to DateTime
*
* @param int $timestamp
* @param \DateTimeZone $timezone
* @return \DateTime
*/
private function formatTimestampToDateTime(int $timestamp, \DateTimeZone $timezone): \DateTime
{
return (new \DateTime())
->setTimestamp($timestamp)
->setTimezone($timezone);
}
/**
* Normalize dates (from timestamp to DateTime using timezone)
*
* @param array<string,mixed> $metrics
* @return array<string,mixed> The normalized metrics
*/
private function normalizePerformanceMetricsDates(array $metrics): array
{
/**
* @var Contact $contact
*/
$contact = $this->getUser();
$timezone = $contact->getTimezone();
$metrics['global']['start'] = $this->formatTimestampToDateTime((int) $metrics['global']['start'], $timezone);
$metrics['global']['end'] = $this->formatTimestampToDateTime((int) $metrics['global']['end'], $timezone);
// Normalize ticks
foreach ($metrics['times'] as $index => $timestamp) {
$metrics['times'][$index] = $this->formatTimestampToDateTime((int) $timestamp, $timezone);
}
return $metrics;
}
/**
* Validate and extract start/end dates from request parameters
*
* @param RequestParametersInterface $requestParameters
* @throws NotFoundHttpException
* @throws \LogicException
* @return array<\DateTime>
* @example [new \Datetime('yesterday'), new \Datetime('today')]
*/
private function extractDatesFromRequestParameters(RequestParametersInterface $requestParameters): array
{
$start = $requestParameters->getExtraParameter('start') ?: '1 day ago';
$end = $requestParameters->getExtraParameter('end') ?: 'now';
foreach (['start' => $start, 'end' => $end] as $param => $value) {
if (strtotime($value) === false) {
throw new NotFoundHttpException(sprintf('Invalid date given for parameter "%s".', $param));
}
}
$start = new \DateTime($start);
$end = new \DateTime($end);
if ($start >= $end) {
throw new \RangeException('End date must be greater than start date.');
}
return [$start, $end];
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Application/Controller/Monitoring/TimelineController.php | centreon/src/Centreon/Application/Controller/Monitoring/TimelineController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Centreon\Application\Controller\Monitoring;
use Centreon\Application\Controller\AbstractController;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Exception\EntityNotFoundException;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\Monitoring\Host;
use Centreon\Domain\Monitoring\Interfaces\MonitoringServiceInterface;
use Centreon\Domain\Monitoring\ResourceStatus;
use Centreon\Domain\Monitoring\Timeline\Interfaces\TimelineServiceInterface;
use Centreon\Domain\Monitoring\Timeline\TimelineContact;
use Centreon\Domain\Monitoring\Timeline\TimelineEvent;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use FOS\RestBundle\Context\Context;
use FOS\RestBundle\View\View;
use Symfony\Component\HttpFoundation\StreamedResponse;
/**
* @package Centreon\Application\Controller\Monitoring
*/
class TimelineController extends AbstractController
{
use LoggerTrait;
public const SERIALIZER_GROUPS_MAIN = ['timeline_main', 'contact_main', 'resource_status_main'];
/**
* TimelineController constructor.
*
* @param MonitoringServiceInterface $monitoringService
* @param TimelineServiceInterface $timelineService
* @param ContactInterface $user
*/
public function __construct(
private readonly MonitoringServiceInterface $monitoringService,
private readonly TimelineServiceInterface $timelineService,
private readonly ContactInterface $user,
) {
}
/**
* Entry point to get timeline for a host
*
* @param int $hostId id of host
* @param RequestParametersInterface $requestParameters Request parameters used to filter the request
*
* @throws EntityNotFoundException
* @return View
*/
public function getHostTimeline(
int $hostId,
RequestParametersInterface $requestParameters,
): View {
$this->denyAccessUnlessGrantedForApiRealtime();
if (! $this->user->hasTopologyRole(Contact::ROLE_MONITORING_RESOURCES_STATUS_RW)) {
$this->error('User doesn\'t have sufficient rights to see the host timeline', [
'user_id' => $this->user->getId(),
]);
throw $this->createAccessDeniedException();
}
$this->info(
'Get host timeline',
['user_id' => $this->user->getId(), 'host_id' => $hostId]
);
$host = $this->getHostById($hostId);
$timeline = $this->timelineService->findTimelineEventsByHost($host);
$context = (new Context())
->setGroups(static::SERIALIZER_GROUPS_MAIN)
->enableMaxDepth();
return $this->view([
'result' => $timeline,
'meta' => $requestParameters->toArray(),
])->setContext($context);
}
/**
* Entry point to get timeline for a service
*
* @param int $hostId id of host
* @param int $serviceId id of service
* @param RequestParametersInterface $requestParameters Request parameters used to filter the request
*
* @throws EntityNotFoundException
* @return View
*/
public function getServiceTimeline(
int $hostId,
int $serviceId,
RequestParametersInterface $requestParameters,
): View {
$this->denyAccessUnlessGrantedForApiRealtime();
if (! $this->user->hasTopologyRole(Contact::ROLE_MONITORING_RESOURCES_STATUS_RW)) {
$this->error('User doesn\'t have sufficient rights to see the service timeline', [
'user_id' => $this->user->getId(),
]);
throw $this->createAccessDeniedException();
}
$this->info(
'Get service timeline',
['user_id' => $this->user->getId(), 'host_id' => $hostId, 'service_id' => $serviceId]
);
$context = (new Context())
->setGroups(static::SERIALIZER_GROUPS_MAIN)
->enableMaxDepth();
return $this->view(
[
'result' => $this->getTimelinesByHostIdAndServiceId($this->user, $hostId, $serviceId),
'meta' => $requestParameters->toArray(),
]
)->setContext($context);
}
/**
* @param int $hostId
* @param RequestParametersInterface $requestParameters
*
* @throws EntityNotFoundException
* @return StreamedResponse
*/
public function downloadHostTimeline(
int $hostId,
RequestParametersInterface $requestParameters,
): StreamedResponse {
$this->denyAccessUnlessGrantedForApiRealtime();
if (! $this->user->hasTopologyRole(Contact::ROLE_MONITORING_RESOURCES_STATUS_RW)) {
$this->error('User doesn\'t have sufficient rights to see the host timeline', [
'user_id' => $this->user->getId(),
]);
throw $this->createAccessDeniedException();
}
$this->addDownloadParametersInRequestParameters($requestParameters);
$timeLines = $this->formatTimeLinesForDownload($this->getTimelinesByHostId($hostId));
return $this->streamTimeLines($timeLines);
}
/**
* @param int $hostId
* @param int $serviceId
* @param RequestParametersInterface $requestParameters
*
* @throws EntityNotFoundException
* @return StreamedResponse
*/
public function downloadServiceTimeline(
int $hostId,
int $serviceId,
RequestParametersInterface $requestParameters,
): StreamedResponse {
$this->denyAccessUnlessGrantedForApiRealtime();
if (! $this->user->hasTopologyRole(Contact::ROLE_MONITORING_RESOURCES_STATUS_RW)) {
$this->error('User doesn\'t have sufficient rights to see the host timeline', [
'user_id' => $this->user->getId(),
]);
throw $this->createAccessDeniedException();
}
$this->addDownloadParametersInRequestParameters($requestParameters);
$timeLines = $this->formatTimeLinesForDownload(
$this->getTimelinesByHostIdAndServiceId($this->user, $hostId, $serviceId)
);
return $this->streamTimeLines($timeLines);
}
/**
* Entry point to get timeline for a meta service
*
* @param int $metaId ID of the Meta
* @param RequestParametersInterface $requestParameters Request parameters used to filter the request
* @throws EntityNotFoundException
* @return View
*/
public function getMetaServiceTimeline(int $metaId, RequestParametersInterface $requestParameters): View
{
$this->denyAccessUnlessGrantedForApiRealtime();
$context = (new Context())
->setGroups(static::SERIALIZER_GROUPS_MAIN)
->enableMaxDepth();
return $this->view(
[
'result' => $this->getMetaServiceTimelineById($metaId),
'meta' => $requestParameters->toArray(),
]
)->setContext($context);
}
/**
* @param int $metaId
* @param RequestParametersInterface $requestParameters
* @throws EntityNotFoundException
* @return StreamedResponse
*/
public function downloadMetaserviceTimeline(
int $metaId,
RequestParametersInterface $requestParameters,
): StreamedResponse {
$this->denyAccessUnlessGrantedForApiRealtime();
$this->addDownloadParametersInRequestParameters($requestParameters);
$timeLines = $this->formatTimeLinesForDownload($this->getMetaServiceTimelineById($metaId));
return $this->streamTimeLines($timeLines);
}
/**
* @param RequestParametersInterface $requestParameters
* @return void
*/
private function addDownloadParametersInRequestParameters(RequestParametersInterface $requestParameters): void
{
$requestParameters->setPage(1);
$requestParameters->setLimit(1000000000);
}
/**
* @param \Iterator<string[]> $timeLines
* @return StreamedResponse
*/
private function streamTimeLines(iterable $timeLines): StreamedResponse
{
$response = new StreamedResponse();
$response->setCallback(function () use ($timeLines): void {
$handle = fopen('php://output', 'r+');
if ($handle === false) {
throw new \RuntimeException('Unable to generate file');
}
$header = ['type', 'date', 'content', 'contact', 'status', 'tries'];
fputcsv($handle, $header, ';');
foreach ($timeLines as $timeLine) {
fputcsv($handle, $timeLine, ';');
}
fclose($handle);
});
$response->headers->set('Content-Type', 'application/force-download');
$response->headers->set('Content-Disposition', 'attachment; filename="export.csv"');
return $response;
}
/**
* @return TimelineEvent[]
*/
private function getMetaServiceTimelineById(int $metaId): array
{
$user = $this->getUser();
$this->monitoringService->filterByContact($user);
$this->timelineService->filterByContact($user);
$service = $this->monitoringService->findOneServiceByDescription('meta_' . $metaId);
if (is_null($service)) {
$errorMsg = sprintf(_('Meta service %d not found'), $metaId);
throw new EntityNotFoundException($errorMsg);
}
$serviceHost = $service->getHost();
if (! $serviceHost instanceof Host) {
throw new EntityNotFoundException(sprintf(_('Unable to find host by service id %d'), $service->getId()));
}
$serviceHostId = $serviceHost->getId() ?? 0;
$host = $this->monitoringService->findOneHost($serviceHostId);
if (is_null($host)) {
throw new EntityNotFoundException(
sprintf(_('Host meta for meta service %d not found'), $metaId)
);
}
$service->setHost($host);
return $this->timelineService->findTimelineEventsByService($service);
}
/**
* @param int $hostId
* @return TimelineEvent[]
*/
private function getTimelinesByHostId(int $hostId): array
{
$host = $this->getHostById($hostId);
return $this->timelineService->findTimelineEventsByHost($host);
}
/**
* @param ContactInterface $user
* @param int $hostId
* @param int $serviceId
*
* @throws EntityNotFoundException
* @return TimelineEvent[]
*/
private function getTimelinesByHostIdAndServiceId(ContactInterface $user, int $hostId, int $serviceId): array
{
$this->monitoringService->filterByContact($user);
$service = $this->monitoringService->findOneService($hostId, $serviceId);
if ($service === null) {
$errorMsg = sprintf(_('Service %d on host %d not found'), $hostId, $serviceId);
throw new EntityNotFoundException($errorMsg);
}
$host = $this->getHostById($hostId);
$service->setHost($host);
return $this->timelineService->findTimelineEventsByService($service);
}
/**
* @param int $hostId
* @throws EntityNotFoundException
* @return Host
*/
private function getHostById(int $hostId): Host
{
$user = $this->getUser();
$this->monitoringService->filterByContact($user);
$this->timelineService->filterByContact($user);
$host = $this->monitoringService->findOneHost($hostId);
if ($host === null) {
throw new EntityNotFoundException(sprintf(_('Host id %d not found'), $hostId));
}
return $host;
}
/**
* @param TimelineEvent[] $timeLines
* @return \Iterator
*/
private function formatTimeLinesForDownload(array $timeLines): iterable
{
foreach ($timeLines as $timeLine) {
$date = $timeLine->getDate() instanceof \DateTime ? $timeLine->getDate()->format('c') : '';
$contact = $timeLine->getContact() instanceof TimelineContact ? $timeLine->getContact()->getName() : '';
$status = $timeLine->getStatus() instanceof ResourceStatus ? $timeLine->getStatus()->getName() : '';
$tries = $timeLine->getTries() ?? '';
yield [
'type' => $timeLine->getType() ?? '',
'date' => $date,
'content' => $timeLine->getContent(),
'contact' => $contact,
'status' => $status,
'tries' => (string) $tries,
];
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Application/Controller/Monitoring/MetaServiceController.php | centreon/src/Centreon/Application/Controller/Monitoring/MetaServiceController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Centreon\Application\Controller\Monitoring;
use Centreon\Application\Controller\AbstractController;
use Centreon\Domain\Monitoring\MetaService\UseCase\V21\MetaServiceMetric\FindMetaServiceMetrics;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Centreon\Infrastructure\Monitoring\MetaService\API\Model\MetaServiceMetricFactoryV21;
use FOS\RestBundle\View\View;
/**
* This class is designed to provide APIs for the context of RealTime Monitoring Servers.
*
* @package Centreon\Application\Controller\RealTimeMonitoringServer\Controller
*/
class MetaServiceController extends AbstractController
{
/**
* @param RequestParametersInterface $requestParameters
* @param FindMetaServiceMetrics $findMetaServiceMetrics
* @return View
*/
public function findMetaServiceMetrics(
RequestParametersInterface $requestParameters,
FindMetaServiceMetrics $findMetaServiceMetrics,
int $metaId,
): View {
$this->denyAccessUnlessGrantedForApiRealtime();
$response = $findMetaServiceMetrics->execute($metaId);
return $this->view(
[
'result' => MetaServiceMetricFactoryV21::createFromResponse($response),
'meta' => $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/Centreon/Application/Controller/Monitoring/CommentController.php | centreon/src/Centreon/Application/Controller/Monitoring/CommentController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Centreon\Application\Controller\Monitoring;
use Centreon\Application\Controller\AbstractController;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Exception\EntityNotFoundException;
use Centreon\Domain\Monitoring\Comment\Comment;
use Centreon\Domain\Monitoring\Comment\Interfaces\CommentServiceInterface;
use Centreon\Domain\Monitoring\Host;
use Centreon\Domain\Monitoring\Interfaces\MonitoringServiceInterface;
use Centreon\Domain\Monitoring\Resource as ResourceEntity;
use Centreon\Domain\Monitoring\Service;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Exception;
use FOS\RestBundle\View\View;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class CommentController extends AbstractController
{
private const COMMENT_RESOURCES_PAYLOAD_VALIDATION_FILE
= __DIR__ . '/../../../../../config/json_validator/latest/Centreon/Comment/CommentResources.json';
private const SINGLE_COMMENT_PAYLOAD_VALIDATION_FILE
= __DIR__ . '/../../../../../config/json_validator/latest/Centreon/Comment/Comment.json';
public function __construct(
private CommentServiceInterface $commentService,
private MonitoringServiceInterface $monitoringService,
private ReadAccessGroupRepositoryInterface $readAccessGroupRepository,
) {
}
/**
* Entry point to add comments to multiple resources
*
* @param Request $request
* @throws Exception
* @throws \InvalidArgumentException
* @return View
*/
public function addResourcesComment(
Request $request,
): View {
$this->denyAccessUnlessGrantedForApiRealtime();
/**
* @var Contact $contact
*/
$contact = $this->getUser();
if ($contact->isAdmin() === false) {
$accessGroups = $this->readAccessGroupRepository->findByContact($contact);
$accessGroupIds = array_map(
fn ($accessGroup) => $accessGroup->getId(),
$accessGroups
);
if ($this->readAccessGroupRepository->hasAccessToResources($accessGroupIds) === false) {
return $this->view(null, Response::HTTP_FORBIDDEN);
}
}
$this->commentService->filterByContact($contact);
// Validate the content of the request against the JSON schema validator
$payload = $this->validateAndRetrieveDataSent($request, self::COMMENT_RESOURCES_PAYLOAD_VALIDATION_FILE);
/**
* If user has no rights to add a comment for host and/or service
* return view with unauthorized HTTP header response
*/
if (! $this->hasCommentRightsForResources($contact, $payload['resources'])) {
return $this->view(null, Response::HTTP_UNAUTHORIZED);
}
/**
* Dissect the results to extract the hostids and serviceids from it
*/
$resourceIds = [];
$comments = [];
$now = new \DateTime();
foreach ($payload['resources'] as $resource) {
$date = ($resource['date'] !== null) ? new \DateTime($resource['date']) : $now;
$comments[$resource['id']] = (new Comment($resource['id'], $resource['comment']))
->setDate($date);
if ($resource['type'] === ResourceEntity::TYPE_HOST) {
$resourceIds['host'][] = $resource['id'];
} elseif ($resource['type'] === ResourceEntity::TYPE_SERVICE) {
$comments[$resource['id']]->setParentResourceId($resource['parent']['id']);
$resourceIds['service'][] = [
'host_id' => $resource['parent']['id'],
'service_id' => $resource['id'],
];
} elseif ($resource['type'] === ResourceEntity::TYPE_META) {
$resourceIds['metaservice'][] = [
'service_id' => $resource['id'],
];
}
}
$this->commentService->addResourcesComment($comments, $resourceIds);
return $this->view(null, Response::HTTP_NO_CONTENT);
}
/**
* Entry point to add a comment on a host resource
*
* @param Request $request
* @param int $hostId ID of the host
* @throws Exception
* @throws \InvalidArgumentException
* @return View
*/
public function addHostComment(
Request $request,
int $hostId,
): View {
$this->denyAccessUnlessGrantedForApiRealtime();
/**
* @var Contact $contact
*/
$contact = $this->getUser();
$this->commentService->filterByContact($contact);
/**
* Checking that user is allowed to add a comment for a host resource
*/
if (! $contact->isAdmin() && ! $contact->hasRole(Contact::ROLE_HOST_ADD_COMMENT)) {
return $this->view(null, Response::HTTP_UNAUTHORIZED);
}
// Validate the content of the request against the JSON schema validator
$payload = $this->validateAndRetrieveDataSent($request, self::SINGLE_COMMENT_PAYLOAD_VALIDATION_FILE);
$date = ($payload['date'] !== null) ? new \DateTime($payload['date']) : new \DateTime();
$comment = (new Comment($hostId, $payload['comment']))
->setDate($date);
$host = new Host();
$host->setId($hostId);
$this->commentService->addHostComment($comment, $host);
return $this->view(null, Response::HTTP_NO_CONTENT);
}
/**
* Entry point to add a comment on a service
*
* @param Request $request
* @param int $hostId ID of service parent (host)
* @param int $serviceId ID of the service
* @throws Exception
* @throws \InvalidArgumentException
* @return View
*/
public function addServiceComment(
Request $request,
int $hostId,
int $serviceId,
): View {
$this->denyAccessUnlessGrantedForApiRealtime();
/**
* @var Contact $contact
*/
$contact = $this->getUser();
$this->commentService->filterByContact($contact);
if (! $contact->isAdmin() && ! $contact->hasRole(Contact::ROLE_SERVICE_ADD_COMMENT)) {
return $this->view(null, Response::HTTP_UNAUTHORIZED);
}
// Validate the content of the request against the JSON schema validator
$payload = $this->validateAndRetrieveDataSent($request, self::SINGLE_COMMENT_PAYLOAD_VALIDATION_FILE);
/**
* At this point we validate the JSON sent with the JSON validator.
*/
$date = ($payload['date'] !== null) ? new \DateTime($payload['date']) : new \DateTime();
$comment = (new Comment($serviceId, $payload['comment']))
->setDate($date)
->setParentResourceId($hostId);
$service = new Service();
$host = new Host();
$host->setId($hostId);
$service->setId($serviceId)->setHost($host);
$this->commentService->addServiceComment($comment, $service);
return $this->view(null, Response::HTTP_NO_CONTENT);
}
/**
* Entry point to add a comment on a service
*
* @param Request $request
* @param int $metaId ID of the Meta Service
* @throws Exception
* @throws \InvalidArgumentException
* @return View
*/
public function addMetaServiceComment(
Request $request,
int $metaId,
): View {
$this->denyAccessUnlessGrantedForApiRealtime();
/**
* @var Contact $contact
*/
$contact = $this->getUser();
$this->commentService->filterByContact($contact);
if (! $contact->isAdmin() && ! $contact->hasRole(Contact::ROLE_SERVICE_ADD_COMMENT)) {
return $this->view(null, Response::HTTP_UNAUTHORIZED);
}
// Validate the content of the request against the JSON schema validator
$payload = $this->validateAndRetrieveDataSent($request, self::SINGLE_COMMENT_PAYLOAD_VALIDATION_FILE);
/**
* At this point we validate the JSON sent with the JSON validator.
*/
$date = ($payload['date'] !== null) ? new \DateTime($payload['date']) : new \DateTime();
$service = $this->monitoringService->findOneServiceByDescription('meta_' . $metaId);
if ($service === null) {
throw new EntityNotFoundException(
sprintf(
_('Meta service %d not found'),
$metaId
)
);
}
$comment = (new Comment($service->getId(), $payload['comment']))
->setParentResourceId($service->getHost()->getId())
->setDate($date);
$this->commentService->addServiceComment($comment, $service);
return $this->view(null, Response::HTTP_NO_CONTENT);
}
/**
* This function will verify that the contact is authorized to add a comment
* on the selected resources
*
* @param Contact $contact
* @param array<string,mixed> $resources
* @return bool
*/
private function hasCommentRightsForResources(Contact $contact, array $resources): bool
{
if ($contact->isAdmin()) {
return true;
}
/**
* Retrieving the current rights of the user for adding comments
*/
$hasHostRights = $contact->hasRole(Contact::ROLE_HOST_ADD_COMMENT);
$hasServiceRights = $contact->hasRole(Contact::ROLE_SERVICE_ADD_COMMENT);
/**
* If the user has no rights at all, do not go further
*/
if (! $hasHostRights && ! $hasServiceRights) {
return false;
}
foreach ($resources as $resource) {
if (
($resource['type'] === ResourceEntity::TYPE_HOST && $hasHostRights)
|| ($resource['type'] === ResourceEntity::TYPE_SERVICE && $hasServiceRights)
|| ($resource['type'] === ResourceEntity::TYPE_META && $hasServiceRights)
) {
continue;
}
return false;
}
return true;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Application/Controller/Monitoring/RealTimeMonitoringServerController.php | centreon/src/Centreon/Application/Controller/Monitoring/RealTimeMonitoringServerController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Centreon\Application\Controller\Monitoring;
use Centreon\Application\Controller\AbstractController;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\MonitoringServer\Exception\RealTimeMonitoringServerException;
use Centreon\Domain\MonitoringServer\UseCase\RealTimeMonitoringServer\FindRealTimeMonitoringServers;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Centreon\Infrastructure\MonitoringServer\API\Model\RealTimeMonitoringServerFactory;
use FOS\RestBundle\View\View;
/**
* This class is designed to provide APIs for the context of RealTime Monitoring Servers.
*
* @package Centreon\Application\Controller\RealTimeMonitoringServer\Controller
*/
class RealTimeMonitoringServerController extends AbstractController
{
use LoggerTrait;
/**
* @param RequestParametersInterface $requestParameters
* @param FindRealTimeMonitoringServers $findRealTimeMonitoringServers
*
* @throws RealTimeMonitoringServerException
* @throws \Throwable
* @return View
*/
public function findRealTimeMonitoringServers(
RequestParametersInterface $requestParameters,
FindRealTimeMonitoringServers $findRealTimeMonitoringServers,
): View {
$this->denyAccessUnlessGrantedForApiRealtime();
$response = $findRealTimeMonitoringServers->execute();
return $this->view(
[
'result' => RealTimeMonitoringServerFactory::createFromResponse($response),
'meta' => $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/Centreon/Application/Controller/Monitoring/SubmitResultController.php | centreon/src/Centreon/Application/Controller/Monitoring/SubmitResultController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Centreon\Application\Controller\Monitoring;
use Centreon\Application\Controller\AbstractController;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Exception\EntityNotFoundException;
use Centreon\Domain\Monitoring\Resource as ResourceEntity;
use Centreon\Domain\Monitoring\SubmitResult\Interfaces\SubmitResultServiceInterface;
use Centreon\Domain\Monitoring\SubmitResult\SubmitResult;
use Exception;
use FOS\RestBundle\View\View;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class SubmitResultController extends AbstractController
{
private const SUBMIT_RESULT_RESOURCES_PAYLOAD_VALIDATION_FILE
= __DIR__ . '/../../../../../config/json_validator/latest/Centreon/SubmitResult/SubmitResultResources.json';
private const SUBMIT_SINGLE_RESULT_PAYLOAD_VALIDATION_FILE
= __DIR__ . '/../../../../../config/json_validator/latest/Centreon/SubmitResult/SubmitResult.json';
/**
* submitResult
*
* @var SubmitResultServiceInterface
*/
private $submitResultService;
/**
* @param SubmitResultServiceInterface $submitResultService
*/
public function __construct(SubmitResultServiceInterface $submitResultService)
{
$this->submitResultService = $submitResultService;
}
/**
* Entry point to submit result to multiple hosts.
*
* @param Request $request
* @throws Exception
* @throws \InvalidArgumentException
* @return View
*/
public function submitResultResources(
Request $request,
): View {
$this->denyAccessUnlessGrantedForApiRealtime();
/**
* @var Contact $contact
*/
$contact = $this->getUser();
$this->submitResultService->filterByContact($contact);
// Validate the content of the POST request against the JSON schema validator
$payload = $this->validateAndRetrieveDataSent($request, self::SUBMIT_RESULT_RESOURCES_PAYLOAD_VALIDATION_FILE);
/**
* If user has no rights to submit result for host and/or service
* return view with unauthorized HTTP header response
*/
if (! $this->hasSubmitResultRightsForResources($contact, $payload['resources'])) {
return $this->view(null, Response::HTTP_UNAUTHORIZED);
}
foreach ($payload['resources'] as $resource) {
$result = (new SubmitResult($resource['id'], $resource['status']))
->setOutput($resource['output'])
->setPerformanceData($resource['performance_data']);
try {
if ($resource['type'] === ResourceEntity::TYPE_SERVICE) {
$result->setParentResourceId($resource['parent']['id']);
$this->submitResultService
->submitServiceResult($result);
} elseif ($resource['type'] === ResourceEntity::TYPE_HOST) {
$this->submitResultService
->submitHostResult($result);
} elseif ($resource['type'] === ResourceEntity::TYPE_META) {
$this->submitResultService
->submitMetaServiceResult($result);
}
} catch (EntityNotFoundException $e) {
throw $e;
}
}
return $this->view(null, Response::HTTP_NO_CONTENT);
}
/**
* Entry point to submit result to a host.
*
* @param Request $request
* @param int $hostId ID of the host
* @throws Exception
* @throws \InvalidArgumentException
* @return View
*/
public function submitResultHost(
Request $request,
int $hostId,
): View {
$this->denyAccessUnlessGrantedForApiRealtime();
/**
* @var Contact $contact
*/
$contact = $this->getUser();
if (! $contact->isAdmin() && ! $contact->hasRole(Contact::ROLE_HOST_SUBMIT_RESULT)) {
return $this->view(null, Response::HTTP_UNAUTHORIZED);
}
// Validate the content of the POST request against the JSON schema validator
$payload = $this->validateAndRetrieveDataSent($request, self::SUBMIT_SINGLE_RESULT_PAYLOAD_VALIDATION_FILE);
if ($payload !== []) {
/**
* At this point we made sure that the mapping will work since we validate
* the JSON sent with the JSON validator.
*/
$result = (new SubmitResult($hostId, $payload['status']))
->setOutput($payload['output'])
->setPerformanceData($payload['performance_data']);
$this->submitResultService
->filterByContact($contact)
->submitHostResult($result);
}
return $this->view(null, Response::HTTP_NO_CONTENT);
}
/**
* Entry point to submit result to a service.
*
* @param Request $request
* @param int $hostId ID of service parent (host)
* @param int $serviceId ID of the service
* @throws Exception
* @throws \InvalidArgumentException
* @return View
*/
public function submitResultService(
Request $request,
int $hostId,
int $serviceId,
): View {
$this->denyAccessUnlessGrantedForApiRealtime();
/**
* @var Contact $contact
*/
$contact = $this->getUser();
if (! $contact->isAdmin() && ! $contact->hasRole(Contact::ROLE_SERVICE_SUBMIT_RESULT)) {
return $this->view(null, Response::HTTP_UNAUTHORIZED);
}
// Validate the content of the POST request against the JSON schema validator
$payload = $this->validateAndRetrieveDataSent($request, self::SUBMIT_SINGLE_RESULT_PAYLOAD_VALIDATION_FILE);
if ($payload !== []) {
$result = (new SubmitResult($serviceId, $payload['status']))
->setOutput($payload['output'])
->setPerformanceData($payload['performance_data'])
->setParentResourceId($hostId);
$this->submitResultService
->filterByContact($contact)
->submitServiceResult($result);
}
return $this->view(null, Response::HTTP_NO_CONTENT);
}
/**
* Check if all resources provided can be submitted a result
* by the current user.
*
* @param Contact $contact
* @param array<string,mixed> $resources
* @return bool
*/
private function hasSubmitResultRightsForResources(Contact $contact, array $resources): bool
{
if ($contact->isAdmin()) {
return true;
}
/**
* Retrieving the current submit result rights of the user.
*/
$hasHostRights = $contact->hasRole(Contact::ROLE_HOST_SUBMIT_RESULT);
$hasServiceRights = $contact->hasRole(Contact::ROLE_SERVICE_SUBMIT_RESULT);
foreach ($resources as $resource) {
if (
($resource['type'] === ResourceEntity::TYPE_HOST && $hasHostRights)
|| ($resource['type'] === ResourceEntity::TYPE_SERVICE && $hasServiceRights)
|| ($resource['type'] === ResourceEntity::TYPE_META && $hasServiceRights)
) {
continue;
}
return false;
}
return true;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Application/Controller/Administration/ParametersController.php | centreon/src/Centreon/Application/Controller/Administration/ParametersController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Centreon\Application\Controller\Administration;
use Centreon\Application\Controller\AbstractController;
use Centreon\Domain\Option\Interfaces\OptionServiceInterface;
use FOS\RestBundle\View\View;
use Symfony\Component\Security\Http\Attribute\IsGranted;
/**
* Used to get global parameters
*
* @package Centreon\Application\Controller
*/
class ParametersController extends AbstractController
{
private const DEFAULT_DOWNTIME_DURATION = 'monitoring_dwt_duration';
private const DEFAULT_DOWNTIME_DURATION_SCALE = 'monitoring_dwt_duration_scale';
private const DEFAULT_REFRESH_INTERVAL = 'AjaxTimeReloadMonitoring';
private const DEFAULT_STATISTICS_REFRESH_INTERVAL = 'AjaxTimeReloadStatistic';
private const DEFAULT_ACKNOWLEDGEMENT_STICKY = 'monitoring_ack_sticky';
private const DEFAULT_ACKNOWLEDGEMENT_PERSISTENT = 'monitoring_ack_persistent';
private const DEFAULT_ACKNOWLEDGEMENT_NOTIFY = 'monitoring_ack_notify';
private const DEFAULT_ACKNOWLEDGEMENT_WITH_SERVICES = 'monitoring_ack_svc';
private const DEFAULT_ACKNOWLEDGEMENT_FORCE_ACTIVE_CHECKS = 'monitoring_ack_active_checks';
private const DEFAULT_DOWNTIME_FIXED = 'monitoring_dwt_fixed';
private const DEFAULT_DOWNTIME_WITH_SERVICES = 'monitoring_dwt_svc';
private const RESOURCE_STATUS_SEARCH_MODE = 'resource_status_search_mode';
/**
* Needed to make response "more readable"
*/
private const KEY_NAME_CONCORDANCE = [
self::DEFAULT_REFRESH_INTERVAL => 'monitoring_default_refresh_interval',
self::DEFAULT_STATISTICS_REFRESH_INTERVAL => 'statistics_default_refresh_interval',
self::DEFAULT_DOWNTIME_DURATION => 'monitoring_default_downtime_duration',
self::DEFAULT_ACKNOWLEDGEMENT_STICKY => 'monitoring_default_acknowledgement_sticky',
self::DEFAULT_ACKNOWLEDGEMENT_PERSISTENT => 'monitoring_default_acknowledgement_persistent',
self::DEFAULT_ACKNOWLEDGEMENT_NOTIFY => 'monitoring_default_acknowledgement_notify',
self::DEFAULT_ACKNOWLEDGEMENT_WITH_SERVICES => 'monitoring_default_acknowledgement_with_services',
self::DEFAULT_ACKNOWLEDGEMENT_FORCE_ACTIVE_CHECKS => 'monitoring_default_acknowledgement_force_active_checks',
self::DEFAULT_DOWNTIME_FIXED => 'monitoring_default_downtime_fixed',
self::DEFAULT_DOWNTIME_WITH_SERVICES => 'monitoring_default_downtime_with_services',
self::RESOURCE_STATUS_SEARCH_MODE => 'is_resource_status_full_search_enabled',
];
public function __construct(
private OptionServiceInterface $optionService,
) {
}
/**
* Entry point to get global parameters stored in options table
*
* @return View
*/
#[IsGranted('IS_AUTHENTICATED', message: 'You are not allowed to access this resource.')]
public function getParameters(): View
{
$parameters = [];
$downtimeDuration = '';
$downtimeScale = '';
$refreshInterval = '';
$statisticsRefreshInterval = '';
$isAcknowledgementPersistent = true;
$isAcknowledgementSticky = true;
$isAcknowledgementNotify = false;
$isAcknowledgementWithServices = true;
$isAcknowledgementForceActiveChecks = true;
$isDowntimeFixed = true;
$isDowntimeWithServices = true;
$isResourceStatusFullSearchEnabled = true;
$options = $this->optionService->findSelectedOptions([
self::DEFAULT_REFRESH_INTERVAL,
self::DEFAULT_STATISTICS_REFRESH_INTERVAL,
self::DEFAULT_ACKNOWLEDGEMENT_STICKY,
self::DEFAULT_ACKNOWLEDGEMENT_PERSISTENT,
self::DEFAULT_ACKNOWLEDGEMENT_NOTIFY,
self::DEFAULT_ACKNOWLEDGEMENT_WITH_SERVICES,
self::DEFAULT_ACKNOWLEDGEMENT_FORCE_ACTIVE_CHECKS,
self::DEFAULT_DOWNTIME_DURATION,
self::DEFAULT_DOWNTIME_DURATION_SCALE,
self::DEFAULT_DOWNTIME_FIXED,
self::DEFAULT_DOWNTIME_WITH_SERVICES,
self::RESOURCE_STATUS_SEARCH_MODE,
]);
foreach ($options as $option) {
switch ($option->getName()) {
case self::DEFAULT_DOWNTIME_DURATION:
$downtimeDuration = $option->getValue();
break;
case self::DEFAULT_DOWNTIME_DURATION_SCALE:
$downtimeScale = $option->getValue();
break;
case self::DEFAULT_REFRESH_INTERVAL:
$refreshInterval = $option->getValue();
break;
case self::DEFAULT_STATISTICS_REFRESH_INTERVAL:
$statisticsRefreshInterval = $option->getValue();
break;
case self::DEFAULT_ACKNOWLEDGEMENT_PERSISTENT:
$isAcknowledgementPersistent = (int) $option->getValue() === 1;
break;
case self::DEFAULT_ACKNOWLEDGEMENT_STICKY:
$isAcknowledgementSticky = (int) $option->getValue() === 1;
break;
case self::DEFAULT_ACKNOWLEDGEMENT_NOTIFY:
$isAcknowledgementNotify = (int) $option->getValue() === 1;
break;
case self::DEFAULT_ACKNOWLEDGEMENT_WITH_SERVICES:
$isAcknowledgementWithServices = (int) $option->getValue() === 1;
break;
case self::DEFAULT_ACKNOWLEDGEMENT_FORCE_ACTIVE_CHECKS:
$isAcknowledgementForceActiveChecks = (int) $option->getValue() === 1;
break;
case self::DEFAULT_DOWNTIME_WITH_SERVICES:
$isDowntimeWithServices = (int) $option->getValue() === 1;
break;
case self::DEFAULT_DOWNTIME_FIXED:
$isDowntimeFixed = (int) $option->getValue() === 1;
break;
case self::RESOURCE_STATUS_SEARCH_MODE:
$isResourceStatusFullSearchEnabled = (int) $option->getValue() === 1;
break;
default:
break;
}
}
$parameters[self::KEY_NAME_CONCORDANCE[self::DEFAULT_DOWNTIME_DURATION]]
= $this->convertToSeconds((int) $downtimeDuration, $downtimeScale);
$parameters[self::KEY_NAME_CONCORDANCE[self::DEFAULT_REFRESH_INTERVAL]] = (int) $refreshInterval;
$parameters[self::KEY_NAME_CONCORDANCE[self::DEFAULT_STATISTICS_REFRESH_INTERVAL]]
= (int) $statisticsRefreshInterval;
$parameters[self::KEY_NAME_CONCORDANCE[self::DEFAULT_ACKNOWLEDGEMENT_PERSISTENT]]
= $isAcknowledgementPersistent;
$parameters[self::KEY_NAME_CONCORDANCE[self::DEFAULT_ACKNOWLEDGEMENT_STICKY]] = $isAcknowledgementSticky;
$parameters[self::KEY_NAME_CONCORDANCE[self::DEFAULT_ACKNOWLEDGEMENT_NOTIFY]] = $isAcknowledgementNotify;
$parameters[self::KEY_NAME_CONCORDANCE[self::DEFAULT_ACKNOWLEDGEMENT_WITH_SERVICES]]
= $isAcknowledgementWithServices;
$parameters[self::KEY_NAME_CONCORDANCE[self::DEFAULT_ACKNOWLEDGEMENT_FORCE_ACTIVE_CHECKS]]
= $isAcknowledgementForceActiveChecks;
$parameters[self::KEY_NAME_CONCORDANCE[self::DEFAULT_DOWNTIME_FIXED]] = $isDowntimeFixed;
$parameters[self::KEY_NAME_CONCORDANCE[self::DEFAULT_DOWNTIME_WITH_SERVICES]] = $isDowntimeWithServices;
$parameters[self::KEY_NAME_CONCORDANCE[self::RESOURCE_STATUS_SEARCH_MODE]] = $isResourceStatusFullSearchEnabled;
return $this->view($parameters);
}
/**
* Converts the combination stored in DB into seconds
*
* @param int $duration
* @param string $scale
* @return int
*/
private function convertToSeconds(int $duration, string $scale): int
{
switch ($scale) {
case 'm':
return $duration * 60;
case 'h':
return $duration * 3600;
case 'd':
return $duration * 86400;
default:
return $duration;
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Centreon/Application/Webservice/ImagesWebservice.php | centreon/src/Centreon/Application/Webservice/ImagesWebservice.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace Centreon\Application\Webservice;
use Centreon\Application\DataRepresenter\Response;
use Centreon\Application\Serializer;
use Centreon\Domain\Repository\ImagesRepository;
use Centreon\Infrastructure\Webservice;
use Centreon\ServiceProvider;
/**
* @OA\Tag(name="centreon_images", description="Web Service for Images")
*/
class ImagesWebservice extends Webservice\WebServiceAbstract implements
Webservice\WebserviceAutorizeRestApiInterface
{
use Webservice\DependenciesTrait;
/**
* {@inheritDoc}
*/
public static function getName(): string
{
return 'centreon_images';
}
/**
* {@inheritDoc}
*/
public static function dependencies(): array
{
return [
ServiceProvider::CENTREON_PAGINATION,
];
}
/**
* @OA\Get(
* path="/internal.php?object=centreon_images&action=list",
* description="Get images list",
* tags={"centreon_images"},
* security={{"Session": {}}},
* @OA\Parameter(
* in="query",
* name="object",
* @OA\Schema(
* type="string",
* enum={"centreon_images"},
* default="centreon_images"
* ),
* description="the name of the API object class",
* required=true
* ),
* @OA\Parameter(
* in="query",
* name="action",
* @OA\Schema(
* type="string",
* enum={"list"},
* default="list"
* ),
* description="the name of the action in the API class",
* required=true
* ),
* @OA\Parameter(
* in="query",
* name="name",
* @OA\Schema(
* type="string"
* ),
* description="filter the list by name",
* required=false
* ),
* @OA\Parameter(
* in="query",
* name="id",
* @OA\Schema(
* type="string"
* ),
* description="filter the list by id",
* required=false
* ),
* @OA\Parameter(
* in="query",
* name="offset",
* @OA\Schema(
* type="integer"
* ),
* description="offset",
* required=false
* ),
* @OA\Parameter(
* in="query",
* name="limit",
* @OA\Schema(
* type="integer"
* ),
* description="limit",
* required=false
* ),
* @OA\Response(
* response="200",
* description="OK",
* @OA\JsonContent(
* @OA\Property(
* property="entities",
* type="array",
* @OA\Items(ref="#/components/schemas/ImageEntity")
* ),
* @OA\Property(
* property="pagination",
* ref="#/components/schemas/Pagination"
* )
* )
* )
* )
*
* Get images list
*
* @throws \RestBadRequestException
* @return Response
*/
public function getList(): Response
{
// process request
$request = $this->query();
$limit = isset($request['limit']) ? (int) $request['limit'] : null;
$offset = isset($request['offset']) ? (int) $request['offset'] : null;
$filters = [];
if (isset($request['search']) && $request['search']) {
$filters['search'] = $request['search'];
}
if (isset($request['searchByIds']) && $request['searchByIds']) {
$filters['ids'] = explode(',', $request['searchByIds']);
}
$pagination = $this->services->get(ServiceProvider::CENTREON_PAGINATION);
$pagination->setRepository(ImagesRepository::class);
$pagination->setContext(Serializer\Image\ListContext::context());
$pagination->setFilters($filters);
$pagination->setLimit($limit);
$pagination->setOffset($offset);
return $pagination->getResponse();
}
}
| 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.