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/Resources/Infrastructure/API/CountResources/CountResourcesInput.php
centreon/src/Core/Resources/Infrastructure/API/CountResources/CountResourcesInput.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\Resources\Infrastructure\API\CountResources; use Symfony\Component\Validator\Constraints as Assert; final readonly class CountResourcesInput { public function __construct( #[Assert\NotBlank(message: 'search parameter is required')] #[Assert\Json(message: 'search parameter must be a valid JSON')] public mixed $search, #[Assert\NotNull(message: 'all_pages parameter is required')] #[Assert\Type('bool', message: 'all_pages parameter must be a boolean')] public mixed $allPages, #[Assert\When( expression: 'this.allPages === false', constraints: [ new Assert\Sequentially([ new Assert\NotBlank(message: 'page parameter is required when all_pages is false'), new Assert\Type('int', message: 'page parameter must be an integer'), new Assert\Range( minMessage: 'page parameter must be greater than 1', min: 1 ), ]), ] )] public mixed $page, #[Assert\When( expression: 'this.allPages === false', constraints: [ new Assert\NotBlank(message: 'limit parameter is required when all_pages is false'), new Assert\Type('int', message: 'limit parameter must be an integer'), ] )] public mixed $limit, ) { } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Resources/Infrastructure/API/FindResources/FindResourcesRequestValidator.php
centreon/src/Core/Resources/Infrastructure/API/FindResources/FindResourcesRequestValidator.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\Resources\Infrastructure\API\FindResources; use Centreon\Domain\Log\LoggerTrait; use Centreon\Domain\Monitoring\ResourceFilter; use Centreon\Domain\RequestParameters\RequestParameters; use Core\Domain\RealTime\ResourceTypeInterface; /** * @phpstan-type _RequestParameters array{ * types: list<string>, * states: list<string>, * statuses: list<string>, * hostgroup_names: list<string>, * servicegroup_names: list<string>, * monitoring_server_names: list<string>, * service_category_names: list<string>, * host_category_names: list<string>, * service_severity_names: list<string>, * host_severity_names: list<string>, * host_severity_levels: list<int>, * service_severity_levels: list<int>, * status_types: list<string>, * only_with_performance_data: bool, * only_with_opened_tickets: bool, * ticket_provider_id: int|null * } */ final class FindResourcesRequestValidator { use LoggerTrait; // Query parameters fields. public const PARAM_RESOURCE_TYPE = 'types'; public const PARAM_STATES = 'states'; public const PARAM_STATUSES = 'statuses'; public const PARAM_HOSTGROUP_NAMES = 'hostgroup_names'; public const PARAM_SERVICEGROUP_NAMES = 'servicegroup_names'; public const PARAM_MONITORING_SERVER_NAMES = 'monitoring_server_names'; public const PARAM_SERVICE_CATEGORY_NAMES = 'service_category_names'; public const PARAM_HOST_CATEGORY_NAMES = 'host_category_names'; public const PARAM_SERVICE_SEVERITY_NAMES = 'service_severity_names'; public const PARAM_HOST_SEVERITY_NAMES = 'host_severity_names'; public const PARAM_HOST_SEVERITY_LEVELS = 'host_severity_levels'; public const PARAM_SERVICE_SEVERITY_LEVELS = 'service_severity_levels'; public const PARAM_STATUS_TYPES = 'status_types'; public const PARAM_RESOURCES_ON_PERFORMANCE_DATA_AVAILABILITY = 'only_with_performance_data'; public const PARAM_RESOURCES_WITH_OPENED_TICKETS = 'only_with_opened_tickets'; public const PARAM_OPEN_TICKET_RULE_ID = 'ticket_provider_id'; // Errors Codes for exceptions. public const ERROR_UNKNOWN_PARAMETER = 1; public const ERROR_NOT_A_RESOURCE_TYPE = 2; public const ERROR_NOT_A_STATUS = 3; public const ERROR_NOT_A_STATE = 4; public const ERROR_NOT_A_STATUS_TYPE = 5; public const ERROR_NOT_AN_ARRAY_OF_STRING = 6; public const ERROR_NOT_AN_ARRAY_OF_INTEGER = 7; public const ERROR_NOT_AN_ARRAY = 8; public const ERROR_NOT_A_BOOLEAN = 9; public const ERROR_NO_PROVIDERS = 10; public const ERROR_NOT_A_INT = 11; /** Allowed values for statuses. */ public const ALLOWED_STATUSES = [ ResourceFilter::STATUS_OK, ResourceFilter::STATUS_WARNING, ResourceFilter::STATUS_CRITICAL, ResourceFilter::STATUS_UNKNOWN, ResourceFilter::STATUS_UNREACHABLE, ResourceFilter::STATUS_PENDING, ResourceFilter::STATUS_UP, ResourceFilter::STATUS_DOWN, ]; /** Allowed values for states. */ public const ALLOWED_STATES = [ ResourceFilter::STATE_UNHANDLED_PROBLEMS, ResourceFilter::STATE_RESOURCES_PROBLEMS, ResourceFilter::STATE_IN_DOWNTIME, ResourceFilter::STATE_ACKNOWLEDGED, ResourceFilter::STATE_IN_FLAPPING, ]; /** Allowed values for status types. */ public const ALLOWED_STATUS_TYPES = [ ResourceFilter::HARD_STATUS_TYPE, ResourceFilter::SOFT_STATUS_TYPE, ]; /** @var _RequestParameters */ private const EMPTY_FILTERS = [ self::PARAM_RESOURCE_TYPE => [], self::PARAM_STATES => [], self::PARAM_STATUSES => [], self::PARAM_HOSTGROUP_NAMES => [], self::PARAM_SERVICEGROUP_NAMES => [], self::PARAM_MONITORING_SERVER_NAMES => [], self::PARAM_SERVICE_CATEGORY_NAMES => [], self::PARAM_HOST_CATEGORY_NAMES => [], self::PARAM_SERVICE_SEVERITY_NAMES => [], self::PARAM_HOST_SEVERITY_NAMES => [], self::PARAM_HOST_SEVERITY_LEVELS => [], self::PARAM_SERVICE_SEVERITY_LEVELS => [], self::PARAM_STATUS_TYPES => [], self::PARAM_RESOURCES_ON_PERFORMANCE_DATA_AVAILABILITY => false, self::PARAM_RESOURCES_WITH_OPENED_TICKETS => false, self::PARAM_OPEN_TICKET_RULE_ID => null, ]; /** Query parameters that should be ignored but not forbidden. */ private const IGNORED_PARAMETERS = [ RequestParameters::NAME_FOR_LIMIT, RequestParameters::NAME_FOR_PAGE, RequestParameters::NAME_FOR_SEARCH, RequestParameters::NAME_FOR_SORT, RequestParameters::NAME_FOR_TOTAL, ]; /** Query parameters for export that should be ignored but not forbidden only on export */ private const EXPORT_IGNORED_PARAMETERS = [ 'format', 'columns', 'all_pages', 'max_lines', ]; /** @var array<string> */ private array $resourceTypes; /** * @param \Traversable<ResourceTypeInterface> $resourceTypes * * @throws \InvalidArgumentException */ public function __construct(\Traversable $resourceTypes) { $this->resourceTypes = array_map( static fn (ResourceTypeInterface $resourceType): string => $resourceType->getName(), iterator_to_array($resourceTypes) ); if ($this->resourceTypes === []) { throw new \InvalidArgumentException( 'You must add at least one provider', self::ERROR_NO_PROVIDERS ); } } /** * @return array<string> */ public function getResourceTypes(): array { return $this->resourceTypes; } /** * @param array<mixed> $queryParameters * @param bool $isExport * * @return _RequestParameters */ public function validateAndRetrieveRequestParameters(array $queryParameters, bool $isExport = false): array { $filterData = self::EMPTY_FILTERS; // Do not handle pagination query parameters and check that parameters are handled foreach ($queryParameters as $param => $data) { // skip pagination parameters if (in_array($param, self::IGNORED_PARAMETERS, true)) { continue; } // export parameters are allowed and ignored if ($isExport && in_array($param, self::EXPORT_IGNORED_PARAMETERS, true)) { continue; } // do not allow query parameters not managed if (! array_key_exists($param, $filterData)) { throw new \InvalidArgumentException( 'Request parameter provided not handled', self::ERROR_UNKNOWN_PARAMETER ); } $value = $this->tryJsonDecodeParameterValue($data); switch ($param) { case self::PARAM_RESOURCE_TYPE: $filterData[$param] = $this->ensureResourceTypeFilter($param, $value); break; case self::PARAM_STATES: $filterData[$param] = $this->ensureStatesFilter($param, $value); break; case self::PARAM_STATUSES: $filterData[$param] = $this->ensureStatusesFilter($param, $value); break; case self::PARAM_HOSTGROUP_NAMES: case self::PARAM_SERVICEGROUP_NAMES: case self::PARAM_MONITORING_SERVER_NAMES: case self::PARAM_SERVICE_CATEGORY_NAMES: case self::PARAM_HOST_CATEGORY_NAMES: case self::PARAM_SERVICE_SEVERITY_NAMES: case self::PARAM_HOST_SEVERITY_NAMES: $filterData[$param] = $this->ensureArrayOfString($param, $value); break; case self::PARAM_HOST_SEVERITY_LEVELS: case self::PARAM_SERVICE_SEVERITY_LEVELS: $filterData[$param] = $this->ensureArrayOfInteger($param, $value); break; case self::PARAM_STATUS_TYPES: $filterData[$param] = $this->ensureStatusTypes($param, $value); break; case self::PARAM_RESOURCES_ON_PERFORMANCE_DATA_AVAILABILITY: case self::PARAM_RESOURCES_WITH_OPENED_TICKETS: $filterData[$param] = $this->ensureBoolean($param, $value); break; case self::PARAM_OPEN_TICKET_RULE_ID: $filterData[$param] = $this->ensureInt($param, $value); break; } } return $filterData; } /** * The input data can be JSON injected in the parameter value. * * @param mixed $parameterValue * * @return mixed */ private function tryJsonDecodeParameterValue(mixed $parameterValue): mixed { try { return is_string($parameterValue) ? json_decode($parameterValue, true, 512, JSON_THROW_ON_ERROR) : $parameterValue; } catch (\JsonException) { return $parameterValue; } } /** * Ensures that resource types filter provided in the payload are supported. * * @param string $parameterName * @param mixed $values * * @throws \InvalidArgumentException * * @return list<string> */ private function ensureResourceTypeFilter(string $parameterName, mixed $values): array { $types = []; foreach ($this->ensureArrayOfString($parameterName, $values) as $string) { if (! in_array($string, $this->resourceTypes, true)) { $message = sprintf( 'Value provided for %s parameter is not supported (was: %s)', $parameterName, $string ); throw new \InvalidArgumentException($message, self::ERROR_NOT_A_RESOURCE_TYPE); } $types[] = $string; } return $types; } /** * Ensures that statuses filter provided in the payload are supported. * * @param string $parameterName * @param mixed $values * * @throws \InvalidArgumentException * * @return list<value-of<self::ALLOWED_STATUSES>> */ private function ensureStatusesFilter(string $parameterName, mixed $values): array { $statuses = []; foreach ($this->ensureArrayOfString($parameterName, $values) as $string) { if (! in_array($string, self::ALLOWED_STATUSES, true)) { $message = sprintf( 'Value provided for %s parameter is not supported (was: %s)', $parameterName, $string ); throw new \InvalidArgumentException($message, self::ERROR_NOT_A_STATUS); } $statuses[] = $string; } return $statuses; } /** * Ensures that states filter provided in the payload are supported. * * @param string $parameterName * @param mixed $values * * @throws \InvalidArgumentException * * @return list<value-of<self::ALLOWED_STATES>> */ private function ensureStatesFilter(string $parameterName, mixed $values): array { $states = []; foreach ($this->ensureArrayOfString($parameterName, $values) as $string) { if (! in_array($string, self::ALLOWED_STATES, true)) { $message = sprintf( 'Value provided for %s parameter is not supported (was: %s)', $parameterName, $string ); throw new \InvalidArgumentException($message, self::ERROR_NOT_A_STATE); } $states[] = $string; } return $states; } /** * Ensures that status types filter provided in the payload are supported. * * @param string $parameterName * @param mixed $values * * @throws \InvalidArgumentException * * @return list<value-of<self::ALLOWED_STATUS_TYPES>> */ private function ensureStatusTypes(string $parameterName, mixed $values): array { $statusTypes = []; foreach ($this->ensureArrayOfString($parameterName, $values) as $string) { if (! in_array($string, self::ALLOWED_STATUS_TYPES, true)) { $message = sprintf( 'Value provided for %s parameter is not supported (was: %s)', $parameterName, $string ); throw new \InvalidArgumentException($message, self::ERROR_NOT_A_STATUS_TYPE); } $statusTypes[] = $string; } return $statusTypes; } /** * Ensures that array provided is only made of strings. * * @param string $parameterName * @param mixed $values * * @throws \InvalidArgumentException * * @return list<string> */ private function ensureArrayOfString(string $parameterName, mixed $values): array { $strings = []; foreach ($this->ensureArray($parameterName, $values) as $value) { if (! is_string($value)) { $message = sprintf('Values provided for %s should only be strings', $parameterName); $this->error($message); throw new \InvalidArgumentException($message, self::ERROR_NOT_AN_ARRAY_OF_STRING); } $strings[] = $value; } return $strings; } /** * Ensures that array provided is only made of integers. * * @param string $parameterName * @param mixed $values * * @throws \InvalidArgumentException * * @return list<int> */ private function ensureArrayOfInteger(string $parameterName, mixed $values): array { $integers = []; foreach ($this->ensureArray($parameterName, $values) as $value) { if (is_string($value) && ctype_digit($value)) { // Cast strings which are string-integers. $value = (int) $value; } elseif (! is_int($value)) { $message = sprintf('Values provided for %s should only be integers', $parameterName); $this->error($message); throw new \InvalidArgumentException($message, self::ERROR_NOT_AN_ARRAY_OF_INTEGER); } $integers[] = $value; } return $integers; } /** * Ensures that value provided is an array. * * @param string $parameterName * @param mixed $value * * @throws \InvalidArgumentException * * @return array<mixed> */ private function ensureArray(string $parameterName, mixed $value): array { if (! is_array($value)) { $message = sprintf('Value provided for %s is not correctly formatted. Array expected.', $parameterName); throw new \InvalidArgumentException($message, self::ERROR_NOT_AN_ARRAY); } return $value; } /** * Ensures that value provided is a boolean. * * @param string $parameterName * @param mixed $value * * @throws \InvalidArgumentException * * @return bool */ private function ensureBoolean(string $parameterName, mixed $value): bool { if (! is_bool($value)) { throw new \InvalidArgumentException( sprintf('Value provided for %s is not correctly formatted. Boolean expected', $parameterName), self::ERROR_NOT_A_BOOLEAN ); } return $value; } /** * Ensures that value provided is a integer. * * @param string $parameterName * @param mixed $value * * @throws \InvalidArgumentException * * @return int */ private function ensureInt(string $parameterName, mixed $value): int { if (! is_int($value)) { throw new \InvalidArgumentException( sprintf('Value provided for %s is not correctly formatted. Integer expected', $parameterName), self::ERROR_NOT_A_INT ); } return $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/Resources/Infrastructure/API/FindResources/FindResourcesController.php
centreon/src/Core/Resources/Infrastructure/API/FindResources/FindResourcesController.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\Resources\Infrastructure\API\FindResources; use Centreon\Application\Controller\AbstractController; use Centreon\Domain\Monitoring\ResourceFilter; use Core\Resources\Application\UseCase\FindResources\FindResources; use Core\Resources\Infrastructure\API\FindResources\FindResourcesRequestValidator as RequestValidator; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Security\Core\Exception\AccessDeniedException; /** * @phpstan-import-type _RequestParameters from RequestValidator */ final class FindResourcesController extends AbstractController { public function __construct(private readonly RequestValidator $validator) { } /** * @param FindResources $useCase * @param FindResourcesPresenter $presenter * @param Request $request * * @throws AccessDeniedException * * @return Response */ public function __invoke( FindResources $useCase, FindResourcesPresenter $presenter, Request $request, ): Response { $this->denyAccessUnlessGrantedForApiRealtime(); $filter = $this->validator->validateAndRetrieveRequestParameters($request->query->all()); $useCase($presenter, $this->createResourceFilter($filter)); return $presenter->show(); } /** * @param _RequestParameters $filter * * @return ResourceFilter */ private function createResourceFilter(array $filter): ResourceFilter { return (new ResourceFilter()) ->setTypes($filter[RequestValidator::PARAM_RESOURCE_TYPE]) ->setStates($filter[RequestValidator::PARAM_STATES]) ->setStatuses($filter[RequestValidator::PARAM_STATUSES]) ->setStatusTypes($filter[RequestValidator::PARAM_STATUS_TYPES]) ->setServicegroupNames($filter[RequestValidator::PARAM_SERVICEGROUP_NAMES]) ->setServiceCategoryNames($filter[RequestValidator::PARAM_SERVICE_CATEGORY_NAMES]) ->setServiceSeverityNames($filter[RequestValidator::PARAM_SERVICE_SEVERITY_NAMES]) ->setServiceSeverityLevels($filter[RequestValidator::PARAM_SERVICE_SEVERITY_LEVELS]) ->setHostgroupNames($filter[RequestValidator::PARAM_HOSTGROUP_NAMES]) ->setHostCategoryNames($filter[RequestValidator::PARAM_HOST_CATEGORY_NAMES]) ->setHostSeverityNames($filter[RequestValidator::PARAM_HOST_SEVERITY_NAMES]) ->setMonitoringServerNames($filter[RequestValidator::PARAM_MONITORING_SERVER_NAMES]) ->setHostSeverityLevels($filter[RequestValidator::PARAM_HOST_SEVERITY_LEVELS]) ->setOnlyWithPerformanceData($filter[RequestValidator::PARAM_RESOURCES_ON_PERFORMANCE_DATA_AVAILABILITY]) ->setOnlyWithTicketsOpened($filter[RequestValidator::PARAM_RESOURCES_WITH_OPENED_TICKETS]) ->setRuleId($filter[RequestValidator::PARAM_OPEN_TICKET_RULE_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/Resources/Infrastructure/API/FindResources/FindResourcesPresenter.php
centreon/src/Core/Resources/Infrastructure/API/FindResources/FindResourcesPresenter.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\Resources\Infrastructure\API\FindResources; use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface; use Core\Application\Common\UseCase\AbstractPresenter; use Core\Application\Common\UseCase\ErrorResponse; use Core\Application\Common\UseCase\ResponseStatusInterface; use Core\Common\Infrastructure\ExceptionLogger\ExceptionLogger; use Core\Infrastructure\Common\Api\HttpUrlTrait; use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface; use Core\Infrastructure\Common\Presenter\PresenterTrait; use Core\Infrastructure\RealTime\Hypermedia\HypermediaCreator; use Core\Resources\Application\UseCase\FindResources\FindResourcesPresenterInterface; use Core\Resources\Application\UseCase\FindResources\FindResourcesResponse; use Core\Resources\Application\UseCase\FindResources\Response\ResourceResponseDto; use Core\Resources\Infrastructure\API\ExtraDataNormalizer\ExtraDataNormalizerInterface; /** * Class * * @class FindResourcesPresenter * @package Core\Resources\Infrastructure\API\FindResources */ class FindResourcesPresenter extends AbstractPresenter implements FindResourcesPresenterInterface { use HttpUrlTrait; use PresenterTrait; private const IMAGE_DIRECTORY = '/img/media/'; private const SERVICE_RESOURCE_TYPE = 'service'; /** * @param HypermediaCreator $hypermediaCreator * @param RequestParametersInterface $requestParameters * @param PresenterFormatterInterface $presenterFormatter * @param \Traversable<ExtraDataNormalizerInterface> $extraDataNormalizers * @param ExceptionLogger $exceptionLogger */ public function __construct( private readonly HypermediaCreator $hypermediaCreator, protected RequestParametersInterface $requestParameters, PresenterFormatterInterface $presenterFormatter, private readonly \Traversable $extraDataNormalizers, private readonly ExceptionLogger $exceptionLogger, ) { parent::__construct($presenterFormatter); } /** * @param FindResourcesResponse|ResponseStatusInterface $response * * @return void */ public function presentResponse(FindResourcesResponse|ResponseStatusInterface $response): void { if ($response instanceof ResponseStatusInterface) { if ($response instanceof ErrorResponse && ! is_null($response->getException())) { $this->exceptionLogger->log($response->getException()); } $this->setResponseStatus($response); return; } $result = []; foreach ($response->resources as $resource) { $parentResource = ($resource->parent !== null && $resource->parent->resourceId !== null) ? [ 'uuid' => $resource->parent->uuid, 'id' => $resource->parent->id, 'name' => $resource->parent->name, 'type' => $resource->parent->type, 'short_type' => $resource->parent->shortType, 'status' => [ 'code' => $resource->parent->status?->code, 'name' => $resource->parent->status?->name, 'severity_code' => $resource->parent->status?->severityCode, ], 'alias' => $resource->parent->alias, 'fqdn' => $resource->parent->fqdn, 'monitoring_server_name' => $resource->parent->monitoringServerName, 'extra' => $this->normalizeExtraDataForResource( $resource->parent->resourceId, $response->extraData, ), ] : null; $duration = $resource->lastStatusChange !== null ? \CentreonDuration::toString(time() - $resource->lastStatusChange->getTimestamp()) : null; $lastCheck = $resource->lastCheck !== null ? \CentreonDuration::toString(time() - $resource->lastCheck->getTimestamp()) : null; $severity = $resource->severity !== null ? [ 'id' => $resource->severity->id, 'name' => $resource->severity->name, 'level' => $resource->severity->level, 'type' => $resource->severity->type, 'icon' => [ 'id' => $resource->severity->icon->id, 'name' => $resource->severity->icon->name, 'url' => $this->generateNormalizedIconUrl($resource->severity->icon->url), ], ] : null; $icon = $resource->icon !== null ? [ 'id' => $resource->icon->id, 'name' => $resource->icon->name, 'url' => $this->generateNormalizedIconUrl($resource->icon->url), ] : null; $parameters = [ 'type' => $resource->type, 'serviceId' => $resource->serviceId, 'hostId' => $resource->hostId, 'hasGraphData' => $resource->hasGraphData, 'internalId' => $resource->internalId, ]; $endpoints = $this->hypermediaCreator->createEndpoints($parameters); $links = [ 'endpoints' => [ 'details' => $endpoints['details'], 'timeline' => $endpoints['timeline'], 'status_graph' => $endpoints['status_graph'] ?? null, 'performance_graph' => $endpoints['performance_graph'] ?? null, 'acknowledgement' => $endpoints['acknowledgement'], 'downtime' => $endpoints['downtime'], 'check' => $endpoints['check'], 'forced_check' => $endpoints['forced_check'], 'metrics' => $endpoints['metrics'] ?? null, ], 'uris' => $this->hypermediaCreator->createInternalUris($parameters), 'externals' => [ 'action_url' => $resource->actionUrl !== null ? $this->generateUrlWithMacrosResolved($resource->actionUrl, $resource) : $resource->actionUrl, 'notes' => [ 'label' => $resource->notes?->label, 'url' => $resource->notes?->url !== null ? $this->generateUrlWithMacrosResolved($resource->notes->url, $resource) : $resource->notes?->url, ], ], ]; $result[] = [ 'uuid' => $resource->uuid, 'duration' => $duration, 'last_check' => $lastCheck, 'short_type' => $resource->shortType, 'id' => $resource->id, 'type' => $resource->type, 'name' => $resource->name, 'alias' => $resource->alias, 'fqdn' => $resource->fqdn, 'host_id' => $resource->hostId, 'service_id' => $resource->serviceId, 'icon' => $icon, 'monitoring_server_name' => $resource->monitoringServerName, 'parent' => $parentResource, 'status' => [ 'code' => $resource->status?->code, 'name' => $resource->status?->name, 'severity_code' => $resource->status?->severityCode, ], 'is_in_downtime' => $resource->isInDowntime, 'is_acknowledged' => $resource->isAcknowledged, 'is_in_flapping' => $resource->isInFlapping, 'percent_state_change' => $resource->percentStateChange, 'has_active_checks_enabled' => $resource->withActiveChecks, 'has_passive_checks_enabled' => $resource->withPassiveChecks, 'last_status_change' => $this->formatDateToIso8601($resource->lastStatusChange), 'tries' => $resource->tries, 'information' => $resource->information, 'performance_data' => null, 'is_notification_enabled' => $resource->areNotificationsEnabled, 'severity' => $severity, 'links' => $links, 'extra' => $resource->resourceId !== null ? $this->normalizeExtraDataForResource($resource->resourceId, $response->extraData) : [], ]; } $this->present([ 'result' => $result, 'meta' => $this->requestParameters->toArray(), ]); } /** * @param int $resourceId * @param array<string, array<mixed, mixed>> $extraData * * @return mixed[] */ private function normalizeExtraDataForResource(int $resourceId, array $extraData): array { $data = []; foreach ($extraData as $sourceName => $sourceData) { foreach (iterator_to_array($this->extraDataNormalizers) as $provider) { if ($provider->isValidFor($sourceName)) { if (array_key_exists($resourceId, $sourceData)) { $data[$sourceName] = $provider->normalizeExtraDataForResource( $sourceData[$resourceId], ); } } } } return $data; } /** * @param string $url * @param ResourceResponseDto $resource * * @return string */ private function generateUrlWithMacrosResolved(string $url, ResourceResponseDto $resource): string { $isServiceTypedResource = $resource->type === self::SERVICE_RESOURCE_TYPE; $macrosConcordanceArray = [ '$HOSTADDRESS$' => $isServiceTypedResource ? $resource->parent?->fqdn : $resource->fqdn, '$HOSTNAME$' => $isServiceTypedResource ? $resource->parent?->name : $resource->name, '$HOSTSTATE$' => $isServiceTypedResource ? $resource->parent?->status?->name : $resource->status?->name, '$HOSTSTATEID$' => $isServiceTypedResource ? (string) $resource->parent?->status?->code : (string) $resource->status?->code, '$HOSTALIAS$' => $isServiceTypedResource ? $resource->parent?->alias : $resource->alias, '$SERVICEDESC$' => $isServiceTypedResource ? $resource->name : '', '$SERVICESTATE$' => $isServiceTypedResource ? $resource->status?->name : '', '$SERVICESTATEID$' => $isServiceTypedResource ? (string) $resource->status?->code : '', ]; return str_replace(array_keys($macrosConcordanceArray), array_values($macrosConcordanceArray), $url); } /** * @param string|null $url * * @return string|null */ private function generateNormalizedIconUrl(?string $url): ?string { return $url !== null ? $this->getBaseUri() . self::IMAGE_DIRECTORY . $url : $url; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Resources/Infrastructure/API/FindResourcesByParent/FindResourcesByParentPresenter.php
centreon/src/Core/Resources/Infrastructure/API/FindResourcesByParent/FindResourcesByParentPresenter.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\Resources\Infrastructure\API\FindResourcesByParent; use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface; use Core\Application\Common\UseCase\AbstractPresenter; use Core\Application\Common\UseCase\ResponseStatusInterface; use Core\Infrastructure\Common\Api\HttpUrlTrait; use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface; use Core\Infrastructure\Common\Presenter\PresenterTrait; use Core\Infrastructure\RealTime\Hypermedia\HypermediaCreator; use Core\Resources\Application\UseCase\FindResources\Response\ResourceResponseDto; use Core\Resources\Application\UseCase\FindResourcesByParent\FindResourcesByParentPresenterInterface; use Core\Resources\Application\UseCase\FindResourcesByParent\FindResourcesByParentResponse; use Core\Resources\Application\UseCase\FindResourcesByParent\Response\ResourcesByParentResponseDto; use Core\Resources\Infrastructure\API\ExtraDataNormalizer\ExtraDataNormalizerInterface; class FindResourcesByParentPresenter extends AbstractPresenter implements FindResourcesByParentPresenterInterface { use HttpUrlTrait; use PresenterTrait; private const IMAGE_DIRECTORY = '/img/media/'; private const HOST_RESOURCE_TYPE = 'host'; private const SERVICE_RESOURCE_TYPE = 'service'; /** * @param HypermediaCreator $hypermediaCreator * @param RequestParametersInterface $requestParameters * @param PresenterFormatterInterface $presenterFormatter * @param \Traversable<ExtraDataNormalizerInterface> $extraDataNormalizers */ public function __construct( private readonly HypermediaCreator $hypermediaCreator, protected RequestParametersInterface $requestParameters, PresenterFormatterInterface $presenterFormatter, private readonly \Traversable $extraDataNormalizers, ) { parent::__construct($presenterFormatter); } /** * @param FindResourcesByParentResponse|ResponseStatusInterface $response */ public function presentResponse(FindResourcesByParentResponse|ResponseStatusInterface $response): void { if ($response instanceof FindResourcesByParentResponse) { $result = []; foreach ($response->resources as $resourcesByParent) { $parent = $this->createResourceFromResponse($resourcesByParent->parent, $response->extraData); $parent['children']['resources'] = $this->createChildrenFromResponse($resourcesByParent->children, $response->extraData); $parent['children']['total'] = $resourcesByParent->total; $parent['children']['status_count'] = $this->createStatusesCountFromResponse($resourcesByParent); $result[] = $parent; } $this->present([ 'result' => $result, 'meta' => $this->requestParameters->toArray(), ]); } else { $this->setResponseStatus($response); } } /** * @param ResourcesByParentResponseDto $response * * @return array<string, int> */ private function createStatusesCountFromResponse(ResourcesByParentResponseDto $response): array { return [ 'ok' => $response->totalOK, 'warning' => $response->totalWarning, 'critical' => $response->totalCritical, 'unknown' => $response->totalUnknown, 'pending' => $response->totalPending, ]; } /** * @param ResourceResponseDto[] $children * @param array<string, array<mixed, mixed>> $extraData * * @return array<int, array<string, mixed>> */ private function createChildrenFromResponse(array $children, array $extraData): array { return array_map( fn (ResourceResponseDto $resource) => $this->createResourceFromResponse($resource, $extraData), $children ); } /** * @param ResourceResponseDto $response * @param array<string, array<mixed, mixed>> $extraData * * @return array<string, mixed> */ private function createResourceFromResponse(ResourceResponseDto $response, array $extraData): array { $duration = $response->lastStatusChange !== null ? \CentreonDuration::toString(time() - $response->lastStatusChange->getTimestamp()) : null; $lastCheck = $response->lastCheck !== null ? \CentreonDuration::toString(time() - $response->lastCheck->getTimestamp()) : null; $severity = $response->severity !== null ? [ 'id' => $response->severity->id, 'name' => $response->severity->name, 'level' => $response->severity->level, 'type' => $response->severity->type, 'icon' => [ 'id' => $response->severity->icon->id, 'name' => $response->severity->icon->name, 'url' => $this->generateNormalizedIconUrl($response->severity->icon->url), ], ] : null; $icon = $response->icon !== null ? [ 'id' => $response->icon->id, 'name' => $response->icon->name, 'url' => $this->generateNormalizedIconUrl($response->icon->url), ] : null; $parameters = [ 'type' => $response->type, 'serviceId' => $response->serviceId, 'hostId' => $response->hostId, 'hasGraphData' => $response->hasGraphData, 'internalId' => $response->internalId, ]; $endpoints = $this->hypermediaCreator->createEndpoints($parameters); $links = [ 'endpoints' => [ 'details' => $endpoints['details'], 'timeline' => $endpoints['timeline'], 'status_graph' => $endpoints['status_graph'] ?? null, 'performance_graph' => $endpoints['performance_graph'] ?? null, 'acknowledgement' => $endpoints['acknowledgement'], 'downtime' => $endpoints['downtime'], 'check' => $endpoints['check'], 'forced_check' => $endpoints['forced_check'], 'metrics' => $endpoints['metrics'] ?? null, ], 'uris' => $this->hypermediaCreator->createInternalUris($parameters), 'externals' => [ 'action_url' => $response->actionUrl !== null ? $this->generateUrlWithMacrosResolved($response->actionUrl, $response) : $response->actionUrl, 'notes' => [ 'label' => $response->notes?->label, 'url' => $response->notes?->url !== null ? $this->generateUrlWithMacrosResolved($response->notes->url, $response) : $response->notes?->url, ], ], ]; $resource = [ 'uuid' => $response->uuid, 'duration' => $duration, 'last_check' => $lastCheck, 'short_type' => $response->shortType, 'id' => $response->id, 'type' => $response->type, 'alias' => $response->alias, 'fqdn' => $response->fqdn, 'icon' => $icon, 'monitoring_server_name' => $response->monitoringServerName, 'status' => [ 'code' => $response->status?->code, 'name' => $response->status?->name, 'severity_code' => $response->status?->severityCode, ], 'is_in_downtime' => $response->isInDowntime, 'is_acknowledged' => $response->isAcknowledged, 'is_in_flapping' => $response->isInFlapping, 'percent_state_change' => $response->percentStateChange, 'has_active_checks_enabled' => $response->withActiveChecks, 'has_passive_checks_enabled' => $response->withPassiveChecks, 'last_status_change' => $this->formatDateToIso8601($response->lastStatusChange), 'tries' => $response->tries, 'information' => $response->information, 'performance_data' => null, 'is_notification_enabled' => false, 'severity' => $severity, 'links' => $links, ]; if ( $response->type === self::HOST_RESOURCE_TYPE && $response->parent !== null ) { $resource['name'] = $response->name; $resource['parent'] = null; $resource['children'] = []; $resource['extra'] = $response->parent->resourceId !== null ? $this->normalizeExtraDataForResource($response->parent->resourceId, $extraData) : []; } else { $resource['resource_name'] = $response->name; $resource['parent'] = ['id' => $response->hostId]; $resource['parent']['extra'] = $response->resourceId !== null ? $this->normalizeExtraDataForResource($response->resourceId, $extraData) : []; } return $resource; } /** * @param int $resourceId * @param array<string, array<mixed, mixed>> $extraData * * @return mixed[] */ private function normalizeExtraDataForResource(int $resourceId, array $extraData): array { $data = []; foreach ($extraData as $sourceName => $sourceData) { foreach (iterator_to_array($this->extraDataNormalizers) as $provider) { if ($provider->isValidFor($sourceName)) { if (array_key_exists($resourceId, $sourceData)) { $data[$sourceName] = $provider->normalizeExtraDataForResource( $sourceData[$resourceId], ); } } } } return $data; } /** * @param string $url * @param ResourceResponseDto $resource * * @return string */ private function generateUrlWithMacrosResolved(string $url, ResourceResponseDto $resource): string { $isServiceTypedResource = $resource->type === self::SERVICE_RESOURCE_TYPE; $macrosConcordanceArray = [ '$HOSTADDRESS$' => $isServiceTypedResource ? $resource->parent?->fqdn : $resource->fqdn, '$HOSTNAME$' => $isServiceTypedResource ? $resource->parent?->name : $resource->name, '$HOSTSTATE$' => $isServiceTypedResource ? $resource->parent?->status?->name : $resource->status?->name, '$HOSTSTATEID$' => $isServiceTypedResource ? (string) $resource->parent?->status?->code : (string) $resource->status?->code, '$HOSTALIAS$' => $isServiceTypedResource ? $resource->parent?->alias : $resource->alias, '$SERVICEDESC$' => $isServiceTypedResource ? $resource->name : '', '$SERVICESTATE$' => $isServiceTypedResource ? $resource->status?->name : '', '$SERVICESTATEID$' => $isServiceTypedResource ? (string) $resource->status?->code : '', ]; return str_replace(array_keys($macrosConcordanceArray), array_values($macrosConcordanceArray), $url); } /** * @param string|null $url * * @return string|null */ private function generateNormalizedIconUrl(?string $url): ?string { return $url !== null ? $this->getBaseUri() . self::IMAGE_DIRECTORY . $url : $url; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Resources/Infrastructure/API/FindResourcesByParent/FindResourcesByParentController.php
centreon/src/Core/Resources/Infrastructure/API/FindResourcesByParent/FindResourcesByParentController.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\Resources\Infrastructure\API\FindResourcesByParent; use Centreon\Application\Controller\AbstractController; use Centreon\Domain\Monitoring\ResourceFilter; use Core\Resources\Application\UseCase\FindResourcesByParent\FindResourcesByParent; use Core\Resources\Infrastructure\API\FindResources\FindResourcesRequestValidator as RequestValidator; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; /** * @phpstan-import-type _RequestParameters from RequestValidator */ final class FindResourcesByParentController extends AbstractController { private const HOST_RESOURCE_TYPE = 'host'; public function __construct(private readonly RequestValidator $validator) { } /** * @param FindResourcesByParent $useCase * @param FindResourcesByParentPresenter $presenter * @param Request $request * * @return Response */ public function __invoke( FindResourcesByParent $useCase, FindResourcesByParentPresenter $presenter, Request $request, ): Response { $this->denyAccessUnlessGrantedForApiRealtime(); $filter = $this->validator->validateAndRetrieveRequestParameters($request->query->all()); $useCase($presenter, $this->createResourceFilter($filter)); return $presenter->show(); } /** * @param _RequestParameters $filter * * @return ResourceFilter */ private function createResourceFilter(array $filter): ResourceFilter { return (new ResourceFilter()) ->setStates($filter[RequestValidator::PARAM_STATES]) ->setStatuses($filter[RequestValidator::PARAM_STATUSES]) ->setStatusTypes($filter[RequestValidator::PARAM_STATUS_TYPES]) ->setServicegroupNames($filter[RequestValidator::PARAM_SERVICEGROUP_NAMES]) ->setServiceCategoryNames($filter[RequestValidator::PARAM_SERVICE_CATEGORY_NAMES]) ->setServiceSeverityNames($filter[RequestValidator::PARAM_SERVICE_SEVERITY_NAMES]) ->setServiceSeverityLevels($filter[RequestValidator::PARAM_SERVICE_SEVERITY_LEVELS]) ->setHostgroupNames($filter[RequestValidator::PARAM_HOSTGROUP_NAMES]) ->setHostCategoryNames($filter[RequestValidator::PARAM_HOST_CATEGORY_NAMES]) ->setHostSeverityNames($filter[RequestValidator::PARAM_HOST_SEVERITY_NAMES]) ->setMonitoringServerNames($filter[RequestValidator::PARAM_MONITORING_SERVER_NAMES]) ->setHostSeverityLevels($filter[RequestValidator::PARAM_HOST_SEVERITY_LEVELS]) ->setOnlyWithPerformanceData($filter[RequestValidator::PARAM_RESOURCES_ON_PERFORMANCE_DATA_AVAILABILITY]) ->setOnlyWithTicketsOpened($filter[RequestValidator::PARAM_RESOURCES_WITH_OPENED_TICKETS]) ->setRuleId($filter[RequestValidator::PARAM_OPEN_TICKET_RULE_ID]) ->setTypes( array_filter( $this->validator->getResourceTypes(), $this->removeHostFromTypes(...) ) ); } /** * We do not want HOST resource type to be explicitely searched. * * @param string $resourceType * * @return bool */ private function removeHostFromTypes(string $resourceType): bool { return $resourceType !== self::HOST_RESOURCE_TYPE; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Resources/Infrastructure/API/ExportResources/ExportResourcesPresenterCsv.php
centreon/src/Core/Resources/Infrastructure/API/ExportResources/ExportResourcesPresenterCsv.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\Resources\Infrastructure\API\ExportResources; use Centreon\Domain\Monitoring\Resource as ResourceEntity; use Core\Application\Common\UseCase\AbstractPresenter; use Core\Application\Common\UseCase\ErrorResponse; use Core\Application\Common\UseCase\ResponseStatusInterface; use Core\Common\Domain\Collection\StringCollection; use Core\Common\Domain\Exception\CollectionException; use Core\Common\Infrastructure\ExceptionLogger\ExceptionLogger; use Core\Infrastructure\Common\Api\HttpUrlTrait; use Core\Infrastructure\Common\Presenter\CsvFormatter; use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface; use Core\Resources\Application\UseCase\ExportResources\ExportResourcesPresenterInterface; use Core\Resources\Application\UseCase\ExportResources\ExportResourcesResponse; /** * Class * * @class ExportResourcesPresenterCsv * @package Core\Resources\Infrastructure\API\ExportResources */ final class ExportResourcesPresenterCsv extends AbstractPresenter implements ExportResourcesPresenterInterface { use HttpUrlTrait; /** @var ExportResourcesViewModel */ private ExportResourcesViewModel $viewModel; /** * ExportResourcesPresenterCsv constructor * * @param CsvFormatter $presenterFormatter * @param ExceptionLogger $exceptionLogger */ public function __construct( PresenterFormatterInterface $presenterFormatter, private readonly ExceptionLogger $exceptionLogger, ) { parent::__construct($presenterFormatter); } /** * @param ExportResourcesResponse|ResponseStatusInterface $response * * @return void */ public function presentResponse(ExportResourcesResponse|ResponseStatusInterface $response): void { $this->viewModel = new ExportResourcesViewModel(); if ($response instanceof ResponseStatusInterface) { if ($response instanceof ErrorResponse && ! is_null($response->getException())) { $this->exceptionLogger->log($response->getException()); } $this->setResponseStatus($response); return; } try { $csvHeader = $this->getHeaderByFilteredColumns($response->getFilteredColumns()); } catch (CollectionException $exception) { $this->exceptionLogger->log($exception); $this->setResponseStatus(new ErrorResponse('An error occurred while filtering columns')); return; } if (! $response->getFilteredColumns()->isEmpty()) { $csvHeader = $this->sortHeaderByFilteredColumns($csvHeader, $response->getFilteredColumns()); } $csvResources = $this->transformToCsvByHeader($response->getResources(), $csvHeader); $this->viewModel->setHeaders($csvHeader); $this->viewModel->setResources($csvResources); $this->viewModel->setExportedFormat($response->getExportedFormat()); } /** * @return ExportResourcesViewModel */ public function getViewModel(): ExportResourcesViewModel { return $this->viewModel; } // ---------------------------------- PRIVATE METHODS ---------------------------------- // /** * @param \Traversable<ResourceEntity> $resources * @param StringCollection $csvHeader * * @return \Traversable<array<string,mixed>> */ private function transformToCsvByHeader(\Traversable $resources, StringCollection $csvHeader): \Traversable { /** @var ResourceEntity $resource */ foreach ($resources as $resource) { $resource = [ _('Resource Type') => _($this->formatLabel($resource->getType() ?? '')), _('Resource Name') => _($resource->getName() ?? ''), _('Status') => _($this->formatLabel($resource->getStatus()?->getName() ?? '')), _('Parent Resource Type') => _($this->formatLabel($resource->getParent()?->getType() ?? '')), _('Parent Resource Name') => _($resource->getParent()?->getName() ?? ''), _('Parent Resource Status') => _( $this->formatLabel($resource->getParent()?->getStatus()?->getName() ?? '') ), _('Duration') => $resource->getDuration() ?? '', _('Last Check') => $resource->getLastCheckAsString() ?? '', _('Information') => $resource->getInformation() ?? '', _('Tries') => $resource->getTries() ?? '', _('Severity') => $resource->getSeverity()?->getLevel() ?? '', _('Notes') => $this->getResourceNotes($resource), _('Action') => $this->formatUrl( $resource->getLinks()->getExternals()->getActionUrl() ?? '', $resource ), _('State') => _($this->getResourceState($resource)), _('Alias') => $resource->getAlias() ?? '', _('Parent alias') => $resource->getParent()?->getAlias() ?? '', _('FQDN / Address') => $resource->getFqdn() ?? '', _('Monitoring server') => $resource->getMonitoringServerName(), _('Notif') => $resource->isNotificationEnabled() ? _('Notifications enabled') : _('Notifications disabled'), _('Check') => _($this->getResourceCheck($resource)), ]; $line = array_map( fn ($key) => $resource[$key], $csvHeader->values() ); yield $line; } } /** * @param StringCollection $filteredColumns * * @throws CollectionException * @return StringCollection */ private function getHeaderByFilteredColumns(StringCollection $filteredColumns): StringCollection { $csvHeader = StringCollection::create([ 'resource_type' => _('Resource Type'), 'resource_name' => _('Resource Name'), 'status' => _('Status'), 'parent_resource_type' => _('Parent Resource Type'), 'parent_resource_name' => _('Parent Resource Name'), 'parent_resource_status' => _('Parent Resource Status'), 'duration' => _('Duration'), 'last_check' => _('Last Check'), 'information' => _('Information'), 'tries' => _('Tries'), 'severity' => _('Severity'), 'notes_url' => _('Notes'), 'action_url' => _('Action'), 'state' => _('State'), 'alias' => _('Alias'), 'parent_alias' => _('Parent alias'), 'fqdn' => _('FQDN / Address'), 'monitoring_server_name' => _('Monitoring server'), 'notification' => _('Notif'), 'checks' => _('Check'), ]); if ($filteredColumns->isEmpty()) { return $csvHeader; } return $csvHeader->filterOnKey(function ($key) use ($filteredColumns) { // if the key is a resource or parent_resource, we keep all columns starting with this key if (str_starts_with($key, 'resource_')) { $key = 'resource'; } elseif (str_starts_with($key, 'parent_resource_')) { $key = 'parent_resource'; } return $filteredColumns->contains($key); }); } /** * @param StringCollection $csvHeader * @param StringCollection $filteredColumns * * @return StringCollection */ private function sortHeaderByFilteredColumns( StringCollection $csvHeader, StringCollection $filteredColumns, ): StringCollection { $csvHeader->sortByKeys(function ($keyA, $keyB) use ($filteredColumns) { // if the key is a resource or parent_resource, we keep all columns starting with this key if (str_starts_with($keyA, 'resource_')) { $keyA = 'resource'; } elseif (str_starts_with($keyA, 'parent_resource_')) { $keyA = 'parent_resource'; } if (str_starts_with($keyB, 'resource_')) { $keyB = 'resource'; } elseif (str_starts_with($keyB, 'parent_resource_')) { $keyB = 'parent_resource'; } return $filteredColumns->indexOf($keyA) <=> $filteredColumns->indexOf($keyB); }); return $csvHeader; } /** * @param string $label * * @return string */ private function formatLabel(string $label): string { return ucfirst(mb_strtolower($label)); } /** * @param ResourceEntity $resource * * @return string */ private function getResourceNotes(ResourceEntity $resource): string { $notes = ''; if (! is_null($resource->getLinks()->getExternals()->getNotes())) { $notes = $resource->getLinks()->getExternals()->getNotes()->getUrl() ?? null; $notes = $notes ? $this->formatUrl($notes, $resource) : null; $notes = $notes ?: $resource->getLinks()->getExternals()->getNotes()->getLabel() ?? ''; } return $notes; } /** * @param ResourceEntity $resource * * @return string */ private function getResourceState(ResourceEntity $resource): string { $state = []; if ($resource->getAcknowledged()) { $state[] = 'Acknowledged'; } if ($resource->getInDowntime()) { $state[] = 'In Downtime'; } if ($resource->isInFlapping()) { $state[] = 'Flapping'; } return implode(', ', $state); } /** * @param ResourceEntity $resource * * @return string */ private function getResourceCheck(ResourceEntity $resource): string { $check = ''; if (! $resource->getActiveChecks() && ! $resource->getPassiveChecks()) { $check = 'All checks are disabled'; } elseif ($resource->getActiveChecks() && $resource->getPassiveChecks()) { $check = 'All checks are enabled'; } elseif ($resource->getActiveChecks()) { $check = 'Only active checks are enabled'; } elseif ($resource->getPassiveChecks()) { $check = 'Only passive checks are enabled'; } return $check; } /** * @param string $url * @param ResourceEntity $resource * * @return string */ private function formatUrl(string $url, ResourceEntity $resource): string { if (empty($url)) { return ''; } $url = $this->replaceMacrosInUrl($url, $resource); if (! str_starts_with($url, 'http')) { $baseurl = $this->getHost(true); if (! str_starts_with($url, '/')) { $url = '/' . $url; } if (str_starts_with($url, '/centreon/')) { $url = str_replace('/centreon/', '/', $url); } $url = $baseurl . $url; } return $url; } /** * @param string $url * @param ResourceEntity $resource * * @return string */ private function replaceMacrosInUrl(string $url, ResourceEntity $resource): string { $isServiceTypedResource = $resource->getType() === 'service'; $macrosConcordanceArray = [ '$HOSTADDRESS$' => $isServiceTypedResource ? $resource->getParent()?->getFqdn() : $resource->getFqdn(), '$HOSTNAME$' => $isServiceTypedResource ? $resource->getParent()?->getName() : $resource->getName(), '$HOSTSTATE$' => $isServiceTypedResource ? $resource->getParent()?->getStatus()?->getName( ) : $resource->getStatus()?->getName(), '$HOSTSTATEID$' => $isServiceTypedResource ? (string) $resource->getParent()?->getStatus()?->getCode( ) : (string) $resource->getStatus()?->getCode(), '$HOSTALIAS$' => $isServiceTypedResource ? $resource->getParent()?->getAlias() : $resource->getAlias(), '$SERVICEDESC$' => $isServiceTypedResource ? $resource->getName() : '', '$SERVICESTATE$' => $isServiceTypedResource ? $resource->getStatus()?->getName() : '', '$SERVICESTATEID$' => $isServiceTypedResource ? (string) $resource->getStatus()?->getCode() : '', ]; return str_replace(array_keys($macrosConcordanceArray), array_values($macrosConcordanceArray), $url); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Resources/Infrastructure/API/ExportResources/ExportResourcesRequestTransformer.php
centreon/src/Core/Resources/Infrastructure/API/ExportResources/ExportResourcesRequestTransformer.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\Resources\Infrastructure\API\ExportResources; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Centreon\Domain\Monitoring\ResourceFilter; use Core\Common\Domain\Collection\StringCollection; use Core\Common\Domain\Exception\CollectionException; use Core\Common\Domain\Exception\TransformerException; use Core\Resources\Application\UseCase\ExportResources\ExportResourcesRequest; /** * Class * * @class ExportResourcesRequestTransformer * @package Core\Resources\Infrastructure\API\ExportResources */ final readonly class ExportResourcesRequestTransformer { /** * @param ExportResourcesInput $input * @param ResourceFilter $resourceFilter * @param ContactInterface $contact * * @throws TransformerException * @return ExportResourcesRequest */ public static function transform( ExportResourcesInput $input, ResourceFilter $resourceFilter, ContactInterface $contact, ): ExportResourcesRequest { $allPages = filter_var($input->allPages, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE); if ($allPages === null) { throw new TransformerException( 'Error while transforming input to request for export resources with all_pages', ['input_all_pages' => $input->allPages, 'all_pages' => $allPages] ); } try { $columns = is_null($input->columns) ? new StringCollection() : new StringCollection($input->columns); } catch (CollectionException $e) { throw new TransformerException( 'Error while transforming input to request for export resources with columns', ['columns' => $input->columns], $e ); } return new ExportResourcesRequest( exportedFormat: $input->format ?? '', resourceFilter: $resourceFilter, allPages: $allPages, maxResults: is_null($input->maxLines) ? 0 : (int) $input->maxLines, columns: $columns, contactId: $contact->getId(), isAdmin: $contact->isAdmin() ); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Resources/Infrastructure/API/ExportResources/ExportResourcesViewModel.php
centreon/src/Core/Resources/Infrastructure/API/ExportResources/ExportResourcesViewModel.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\Resources\Infrastructure\API\ExportResources; use Core\Common\Domain\Collection\StringCollection; /** * Class * * @class ExportResourcesViewModel * @package Core\Resources\Infrastructure\API\ExportResources */ final class ExportResourcesViewModel { /** @var StringCollection */ private StringCollection $headers; /** @var \Traversable<array<string,mixed>> */ private \Traversable $resources; /** @var string */ private string $exportedFormat; /** * @return StringCollection */ public function getHeaders(): StringCollection { return $this->headers; } /** * @param StringCollection $headers * * @return void */ public function setHeaders(StringCollection $headers): void { $this->headers = $headers; } /** * @return \Traversable<array<string,mixed>> */ public function getResources(): \Traversable { return $this->resources; } /** * @param \Traversable<array<string,mixed>> $resources * * @return void */ public function setResources(\Traversable $resources): void { $this->resources = $resources; } /** * @return string */ public function getExportedFormat(): string { return $this->exportedFormat; } /** * @param string $exportedFormat * * @return void */ public function setExportedFormat(string $exportedFormat): void { $this->exportedFormat = $exportedFormat; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Resources/Infrastructure/API/ExportResources/ExportResourcesController.php
centreon/src/Core/Resources/Infrastructure/API/ExportResources/ExportResourcesController.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\Resources\Infrastructure\API\ExportResources; use Centreon\Application\Controller\AbstractController; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Centreon\Domain\Monitoring\ResourceFilter; use Core\Application\Common\UseCase\ErrorResponse; use Core\Common\Domain\Exception\TransformerException; use Core\Common\Infrastructure\ExceptionLogger\ExceptionLogger; use Core\Resources\Application\UseCase\ExportResources\Enum\AllowedFormatEnum; use Core\Resources\Application\UseCase\ExportResources\ExportResources; use Core\Resources\Application\UseCase\ExportResources\ExportResourcesRequest; use Core\Resources\Infrastructure\API\ExportResources\Enum\ExportViewEnum; use Core\Resources\Infrastructure\API\FindResources\FindResourcesRequestValidator as RequestValidator; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\StreamedResponse; use Symfony\Component\HttpKernel\Attribute\MapQueryString; use Symfony\Component\Serializer\Encoder\CsvEncoder; /** * @phpstan-import-type _RequestParameters from RequestValidator */ final class ExportResourcesController extends AbstractController { /** * ExportResourcesController constructor * * @param ContactInterface $contact * @param RequestValidator $validator * @param ExceptionLogger $exceptionLogger */ public function __construct( private readonly ContactInterface $contact, private readonly RequestValidator $validator, private readonly ExceptionLogger $exceptionLogger, ) { } /** * @param ExportResources $useCase * @param ExportResourcesPresenterCsv $presenter * @param Request $request * @param ExportResourcesInput $input * * @return Response */ public function __invoke( ExportResources $useCase, ExportResourcesPresenterCsv $presenter, Request $request, #[MapQueryString(validationFailedStatusCode: Response::HTTP_UNPROCESSABLE_ENTITY)] ExportResourcesInput $input, ): Response { try { $useCaseRequest = $this->createExportRequest($request, $input); } catch (TransformerException $exception) { $this->exceptionLogger->log($exception); $presenter->setResponseStatus(new ErrorResponse('Error while creating export request')); return $presenter->show(); } $useCase($useCaseRequest, $presenter); // if a response status is set before iterating resources to export them, return it (in case of error) if ($presenter->getResponseStatus() !== null) { return $presenter->show(); } if ($presenter->getViewModel()->getExportedFormat() === AllowedFormatEnum::CSV->value) { return $this->createCsvResponse($presenter->getViewModel()); } $presenter->setResponseStatus(new ErrorResponse('Export format not supported')); return $presenter->show(); } // ---------------------------------- PRIVATE METHODS ---------------------------------- // /** * @param Request $request * @param ExportResourcesInput $input * * @throws TransformerException * @return ExportResourcesRequest */ private function createExportRequest(Request $request, ExportResourcesInput $input): ExportResourcesRequest { $filter = $this->validator->validateAndRetrieveRequestParameters($request->query->all(), true); $resourceFilter = $this->createResourceFilter($filter); return ExportResourcesRequestTransformer::transform( input: $input, resourceFilter: $resourceFilter, contact: $this->contact, ); } /** * @param _RequestParameters $filter * * @return ResourceFilter */ private function createResourceFilter(array $filter): ResourceFilter { return (new ResourceFilter()) ->setTypes($filter[RequestValidator::PARAM_RESOURCE_TYPE]) ->setStates($filter[RequestValidator::PARAM_STATES]) ->setStatuses($filter[RequestValidator::PARAM_STATUSES]) ->setStatusTypes($filter[RequestValidator::PARAM_STATUS_TYPES]) ->setServicegroupNames($filter[RequestValidator::PARAM_SERVICEGROUP_NAMES]) ->setServiceCategoryNames($filter[RequestValidator::PARAM_SERVICE_CATEGORY_NAMES]) ->setServiceSeverityNames($filter[RequestValidator::PARAM_SERVICE_SEVERITY_NAMES]) ->setServiceSeverityLevels($filter[RequestValidator::PARAM_SERVICE_SEVERITY_LEVELS]) ->setHostgroupNames($filter[RequestValidator::PARAM_HOSTGROUP_NAMES]) ->setHostCategoryNames($filter[RequestValidator::PARAM_HOST_CATEGORY_NAMES]) ->setHostSeverityNames($filter[RequestValidator::PARAM_HOST_SEVERITY_NAMES]) ->setMonitoringServerNames($filter[RequestValidator::PARAM_MONITORING_SERVER_NAMES]) ->setHostSeverityLevels($filter[RequestValidator::PARAM_HOST_SEVERITY_LEVELS]) ->setOnlyWithPerformanceData($filter[RequestValidator::PARAM_RESOURCES_ON_PERFORMANCE_DATA_AVAILABILITY]) ->setOnlyWithTicketsOpened($filter[RequestValidator::PARAM_RESOURCES_WITH_OPENED_TICKETS]) ->setRuleId($filter[RequestValidator::PARAM_OPEN_TICKET_RULE_ID]); } /** * @param ExportResourcesViewModel $viewModel * * @return Response */ private function createCsvResponse(ExportResourcesViewModel $viewModel): Response { $csvHeaders = $viewModel->getHeaders(); $resources = $viewModel->getResources(); /* create a streamed response to avoid memory issues with large data. If an error occurs during the export, the error message will be displayed in the csv file and logged (streamed response) */ $response = new StreamedResponse(function () use ($csvHeaders, $resources): void { $csvEncoder = new CsvEncoder(); try { echo $csvEncoder->encode($csvHeaders->values(), CsvEncoder::FORMAT, [ CsvEncoder::NO_HEADERS_KEY => true, CsvEncoder::DELIMITER_KEY => ';', ]); foreach ($resources as $resource) { echo $csvEncoder->encode($resource, CsvEncoder::FORMAT, [ CsvEncoder::NO_HEADERS_KEY => true, CsvEncoder::DELIMITER_KEY => ';', ]); } } catch (\Throwable $exception) { $this->exceptionLogger->log($exception); echo $csvEncoder->encode("Oops ! An error occurred: {$exception->getMessage()}", CsvEncoder::FORMAT); } }); // modify headers to download a csv file $response->headers->set('Content-Type', 'text/csv; charset=utf-8'); $response->headers->set('Content-Disposition', 'attachment; filename="' . $this->getCsvFileName() . '"'); return $response; } /** * @param ExportViewEnum $exportView * * @return string */ private function getCsvFileName(ExportViewEnum $exportView = ExportViewEnum::ALL): string { $dateNormalized = str_replace([' ', ':', ',', '/'], '-', $this->getDateFormatted()); return "ResourceStatusExport_{$exportView->value}_{$dateNormalized}.csv"; } /** * @return string */ private function getDateFormatted(): string { return (new \DateTime('now'))->format($this->contact->getFormatDate()); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Resources/Infrastructure/API/ExportResources/ExportResourcesInput.php
centreon/src/Core/Resources/Infrastructure/API/ExportResources/ExportResourcesInput.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\Resources\Infrastructure\API\ExportResources; use Core\Resources\Application\UseCase\ExportResources\Enum\AllowedFormatEnum; use Symfony\Component\Validator\Constraints as Assert; final readonly class ExportResourcesInput { public const EXPORT_MAX_LINES = 10000; public const EXPORT_ALLOWED_COLUMNS = [ 'resource', 'status', 'parent_resource', 'duration', 'last_check', 'information', 'tries', 'severity', 'notes_url', 'action_url', 'state', 'alias', 'parent_alias', 'fqdn', 'monitoring_server_name', 'notification', 'checks', ]; public function __construct( #[Assert\NotBlank(message: 'format parameter is required')] #[Assert\Choice( callback: [AllowedFormatEnum::class, 'values'], message: 'format parameter must be one of the following: {{ choices }}' )] public mixed $format, #[Assert\NotNull(message: 'all_pages parameter is required')] #[Assert\Type('bool', message: 'all_pages parameter must be a boolean')] public mixed $allPages, #[Assert\Type('array', message: 'columns parameter must be an array')] #[Assert\All([ new Assert\Type('string', message: 'columns parameter must be an array of strings'), new Assert\NotBlank(message: 'columns parameter value must not be empty'), new Assert\Choice( choices: self::EXPORT_ALLOWED_COLUMNS, message: 'columns parameter must be one of the following: {{ choices }}' ), ])] public mixed $columns, #[Assert\When( expression: 'this.allPages === true', constraints: [ new Assert\Sequentially([ new Assert\NotBlank(message: 'max_lines parameter is required when all_pages is true'), new Assert\Type(type: 'int', message: 'max_lines parameter must be an integer'), new Assert\Range( notInRangeMessage: 'max_lines parameter must be between {{ min }} and {{ max }}', min: 1, max: self::EXPORT_MAX_LINES ), ]), ] )] public mixed $maxLines, #[Assert\When( expression: 'this.allPages === false', constraints: [ new Assert\Sequentially([ new Assert\NotBlank(message: 'page parameter is required when all_pages is false'), new Assert\Type('int', message: 'page parameter must be an integer'), new Assert\Range( minMessage: 'page parameter must be greater than 1', min: 1 ), ]), ] )] public mixed $page, #[Assert\When( expression: 'this.allPages === false', constraints: [ new Assert\NotBlank(message: 'limit parameter is required when all_pages is false'), new Assert\Type('int', message: 'limit parameter must be an integer'), ] )] public mixed $limit, #[Assert\NotBlank(message: 'sort_by parameter is required')] #[Assert\Json(message: 'sort_by parameter must be a valid JSON')] public mixed $sort_by, #[Assert\NotBlank(message: 'search parameter is required')] #[Assert\Json(message: 'search parameter must be a valid JSON')] public mixed $search, ) { } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Resources/Infrastructure/API/ExportResources/ExportResourcesInputDenormalizer.php
centreon/src/Core/Resources/Infrastructure/API/ExportResources/ExportResourcesInputDenormalizer.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\Resources\Infrastructure\API\ExportResources; use Symfony\Component\Serializer\Exception\ExceptionInterface; use Symfony\Component\Serializer\Normalizer\DenormalizerAwareInterface; use Symfony\Component\Serializer\Normalizer\DenormalizerAwareTrait; use Symfony\Component\Serializer\Normalizer\DenormalizerInterface; /** * Class * * @class ExportResourcesInputDenormalizer * @package Core\Resources\Infrastructure\API\ExportResources */ class ExportResourcesInputDenormalizer implements DenormalizerInterface, DenormalizerAwareInterface { use DenormalizerAwareTrait; private const ALREADY_CALL = self::class . 'already_called'; /** * @param mixed $data * @param string $type * @param string|null $format * @param array<string,mixed> $context * * @throws ExceptionInterface * @return ExportResourcesInput */ public function denormalize( mixed $data, string $type, ?string $format = null, array $context = [], ): ExportResourcesInput { $context[self::ALREADY_CALL] = true; if (isset($data['all_pages']) && $data['all_pages'] !== '') { $data['all_pages'] = filter_var($data['all_pages'], FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE) ?? $data['all_pages']; } if (isset($data['page'])) { $data['page'] = filter_var($data['page'], FILTER_VALIDATE_INT, FILTER_NULL_ON_FAILURE) ?? $data['page']; } if (isset($data['limit'])) { $data['limit'] = filter_var($data['limit'], FILTER_VALIDATE_INT, FILTER_NULL_ON_FAILURE) ?? $data['limit']; } if (isset($data['max_lines'])) { $data['max_lines'] = filter_var($data['max_lines'], FILTER_VALIDATE_INT, FILTER_NULL_ON_FAILURE) ?? $data['max_lines']; } return $this->denormalizer->denormalize($data, $type, $format, $context); } /** * @param mixed $data * @param string $type * @param string|null $format * @param array<string,mixed> $context * * @return bool */ public function supportsDenormalization( mixed $data, string $type, ?string $format = null, array $context = [], ): bool { if ($context[self::ALREADY_CALL] ?? false) { return false; } return $type === ExportResourcesInput::class && is_array($data); } /** * @param ?string $format * @return array<class-string|'*'|'object'|string, bool|null> */ public function getSupportedTypes(?string $format): array { return [ ExportResourcesInput::class => 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/Resources/Infrastructure/API/ExportResources/Enum/ExportViewEnum.php
centreon/src/Core/Resources/Infrastructure/API/ExportResources/Enum/ExportViewEnum.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\Resources\Infrastructure\API\ExportResources\Enum; /** * Enum * * @class ExportViewEnum * @package Core\Resources\Infrastructure\API\ExportResources\Enum */ enum ExportViewEnum: string { case ALL = 'all'; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostCategory/Application/UseCase/FindHostCategories/FindHostCategories.php
centreon/src/Core/HostCategory/Application/UseCase/FindHostCategories/FindHostCategories.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\HostCategory\Application\UseCase\FindHostCategories; use Centreon\Domain\Contact\Contact; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Centreon\Domain\Log\LoggerTrait; use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface; use Core\Application\Common\UseCase\ErrorResponse; use Core\Application\Common\UseCase\ForbiddenResponse; use Core\Application\Common\UseCase\PresenterInterface; use Core\HostCategory\Application\Exception\HostCategoryException; use Core\HostCategory\Application\Repository\ReadHostCategoryRepositoryInterface; use Core\HostCategory\Domain\Model\HostCategory; use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface; use Core\Security\AccessGroup\Domain\Model\AccessGroup; final class FindHostCategories { use LoggerTrait; public const AUTHORIZED_ACL_GROUPS = ['customer_admin_acl']; /** * @param ReadHostCategoryRepositoryInterface $readHostCategoryRepository * @param ReadAccessGroupRepositoryInterface $readAccessGroupRepository * @param RequestParametersInterface $requestParameters * @param ContactInterface $user * @param bool $isCloudPlatform */ public function __construct( private readonly ReadHostCategoryRepositoryInterface $readHostCategoryRepository, private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepository, private readonly RequestParametersInterface $requestParameters, private readonly ContactInterface $user, private readonly bool $isCloudPlatform, ) { } /** * @param PresenterInterface $presenter */ public function __invoke(PresenterInterface $presenter): void { try { if (! $this->isAuthorized()) { $this->error( 'User doesn\'t have sufficient rights to see host categories', ['user_id' => $this->user->getId()] ); $presenter->setResponseStatus( new ForbiddenResponse(HostCategoryException::accessNotAllowed()->getMessage()) ); return; } $this->info('Finding host categories'); $presenter->present( $this->createResponse($this->isUserAdmin() ? $this->findAllAsAdmin() : $this->findAllAsUser()) ); } catch (\Throwable $ex) { $presenter->setResponseStatus( new ErrorResponse(HostCategoryException::findHostCategories($ex)->getMessage()) ); $this->error($ex->getMessage()); } } /** * Indicates if the current user is admin or not (cloud + onPremise context). * * @return bool */ private function isUserAdmin(): bool { if ($this->user->isAdmin()) { return true; } $userAccessGroupNames = array_map( static fn (AccessGroup $accessGroup): string => $accessGroup->getName(), $this->readAccessGroupRepository->findByContact($this->user) ); return ! empty(array_intersect($userAccessGroupNames, self::AUTHORIZED_ACL_GROUPS)) && $this->isCloudPlatform; } /** * @throws \Throwable * * @return HostCategory[] */ private function findAllAsAdmin(): array { $this->debug('Retrieve all categories as an admin user'); return $this->readHostCategoryRepository->findAll($this->requestParameters); } /** * @throws \Throwable * * @return HostCategory[] */ private function findAllAsUser(): array { $categories = []; $this->debug( 'User is not admin, use ACLs to retrieve host categories', ['user' => $this->user->getName()] ); $accessGroupIds = array_map( fn (AccessGroup $accessGroup) => $accessGroup->getId(), $this->readAccessGroupRepository->findByContact($this->user) ); if ($accessGroupIds === []) { return $categories; } // If the current user has ACL filter on Host Categories it means that not all categories are visible so // we need to apply the ACL if ($this->readHostCategoryRepository->hasRestrictedAccessToHostCategories($accessGroupIds)) { $categories = $this->readHostCategoryRepository->findAllByAccessGroupIds( $accessGroupIds, $this->requestParameters ); } else { $this->debug( 'No ACL filter found on host categories for user. Retrieving all host categories', ['user' => $this->user->getName()] ); $categories = $this->readHostCategoryRepository->findAll($this->requestParameters); } return $categories; } /** * Check if current user is authorized to perform the action. * Only admin users and users under ACL with access to the host categories configuration page are authorized. * * @return bool */ private function isAuthorized(): bool { return $this->user->isAdmin() || ( $this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_HOSTS_CATEGORIES_READ) || $this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_HOSTS_CATEGORIES_READ_WRITE) ); } /** * @param HostCategory[] $hostCategories * * @return FindHostCategoriesResponse */ private function createResponse( array $hostCategories, ): FindHostCategoriesResponse { $response = new FindHostCategoriesResponse(); foreach ($hostCategories as $hostCategory) { $response->hostCategories[] = [ 'id' => $hostCategory->getId(), 'name' => $hostCategory->getName(), 'alias' => $hostCategory->getAlias(), 'is_activated' => $hostCategory->isActivated(), 'comment' => $hostCategory->getComment(), ]; } return $response; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostCategory/Application/UseCase/FindHostCategories/FindHostCategoriesResponse.php
centreon/src/Core/HostCategory/Application/UseCase/FindHostCategories/FindHostCategoriesResponse.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\HostCategory\Application\UseCase\FindHostCategories; final class FindHostCategoriesResponse { /** @var array<array{id:int,name:string,alias:string,is_activated:bool,comment:string|null}> */ public array $hostCategories = []; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostCategory/Application/UseCase/UpdateHostCategory/UpdateHostCategoryRequest.php
centreon/src/Core/HostCategory/Application/UseCase/UpdateHostCategory/UpdateHostCategoryRequest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\HostCategory\Application\UseCase\UpdateHostCategory; final class UpdateHostCategoryRequest { public int $id = 0; public string $name = ''; public string $alias = ''; public bool $isActivated = true; public ?string $comment = 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/HostCategory/Application/UseCase/UpdateHostCategory/UpdateHostCategory.php
centreon/src/Core/HostCategory/Application/UseCase/UpdateHostCategory/UpdateHostCategory.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\HostCategory\Application\UseCase\UpdateHostCategory; use Centreon\Domain\Contact\Contact; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Centreon\Domain\Log\LoggerTrait; use Core\Application\Common\UseCase\ConflictResponse; use Core\Application\Common\UseCase\ErrorResponse; use Core\Application\Common\UseCase\ForbiddenResponse; use Core\Application\Common\UseCase\InvalidArgumentResponse; use Core\Application\Common\UseCase\NoContentResponse; use Core\Application\Common\UseCase\NotFoundResponse; use Core\Application\Common\UseCase\PresenterInterface; use Core\Common\Domain\TrimmedString; use Core\HostCategory\Application\Exception\HostCategoryException; use Core\HostCategory\Application\Repository\ReadHostCategoryRepositoryInterface; use Core\HostCategory\Application\Repository\WriteHostCategoryRepositoryInterface; use Core\HostCategory\Domain\Model\HostCategory; use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface; final class UpdateHostCategory { use LoggerTrait; public function __construct( private readonly WriteHostCategoryRepositoryInterface $writeHostCategoryRepository, private readonly ReadHostCategoryRepositoryInterface $readHostCategoryRepository, private readonly ReadAccessGroupRepositoryInterface $readAccessGroupRepositoryInterface, private readonly ContactInterface $user, ) { } /** * @param UpdateHostCategoryRequest $request * @param PresenterInterface $presenter */ public function __invoke(UpdateHostCategoryRequest $request, PresenterInterface $presenter): void { try { if (! $this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_HOSTS_CATEGORIES_READ_WRITE)) { $this->error('User doesn\'t have sufficient rights to edit host categories', [ 'user_id' => $this->user->getId(), ]); $presenter->setResponseStatus( new ForbiddenResponse(HostCategoryException::writingActionsNotAllowed()) ); return; } if ($this->user->isAdmin()) { if (! $this->readHostCategoryRepository->exists($request->id)) { $this->error('Host category not found', [ 'hostcategory_id' => $request->id, ]); $presenter->setResponseStatus(new NotFoundResponse('Host category')); return; } } else { $accessGroups = $this->readAccessGroupRepositoryInterface->findByContact($this->user); if (! $this->readHostCategoryRepository->existsByAccessGroups($request->id, $accessGroups)) { $this->error('Host category not found', [ 'hostcategory_id' => $request->id, 'accessgroups' => $accessGroups, ]); $presenter->setResponseStatus(new NotFoundResponse('Host category')); return; } } $hostCategory = $this->readHostCategoryRepository->findById($request->id); if (! $hostCategory) { $presenter->setResponseStatus( new ErrorResponse(HostCategoryException::errorWhileRetrievingObject()) ); return; } if ( $hostCategory->getName() !== $request->name && $this->readHostCategoryRepository->existsByName(new TrimmedString($request->name)) ) { $this->error('Host category name already exists', [ 'hostcategory_name' => trim($request->name), ]); $presenter->setResponseStatus( new ConflictResponse(HostCategoryException::hostNameAlreadyExists()) ); return; } if ($this->hasDifferences($request, $hostCategory)) { $hostCategory->setName($request->name); $hostCategory->setAlias($request->alias); $hostCategory->setActivated($request->isActivated); $hostCategory->setComment($request->comment); $this->writeHostCategoryRepository->update($hostCategory); } $presenter->setResponseStatus(new NoContentResponse()); } catch (\Assert\AssertionFailedException $ex) { $presenter->setResponseStatus(new InvalidArgumentResponse($ex)); $this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]); } catch (\Throwable $ex) { $presenter->setResponseStatus( new ErrorResponse(HostCategoryException::updateHostCategory($ex)) ); $this->error($ex->getMessage()); } } /** * Verify if the Request Payload has changed compare to retrieved hostCategory. * * @param UpdateHostCategoryRequest $request * @param HostCategory $hostCategory * * @return bool */ private function hasDifferences(UpdateHostCategoryRequest $request, HostCategory $hostCategory): bool { return $request->name !== $hostCategory->getName() || $request->alias !== $hostCategory->getAlias() || $request->isActivated !== $hostCategory->isActivated() || $request->comment !== $hostCategory->getComment(); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostCategory/Application/UseCase/DeleteHostCategory/DeleteHostCategory.php
centreon/src/Core/HostCategory/Application/UseCase/DeleteHostCategory/DeleteHostCategory.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\HostCategory\Application\UseCase\DeleteHostCategory; use Centreon\Domain\Contact\Contact; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Centreon\Domain\Log\LoggerTrait; use Core\Application\Common\UseCase\ErrorResponse; use Core\Application\Common\UseCase\ForbiddenResponse; use Core\Application\Common\UseCase\NoContentResponse; use Core\Application\Common\UseCase\NotFoundResponse; use Core\Application\Common\UseCase\PresenterInterface; use Core\HostCategory\Application\Exception\HostCategoryException; use Core\HostCategory\Application\Repository\ReadHostCategoryRepositoryInterface; use Core\HostCategory\Application\Repository\WriteHostCategoryRepositoryInterface; use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface; final class DeleteHostCategory { use LoggerTrait; public function __construct( private WriteHostCategoryRepositoryInterface $writeHostCategoryRepository, private ReadHostCategoryRepositoryInterface $readHostCategoryRepository, private ReadAccessGroupRepositoryInterface $readAccessGroupRepositoryInterface, private ContactInterface $user, ) { } /** * @param int $hostCategoryId * @param PresenterInterface $presenter */ public function __invoke(int $hostCategoryId, PresenterInterface $presenter): void { try { if ($this->user->isAdmin()) { if ($this->readHostCategoryRepository->exists($hostCategoryId)) { $this->writeHostCategoryRepository->deleteById($hostCategoryId); $presenter->setResponseStatus(new NoContentResponse()); } else { $this->error('Host category not found', [ 'hostcategory_id' => $hostCategoryId, ]); $presenter->setResponseStatus(new NotFoundResponse('Host category')); } } elseif ($this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_HOSTS_CATEGORIES_READ_WRITE)) { $accessGroups = $this->readAccessGroupRepositoryInterface->findByContact($this->user); if ($this->readHostCategoryRepository->existsByAccessGroups($hostCategoryId, $accessGroups)) { $this->writeHostCategoryRepository->deleteById($hostCategoryId); $presenter->setResponseStatus(new NoContentResponse()); } else { $this->error('Host category not found', [ 'hostcategory_id' => $hostCategoryId, 'accessgroups' => $accessGroups, ]); $presenter->setResponseStatus(new NotFoundResponse('Host category')); } } else { $this->error('User doesn\'t have sufficient rights to see host category', [ 'user_id' => $this->user->getId(), ]); $presenter->setResponseStatus( new ForbiddenResponse(HostCategoryException::deleteNotAllowed()->getMessage()) ); } } catch (\Throwable $ex) { $presenter->setResponseStatus( new ErrorResponse(HostCategoryException::deleteHostCategory($ex)->getMessage()) ); $this->error($ex->getMessage()); } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostCategory/Application/UseCase/AddHostCategory/AddHostCategoryResponse.php
centreon/src/Core/HostCategory/Application/UseCase/AddHostCategory/AddHostCategoryResponse.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\HostCategory\Application\UseCase\AddHostCategory; final class AddHostCategoryResponse { public int $id = 0; public string $name = ''; public string $alias = ''; public bool $isActivated = true; public ?string $comment = 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/HostCategory/Application/UseCase/AddHostCategory/AddHostCategory.php
centreon/src/Core/HostCategory/Application/UseCase/AddHostCategory/AddHostCategory.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\HostCategory\Application\UseCase\AddHostCategory; 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\CreatedResponse; use Core\Application\Common\UseCase\ErrorResponse; use Core\Application\Common\UseCase\ForbiddenResponse; use Core\Application\Common\UseCase\InvalidArgumentResponse; use Core\Application\Common\UseCase\PresenterInterface; use Core\Common\Domain\TrimmedString; use Core\HostCategory\Application\Exception\HostCategoryException; use Core\HostCategory\Application\Repository\ReadHostCategoryRepositoryInterface; use Core\HostCategory\Application\Repository\WriteHostCategoryRepositoryInterface; use Core\HostCategory\Domain\Model\HostCategory; use Core\HostCategory\Domain\Model\NewHostCategory; use Core\HostCategory\Infrastructure\API\AddHostCategory\AddHostCategoryPresenter; final class AddHostCategory { use LoggerTrait; public function __construct( private WriteHostCategoryRepositoryInterface $writeHostCategoryRepository, private ReadHostCategoryRepositoryInterface $readHostCategoryRepository, private ContactInterface $user, ) { } /** * @param AddHostCategoryRequest $request * @param AddHostCategoryPresenter $presenter */ public function __invoke(AddHostCategoryRequest $request, PresenterInterface $presenter): void { try { if (! $this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_HOSTS_CATEGORIES_READ_WRITE)) { $this->error('User doesn\'t have sufficient rights to see host categories', [ 'user_id' => $this->user->getId(), ]); $presenter->setResponseStatus( new ForbiddenResponse(HostCategoryException::writingActionsNotAllowed()) ); } elseif ($this->readHostCategoryRepository->existsByName(new TrimmedString($request->name))) { $this->error('Host category name already exists', [ 'hostcategory_name' => trim($request->name), ]); $presenter->setResponseStatus( new ConflictResponse(HostCategoryException::hostNameAlreadyExists()) ); } else { $newHostCategory = new NewHostCategory($request->name, $request->alias); $newHostCategory->setComment($request->comment ?: null); $newHostCategory->setActivated($request->isActivated); $hostCategoryId = $this->writeHostCategoryRepository->add($newHostCategory); $hostCategory = $this->readHostCategoryRepository->findById($hostCategoryId); if (! $hostCategory) { $presenter->setResponseStatus( new ErrorResponse(HostCategoryException::errorWhileRetrievingObject()) ); return; } $presenter->present( new CreatedResponse($hostCategoryId, $this->createResponse($hostCategory)) ); } } catch (\Assert\AssertionFailedException $ex) { $presenter->setResponseStatus(new InvalidArgumentResponse($ex)); $this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]); } catch (\Throwable $ex) { $presenter->setResponseStatus( new ErrorResponse(HostCategoryException::addHostCategory($ex)) ); $this->error($ex->getMessage()); } } /** * @param HostCategory|null $hostCategory * * @return AddHostCategoryResponse */ private function createResponse(?HostCategory $hostCategory): AddHostCategoryResponse { $response = new AddHostCategoryResponse(); if ($hostCategory !== null) { $response->id = $hostCategory->getId(); $response->name = $hostCategory->getName(); $response->alias = $hostCategory->getAlias(); $response->isActivated = $hostCategory->isActivated(); $response->comment = $hostCategory->getComment(); } return $response; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostCategory/Application/UseCase/AddHostCategory/AddHostCategoryRequest.php
centreon/src/Core/HostCategory/Application/UseCase/AddHostCategory/AddHostCategoryRequest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\HostCategory\Application\UseCase\AddHostCategory; final class AddHostCategoryRequest { public string $name = ''; public string $alias = ''; public bool $isActivated = true; public ?string $comment = 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/HostCategory/Application/UseCase/FindHostCategory/FindHostCategory.php
centreon/src/Core/HostCategory/Application/UseCase/FindHostCategory/FindHostCategory.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\HostCategory\Application\UseCase\FindHostCategory; use Centreon\Domain\Contact\Contact; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Centreon\Domain\Log\LoggerTrait; use Core\Application\Common\UseCase\ErrorResponse; use Core\Application\Common\UseCase\ForbiddenResponse; use Core\Application\Common\UseCase\NotFoundResponse; use Core\Application\Common\UseCase\PresenterInterface; use Core\HostCategory\Application\Exception\HostCategoryException; use Core\HostCategory\Application\Repository\ReadHostCategoryRepositoryInterface; use Core\HostCategory\Domain\Model\HostCategory; use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface; final class FindHostCategory { use LoggerTrait; /** * @param ReadHostCategoryRepositoryInterface $readHostCategoryRepository * @param ReadAccessGroupRepositoryInterface $readAccessGroupRepositoryInterface * @param ContactInterface $user */ public function __construct( private ReadHostCategoryRepositoryInterface $readHostCategoryRepository, private ReadAccessGroupRepositoryInterface $readAccessGroupRepositoryInterface, private ContactInterface $user, ) { } /** * @param int $hostCategoryId * @param PresenterInterface $presenter */ public function __invoke(int $hostCategoryId, PresenterInterface $presenter): void { try { if ($this->user->isAdmin()) { if (! $this->readHostCategoryRepository->exists($hostCategoryId)) { $this->error('Host category not found', [ 'hostcategory_id' => $hostCategoryId, ]); $presenter->setResponseStatus(new NotFoundResponse('Host category')); return; } $this->retrieveObjectAndSetResponse($presenter, $hostCategoryId); } elseif ( $this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_HOSTS_CATEGORIES_READ) || $this->user->hasTopologyRole(Contact::ROLE_CONFIGURATION_HOSTS_CATEGORIES_READ_WRITE) ) { $this->debug( 'User is not admin, use ACLs to retrieve a host category', ['user_id' => $this->user->getId()] ); $accessGroups = $this->readAccessGroupRepositoryInterface->findByContact($this->user); if (! $this->readHostCategoryRepository->existsByAccessGroups($hostCategoryId, $accessGroups)) { $this->error('Host category not found', [ 'hostcategory_id' => $hostCategoryId, 'accessgroups' => $accessGroups, ]); $presenter->setResponseStatus(new NotFoundResponse('Host category')); return; } $this->retrieveObjectAndSetResponse($presenter, $hostCategoryId); } else { $this->error('User doesn\'t have sufficient rights to see a host category', [ 'user_id' => $this->user->getId(), 'host_category_id' => $hostCategoryId, ]); $presenter->setResponseStatus( new ForbiddenResponse(HostCategoryException::accessNotAllowed()) ); } } catch (\Throwable $ex) { $presenter->setResponseStatus( new ErrorResponse(HostCategoryException::findHostCategory($ex, $hostCategoryId)) ); $this->error($ex->getMessage()); } } /** * @param HostCategory $hostCategory * * @return FindHostCategoryResponse */ private function createResponse( HostCategory $hostCategory, ): FindHostCategoryResponse { $response = new FindHostCategoryResponse(); $response->id = $hostCategory->getId(); $response->name = $hostCategory->getName(); $response->alias = $hostCategory->getAlias(); $response->isActivated = $hostCategory->isActivated(); $response->comment = $hostCategory->getComment(); return $response; } /** * Retrieve host category and set response with object or error if retrieving fails. * * @param PresenterInterface $presenter * @param int $hostCategoryId */ private function retrieveObjectAndSetResponse(PresenterInterface $presenter, int $hostCategoryId): void { $hostCategory = $this->readHostCategoryRepository->findById($hostCategoryId); if (! $hostCategory) { $presenter->setResponseStatus( new ErrorResponse(HostCategoryException::errorWhileRetrievingObject()) ); return; } $presenter->present($this->createResponse($hostCategory)); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostCategory/Application/UseCase/FindHostCategory/FindHostCategoryResponse.php
centreon/src/Core/HostCategory/Application/UseCase/FindHostCategory/FindHostCategoryResponse.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\HostCategory\Application\UseCase\FindHostCategory; final class FindHostCategoryResponse { public int $id = 0; public string $name = ''; public string $alias = ''; public bool $isActivated = true; public string|null $comment = 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/HostCategory/Application/UseCase/FindRealTimeHostCategories/FindRealTimeHostCategories.php
centreon/src/Core/HostCategory/Application/UseCase/FindRealTimeHostCategories/FindRealTimeHostCategories.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\HostCategory\Application\UseCase\FindRealTimeHostCategories; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Centreon\Domain\Log\LoggerTrait; use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface; use Core\Application\Common\UseCase\ErrorResponse; use Core\HostCategory\Application\Exception\HostCategoryException; use Core\HostCategory\Application\Repository\ReadHostCategoryRepositoryInterface; use Core\HostCategory\Application\Repository\ReadRealTimeHostCategoryRepositoryInterface; use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface; use Core\Security\AccessGroup\Domain\Model\AccessGroup; use Core\Tag\RealTime\Domain\Model\Tag; final class FindRealTimeHostCategories { use LoggerTrait; /** * @param ContactInterface $user * @param ReadRealTimeHostCategoryRepositoryInterface $repository * @param ReadHostCategoryRepositoryInterface $configurationRepository * @param RequestParametersInterface $requestParameters * @param ReadAccessGroupRepositoryInterface $accessGroupRepository */ public function __construct( private readonly ContactInterface $user, private readonly ReadRealTimeHostCategoryRepositoryInterface $repository, private readonly ReadHostCategoryRepositoryInterface $configurationRepository, private readonly RequestParametersInterface $requestParameters, private readonly ReadAccessGroupRepositoryInterface $accessGroupRepository, ) { } /** * @param FindRealTimeHostCategoriesPresenterInterface $presenter */ public function __invoke(FindRealTimeHostCategoriesPresenterInterface $presenter): void { $this->info('Find service categories', ['user_id' => $this->user->getId()]); try { $serviceCategories = $this->user->isAdmin() ? $this->findHostCategoriesAsAdmin() : $this->findHostCategoriesAsUser(); $presenter->presentResponse($this->createResponse($serviceCategories)); } catch (\Throwable $exception) { $presenter->presentResponse( new ErrorResponse(HostCategoryException::errorWhileRetrievingRealTimeHostCategories($exception)) ); $this->error($exception->getMessage(), ['trace' => $exception->getTraceAsString()]); } } /** * @param Tag[] $serviceCategories * * @return FindRealTimeHostCategoriesResponse */ private function createResponse(array $serviceCategories): FindRealTimeHostCategoriesResponse { return new FindRealTimeHostCategoriesResponse($serviceCategories); } /** * @return Tag[] */ private function findHostCategoriesAsUser(): array { $categories = []; $this->debug( 'User is not admin, use ACLs to retrieve service categories', ['user' => $this->user->getName()] ); $accessGroupIds = array_map( static fn (AccessGroup $accessGroup): int => $accessGroup->getId(), $this->accessGroupRepository->findByContact($this->user) ); if ($accessGroupIds === []) { return $categories; } // If the current user has ACL filter on Host Categories it means that not all categories are visible so // we need to apply the ACL if ($this->configurationRepository->hasRestrictedAccessToHostCategories($accessGroupIds)) { return $this->repository->findAllByAccessGroupIds( $this->requestParameters, $accessGroupIds, ); } $this->debug( 'No ACL filter found on service categories for user. Retrieving all service categories', ['user' => $this->user->getName()] ); return $this->repository->findAll($this->requestParameters); } /** * @return Tag[] */ private function findHostCategoriesAsAdmin(): array { return $this->repository->findAll($this->requestParameters); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostCategory/Application/UseCase/FindRealTimeHostCategories/FindRealTimeHostCategoriesPresenterInterface.php
centreon/src/Core/HostCategory/Application/UseCase/FindRealTimeHostCategories/FindRealTimeHostCategoriesPresenterInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\HostCategory\Application\UseCase\FindRealTimeHostCategories; use Core\Application\Common\UseCase\PresenterInterface; use Core\Application\Common\UseCase\ResponseStatusInterface; interface FindRealTimeHostCategoriesPresenterInterface extends PresenterInterface { /** * @param FindRealTimeHostCategoriesResponse|ResponseStatusInterface $response */ public function presentResponse(FindRealTimeHostCategoriesResponse|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/HostCategory/Application/UseCase/FindRealTimeHostCategories/FindRealTimeHostCategoriesResponse.php
centreon/src/Core/HostCategory/Application/UseCase/FindRealTimeHostCategories/FindRealTimeHostCategoriesResponse.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\HostCategory\Application\UseCase\FindRealTimeHostCategories; use Core\Tag\RealTime\Application\UseCase\FindTag\FindTagResponse; final class FindRealTimeHostCategoriesResponse extends FindTagResponse { }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostCategory/Application/Exception/HostCategoryException.php
centreon/src/Core/HostCategory/Application/Exception/HostCategoryException.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\HostCategory\Application\Exception; class HostCategoryException extends \Exception { /** * @return self */ public static function accessNotAllowed(): self { return new self(_('You are not allowed to access host categories')); } /** * @return self */ public static function deleteNotAllowed(): self { return new self(_('You are not allowed to delete host categories')); } /** * @return self */ public static function writingActionsNotAllowed(): self { return new self(_('You are not allowed to create/modify host categories')); } /** * @param \Throwable $ex * @param int $hostCategoryId * * @return self */ public static function findHostCategory(\Throwable $ex, int $hostCategoryId): self { return new self(sprintf(_('Error when searching for the host category #%d'), $hostCategoryId), 0, $ex); } /** * @param \Throwable $ex * * @return self */ public static function findHostCategories(\Throwable $ex): self { return new self(_('Error while searching for host categories'), 0, $ex); } /** * @param \Throwable $ex * * @return self */ public static function deleteHostCategory(\Throwable $ex): self { return new self(_('Error while deleting host category'), 0, $ex); } /** * @param \Throwable $ex * * @return self */ public static function addHostCategory(\Throwable $ex): self { return new self(_('Error while creating host category'), 0, $ex); } /** * @param \Throwable $ex * * @return self */ public static function updateHostCategory(\Throwable $ex): self { return new self(_('Error while updating the host category'), 0, $ex); } /** * @return self */ public static function hostNameAlreadyExists(): self { return new self(_('Host category name already exists')); } /** * @return self */ public static function errorWhileRetrievingObject(): self { return new self(_('Error while retrieving a host category')); } public static function errorWhileRetrievingRealTimeHostCategories(\Throwable $exception): self { return new self(_('Error while searching host categories in real time context'), 0, $exception); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostCategory/Application/Repository/WriteHostCategoryRepositoryInterface.php
centreon/src/Core/HostCategory/Application/Repository/WriteHostCategoryRepositoryInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\HostCategory\Application\Repository; use Core\HostCategory\Domain\Model\HostCategory; use Core\HostCategory\Domain\Model\NewHostCategory; interface WriteHostCategoryRepositoryInterface { /** * Delete host category. * * @param int $hostCategoryId */ public function deleteById(int $hostCategoryId): void; /** * Add a host category * Return the id of the host category. * * @param NewHostCategory $hostCategory * * @throws \Throwable * * @return int */ public function add(NewHostCategory $hostCategory): int; /** * Update a host category. * * @param HostCategory $hostCategory * * @throws \Throwable */ public function update(HostCategory $hostCategory): void; /** * Link a list of categories to a host (or hostTemplate). * * @param int $hostId * @param int[] $categoryIds * * @throws \Throwable */ public function linkToHost(int $hostId, array $categoryIds): void; /** * Unlink a list of categories to a host (or hostTemplate). * * @param int $hostId * @param int[] $categoryIds * * @throws \Throwable */ public function unlinkFromHost(int $hostId, array $categoryIds): 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/HostCategory/Application/Repository/ReadRealTimeHostCategoryRepositoryInterface.php
centreon/src/Core/HostCategory/Application/Repository/ReadRealTimeHostCategoryRepositoryInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\HostCategory\Application\Repository; use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface; use Core\Tag\RealTime\Domain\Model\Tag; interface ReadRealTimeHostCategoryRepositoryInterface { /** * @param null|RequestParametersInterface $requestParameters * * @return Tag[] */ public function findAll(?RequestParametersInterface $requestParameters): array; /** * @param null|RequestParametersInterface $requestParameters * @param int[] $accessGroupIds * * @return Tag[] */ public function findAllByAccessGroupIds(?RequestParametersInterface $requestParameters, array $accessGroupIds): 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/HostCategory/Application/Repository/ReadHostCategoryRepositoryInterface.php
centreon/src/Core/HostCategory/Application/Repository/ReadHostCategoryRepositoryInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\HostCategory\Application\Repository; use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface; use Core\Common\Domain\TrimmedString; use Core\HostCategory\Domain\Model\HostCategory; use Core\HostCategory\Domain\Model\HostCategoryNamesById; use Core\Security\AccessGroup\Domain\Model\AccessGroup; interface ReadHostCategoryRepositoryInterface { /** * Find all host categories. * * @param RequestParametersInterface|null $requestParameters * * @throws \Throwable * * @return HostCategory[] */ public function findAll(?RequestParametersInterface $requestParameters): array; /** * Find all host categories by access groups. * * @param int[] $accessGroupIds * @param RequestParametersInterface|null $requestParameters * * @throws \Throwable * * @return HostCategory[] */ public function findAllByAccessGroupIds(array $accessGroupIds, ?RequestParametersInterface $requestParameters): array; /** * Check existence of a host category. * * @param int $hostCategoryId * * @throws \Throwable * * @return bool */ public function exists(int $hostCategoryId): bool; /** * Check existence of a host category by access groups. * * @param int $hostCategoryId * @param AccessGroup[] $accessGroups * * @throws \Throwable * * @return bool */ public function existsByAccessGroups(int $hostCategoryId, array $accessGroups): bool; /** * Check existence of a list of host categories. * Return the ids of the existing categories. * * @param int[] $hostCategoryIds * * @throws \Throwable * * @return int[] */ public function exist(array $hostCategoryIds): array; /** * Check existence of a list of host categories by access groups. * Return the ids of the existing categories. * * @param int[] $hostCategoryIds * @param AccessGroup[] $accessGroups * * @throws \Throwable * * @return int[] */ public function existByAccessGroups(array $hostCategoryIds, array $accessGroups): array; /** * Check existence of a host category by name. * * @param TrimmedString $hostCategoryName * * @throws \Throwable * * @return bool */ public function existsByName(TrimmedString $hostCategoryName): bool; /** * Find one host category. * * @param int $hostCategoryId * * @throws \Throwable * * @return HostCategory|null */ public function findById(int $hostCategoryId): ?HostCategory; /** * Find host categories by their ID. * * @param int ...$hostCategoryIds * * @throws \Throwable * * @return list<HostCategory> */ public function findByIds(int ...$hostCategoryIds): array; /** * Find host categories linked to a host (or host template) (no ACLs). * * @param int $hostId * * @throws \Throwable * * @return HostCategory[] */ public function findByHost(int $hostId): array; /** * Find host categories linked to a host (or host template) by access groups. * * @param int $hostId * @param AccessGroup[] $accessGroups * * @throws \Throwable * * @return HostCategory[] */ public function findByHostAndAccessGroups(int $hostId, array $accessGroups): array; /** * Find Host Categories names by their IDs. * * @param int[] $hostCategoryIds * * @return HostCategoryNamesById */ public function findNames(array $hostCategoryIds): HostCategoryNamesById; /** * Determine if host categories are filtered for given access group ids. * * @param int[] $accessGroupIds * * @return bool */ public function hasRestrictedAccessToHostCategories(array $accessGroupIds): 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/HostCategory/Domain/Model/NewHostCategory.php
centreon/src/Core/HostCategory/Domain/Model/NewHostCategory.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\HostCategory\Domain\Model; use Centreon\Domain\Common\Assertion\Assertion; class NewHostCategory { public const MAX_NAME_LENGTH = 200; public const MAX_ALIAS_LENGTH = 200; public const MAX_COMMENT_LENGTH = 65535; protected bool $isActivated = true; protected ?string $comment = null; /** * @param string $name * @param string $alias */ public function __construct( protected string $name, protected string $alias, ) { $this->name = trim($name); $this->alias = trim($alias); $shortName = (new \ReflectionClass($this))->getShortName(); Assertion::maxLength($name, self::MAX_NAME_LENGTH, $shortName . '::name'); Assertion::notEmptyString($name, $shortName . '::name'); Assertion::maxLength($alias, self::MAX_ALIAS_LENGTH, $shortName . '::alias'); Assertion::notEmptyString($alias, $shortName . '::alias'); } /** * @return string */ public function getName(): string { return $this->name; } /** * @return string */ public function getAlias(): string { return $this->alias; } /** * @return bool */ public function isActivated(): bool { return $this->isActivated; } /** * @param bool $isActivated */ public function setActivated(bool $isActivated): void { $this->isActivated = $isActivated; } /** * @return string|null */ public function getComment(): ?string { return $this->comment; } /** * @param string|null $comment */ public function setComment(?string $comment): void { if ($comment !== null) { $comment = trim($comment); Assertion::maxLength( $comment, self::MAX_COMMENT_LENGTH, (new \ReflectionClass($this))->getShortName() . '::comment' ); } $this->comment = $comment; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostCategory/Domain/Model/HostCategoryNamesById.php
centreon/src/Core/HostCategory/Domain/Model/HostCategoryNamesById.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\HostCategory\Domain\Model; use Core\Common\Domain\TrimmedString; class HostCategoryNamesById { /** @var array<int,TrimmedString> */ private array $names = []; /** * @param int $hostCategoryId * @param TrimmedString $hostCategoryName */ public function addName(int $hostCategoryId, TrimmedString $hostCategoryName): void { $this->names[$hostCategoryId] = $hostCategoryName; } /** * @param int $hostCategoryId * * @return null|string */ public function getName(int $hostCategoryId): ?string { return isset($this->names[$hostCategoryId]) ? $this->names[$hostCategoryId]->value : null; } /** * @return array<int,TrimmedString> */ public function getNames(): array { return $this->names; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostCategory/Domain/Model/HostCategory.php
centreon/src/Core/HostCategory/Domain/Model/HostCategory.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\HostCategory\Domain\Model; use Centreon\Domain\Common\Assertion\Assertion; class HostCategory extends NewHostCategory { /** * @param int $id * @param string $name * @param string $alias */ public function __construct( private int $id, string $name, string $alias, ) { parent::__construct($name, $alias); } /** * @return int */ public function getId(): int { return $this->id; } /** * @param string $name */ public function setName(string $name): void { $name = trim($name); $shortName = (new \ReflectionClass($this))->getShortName(); Assertion::maxLength($name, self::MAX_NAME_LENGTH, $shortName . '::name'); Assertion::notEmptyString($name, $shortName . '::name'); $this->name = $name; } /** * @param string $alias */ public function setAlias(string $alias): void { $alias = trim($alias); $shortName = (new \ReflectionClass($this))->getShortName(); Assertion::maxLength($alias, self::MAX_NAME_LENGTH, $shortName . '::alias'); Assertion::notEmptyString($alias, $shortName . '::alias'); $this->alias = $alias; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostCategory/Infrastructure/Repository/DbReadHostCategoryRepository.php
centreon/src/Core/HostCategory/Infrastructure/Repository/DbReadHostCategoryRepository.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\HostCategory\Infrastructure\Repository; use Assert\AssertionFailedException; use Centreon\Domain\Log\LoggerTrait; use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface; use Centreon\Domain\RequestParameters\RequestParameters; use Centreon\Infrastructure\DatabaseConnection; use Centreon\Infrastructure\RequestParameters\SqlRequestParametersTranslator; use Core\Common\Domain\TrimmedString; use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB; use Core\Common\Infrastructure\Repository\SqlMultipleBindTrait; use Core\Common\Infrastructure\RequestParameters\Normalizer\BoolToEnumNormalizer; use Core\HostCategory\Application\Repository\ReadHostCategoryRepositoryInterface; use Core\HostCategory\Domain\Model\HostCategory; use Core\HostCategory\Domain\Model\HostCategoryNamesById; use Core\HostGroup\Infrastructure\Repository\HostGroupRepositoryTrait; use Utility\SqlConcatenator; /** * @phpstan-type _Category array{ * hc_id:int, * hc_name:string, * hc_alias:string, * hc_activate:string, * hc_comment:string|null * } */ class DbReadHostCategoryRepository extends AbstractRepositoryRDB implements ReadHostCategoryRepositoryInterface { use LoggerTrait; use SqlMultipleBindTrait; use HostGroupRepositoryTrait; use HostCategoryRepositoryTrait; /** * @param DatabaseConnection $db */ public function __construct(DatabaseConnection $db) { $this->db = $db; } /** * @inheritDoc */ public function findNames(array $hostCategoryIds): HostCategoryNamesById { $concatenator = new SqlConcatenator(); $hostCategoryIds = array_unique($hostCategoryIds); $concatenator->defineSelect( <<<'SQL' SELECT hc.hc_id, hc.hc_name FROM `:db`.hostcategories hc WHERE hc.hc_id IN (:hostCategoryIds) SQL ); $concatenator->storeBindValueMultiple(':hostCategoryIds', $hostCategoryIds, \PDO::PARAM_INT); $statement = $this->db->prepare($this->translateDbName($concatenator->__toString())); $concatenator->bindValuesToStatement($statement); $statement->setFetchMode(\PDO::FETCH_ASSOC); $statement->execute(); $names = new HostCategoryNamesById(); foreach ($statement as $record) { /** @var array{hc_id:int,hc_name:string} $record */ $names->addName( $record['hc_id'], new TrimmedString($record['hc_name']) ); } return $names; } /** * @inheritDoc */ public function findAll(?RequestParametersInterface $requestParameters): array { $request = <<<'SQL_WRAP' SELECT SQL_CALC_FOUND_ROWS DISTINCT hc.hc_id, hc.hc_name, hc.hc_alias, hc.hc_activate, hc.hc_comment FROM `:db`.hostcategories hc SQL_WRAP; // Setup for search, pagination and order $sqlTranslator = $requestParameters ? new SqlRequestParametersTranslator($requestParameters) : null; $sqlTranslator?->getRequestParameters()->setConcordanceStrictMode(RequestParameters::CONCORDANCE_MODE_STRICT); $sqlTranslator?->setConcordanceArray([ 'id' => 'hc.hc_id', 'name' => 'hc.hc_name', 'alias' => 'hc.hc_alias', 'is_activated' => 'hc.hc_activate', 'hostgroup.id' => 'hg.hg_id', 'hostgroup.name' => 'hg.hg_name', ]); $sqlTranslator?->addNormalizer('is_activated', new BoolToEnumNormalizer()); // Update the SQL string builder with the RequestParameters through SqlRequestParametersTranslator $searchRequest = $sqlTranslator?->translateSearchParameterToSql(); if ($searchRequest !== null && str_contains($searchRequest, 'hg.')) { $request .= <<<'SQL' INNER JOIN `:db`.hostcategories_relation hcr ON hc.hc_id = hcr.hostcategories_hc_id INNER JOIN `:db`.hostgroup_relation hgr ON hcr.host_host_id = hgr.host_host_id INNER JOIN `:db`.hostgroup hg ON hgr.hostgroup_hg_id = hg.hg_id SQL; } $request .= $searchRequest !== null ? $searchRequest . ' AND ' : ' WHERE '; // avoid severities $request .= 'hc.level IS NULL'; // handle sort $request .= $sqlTranslator?->translateSortParameterToSql(); // handle pagination $request .= $sqlTranslator?->translatePaginationToSql(); $statement = $this->db->prepare($this->translateDbName($request)); $sqlTranslator?->bindSearchValues($statement); $statement->setFetchMode(\PDO::FETCH_ASSOC); $statement->execute(); // Calculate the number of rows for the pagination. $sqlTranslator?->calculateNumberOfRows($this->db); $hostCategories = []; while (is_array($result = $statement->fetch())) { /** @var array{hc_id:int,hc_name:string,hc_alias:string,hc_activate:'0'|'1',hc_comment:string|null} $result */ $hostCategories[] = $this->createHostCategoryFromArray($result); } return $hostCategories; } /** * @inheritDoc */ public function findAllByAccessGroupIds(array $accessGroupIds, ?RequestParametersInterface $requestParameters): array { if ($accessGroupIds === []) { return []; } [$bindValues, $bindQuery] = $this->createMultipleBindQuery($accessGroupIds, ':access_group_id_'); $request = <<<'SQL_WRAP' SELECT SQL_CALC_FOUND_ROWS DISTINCT hc.hc_id, hc.hc_name, hc.hc_alias, hc.hc_activate, hc.hc_comment FROM `:db`.hostcategories hc INNER JOIN `:db`.acl_resources_hc_relations arhr ON hc.hc_id = arhr.hc_id INNER JOIN `:db`.acl_resources res ON arhr.acl_res_id = res.acl_res_id INNER JOIN `:db`.acl_res_group_relations argr ON res.acl_res_id = argr.acl_res_id INNER JOIN `:db`.acl_groups ag ON argr.acl_group_id = ag.acl_group_id SQL_WRAP; // Setup for search, pagination and order $sqlTranslator = $requestParameters ? new SqlRequestParametersTranslator($requestParameters) : null; $sqlTranslator?->getRequestParameters()->setConcordanceStrictMode(RequestParameters::CONCORDANCE_MODE_STRICT); $sqlTranslator?->setConcordanceArray([ 'id' => 'hc.hc_id', 'name' => 'hc.hc_name', 'alias' => 'hc.hc_alias', 'is_activated' => 'hc.hc_activate', 'hostgroup.id' => 'hg.hg_id', 'hostgroup.name' => 'hg.hg_name', ]); $sqlTranslator?->addNormalizer('is_activated', new BoolToEnumNormalizer()); // Update the SQL string builder with the RequestParameters through SqlRequestParametersTranslator $searchRequest = $sqlTranslator?->translateSearchParameterToSql(); if ($searchRequest !== null && str_contains($searchRequest, 'hg.')) { $request .= <<<'SQL' INNER JOIN `:db`.hostcategories_relation hcr ON hc.hc_id = hcr.hostcategories_hc_id INNER JOIN `:db`.hostgroup_relation hgr ON hcr.host_host_id = hgr.host_host_id INNER JOIN `:db`.hostgroup hg ON hgr.hostgroup_hg_id = hg.hg_id SQL; if (! $this->hasAccessToAllHostGroups($accessGroupIds)) { $hostGroupAcl = $this->generateHostGroupAclSubRequest($accessGroupIds); $request .= <<<SQL AND hgr.hostgroup_hg_id IN ({$hostGroupAcl}) SQL; } } $request .= $searchRequest !== null ? $searchRequest . ' AND ' : ' WHERE '; // avoid severities $request .= "hc.level IS NULL AND ag.acl_group_id IN ({$bindQuery})"; // handle sort $request .= $sqlTranslator?->translateSortParameterToSql(); // handle pagination $request .= $sqlTranslator?->translatePaginationToSql(); $statement = $this->db->prepare($this->translateDbName($request)); $sqlTranslator?->bindSearchValues($statement); foreach ($bindValues as $key => $value) { $statement->bindValue($key, $value, \PDO::PARAM_INT); } $statement->setFetchMode(\PDO::FETCH_ASSOC); $statement->execute(); // Calculate the number of rows for the pagination. $sqlTranslator?->calculateNumberOfRows($this->db); $hostCategories = []; while (is_array($result = $statement->fetch())) { /** @var array{hc_id:int,hc_name:string,hc_alias:string,hc_activate:'0'|'1',hc_comment:string|null} $result */ $hostCategories[] = $this->createHostCategoryFromArray($result); } return $hostCategories; } /** * @inheritDoc */ public function exists(int $hostCategoryId): bool { $this->info('Check existence of host category with id #' . $hostCategoryId); $request = $this->translateDbName( 'SELECT 1 FROM `:db`.hostcategories hc WHERE hc.hc_id = :hostCategoryId AND hc.level IS NULL' ); $statement = $this->db->prepare($request); $statement->bindValue(':hostCategoryId', $hostCategoryId, \PDO::PARAM_INT); $statement->execute(); return (bool) $statement->fetchColumn(); } /** * @inheritDoc */ public function existsByAccessGroups(int $hostCategoryId, array $accessGroups): bool { $this->info( 'Check existence of host category by access groups', ['id' => $hostCategoryId, 'accessgroups' => $accessGroups] ); if ($accessGroups === []) { $this->debug('Access groups array empty'); return false; } $concat = new SqlConcatenator(); $accessGroupIds = array_map( fn ($accessGroup) => $accessGroup->getId(), $accessGroups ); // if host categories are not filtered in ACLs, then user has access to ALL host categories if (! $this->hasRestrictedAccessToHostCategories($accessGroupIds)) { $this->info('Host categories access not filtered'); return $this->exists($hostCategoryId); } $request = $this->translateDbName( 'SELECT 1 FROM `:db`.hostcategories hc INNER JOIN `:db`.acl_resources_hc_relations arhr ON hc.hc_id = arhr.hc_id INNER JOIN `:db`.acl_resources res ON arhr.acl_res_id = res.acl_res_id INNER JOIN `:db`.acl_res_group_relations argr ON res.acl_res_id = argr.acl_res_id INNER JOIN `:db`.acl_groups ag ON argr.acl_group_id = ag.acl_group_id' ); $concat->appendWhere('hc.hc_id = :hostCategoryId'); $concat->appendWhere('hc.level IS NULL'); $concat->storeBindValueMultiple(':access_group_ids', $accessGroupIds, \PDO::PARAM_INT) ->appendWhere('ag.acl_group_id IN (:access_group_ids)'); $statement = $this->db->prepare($this->translateDbName($request . ' ' . $concat)); foreach ($concat->retrieveBindValues() as $param => [$value, $type]) { $statement->bindValue($param, $value, $type); } $statement->bindValue(':hostCategoryId', $hostCategoryId, \PDO::PARAM_INT); $statement->execute(); return (bool) $statement->fetchColumn(); } /** * @inheritDoc */ public function exist(array $hostCategoryIds): array { $this->info('Check existence of host categories', ['host_category_ids' => $hostCategoryIds]); if ($hostCategoryIds === []) { return []; } $concatenator = new SqlConcatenator(); $concatenator ->defineSelect( <<<'SQL' SELECT hc.hc_id FROM `:db`.`hostcategories` hc SQL ) ->appendWhere('hc.hc_id IN (:host_category_ids)') ->appendWhere('hc.level IS NULL') ->storeBindValueMultiple(':host_category_ids', $hostCategoryIds, \PDO::PARAM_INT); $statement = $this->db->prepare($this->translateDbName($concatenator->__toString())); $concatenator->bindValuesToStatement($statement); $statement->execute(); return $statement->fetchAll(\PDO::FETCH_COLUMN); } /** * @inheritDoc */ public function existByAccessGroups(array $hostCategoryIds, array $accessGroups): array { $this->info( 'Check existence of host category by access groups', ['host_category_ids' => $hostCategoryIds, 'accessgroups' => $accessGroups] ); if ($hostCategoryIds === []) { return []; } if ($accessGroups === []) { $this->debug('Access groups array empty'); return []; } $accessGroupIds = array_map( fn ($accessGroup) => $accessGroup->getId(), $accessGroups ); // if host categories are not filtered in ACLs, then user has access to ALL host categories if (! $this->hasRestrictedAccessToHostCategories($accessGroupIds)) { $this->info('Host categories access not filtered'); return $this->exist($hostCategoryIds); } $concatenator = new SqlConcatenator(); $concatenator ->defineSelect( <<<'SQL' SELECT arhr.hc_id FROM `:db`.`hostcategories` hc INNER JOIN `:db`.`acl_resources_hc_relations` arhr ON hc.hc_id = arhr.hc_id INNER JOIN `:db`.`acl_resources` res ON arhr.acl_res_id = res.acl_res_id INNER JOIN `:db`.`acl_res_group_relations` argr ON res.acl_res_id = argr.acl_res_id INNER JOIN `:db`.`acl_groups` ag ON argr.acl_group_id = ag.acl_group_id SQL ) ->appendWhere('hc.hc_id IN (:host_category_ids)') ->appendWhere('hc.level IS NULL') ->appendWhere('ag.acl_group_id IN (:access_group_ids)') ->storeBindValueMultiple(':access_group_ids', $accessGroupIds, \PDO::PARAM_INT) ->storeBindValueMultiple(':host_category_ids', $hostCategoryIds, \PDO::PARAM_INT); $statement = $this->db->prepare($this->translateDbName($concatenator->__toString())); $concatenator->bindValuesToStatement($statement); $statement->execute(); return $statement->fetchAll(\PDO::FETCH_COLUMN); } /** * @inheritDoc */ public function existsByName(TrimmedString $hostCategoryName): bool { $this->info('Check existence of host category with name ' . $hostCategoryName); $request = $this->translateDbName( 'SELECT 1 FROM `:db`.hostcategories hc WHERE hc.hc_name = :hostCategoryName' ); $statement = $this->db->prepare($request); $statement->bindValue(':hostCategoryName', $hostCategoryName->value, \PDO::PARAM_STR); $statement->execute(); return (bool) $statement->fetchColumn(); } /** * {@inheritDoc} * * @throws AssertionFailedException */ public function findById(int $hostCategoryId): ?HostCategory { $this->info('Get a host category with ID #' . $hostCategoryId); $request = $this->translateDbName( <<<'SQL' SELECT hc.hc_id, hc.hc_name, hc.hc_alias, hc.hc_activate, hc.hc_comment FROM `:db`.hostcategories hc WHERE hc.hc_id = :hostCategoryId AND hc.level IS NULL SQL ); $statement = $this->db->prepare($request); $statement->bindValue(':hostCategoryId', $hostCategoryId, \PDO::PARAM_INT); $statement->execute(); $result = $statement->fetch(\PDO::FETCH_ASSOC); if ($result === false) { return null; } /** @var _Category $result */ return $this->createHostCategoryFromArray($result); } /** * {@inheritDoc} * * @throws AssertionFailedException */ public function findByIds(int ...$hostCategoryIds): array { if ($hostCategoryIds === []) { return []; } $bindValues = []; foreach ($hostCategoryIds as $index => $categoryId) { $bindValues[':hct_' . $index] = $categoryId; } $hostCategoryIdsQuery = implode(', ', array_keys($bindValues)); $request = $this->translateDbName( <<<SQL SELECT hc.hc_id, hc.hc_name, hc.hc_alias, hc.hc_activate, hc.hc_comment FROM `:db`.hostcategories hc WHERE hc.hc_id IN ({$hostCategoryIdsQuery}) AND hc.level IS NULL SQL ); $statement = $this->db->prepare($request); foreach ($bindValues as $bindKey => $categoryId) { $statement->bindValue($bindKey, $categoryId, \PDO::PARAM_INT); } $statement->setFetchMode(\PDO::FETCH_ASSOC); $statement->execute(); $categories = []; foreach ($statement as $result) { /** @var _Category $result */ $categories[] = $this->createHostCategoryFromArray($result); } return $categories; } /** * @inheritDoc */ public function findByHost(int $hostId): array { $this->info("Getting host categories linked to a host/host template #{$hostId}"); $concatenator = new SqlConcatenator(); $concatenator ->defineSelect( <<<'SQL' SELECT hc.hc_id, hc.hc_name, hc.hc_alias, hc.hc_activate, hc.hc_comment FROM `:db`.hostcategories hc JOIN `:db`.hostcategories_relation hcr ON hc.hc_id = hcr.hostcategories_hc_id SQL ) ->appendWhere('hcr.host_host_id = :host_id') ->storeBindValue(':host_id', $hostId, \PDO::PARAM_INT); return $this->retrieveHostCategories($concatenator, null); } /** * @inheritDoc */ public function findByHostAndAccessGroups(int $hostId, array $accessGroups): array { $this->info( "Getting host categories linked to host/host template #{$hostId} by access groups", ['access_groups' => $accessGroups] ); if ($accessGroups === []) { $this->debug('No access group for this user, return empty'); return []; } $accessGroupIds = array_map( fn ($accessGroup) => $accessGroup->getId(), $accessGroups ); // if host categories are not filtered in ACLs, then user has access to ALL host categories if (! $this->hasRestrictedAccessToHostCategories($accessGroupIds)) { $this->info('Host categories access not filtered'); return $this->findByHost($hostId); } $concatenator = new SqlConcatenator(); $concatenator ->defineSelect( <<<'SQL' SELECT hc.hc_id, hc.hc_name, hc.hc_alias, hc.hc_activate, hc.hc_comment FROM `:db`.hostcategories hc JOIN `:db`.hostcategories_relation hcr ON hc.hc_id = hcr.hostcategories_hc_id INNER JOIN `:db`.acl_resources_hc_relations arhr ON hc.hc_id = arhr.hc_id INNER JOIN `:db`.acl_resources res ON arhr.acl_res_id = res.acl_res_id INNER JOIN `:db`.acl_res_group_relations argr ON res.acl_res_id = argr.acl_res_id INNER JOIN `:db`.acl_groups ag ON argr.acl_group_id = ag.acl_group_id SQL ) ->appendWhere('hcr.host_host_id = :host_id AND hc.level IS NULL') ->appendWhere('ag.acl_group_id IN (:access_group_ids)') ->storeBindValue(':host_id', $hostId, \PDO::PARAM_INT) ->storeBindValueMultiple(':access_group_ids', $accessGroupIds, \PDO::PARAM_INT); return $this->retrieveHostCategories($concatenator, null); } /** * @param SqlConcatenator $concatenator * @param RequestParametersInterface|null $requestParameters * * @throws AssertionFailedException * * @return HostCategory[] */ private function retrieveHostCategories( SqlConcatenator $concatenator, ?RequestParametersInterface $requestParameters, ): array { // Exclude severities from the results $concatenator->appendWhere('hc.level IS NULL'); // Settup for search, pagination, order $sqlTranslator = $requestParameters ? new SqlRequestParametersTranslator($requestParameters) : null; $sqlTranslator?->getRequestParameters()->setConcordanceStrictMode(RequestParameters::CONCORDANCE_MODE_STRICT); $sqlTranslator?->setConcordanceArray([ 'id' => 'hc.hc_id', 'name' => 'hc.hc_name', 'alias' => 'hc.hc_alias', 'is_activated' => 'hc.hc_activate', ]); $sqlTranslator?->addNormalizer('is_activated', new BoolToEnumNormalizer()); $sqlTranslator?->translateForConcatenator($concatenator); $statement = $this->db->prepare($this->translateDbName($concatenator->__toString())); $sqlTranslator?->bindSearchValues($statement); $concatenator->bindValuesToStatement($statement); $statement->execute(); $sqlTranslator?->calculateNumberOfRows($this->db); $hostCategories = []; while (is_array($result = $statement->fetch(\PDO::FETCH_ASSOC))) { /** @var array{hc_id:int,hc_name:string,hc_alias:string,hc_activate:'0'|'1',hc_comment:string|null} $result */ $hostCategories[] = $this->createHostCategoryFromArray($result); } return $hostCategories; } /** * @param _Category $result * * @throws AssertionFailedException * * @return HostCategory */ private function createHostCategoryFromArray(array $result): HostCategory { $hostCategory = new HostCategory( $result['hc_id'], $result['hc_name'], $result['hc_alias'] ); $hostCategory->setActivated((bool) $result['hc_activate']); $hostCategory->setComment($result['hc_comment']); return $hostCategory; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostCategory/Infrastructure/Repository/DbWriteHostCategoryRepository.php
centreon/src/Core/HostCategory/Infrastructure/Repository/DbWriteHostCategoryRepository.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\HostCategory\Infrastructure\Repository; use Centreon\Domain\Log\LoggerTrait; use Centreon\Infrastructure\DatabaseConnection; use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB; use Core\Common\Infrastructure\RequestParameters\Normalizer\BoolToEnumNormalizer; use Core\HostCategory\Application\Repository\WriteHostCategoryRepositoryInterface; use Core\HostCategory\Domain\Model\HostCategory; use Core\HostCategory\Domain\Model\NewHostCategory; use Utility\SqlConcatenator; class DbWriteHostCategoryRepository extends AbstractRepositoryRDB implements WriteHostCategoryRepositoryInterface { use LoggerTrait; public function __construct(DatabaseConnection $db) { $this->db = $db; } /** * @inheritDoc */ public function deleteById(int $hostCategoryId): void { $this->debug('Delete host category', ['hostCategoryId' => $hostCategoryId]); $request = $this->translateDbName( <<<'SQL' DELETE hc FROM `:db`.hostcategories hc WHERE hc.hc_id = :hostCategoryId SQL ); $request .= ' AND hc.level IS NULL '; $statement = $this->db->prepare($request); $statement->bindValue(':hostCategoryId', $hostCategoryId, \PDO::PARAM_INT); $statement->execute(); } /** * @inheritDoc */ public function add(NewHostCategory $hostCategory): int { $this->debug('Add host category', ['hostCategory' => $hostCategory]); $request = $this->translateDbName( <<<'SQL' INSERT INTO `:db`.hostcategories (hc_name, hc_alias, hc_comment, hc_activate) VALUES (:name, :alias, :comment, :isActivated) SQL ); $statement = $this->db->prepare($request); $statement->bindValue(':name', $hostCategory->getName(), \PDO::PARAM_STR); $statement->bindValue(':alias', $hostCategory->getAlias(), \PDO::PARAM_STR); $statement->bindValue(':comment', $hostCategory->getComment(), \PDO::PARAM_STR); $statement->bindValue( ':isActivated', (new BoolToEnumNormalizer())->normalize($hostCategory->isActivated()), \PDO::PARAM_STR ); $statement->execute(); return (int) $this->db->lastInsertId(); } /** * @inheritDoc */ public function update(HostCategory $hostCategory): void { $this->debug('Update host category', ['hostCategory' => $hostCategory]); $request = $this->translateDbName( <<<'SQL' UPDATE `:db`.hostcategories set hc_name = :name, hc_alias = :alias, hc_comment = :comment, hc_activate = :isActivated WHERE hc_id = :id AND level IS NULL SQL ); $statement = $this->db->prepare($request); $statement->bindValue(':id', $hostCategory->getId(), \PDO::PARAM_INT); $statement->bindValue(':name', $hostCategory->getName(), \PDO::PARAM_STR); $statement->bindValue(':alias', $hostCategory->getAlias(), \PDO::PARAM_STR); $statement->bindValue(':comment', $hostCategory->getComment(), \PDO::PARAM_STR); $statement->bindValue( ':isActivated', (new BoolToEnumNormalizer())->normalize($hostCategory->isActivated()), \PDO::PARAM_STR ); $statement->execute(); } /** * @inheritDoc */ public function linkToHost(int $hostId, array $categoryIds): void { $this->info('Linking host categories to host/host template', [ 'host_id' => $hostId, 'category_ids' => $categoryIds, ]); if ($categoryIds === []) { return; } $bindValues = []; $subQuery = []; foreach ($categoryIds as $key => $categoryId) { $bindValues[":category_id_{$key}"] = $categoryId; $subQuery[] = "(:category_id_{$key}, :host_id)"; } $statement = $this->db->prepare($this->translateDbName( 'INSERT INTO `:db`.`hostcategories_relation` (hostcategories_hc_id, host_host_id) VALUES ' . implode(', ', $subQuery) )); foreach ($bindValues as $key => $value) { $statement->bindValue($key, $value, \PDO::PARAM_INT); } $statement->bindValue(':host_id', $hostId, \PDO::PARAM_INT); $statement->execute(); } /** * @inheritDoc */ public function unlinkFromHost(int $hostId, array $categoryIds): void { $this->info('Unlinking host categories from host/host template', [ 'host_id' => $hostId, 'category_ids' => $categoryIds, ]); if ($categoryIds === []) { return; } $concatenator = new SqlConcatenator(); $concatenator ->appendWhere('host_host_id = :host_id') ->appendWhere('hostcategories_hc_id in (:category_ids)') ->storeBindValue(':host_id', $hostId, \PDO::PARAM_INT) ->storeBindValueMultiple(':category_ids', $categoryIds, \PDO::PARAM_INT); $statement = $this->db->prepare($this->translateDbName( 'DELETE FROM `:db`.`hostcategories_relation`' . $concatenator->__toString() )); $concatenator->bindValuesToStatement($statement); $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/HostCategory/Infrastructure/Repository/DbWriteHostCategoryActionLogRepository.php
centreon/src/Core/HostCategory/Infrastructure/Repository/DbWriteHostCategoryActionLogRepository.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\HostCategory\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\Common\Infrastructure\Repository\AbstractRepositoryRDB; use Core\HostCategory\Application\Repository\ReadHostCategoryRepositoryInterface; use Core\HostCategory\Application\Repository\WriteHostCategoryRepositoryInterface; use Core\HostCategory\Domain\Model\HostCategory; use Core\HostCategory\Domain\Model\NewHostCategory; class DbWriteHostCategoryActionLogRepository extends AbstractRepositoryRDB implements WriteHostCategoryRepositoryInterface { use LoggerTrait; public const HOST_CATEGORY_PROPERTIES_MAP = [ 'name' => 'hc_name', 'alias' => 'hc_alias', 'comment' => 'hc_comment', 'isActivated' => 'hc_activate', ]; public function __construct( private readonly WriteHostCategoryRepositoryInterface $writeHostCategoryRepository, private readonly WriteActionLogRepositoryInterface $writeActionLogRepository, private readonly ReadHostCategoryRepositoryInterface $readHostCategoryRepository, private readonly ContactInterface $user, DatabaseConnection $db, ) { $this->db = $db; } /** * @inheritDoc */ public function deleteById(int $hostCategoryId): void { try { $hostCategory = $this->readHostCategoryRepository->findById($hostCategoryId); if ($hostCategory === null) { throw new RepositoryException('Cannot find host category to delete.'); } $this->writeHostCategoryRepository->deleteById($hostCategoryId); $actionLog = new ActionLog( objectType: ActionLog::OBJECT_TYPE_HOSTCATEGORIES, objectId: $hostCategoryId, objectName: $hostCategory->getName(), actionType: ActionLog::ACTION_TYPE_DELETE, contactId: $this->user->getId(), ); $this->writeActionLogRepository->addAction($actionLog); } catch (\Throwable $ex) { $this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]); throw $ex; } } /** * @inheritDoc */ public function add(NewHostCategory $hostCategory): int { try { $hostCategoryId = $this->writeHostCategoryRepository->add($hostCategory); if ($hostCategoryId === 0) { throw new RepositoryException('Host Category ID cannot be 0'); } $actionLog = new ActionLog( objectType: ActionLog::OBJECT_TYPE_HOSTCATEGORIES, objectId: $hostCategoryId, objectName: $hostCategory->getName(), actionType: ActionLog::ACTION_TYPE_ADD, contactId: $this->user->getId(), ); $actionLogId = $this->writeActionLogRepository->addAction($actionLog); $actionLog->setId($actionLogId); $this->writeActionLogRepository->addActionDetails( $actionLog, $this->getNewHostCategoryAsArray($hostCategory) ); return $hostCategoryId; } catch (\Throwable $ex) { $this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]); throw $ex; } } /** * @inheritDoc */ public function update(HostCategory $hostCategory): void { try { $initialHostCategory = $this->readHostCategoryRepository->findById($hostCategory->getId()); if ($initialHostCategory === null) { throw new RepositoryException('Cannot find host category to update.'); } $diff = $this->getHostCategoryDiff($initialHostCategory, $hostCategory); $this->writeHostCategoryRepository->update($hostCategory); // If enable/disable has been updated if (array_key_exists('hc_activate', $diff)) { // If only this property has been changed, we log a specific action if (count($diff) === 1) { $actionLog = new ActionLog( objectType: ActionLog::OBJECT_TYPE_HOSTCATEGORIES, objectId: $hostCategory->getId(), objectName: $hostCategory->getName(), actionType: $diff['hc_activate'] ? ActionLog::ACTION_TYPE_ENABLE : ActionLog::ACTION_TYPE_DISABLE, contactId: $this->user->getId(), ); $this->writeActionLogRepository->addAction($actionLog); } // If additional properties has changed, we log both a change and enable/disable action if (count($diff) > 1) { $actionLog = new ActionLog( objectType: ActionLog::OBJECT_TYPE_HOSTCATEGORIES, objectId: $hostCategory->getId(), objectName: $hostCategory->getName(), actionType: $diff['hc_activate'] ? ActionLog::ACTION_TYPE_ENABLE : ActionLog::ACTION_TYPE_DISABLE, contactId: $this->user->getId(), ); $this->writeActionLogRepository->addAction($actionLog); $actionLog = new ActionLog( objectType: ActionLog::OBJECT_TYPE_HOSTCATEGORIES, objectId: $hostCategory->getId(), objectName: $hostCategory->getName(), actionType: ActionLog::ACTION_TYPE_CHANGE, contactId: $this->user->getId(), ); $actionLogId = $this->writeActionLogRepository->addAction($actionLog); $actionLog->setId($actionLogId); $this->writeActionLogRepository->addActionDetails($actionLog, $diff); } return; } // If more than one property has changed, we log a change action $actionLog = new ActionLog( objectType: ActionLog::OBJECT_TYPE_HOSTCATEGORIES, objectId: $hostCategory->getId(), objectName: $hostCategory->getName(), actionType: ActionLog::ACTION_TYPE_CHANGE, contactId: $this->user->getId(), ); $actionLogId = $this->writeActionLogRepository->addAction($actionLog); $actionLog->setId($actionLogId); $this->writeActionLogRepository->addActionDetails($actionLog, $diff); } catch (\Throwable $ex) { $this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]); throw $ex; } } /** * @inheritDoc */ public function linkToHost(int $hostId, array $categoryIds): void { $this->writeHostCategoryRepository->linkToHost($hostId, $categoryIds); } /** * @inheritDoc */ public function unlinkFromHost(int $hostId, array $categoryIds): void { $this->writeHostCategoryRepository->unlinkFromHost($hostId, $categoryIds); } /** * Compare the initial and updated HostCategory and return the differences. * * @param HostCategory $initialHostCategory * @param HostCategory $updatedHostCategory * * @return array{ * hc_name?: string, * hc_alias?: string, * hc_activate?: string, * hc_comment?: string * } */ private function getHostCategoryDiff( HostCategory $initialHostCategory, HostCategory $updatedHostCategory, ): array { $diff = []; $reflection = new \ReflectionClass($initialHostCategory); $properties = $reflection->getProperties(); foreach ($properties as $property) { $property->setAccessible(true); $value1 = $property->getValue($initialHostCategory); $value2 = $property->getValue($updatedHostCategory); if ($value1 !== $value2) { if ($property->getName() === 'isActivated') { $diff[self::HOST_CATEGORY_PROPERTIES_MAP[$property->getName()]] = $value2 ? '1' : '0'; continue; } if ($property->getName() === 'comment') { $diff[self::HOST_CATEGORY_PROPERTIES_MAP[$property->getName()]] = $value2 ?? ''; continue; } if ((string) $property->getType() === 'string') { $diff[self::HOST_CATEGORY_PROPERTIES_MAP[$property->getName()]] = is_string($value2) ? $value2 : throw new RepositoryException('Property value is not a string'); continue; } } } return $diff; } /** * Format the Host Category as property => value array. * * @param NewHostCategory $hostCategory * * @return array<string, string> */ private function getNewHostCategoryAsArray( NewHostCategory $hostCategory, ): array { $reflection = new \ReflectionClass($hostCategory); $properties = $reflection->getProperties(); $hostCategoryAsArray = []; foreach ($properties as $property) { $property->setAccessible(true); if ($property->getName() === 'isActivated') { $hostCategoryAsArray[self::HOST_CATEGORY_PROPERTIES_MAP[$property->getName()]] = $property->getValue($hostCategory) ? '1' : '0'; } elseif ($property->getName() === 'comment') { $hostCategoryAsArray[self::HOST_CATEGORY_PROPERTIES_MAP[$property->getName()]] = $property->getValue($hostCategory) ?? ''; } else { $hostCategoryAsArray[self::HOST_CATEGORY_PROPERTIES_MAP[$property->getName()]] = is_string($property->getValue($hostCategory)) ? $property->getValue($hostCategory) : throw new RepositoryException('Property value is not a string'); } } return $hostCategoryAsArray; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostCategory/Infrastructure/Repository/HostCategoryRepositoryTrait.php
centreon/src/Core/HostCategory/Infrastructure/Repository/HostCategoryRepositoryTrait.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\HostCategory\Infrastructure\Repository; use Core\Common\Infrastructure\Repository\SqlMultipleBindTrait; trait HostCategoryRepositoryTrait { use SqlMultipleBindTrait; /** * @param int[] $accessGroupIds * * @return bool */ public function hasRestrictedAccessToHostCategories(array $accessGroupIds): bool { if ($accessGroupIds === []) { return false; } [$bindValues, $bindQuery] = $this->createMultipleBindQuery($accessGroupIds, ':access_group_id_'); $request = <<<SQL SELECT 1 FROM `:db`.acl_resources_hc_relations arhcr INNER JOIN `:db`.acl_resources res ON res.acl_res_id = arhcr.acl_res_id INNER JOIN `:db`.acl_res_group_relations argr ON argr.acl_res_id = res.acl_res_id INNER JOIN `:db`.acl_groups ag ON ag.acl_group_id = argr.acl_group_id WHERE res.acl_res_activate = '1' AND ag.acl_group_id IN ({$bindQuery}) SQL; $statement = $this->db->prepare($this->translateDbName($request)); foreach ($bindValues as $key => $value) { $statement->bindValue($key, $value, \PDO::PARAM_INT); } $statement->execute(); return (bool) $statement->fetchColumn(); } /** * @param int[] $accessGroupIds * * @return string */ private function generateHostCategoryAclSubRequest(array $accessGroupIds = []): string { $request = ''; if ( $accessGroupIds !== [] && $this->hasRestrictedAccessToHostCategories($accessGroupIds) ) { [, $bindQuery] = $this->createMultipleBindQuery($accessGroupIds, ':access_group_id_'); $request = <<<SQL SELECT arhcr.hc_id FROM `:db`.acl_resources_hc_relations arhcr INNER JOIN `:db`.acl_resources res ON res.acl_res_id = arhcr.acl_res_id INNER JOIN `:db`.acl_res_group_relations argr ON argr.acl_res_id = res.acl_res_id INNER JOIN `:db`.acl_groups ag ON ag.acl_group_id = argr.acl_group_id WHERE ag.acl_group_id IN ({$bindQuery}) SQL; } return $request; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostCategory/Infrastructure/Repository/DbReadRealTimeHostCategoryRepository.php
centreon/src/Core/HostCategory/Infrastructure/Repository/DbReadRealTimeHostCategoryRepository.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\HostCategory\Infrastructure\Repository; use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface; use Centreon\Infrastructure\DatabaseConnection; use Centreon\Infrastructure\RequestParameters\SqlRequestParametersTranslator; use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB; use Core\Common\Infrastructure\Repository\SqlMultipleBindTrait; use Core\HostCategory\Application\Repository\ReadRealTimeHostCategoryRepositoryInterface; use Core\Tag\RealTime\Domain\Model\Tag; /** * @phpstan-type _HostCategoryResultSet array{ * id: int, * name: string, * type: int * } */ class DbReadRealTimeHostCategoryRepository extends AbstractRepositoryRDB implements ReadRealTimeHostCategoryRepositoryInterface { use SqlMultipleBindTrait; /** * @param DatabaseConnection $db */ public function __construct(DatabaseConnection $db) { $this->db = $db; } /** * @inheritDoc */ public function findAll(?RequestParametersInterface $requestParameters): array { $sqlTranslator = $requestParameters ? new SqlRequestParametersTranslator($requestParameters) : null; $sqlTranslator?->setConcordanceArray([ 'id' => 'host_categories.id', 'name' => 'host_categories.name', 'host_group.id' => 'host_groups.id', 'host_group.name' => 'host_groups.name', ]); /** * Tag types: * 0 = service groups, * 1 = host groups, * 2 = service categories. * 3 = host categories. */ $request = <<<'SQL' SELECT 1 AS REALTIME, host_categories.id AS id, host_categories.name AS name, host_categories.type AS `type` FROM `:dbstg`.resources INNER JOIN `:dbstg`.resources_tags rtags ON rtags.resource_id = resources.resource_id INNER JOIN `:dbstg`.tags AS host_categories ON host_categories.tag_id = rtags.tag_id AND host_categories.`type` = 3 SQL; $searchRequest = $sqlTranslator?->translateSearchParameterToSql(); if ($searchRequest !== null) { $request .= <<<'SQL' LEFT JOIN `:dbstg`.resources_tags rtags_host_groups ON rtags_host_groups.resource_id = resources.resource_id LEFT JOIN `:dbstg`.tags AS host_groups ON rtags_host_groups.tag_id = host_groups.tag_id AND host_groups.`type` = 1 SQL; $request .= $searchRequest; } $request .= ' GROUP BY host_categories.id, host_categories.name, host_categories.type'; $sortRequest = $sqlTranslator?->translateSortParameterToSql(); $request .= $sortRequest ?? ' ORDER BY host_categories.name ASC'; // handle pagination $request .= $sqlTranslator?->translatePaginationToSql(); // Prepare SQL + bind values $statement = $this->db->prepare($this->translateDbName($request)); $sqlTranslator?->bindSearchValues($statement); $statement->setFetchMode(\PDO::FETCH_ASSOC); $statement->execute(); // Calculate the number of rows for the pagination. $sqlTranslator?->calculateNumberOfRows($this->db); // Retrieve data $hostCategories = []; foreach ($statement as $record) { /** @var _HostCategoryResultSet $record */ $hostCategories[] = $this->createFromRecord($record); } return $hostCategories; } /** * @inheritDoc */ public function findAllByAccessGroupIds(?RequestParametersInterface $requestParameters, array $accessGroupIds): array { $sqlTranslator = $requestParameters ? new SqlRequestParametersTranslator($requestParameters) : null; $sqlTranslator?->setConcordanceArray([ 'id' => 'host_categories.id', 'name' => 'host_categories.name', 'host_group.id' => 'host_groups.id', 'host_group.name' => 'host_groups.name', ]); [$bindValues, $bindQuery] = $this->createMultipleBindQuery($accessGroupIds, ':access_group_id_'); /** * Tag types: * 0 = service groups, * 1 = host groups, * 2 = service categories. * 3 = host categories. */ $request = <<<'SQL' SELECT 1 AS REALTIME, host_categories.id AS id, host_categories.name AS name, host_categories.type AS `type` FROM `:dbstg`.resources INNER JOIN `:dbstg`.resources_tags rtags ON rtags.resource_id = resources.resource_id INNER JOIN `:dbstg`.tags AS host_categories ON host_categories.tag_id = rtags.tag_id AND host_categories.`type` = 3 INNER JOIN `:db`.acl_resources_hc_relations arhr ON host_categories.id = arhr.hc_id INNER JOIN `:db`.acl_resources res ON arhr.acl_res_id = res.acl_res_id INNER JOIN `:db`.acl_res_group_relations argr ON res.acl_res_id = argr.acl_res_id INNER JOIN `:db`.acl_groups ag ON argr.acl_group_id = ag.acl_group_id SQL; $searchRequest = $sqlTranslator?->translateSearchParameterToSql(); if ($searchRequest !== null) { $request .= <<<'SQL' LEFT JOIN `:dbstg`.resources_tags rtags_host_groups ON rtags_host_groups.resource_id = resources.resource_id LEFT JOIN `:dbstg`.tags AS host_groups ON rtags_host_groups.tag_id = host_groups.tag_id AND host_groups.`type` = 1 SQL; } $request .= $searchRequest !== null ? $searchRequest . ' AND ' : ' WHERE '; $request .= " ag.acl_group_id IN ({$bindQuery})"; $request .= ' GROUP BY host_categories.id, host_categories.name, host_categories.type'; $sortRequest = $sqlTranslator?->translateSortParameterToSql(); $request .= $sortRequest ?? ' ORDER BY host_categories.name ASC'; // handle pagination $request .= $sqlTranslator?->translatePaginationToSql(); // Prepare SQL + bind values $statement = $this->db->prepare($this->translateDbName($request)); $sqlTranslator?->bindSearchValues($statement); foreach ($bindValues as $key => $value) { $statement->bindValue($key, $value, \PDO::PARAM_INT); } $statement->setFetchMode(\PDO::FETCH_ASSOC); $statement->execute(); // Calculate the number of rows for the pagination. $sqlTranslator?->calculateNumberOfRows($this->db); // Retrieve data $hostCategories = []; foreach ($statement as $record) { /** @var _HostCategoryResultSet $record */ $hostCategories[] = $this->createFromRecord($record); } return $hostCategories; } /** * @param _HostCategoryResultSet $data * * @return Tag */ private function createFromRecord(array $data): Tag { return new Tag(id: $data['id'], name: $data['name'], type: $data['type']); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostCategory/Infrastructure/API/FindHostCategories/FindHostCategoriesController.php
centreon/src/Core/HostCategory/Infrastructure/API/FindHostCategories/FindHostCategoriesController.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\HostCategory\Infrastructure\API\FindHostCategories; use Centreon\Application\Controller\AbstractController; use Core\HostCategory\Application\UseCase\FindHostCategories\FindHostCategories; final class FindHostCategoriesController extends AbstractController { /** * @param FindHostCategories $useCase * @param FindHostCategoriesPresenter $presenter * * @return object */ public function __invoke(FindHostCategories $useCase, FindHostCategoriesPresenter $presenter): object { $this->denyAccessUnlessGrantedForApiConfiguration(); $useCase($presenter); return $presenter->show(); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostCategory/Infrastructure/API/FindHostCategories/FindHostCategoriesPresenter.php
centreon/src/Core/HostCategory/Infrastructure/API/FindHostCategories/FindHostCategoriesPresenter.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\HostCategory\Infrastructure\API\FindHostCategories; use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface; use Core\Application\Common\UseCase\AbstractPresenter; use Core\HostCategory\Application\UseCase\FindHostCategories\FindHostCategoriesResponse; use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface; class FindHostCategoriesPresenter extends AbstractPresenter { /** * @param RequestParametersInterface $requestParameters * @param PresenterFormatterInterface $presenterFormatter */ public function __construct( private RequestParametersInterface $requestParameters, protected PresenterFormatterInterface $presenterFormatter, ) { parent::__construct($presenterFormatter); } /** * @param FindHostCategoriesResponse $data */ public function present(mixed $data): void { $result = []; foreach ($data->hostCategories as $hostCategory) { $result[] = [ 'id' => $hostCategory['id'], 'name' => $hostCategory['name'], 'alias' => $hostCategory['alias'], 'is_activated' => $hostCategory['is_activated'], 'comment' => $hostCategory['comment'], ]; } parent::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/HostCategory/Infrastructure/API/UpdateHostCategory/UpdateHostCategoryController.php
centreon/src/Core/HostCategory/Infrastructure/API/UpdateHostCategory/UpdateHostCategoryController.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\HostCategory\Infrastructure\API\UpdateHostCategory; use Centreon\Application\Controller\AbstractController; use Centreon\Domain\Log\LoggerTrait; use Core\Application\Common\UseCase\ErrorResponse; use Core\Application\Common\UseCase\InvalidArgumentResponse; use Core\HostCategory\Application\UseCase\UpdateHostCategory\UpdateHostCategory; use Core\HostCategory\Application\UseCase\UpdateHostCategory\UpdateHostCategoryRequest; use Core\Infrastructure\Common\Api\DefaultPresenter; use Symfony\Component\HttpFoundation\Request; final class UpdateHostCategoryController extends AbstractController { use LoggerTrait; /** * @param int $hostCategoryId * @param Request $request * @param UpdateHostCategory $useCase * @param DefaultPresenter $presenter * * @return object */ public function __invoke( int $hostCategoryId, Request $request, UpdateHostCategory $useCase, DefaultPresenter $presenter, ): object { $this->denyAccessUnlessGrantedForApiConfiguration(); try { /** @var array{name:string,alias:string,is_activated?:bool,comment?:string|null} $data */ $data = $this->validateAndRetrieveDataSent($request, __DIR__ . '/UpdateHostCategorySchema.json'); $hostCategoryRequest = $this->createRequestDto($data, $hostCategoryId); $useCase($hostCategoryRequest, $presenter); } catch (\InvalidArgumentException $ex) { $this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]); $presenter->setResponseStatus(new InvalidArgumentResponse($ex)); } catch (\Throwable $ex) { $this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]); $presenter->setResponseStatus(new ErrorResponse($ex)); } return $presenter->show(); } /** * @param array{name:string,alias:string,is_activated?:bool,comment?:string|null} $data * @param int $hostCategoryId * * @return UpdateHostCategoryRequest */ private function createRequestDto(array $data, int $hostCategoryId): UpdateHostCategoryRequest { $hostCategoryRequest = new UpdateHostCategoryRequest(); $hostCategoryRequest->id = $hostCategoryId; $hostCategoryRequest->name = $data['name']; $hostCategoryRequest->alias = $data['alias']; $hostCategoryRequest->isActivated = $data['is_activated'] ?? true; $hostCategoryRequest->comment = $data['comment'] ?? null; return $hostCategoryRequest; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostCategory/Infrastructure/API/DeleteHostCategory/DeleteHostCategoryController.php
centreon/src/Core/HostCategory/Infrastructure/API/DeleteHostCategory/DeleteHostCategoryController.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\HostCategory\Infrastructure\API\DeleteHostCategory; use Centreon\Application\Controller\AbstractController; use Core\HostCategory\Application\UseCase\DeleteHostCategory\DeleteHostCategory; use Core\Infrastructure\Common\Api\DefaultPresenter; final class DeleteHostCategoryController extends AbstractController { public function __invoke( int $hostCategoryId, DeleteHostCategory $useCase, DefaultPresenter $presenter, ): object { $this->denyAccessUnlessGrantedForApiConfiguration(); $useCase($hostCategoryId, $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/HostCategory/Infrastructure/API/AddHostCategory/AddHostCategoryController.php
centreon/src/Core/HostCategory/Infrastructure/API/AddHostCategory/AddHostCategoryController.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\HostCategory\Infrastructure\API\AddHostCategory; use Centreon\Application\Controller\AbstractController; use Centreon\Domain\Log\LoggerTrait; use Core\Application\Common\UseCase\ErrorResponse; use Core\Application\Common\UseCase\InvalidArgumentResponse; use Core\HostCategory\Application\UseCase\AddHostCategory\AddHostCategory; use Core\HostCategory\Application\UseCase\AddHostCategory\AddHostCategoryRequest; use Symfony\Component\HttpFoundation\Request; final class AddHostCategoryController extends AbstractController { use LoggerTrait; /** * @param Request $request * @param AddHostCategory $useCase * @param AddHostCategoryPresenter $presenter * * @return object */ public function __invoke( Request $request, AddHostCategory $useCase, AddHostCategoryPresenter $presenter, ): object { $this->denyAccessUnlessGrantedForApiConfiguration(); try { /** @var array{name:string,alias:string,is_activated?:bool,comment?:string|null} $data */ $data = $this->validateAndRetrieveDataSent($request, __DIR__ . '/AddHostCategorySchema.json'); $hostCategoryRequest = $this->createRequestDto($data); $useCase($hostCategoryRequest, $presenter); } catch (\InvalidArgumentException $ex) { $this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]); $presenter->setResponseStatus(new InvalidArgumentResponse($ex)); } catch (\Throwable $ex) { $this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]); $presenter->setResponseStatus(new ErrorResponse($ex)); } return $presenter->show(); } /** * @param array{name:string,alias:string,is_activated?:bool,comment?:string|null} $data * * @return AddHostCategoryRequest */ private function createRequestDto(array $data): AddHostCategoryRequest { $hostCategoryRequest = new AddHostCategoryRequest(); $hostCategoryRequest->name = $data['name']; $hostCategoryRequest->alias = $data['alias']; $hostCategoryRequest->isActivated = $data['is_activated'] ?? true; $hostCategoryRequest->comment = $data['comment'] ?? null; return $hostCategoryRequest; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostCategory/Infrastructure/API/AddHostCategory/AddHostCategoryPresenter.php
centreon/src/Core/HostCategory/Infrastructure/API/AddHostCategory/AddHostCategoryPresenter.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\HostCategory\Infrastructure\API\AddHostCategory; use Centreon\Domain\Log\LoggerTrait; use Core\Application\Common\UseCase\AbstractPresenter; use Core\Application\Common\UseCase\CreatedResponse; use Core\HostCategory\Application\UseCase\AddHostCategory\AddHostCategoryResponse; use Core\Infrastructure\Common\Api\Router; use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface; class AddHostCategoryPresenter extends AbstractPresenter { use LoggerTrait; private const ROUTE_NAME = 'FindHostCategory'; private const ROUTE_HOST_CATEGORY_ID = 'hostCategoryId'; public function __construct( protected PresenterFormatterInterface $presenterFormatter, readonly private Router $router, ) { parent::__construct($presenterFormatter); } /** * @inheritDoc */ public function present(mixed $data): void { if ( $data instanceof CreatedResponse && $data->getPayload() instanceof AddHostCategoryResponse ) { $payload = $data->getPayload(); $data->setPayload([ 'id' => $payload->id, 'name' => $payload->name, 'alias' => $payload->alias, 'is_activated' => $payload->isActivated, 'comment' => $payload->comment, ]); try { $this->setResponseHeaders([ 'Location' => $this->router->generate(self::ROUTE_NAME, [self::ROUTE_HOST_CATEGORY_ID => $payload->id]), ]); } catch (\Throwable $ex) { $this->error('Impossible to generate the location header', [ 'message' => $ex->getMessage(), 'trace' => $ex->getTraceAsString(), 'route' => self::ROUTE_NAME, 'payload' => $payload, ]); } } parent::present($data); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostCategory/Infrastructure/API/FindHostCategory/FindHostCategoryPresenter.php
centreon/src/Core/HostCategory/Infrastructure/API/FindHostCategory/FindHostCategoryPresenter.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\HostCategory\Infrastructure\API\FindHostCategory; use Core\Application\Common\UseCase\AbstractPresenter; use Core\HostCategory\Application\UseCase\FindHostCategory\FindHostCategoryResponse; use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface; class FindHostCategoryPresenter extends AbstractPresenter { /** * @param PresenterFormatterInterface $presenterFormatter */ public function __construct( protected PresenterFormatterInterface $presenterFormatter, ) { parent::__construct($presenterFormatter); } /** * @param FindHostCategoryResponse $data */ public function present(mixed $data): void { parent::present([ 'id' => $data->id, 'name' => $data->name, 'alias' => $data->alias, 'is_activated' => $data->isActivated, 'comment' => $data->comment, ]); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/HostCategory/Infrastructure/API/FindHostCategory/FindHostCategoryController.php
centreon/src/Core/HostCategory/Infrastructure/API/FindHostCategory/FindHostCategoryController.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\HostCategory\Infrastructure\API\FindHostCategory; use Centreon\Application\Controller\AbstractController; use Core\HostCategory\Application\UseCase\FindHostCategory\FindHostCategory; final class FindHostCategoryController extends AbstractController { /** * @param int $hostCategoryId * @param FindHostCategory $useCase * @param FindHostCategoryPresenter $presenter * * @return object */ public function __invoke( int $hostCategoryId, FindHostCategory $useCase, FindHostCategoryPresenter $presenter, ): object { $this->denyAccessUnlessGrantedForApiConfiguration(); $useCase($hostCategoryId, $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/HostCategory/Infrastructure/API/FindRealTimeHostCategories/FindRealTimeHostCategoriesController.php
centreon/src/Core/HostCategory/Infrastructure/API/FindRealTimeHostCategories/FindRealTimeHostCategoriesController.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\HostCategory\Infrastructure\API\FindRealTimeHostCategories; use Centreon\Application\Controller\AbstractController; use Core\HostCategory\Application\UseCase\FindRealTimeHostCategories\FindRealTimeHostCategories; use Core\HostCategory\Application\UseCase\FindRealTimeHostCategories\FindRealTimeHostCategoriesPresenterInterface; final class FindRealTimeHostCategoriesController extends AbstractController { /** * @param FindRealTimeHostCategories $useCase * @param FindRealTimeHostCategoriesPresenterInterface $presenter * * @return object */ public function __invoke( FindRealTimeHostCategories $useCase, FindRealTimeHostCategoriesPresenterInterface $presenter, ): object { /** * Access denied if no rights given to the realtime for the current user. */ $this->denyAccessUnlessGrantedForApiRealtime(); $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/HostCategory/Infrastructure/API/FindRealTimeHostCategories/FindRealTimeHostCategoriesPresenter.php
centreon/src/Core/HostCategory/Infrastructure/API/FindRealTimeHostCategories/FindRealTimeHostCategoriesPresenter.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\HostCategory\Infrastructure\API\FindRealTimeHostCategories; use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface; use Core\Application\Common\UseCase\AbstractPresenter; use Core\Application\Common\UseCase\ResponseStatusInterface; use Core\HostCategory\Application\UseCase\FindRealTimeHostCategories\FindRealTimeHostCategoriesPresenterInterface; use Core\HostCategory\Application\UseCase\FindRealTimeHostCategories\FindRealTimeHostCategoriesResponse; use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface; class FindRealTimeHostCategoriesPresenter extends AbstractPresenter implements FindRealTimeHostCategoriesPresenterInterface { /** * @param RequestParametersInterface $requestParameters * @param PresenterFormatterInterface $presenterFormatter */ public function __construct( private RequestParametersInterface $requestParameters, protected PresenterFormatterInterface $presenterFormatter, ) { } public function presentResponse(FindRealTimeHostCategoriesResponse|ResponseStatusInterface $response): void { if ($response instanceof ResponseStatusInterface) { $this->setResponseStatus($response); } else { parent::present([ 'result' => $response->tags, '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/Infrastructure/RealTime/Api/FindMetaService/FindMetaServicePresenter.php
centreon/src/Core/Infrastructure/RealTime/Api/FindMetaService/FindMetaServicePresenter.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\Infrastructure\RealTime\Api\FindMetaService; use Core\Application\Common\UseCase\AbstractPresenter; use Core\Application\RealTime\UseCase\FindMetaService\FindMetaServicePresenterInterface; use Core\Application\RealTime\UseCase\FindMetaService\FindMetaServiceResponse; use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface; use Core\Infrastructure\Common\Presenter\PresenterTrait; use Core\Infrastructure\RealTime\Hypermedia\HypermediaCreator; class FindMetaServicePresenter extends AbstractPresenter implements FindMetaServicePresenterInterface { use PresenterTrait; /** * @param HypermediaCreator $hypermediaCreator * @param PresenterFormatterInterface $presenterFormatter */ public function __construct( private HypermediaCreator $hypermediaCreator, protected PresenterFormatterInterface $presenterFormatter, ) { parent::__construct($presenterFormatter); } /** * {@inheritDoc} * * @param FindMetaServiceResponse $data */ public function present(mixed $data): void { $presenterResponse = [ 'uuid' => 'm' . $data->metaId, 'id' => $data->metaId, 'name' => $data->name, 'type' => 'metaservice', 'short_type' => 'm', 'status' => $data->status, 'in_downtime' => $data->isInDowntime, 'acknowledged' => $data->isAcknowledged, 'flapping' => $data->isFlapping, 'performance_data' => $data->performanceData, 'information' => $data->output, 'command_line' => $data->commandLine, 'notification_number' => $data->notificationNumber, 'latency' => $data->latency, 'percent_state_change' => $data->statusChangePercentage, 'passive_checks' => $data->hasPassiveChecks, 'execution_time' => $data->executionTime, 'active_checks' => $data->hasActiveChecks, 'groups' => [], 'parent' => null, 'monitoring_server_name' => $data->monitoringServerName, 'calculation_type' => $data->calculationType, ]; $acknowledgement = null; if ($data->acknowledgement !== []) { /** * Convert Acknowledgement dates into ISO 8601 format. */ $acknowledgement = $data->acknowledgement; $acknowledgement['entry_time'] = $this->formatDateToIso8601($data->acknowledgement['entry_time']); $acknowledgement['deletion_time'] = $this->formatDateToIso8601($data->acknowledgement['deletion_time']); } $presenterResponse['acknowledgement'] = $acknowledgement; /** * Convert downtime dates into ISO 8601 format. */ $formattedDatesDowntimes = []; foreach ($data->downtimes as $key => $downtime) { $formattedDatesDowntimes[$key] = $downtime; $formattedDatesDowntimes[$key]['start_time'] = $this->formatDateToIso8601($downtime['start_time']); $formattedDatesDowntimes[$key]['end_time'] = $this->formatDateToIso8601($downtime['end_time']); $formattedDatesDowntimes[$key]['actual_start_time'] = $this->formatDateToIso8601($downtime['actual_start_time']); $formattedDatesDowntimes[$key]['actual_end_time'] = $this->formatDateToIso8601($downtime['actual_end_time']); $formattedDatesDowntimes[$key]['entry_time'] = $this->formatDateToIso8601($downtime['entry_time']); $formattedDatesDowntimes[$key]['deletion_time'] = $this->formatDateToIso8601($downtime['deletion_time']); } $presenterResponse['downtimes'] = $formattedDatesDowntimes; /** * Calculate the duration. */ $presenterResponse['duration'] = $data->lastStatusChange !== null ? \CentreonDuration::toString(time() - $data->lastStatusChange->getTimestamp()) : null; /** * Convert dates to ISO 8601 format. */ $presenterResponse['next_check'] = $this->formatDateToIso8601($data->nextCheck); $presenterResponse['last_check'] = $this->formatDateToIso8601($data->lastCheck); $presenterResponse['last_time_with_no_issue'] = $this->formatDateToIso8601($data->lastTimeOk); $presenterResponse['last_status_change'] = $this->formatDateToIso8601($data->lastStatusChange); $presenterResponse['last_notification'] = $this->formatDateToIso8601($data->lastNotification); /** * Creating the 'tries' entry. */ $tries = $data->checkAttempts . '/' . $data->maxCheckAttempts; $statusType = $data->status['type'] === 0 ? 'S' : 'H'; $presenterResponse['tries'] = $tries . '(' . $statusType . ')'; /** * Creating Hypermedias. */ $parameters = [ 'type' => $data->type, 'hostId' => $data->hostId, 'serviceId' => $data->serviceId, 'internalId' => $data->metaId, 'hasGraphData' => $data->hasGraphData, ]; $endpoints = $this->hypermediaCreator->createEndpoints($parameters); $presenterResponse['links']['endpoints'] = [ 'notification_policy' => $endpoints['notification_policy'], 'timeline' => $endpoints['timeline'], 'timeline_download' => $endpoints['timeline_download'], 'status_graph' => $endpoints['status_graph'], 'performance_graph' => $endpoints['performance_graph'], 'metrics' => $endpoints['metrics'], 'details' => $endpoints['details'], ]; $presenterResponse['links']['uris'] = $this->hypermediaCreator->createInternalUris($parameters); parent::present($presenterResponse); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Infrastructure/RealTime/Api/FindMetaService/FindMetaServiceController.php
centreon/src/Core/Infrastructure/RealTime/Api/FindMetaService/FindMetaServiceController.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\Infrastructure\RealTime\Api\FindMetaService; use Centreon\Application\Controller\AbstractController; use Core\Application\RealTime\UseCase\FindMetaService\FindMetaService; use Core\Application\RealTime\UseCase\FindMetaService\FindMetaServicePresenterInterface; final class FindMetaServiceController extends AbstractController { /** * @param int $metaId * @param FindMetaService $useCase * @param FindMetaServicePresenterInterface $presenter * * @return object */ public function __invoke( int $metaId, FindMetaService $useCase, FindMetaServicePresenterInterface $presenter, ): object { /** * Deny access if user has no rights on the real time. */ $this->denyAccessUnlessGrantedForApiRealtime(); $useCase($metaId, $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/Infrastructure/RealTime/Api/FindService/FindServiceController.php
centreon/src/Core/Infrastructure/RealTime/Api/FindService/FindServiceController.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\Infrastructure\RealTime\Api\FindService; use Centreon\Application\Controller\AbstractController; use Core\Application\RealTime\UseCase\FindService\FindService; use Core\Application\RealTime\UseCase\FindService\FindServicePresenterInterface; final class FindServiceController extends AbstractController { public function __invoke( int $hostId, int $serviceId, FindService $useCase, FindServicePresenterInterface $presenter, ): object { /** * Deny access if user has no rights on the real time. */ $this->denyAccessUnlessGrantedForApiRealtime(); $useCase($hostId, $serviceId, $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/Infrastructure/RealTime/Api/FindService/FindServicePresenter.php
centreon/src/Core/Infrastructure/RealTime/Api/FindService/FindServicePresenter.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\Infrastructure\RealTime\Api\FindService; use Core\Application\Common\UseCase\AbstractPresenter; use Core\Application\RealTime\UseCase\FindService\FindServicePresenterInterface; use Core\Application\RealTime\UseCase\FindService\FindServiceResponse; use Core\Infrastructure\Common\Api\HttpUrlTrait; use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface; use Core\Infrastructure\Common\Presenter\PresenterTrait; use Core\Infrastructure\RealTime\Hypermedia\HypermediaCreator; class FindServicePresenter extends AbstractPresenter implements FindServicePresenterInterface { use PresenterTrait; use HttpUrlTrait; /** * @param HypermediaCreator $hypermediaCreator * @param PresenterFormatterInterface $presenterFormatter */ public function __construct( private HypermediaCreator $hypermediaCreator, protected PresenterFormatterInterface $presenterFormatter, ) { parent::__construct($presenterFormatter); } /** * {@inheritDoc} * * @param FindServiceResponse $data */ public function present(mixed $data): void { $presenterResponse = [ 'uuid' => 'h' . $data->hostId . '-s' . $data->serviceId, 'id' => $data->serviceId, 'name' => $data->name, 'type' => 'service', 'short_type' => 's', 'status' => $data->status, 'in_downtime' => $data->isInDowntime, 'acknowledged' => $data->isAcknowledged, 'flapping' => $data->isFlapping, 'performance_data' => $data->performanceData, 'information' => $data->output, 'command_line' => $data->commandLine, 'notification_number' => $data->notificationNumber, 'latency' => $data->latency, 'percent_state_change' => $data->statusChangePercentage, 'passive_checks' => $data->hasPassiveChecks, 'execution_time' => $data->executionTime, 'active_checks' => $data->hasActiveChecks, 'icon' => $data->icon, 'groups' => $this->hypermediaCreator->convertGroupsForPresenter($data), 'parent' => $data->host, 'monitoring_server_name' => $data->host['monitoring_server_name'], 'categories' => $this->hypermediaCreator->convertCategoriesForPresenter($data), 'severity' => $data->severity, ]; if (! empty($data->severity['icon'])) { /** * normalize the URL to the severity icon. */ $presenterResponse['severity']['icon']['url'] = $this->getBaseUri() . '/img/media/' . $data->severity['icon']['url']; } $acknowledgement = null; if ($data->acknowledgement !== []) { /** * Convert Acknowledgement dates into ISO 8601 format. */ $acknowledgement = $data->acknowledgement; $acknowledgement['entry_time'] = $this->formatDateToIso8601($data->acknowledgement['entry_time']); $acknowledgement['deletion_time'] = $this->formatDateToIso8601($data->acknowledgement['deletion_time']); } $presenterResponse['acknowledgement'] = $acknowledgement; /** * Convert downtime dates into ISO 8601 format. */ $formattedDatesDowntimes = []; foreach ($data->downtimes as $key => $downtime) { $formattedDatesDowntimes[$key] = $downtime; $formattedDatesDowntimes[$key]['start_time'] = $this->formatDateToIso8601($downtime['start_time']); $formattedDatesDowntimes[$key]['end_time'] = $this->formatDateToIso8601($downtime['end_time']); $formattedDatesDowntimes[$key]['actual_start_time'] = $this->formatDateToIso8601($downtime['actual_start_time']); $formattedDatesDowntimes[$key]['actual_end_time'] = $this->formatDateToIso8601($downtime['actual_end_time']); $formattedDatesDowntimes[$key]['entry_time'] = $this->formatDateToIso8601($downtime['entry_time']); $formattedDatesDowntimes[$key]['deletion_time'] = $this->formatDateToIso8601($downtime['deletion_time']); } $presenterResponse['downtimes'] = $formattedDatesDowntimes; /** * Calculate the duration. */ $presenterResponse['duration'] = $data->lastStatusChange !== null ? \CentreonDuration::toString(time() - $data->lastStatusChange->getTimestamp()) : null; /** * Convert dates to ISO 8601 format. */ $presenterResponse['next_check'] = $this->formatDateToIso8601($data->nextCheck); $presenterResponse['last_check'] = $this->formatDateToIso8601($data->lastCheck); $presenterResponse['last_time_with_no_issue'] = $this->formatDateToIso8601($data->lastTimeOk); $presenterResponse['last_status_change'] = $this->formatDateToIso8601($data->lastStatusChange); $presenterResponse['last_notification'] = $this->formatDateToIso8601($data->lastNotification); /** * Creating the 'tries' entry. */ $tries = $data->checkAttempts . '/' . $data->maxCheckAttempts; $statusType = $data->status['type'] === 0 ? 'S' : 'H'; $presenterResponse['tries'] = $tries . '(' . $statusType . ')'; /** * Creating Hypermedias. */ $parameters = [ 'type' => $data->type, 'hostId' => $data->hostId, 'serviceId' => $data->serviceId, 'hasGraphData' => $data->hasGraphData, ]; $endpoints = $this->hypermediaCreator->createEndpoints($parameters); $presenterResponse['links']['endpoints'] = [ 'notification_policy' => $endpoints['notification_policy'], 'timeline' => $endpoints['timeline'], 'timeline_download' => $endpoints['timeline_download'], 'status_graph' => $endpoints['status_graph'], 'performance_graph' => $endpoints['performance_graph'], 'details' => $endpoints['details'], 'metrics' => $endpoints['metrics'], ]; $presenterResponse['links']['uris'] = $this->hypermediaCreator->createInternalUris($parameters); parent::present($presenterResponse); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Infrastructure/RealTime/Api/FindHost/FindHostController.php
centreon/src/Core/Infrastructure/RealTime/Api/FindHost/FindHostController.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\Infrastructure\RealTime\Api\FindHost; use Centreon\Application\Controller\AbstractController; use Core\Application\RealTime\UseCase\FindHost\FindHost; use Core\Application\RealTime\UseCase\FindHost\FindHostPresenterInterface; final class FindHostController extends AbstractController { /** * @param int $hostId * @param FindHost $useCase * @param FindHostPresenterInterface $presenter * * @return object */ public function __invoke( int $hostId, FindHost $useCase, FindHostPresenterInterface $presenter, ): object { /** * Deny access if user has no rights on the real time. */ $this->denyAccessUnlessGrantedForApiRealtime(); $useCase($hostId, $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/Infrastructure/RealTime/Api/FindHost/FindHostPresenter.php
centreon/src/Core/Infrastructure/RealTime/Api/FindHost/FindHostPresenter.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\Infrastructure\RealTime\Api\FindHost; use CentreonDuration; use Core\Application\Common\UseCase\AbstractPresenter; use Core\Application\RealTime\UseCase\FindHost\FindHostPresenterInterface; use Core\Application\RealTime\UseCase\FindHost\FindHostResponse; use Core\Infrastructure\Common\Api\HttpUrlTrait; use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface; use Core\Infrastructure\Common\Presenter\PresenterTrait; use Core\Infrastructure\RealTime\Hypermedia\HypermediaCreator; class FindHostPresenter extends AbstractPresenter implements FindHostPresenterInterface { use PresenterTrait; use HttpUrlTrait; /** * @param HypermediaCreator $hypermediaCreator * @param PresenterFormatterInterface $presenterFormatter */ public function __construct( private HypermediaCreator $hypermediaCreator, protected PresenterFormatterInterface $presenterFormatter, ) { parent::__construct($presenterFormatter); } /** * {@inheritDoc} * * @param FindHostResponse $response */ public function present(mixed $response): void { $presenterResponse = [ 'uuid' => 'h' . $response->hostId, 'id' => $response->hostId, 'name' => $response->name, 'monitoring_server_name' => $response->monitoringServerName, 'type' => 'host', 'short_type' => 'h', 'fqdn' => $response->address, 'alias' => $response->alias, 'status' => $response->status, 'in_downtime' => $response->isInDowntime, 'acknowledged' => $response->isAcknowledged, 'flapping' => $response->isFlapping, 'performance_data' => $response->performanceData, 'information' => $response->output, 'command_line' => $response->commandLine, 'notification_number' => $response->notificationNumber, 'latency' => $response->latency, 'percent_state_change' => $response->statusChangePercentage, 'passive_checks' => $response->hasPassiveChecks, 'execution_time' => $response->executionTime, 'active_checks' => $response->hasActiveChecks, 'parent' => null, 'icon' => $response->icon, 'groups' => $this->hypermediaCreator->convertGroupsForPresenter($response), 'categories' => $this->hypermediaCreator->convertCategoriesForPresenter($response), 'severity' => $response->severity, ]; if (! empty($response->severity['icon'])) { // normalize the URL to the severity icon $presenterResponse['severity']['icon']['url'] = $this->getBaseUri() . '/img/media/' . $response->severity['icon']['url']; } $acknowledgement = null; if ($response->acknowledgement !== []) { // Convert Acknowledgement dates into ISO 8601 format $acknowledgement = $response->acknowledgement; $acknowledgement['entry_time'] = $this->formatDateToIso8601($response->acknowledgement['entry_time']); $acknowledgement['deletion_time'] = $this->formatDateToIso8601($response->acknowledgement['deletion_time']); } $presenterResponse['acknowledgement'] = $acknowledgement; // Convert downtime dates into ISO 8601 format $formattedDatesDowntimes = []; foreach ($response->downtimes as $key => $downtime) { $formattedDatesDowntimes[$key] = $downtime; $formattedDatesDowntimes[$key]['start_time'] = $this->formatDateToIso8601($downtime['start_time']); $formattedDatesDowntimes[$key]['end_time'] = $this->formatDateToIso8601($downtime['end_time']); $formattedDatesDowntimes[$key]['actual_start_time'] = $this->formatDateToIso8601($downtime['actual_start_time']); $formattedDatesDowntimes[$key]['actual_end_time'] = $this->formatDateToIso8601($downtime['actual_end_time']); $formattedDatesDowntimes[$key]['entry_time'] = $this->formatDateToIso8601($downtime['entry_time']); $formattedDatesDowntimes[$key]['deletion_time'] = $this->formatDateToIso8601($downtime['deletion_time']); } $presenterResponse['downtimes'] = $formattedDatesDowntimes; /** * Remove ':' character from the timezone string. */ $presenterResponse['timezone'] = ! empty($response->timezone) ? preg_replace('/^:/', '', $response->timezone) : null; /** * Calculate the duration. */ $presenterResponse['duration'] = $response->lastStatusChange !== null ? CentreonDuration::toString(time() - $response->lastStatusChange->getTimestamp()) : null; /** * Convert dates to ISO 8601 format. */ $presenterResponse['next_check'] = $this->formatDateToIso8601($response->nextCheck); $presenterResponse['last_check'] = $this->formatDateToIso8601($response->lastCheck); $presenterResponse['last_time_with_no_issue'] = $this->formatDateToIso8601($response->lastTimeUp); $presenterResponse['last_status_change'] = $this->formatDateToIso8601($response->lastStatusChange); $presenterResponse['last_notification'] = $this->formatDateToIso8601($response->lastNotification); /** * Creating the 'tries' entry. */ $tries = $response->checkAttempts . '/' . $response->maxCheckAttempts; $statusType = $response->status['type'] === 0 ? 'S' : 'H'; $presenterResponse['tries'] = $tries . '(' . $statusType . ')'; /** * Creating Hypermedias. */ $parameters = [ 'type' => $response->type, 'hostId' => $response->hostId, ]; $endpoints = $this->hypermediaCreator->createEndpoints($parameters); $presenterResponse['links']['endpoints'] = [ 'notification_policy' => $endpoints['notification_policy'], 'timeline' => $endpoints['timeline'], 'timeline_download' => $endpoints['timeline_download'], 'details' => $endpoints['details'], ]; $presenterResponse['links']['uris'] = $this->hypermediaCreator->createInternalUris($parameters); parent::present($presenterResponse); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Infrastructure/RealTime/Hypermedia/HypermediaProviderInterface.php
centreon/src/Core/Infrastructure/RealTime/Hypermedia/HypermediaProviderInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\Infrastructure\RealTime\Hypermedia; use Centreon\Domain\Contact\Interfaces\ContactInterface; interface HypermediaProviderInterface { /** * @param string $resourceType * * @return bool */ public function isValidFor(string $resourceType): bool; /** * @param ContactInterface $contact */ public function setContact(ContactInterface $contact): void; /** * Create endpoints for the Resource provided. * * @param array<string, mixed> $parameters * * @return array<string, string|null> */ public function createEndpoints(array $parameters): array; /** * Create internal redirection uris for the Resource provided. * * @param array<string, mixed> $parameters * * @return array<string, string|null> */ public function createInternalUris(array $parameters): array; /** * Create internal redirection uris for the Resource group(s). * * @param array<int, array<string, string|int>> $groups * * @return array<array<string, string|int|null>> */ public function convertGroupsForPresenter(array $groups): array; /** * Create internal redirection uris for the Resource categories. * * @param array<int, array<string, string|int>> $categories * * @return array<int, array<string, string|int|null>> */ public function convertCategoriesForPresenter(array $categories): array; /** * @param array<string, int> $parameters * * @return string */ public function generateResourceDetailsUri(array $parameters): string; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Infrastructure/RealTime/Hypermedia/HypermediaCreator.php
centreon/src/Core/Infrastructure/RealTime/Hypermedia/HypermediaCreator.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\Infrastructure\RealTime\Hypermedia; use Centreon\Domain\Contact\Interfaces\ContactInterface; class HypermediaCreator { /** @var HypermediaProviderInterface[] */ private array $hypermediaProviders; /** * @param iterable<HypermediaProviderInterface> $hypermediaProviders */ public function setHypermediaProviders(iterable $hypermediaProviders): void { $hypermediaProviders = $hypermediaProviders instanceof \Traversable ? iterator_to_array($hypermediaProviders) : $hypermediaProviders; $this->hypermediaProviders = $hypermediaProviders; } public function setCustomUser(ContactInterface $user): void { foreach ($this->hypermediaProviders as $hypermediaProvider) { $hypermediaProvider->setContact($user); } } /** * This method will create the internal redirection endpoints for the given resource. * Those links will be created regarding the Users rights and Resource type. * ex: For a service resource type * [ * "timeline": "/centreon/api/v21.10/monitoring/hosts/14/services/26/timeline", * "status_graph": "/centreon/api/v21.10/monitoring/hosts/14/services/26/metrics/status", * "performance_graph": "/centreon/api/v21.10/monitoring/hosts/14/services/26/metrics/performance" * ]. * * @param array<string, mixed> $parameters * * @return array<string, string|null> */ public function createEndpoints(array $parameters): array { foreach ($this->hypermediaProviders as $hypermediaProvider) { if ($hypermediaProvider->isValidFor($parameters['type'])) { return $hypermediaProvider->createEndpoints($parameters); } } return []; } /** * This method will create the internal redirection links for the given resource. * Those links will be created regarding the Users rights and Resource type. * ex: For a service resource type * [ * "configuration": "/centreon/main.php?p=60201&o=c&service_id=26", * "logs": "/centreon/main.php?p=20301&svc=14_26", * "reporting": "/centreon/main.php?p=30702&period=yesterday&start=&end=&host_id=14&item=26" * ]. * * @param array<string, mixed> $parameters * * @return array<string, string|null> */ public function createInternalUris(array $parameters): array { foreach ($this->hypermediaProviders as $hypermediaProvider) { if ($hypermediaProvider->isValidFor($parameters['type'])) { return $hypermediaProvider->createInternalUris($parameters); } } return []; } /** * This method will add the redirection uri to the group configuration page. * This will be done regarding the Users rights and the Resource Type. * ex: For a Host resource type will add the redirection link to the hostgroup * configuration page. * [ * [ * 'id' => 1, * 'name' => ALL, * 'configuration_uri' => 'http://localhost:8080/centreon/main.php?p=60102&o=c&hg_id=53' * ] * ]. * * @param mixed $response * * @return array<array<string, string|int|null>> */ public function convertGroupsForPresenter(mixed $response): array { foreach ($this->hypermediaProviders as $hypermediaProvider) { if ($hypermediaProvider->isValidFor($response->type)) { return $hypermediaProvider->convertGroupsForPresenter($response->groups); } } return []; } /** * This method will add the redirection uri to the category configuration page. * This will be done regarding the Users rights and the Resource Type. * ex: For a Host resource type will add the redirection link to the host category * configuration page. * [ * [ * 'id' => 1, * 'name' => ALL, * 'configuration_uri' => 'http://localhost:8080/centreon/main.php?p=60104&o=c&hc_id=53' * ] * ]. * * @param mixed $response * * @return array<array<string, string|int|null>> */ public function convertCategoriesForPresenter(mixed $response): array { foreach ($this->hypermediaProviders as $hypermediaProvider) { if ($hypermediaProvider->isValidFor($response->type)) { return $hypermediaProvider->convertCategoriesForPresenter($response->categories); } } return []; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Infrastructure/RealTime/Hypermedia/HostHypermediaProvider.php
centreon/src/Core/Infrastructure/RealTime/Hypermedia/HostHypermediaProvider.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\Infrastructure\RealTime\Hypermedia; use Centreon\Domain\Contact\Contact; use Core\Domain\RealTime\Model\ResourceTypes\HostResourceType; class HostHypermediaProvider extends AbstractHypermediaProvider implements HypermediaProviderInterface { public const URI_CONFIGURATION = '/main.php?p=60101&o=c&host_id={hostId}'; public const URI_EVENT_LOGS = '/main.php?p=20301&h={hostId}'; public const URI_REPORTING = '/main.php?p=307&host={hostId}'; public const URI_HOST_CATEGORY_CONFIGURATION = '/main.php?p=60104&o=c&hc_id={hostCategoryId}'; public const ENDPOINT_HOST_ACKNOWLEDGEMENT = 'centreon_application_acknowledgement_addhostacknowledgement'; public const ENDPOINT_DETAILS = 'centreon_application_monitoring_resource_details_host'; public const ENDPOINT_HOST_CHECK = 'centreon_application_check_checkHost'; public const ENDPOINT_SERVICE_DOWNTIME = 'monitoring.downtime.addHostDowntime'; public const ENDPOINT_HOST_NOTIFICATION_POLICY = 'configuration.host.notification-policy'; public const ENDPOINT_HOST_TIMELINE = 'centreon_application_monitoring_gettimelinebyhost'; public const ENDPOINT_HOST_TIMELINE_DOWNLOAD = 'centreon_application_monitoring_download_timeline_by_host'; public const ENDPOINT_HOSTGROUP_CONFIGURATION = 'GetHostGroup'; /** * @inheritDoc */ public function isValidFor(string $resourceType): bool { return $resourceType === HostResourceType::TYPE_NAME; } /** * @inheritDoc */ public function createEndpoints(array $parameters): array { $urlParams = ['hostId' => $parameters['hostId']]; return [ 'timeline' => $this->generateEndpoint(self::ENDPOINT_HOST_TIMELINE, $urlParams), 'timeline_download' => $this->generateEndpoint(self::ENDPOINT_HOST_TIMELINE_DOWNLOAD, $urlParams), 'notification_policy' => $this->generateEndpoint( self::ENDPOINT_HOST_NOTIFICATION_POLICY, $urlParams ), 'details' => $this->generateEndpoint(self::ENDPOINT_DETAILS, $urlParams), 'downtime' => $this->generateDowntimeEndpoint($urlParams), 'acknowledgement' => $this->generateAcknowledgementEndpoint($urlParams), 'check' => $this->generateCheckEndpoint($urlParams), 'forced_check' => $this->generateForcedCheckEndpoint($urlParams), ]; } /** * @inheritDoc */ public function createForConfiguration(array $parameters): ?string { $roles = [ Contact::ROLE_CONFIGURATION_HOSTS_WRITE, Contact::ROLE_CONFIGURATION_HOSTS_READ, ]; if (! $this->canContactAccessPages($this->contact, $roles)) { return null; } return $this->generateUri(self::URI_CONFIGURATION, ['{hostId}' => $parameters['hostId']]); } /** * @inheritDoc */ public function createForReporting(array $parameters): ?string { if (! $this->canContactAccessPages($this->contact, [Contact::ROLE_REPORTING_AVAILABILITY_HOSTS])) { return null; } return $this->generateUri(self::URI_REPORTING, ['{hostId}' => $parameters['hostId']]); } /** * @inheritDoc */ public function createForEventLog(array $parameters): ?string { $urlParams = ['{hostId}' => $parameters['hostId']]; return $this->createUrlForEventLog($urlParams); } /** * Create hostgroup configuration redirection uri. * * @param array<string, mixed> $parameters * * @return string|null */ public function generateHostGroupEndpoint(array $parameters): ?string { $roles = [ Contact::ROLE_CONFIGURATION_HOSTS_HOST_GROUPS_READ_WRITE, Contact::ROLE_CONFIGURATION_HOSTS_HOST_GROUPS_READ, ]; if (! $this->canContactAccessPages($this->contact, $roles)) { return null; } return $this->generateEndpoint( self::ENDPOINT_HOSTGROUP_CONFIGURATION, ['hostGroupId' => $parameters['hostgroupId']] ); } /** * Create host category configuration redirection uri. * * @param array<string, mixed> $parameters * * @return string|null */ public function createForCategory(array $parameters): ?string { $roles = [ Contact::ROLE_CONFIGURATION_HOSTS_CATEGORIES_READ_WRITE, Contact::ROLE_CONFIGURATION_HOSTS_CATEGORIES_READ, ]; if (! $this->canContactAccessPages($this->contact, $roles)) { return null; } return $this->generateUri( self::URI_HOST_CATEGORY_CONFIGURATION, ['{hostCategoryId}' => $parameters['categoryId']] ); } /** * @inheritDoc */ public function convertGroupsForPresenter(array $groups): array { return array_map( fn (array $group) => [ 'id' => $group['id'], 'name' => $group['name'], 'configuration_endpoint' => $this->generateHostGroupEndpoint(['hostgroupId' => $group['id']]), ], $groups ); } /** * @inheritDoc */ public function convertCategoriesForPresenter(array $categories): array { return array_map( fn (array $category) => [ 'id' => $category['id'], 'name' => $category['name'], 'configuration_uri' => $this->createForCategory(['categoryId' => $category['id']]), ], $categories ); } /** * @param array<string, int> $parameters * * @return string */ private function generateAcknowledgementEndpoint(array $parameters): string { $acknowledgementFilter = ['limit' => 1]; return $this->generateEndpoint( self::ENDPOINT_HOST_ACKNOWLEDGEMENT, array_merge($parameters, $acknowledgementFilter) ); } /** * @param array<string, mixed> $parameters * * @return string|null */ private function generateCheckEndpoint(array $parameters): ?string { return ($this->contact->hasRole(Contact::ROLE_HOST_CHECK) || $this->contact->isAdmin()) ? $this->generateEndpoint(self::ENDPOINT_HOST_CHECK, $parameters) : null; } /** * @param array<string, mixed> $parameters * * @return string|null */ private function generateForcedCheckEndpoint(array $parameters): ?string { return ($this->contact->hasRole(Contact::ROLE_HOST_FORCED_CHECK) || $this->contact->isAdmin()) ? $this->generateEndpoint(self::ENDPOINT_HOST_CHECK, $parameters) : 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/Infrastructure/RealTime/Hypermedia/AbstractHypermediaProvider.php
centreon/src/Core/Infrastructure/RealTime/Hypermedia/AbstractHypermediaProvider.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\Infrastructure\RealTime\Hypermedia; use Centreon\Domain\Contact\Contact; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Centreon\Domain\RequestParameters\RequestParameters; abstract class AbstractHypermediaProvider { public const URI_EVENT_LOGS = '/main.php?p=20301&svc={hostId}_{serviceId}'; public const ENDPOINT_SERVICE_DOWNTIME = ''; public const ENDPOINT_DETAILS = ''; /** * @param ContactInterface $contact * @param UriGenerator $uriGenerator */ public function __construct( protected ContactInterface $contact, protected UriGenerator $uriGenerator, ) { } /** * @param ContactInterface $contact */ public function setContact(ContactInterface $contact): void { $this->contact = $contact; } /** * @param array<string, mixed> $parameters * * @return array<string, string|null> */ public function createInternalUris(array $parameters): array { return [ 'configuration' => $this->createForConfiguration($parameters), 'logs' => $this->createForEventLog($parameters), 'reporting' => $this->createForReporting($parameters), ]; } /** * Create configuration redirection uri. * * @param array<string, mixed> $parameters * * @return string|null */ abstract public function createForConfiguration(array $parameters): ?string; /** * Create event logs redirection uri. * * @param array<string, int> $parameters * * @return string|null */ abstract public function createForEventLog(array $parameters): ?string; /** * Create reporting redirection uri. * * @param array<string, int> $parameters * * @return string|null */ abstract public function createForReporting(array $parameters): ?string; /** * @param array<string, int> $parameters */ public function generateResourceDetailsUri(array $parameters): string { return $this->generateEndpoint(static::ENDPOINT_DETAILS, $parameters); } /** * Checks if contact has access to pages defined in roles. * * @param ContactInterface $contact * @param string[] $topologyRoles * * @return bool */ protected function canContactAccessPages(ContactInterface $contact, array $topologyRoles): bool { return $contact->isAdmin() || $this->hasTopologyAccess($contact, $topologyRoles); } /** * Checks if contact has topology roles submited. * * @param ContactInterface $contact * @param string[] $topologyRoles * * @return bool */ protected function hasTopologyAccess(ContactInterface $contact, array $topologyRoles): bool { foreach ($topologyRoles as $topologyRole) { if ($contact->hasTopologyRole($topologyRole)) { return true; } } return false; } /** * Proxy method to generates endpoint call URI with parameters. * * @param string $endpoint * @param array<string, mixed> $parameters * * @return string */ protected function generateEndpoint(string $endpoint, array $parameters): string { return $this->uriGenerator->generateEndpoint($endpoint, $parameters); } /** * Proxy method to generate an uri. * * @param string $uri * @param array<string, mixed> $parameters * * @return string */ protected function generateUri(string $uri, array $parameters): string { return $this->uriGenerator->generateUri($uri, $parameters); } /** * @param array<string, int> $parameters * * @return string */ protected function generateDowntimeEndpoint(array $parameters): string { $downtimeFilter = [ 'search' => json_encode([ RequestParameters::AGGREGATE_OPERATOR_AND => [ [ 'start_time' => [RequestParameters::OPERATOR_LESS_THAN => time()], 'end_time' => [RequestParameters::OPERATOR_GREATER_THAN => time()], [ RequestParameters::AGGREGATE_OPERATOR_OR => [ 'is_cancelled' => [RequestParameters::OPERATOR_NOT_EQUAL => 1], 'deletion_time' => [RequestParameters::OPERATOR_GREATER_THAN => time()], ], ], ], ], ]), ]; return $this->generateEndpoint( static::ENDPOINT_SERVICE_DOWNTIME, array_merge($parameters, $downtimeFilter) ); } /** * @param array<string, int> $urlParams */ protected function createUrlForEventLog(array $urlParams): ?string { if (! $this->canContactAccessPages($this->contact, [Contact::ROLE_MONITORING_EVENT_LOGS])) { return null; } return $this->generateUri(static::URI_EVENT_LOGS, $urlParams); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Infrastructure/RealTime/Hypermedia/ServiceHypermediaProvider.php
centreon/src/Core/Infrastructure/RealTime/Hypermedia/ServiceHypermediaProvider.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\Infrastructure\RealTime\Hypermedia; use Centreon\Domain\Contact\Contact; use Core\Domain\RealTime\Model\ResourceTypes\ServiceResourceType; class ServiceHypermediaProvider extends AbstractHypermediaProvider implements HypermediaProviderInterface { public const ENDPOINT_SERVICE_ACKNOWLEDGEMENT = 'centreon_application_acknowledgement_addserviceacknowledgement'; public const ENDPOINT_DETAILS = 'centreon_application_monitoring_resource_details_service'; public const ENDPOINT_SERVICE_DOWNTIME = 'monitoring.downtime.addServiceDowntime'; public const ENDPOINT_SERVICE_NOTIFICATION_POLICY = 'configuration.service.notification-policy'; public const ENDPOINT_SERVICE_PERFORMANCE_GRAPH = 'monitoring.metric.getServicePerformanceMetrics'; public const ENDPOINT_SERVICE_STATUS_GRAPH = 'monitoring.metric.getServiceStatusMetrics'; public const ENDPOINT_SERVICE_TIMELINE = 'centreon_application_monitoring_gettimelinebyhostandservice'; public const ENDPOINT_SERVICE_CHECK = 'centreon_application_check_checkService'; public const ENDPOINT_SERVICE_METRICS = 'FindMetricsByService'; public const TIMELINE_DOWNLOAD = 'centreon_application_monitoring_download_timeline_by_host_and_service'; public const URI_CONFIGURATION = '/main.php?p=60201&o=c&service_id={serviceId}'; public const URI_EVENT_LOGS = '/main.php?p=20301&svc={hostId}_{serviceId}'; public const URI_REPORTING = '/main.php?p=30702&period=yesterday&start=&end=&host_id={hostId}&item={serviceId}'; public const URI_SERVICEGROUP_CONFIGURATION = '/main.php?p=60203&o=c&sg_id={servicegroupId}'; public const URI_SERVICE_CATEGORY_CONFIGURATION = '/main.php?p=60209&o=c&sc_id={serviceCategoryId}'; /** * @inheritDoc */ public function isValidFor(string $resourceType): bool { return $resourceType === ServiceResourceType::TYPE_NAME; } /** * @inheritDoc */ public function createForConfiguration(array $parameters): ?string { $roles = [ Contact::ROLE_CONFIGURATION_SERVICES_WRITE, Contact::ROLE_CONFIGURATION_SERVICES_READ, ]; if (! $this->canContactAccessPages($this->contact, $roles)) { return null; } return $this->generateUri(self::URI_CONFIGURATION, ['{serviceId}' => $parameters['serviceId']]); } /** * @inheritDoc */ public function createForReporting(array $parameters): ?string { if (! $this->canContactAccessPages($this->contact, [Contact::ROLE_REPORTING_AVAILABILITY_SERVICES])) { return null; } return $this->generateUri( self::URI_REPORTING, [ '{serviceId}' => $parameters['serviceId'], '{hostId}' => $parameters['hostId'], ] ); } /** * @inheritDoc */ public function createForEventLog(array $parameters): ?string { $urlParams = ['{serviceId}' => $parameters['serviceId'], '{hostId}' => $parameters['hostId']]; return $this->createUrlForEventLog($urlParams); } /** * @inheritDoc */ public function createEndpoints(array $parameters): array { $urlParams = ['serviceId' => $parameters['serviceId'], 'hostId' => $parameters['hostId']]; return [ 'details' => $this->generateEndpoint(self::ENDPOINT_DETAILS, $urlParams), 'timeline' => $this->generateEndpoint(self::ENDPOINT_SERVICE_TIMELINE, $urlParams), 'timeline_download' => $this->generateEndpoint(self::TIMELINE_DOWNLOAD, $urlParams), 'status_graph' => $this->generateEndpoint(self::ENDPOINT_SERVICE_STATUS_GRAPH, $urlParams), 'performance_graph' => $parameters['hasGraphData'] ? $this->generateEndpoint(self::ENDPOINT_SERVICE_PERFORMANCE_GRAPH, $urlParams) : null, 'notification_policy' => $this->generateEndpoint( self::ENDPOINT_SERVICE_NOTIFICATION_POLICY, $urlParams ), 'downtime' => $this->generateDowntimeEndpoint($urlParams), 'acknowledgement' => $this->generateAcknowledgementEndpoint($urlParams), 'check' => $this->generateCheckEndpoint($urlParams), 'forced_check' => $this->generateForcedCheckEndpoint($urlParams), 'metrics' => $this->generateMetricsByServiceEndpoint($urlParams), ]; } /** * Create servicegroup configuration redirection uri. * * @param array<string, mixed> $parameters * * @return string|null */ public function createForGroup(array $parameters): ?string { $roles = [ Contact::ROLE_CONFIGURATION_SERVICES_SERVICE_GROUPS_READ_WRITE, Contact::ROLE_CONFIGURATION_SERVICES_SERVICE_GROUPS_READ, ]; if (! $this->canContactAccessPages($this->contact, $roles)) { return null; } return $this->generateUri( self::URI_SERVICEGROUP_CONFIGURATION, ['{servicegroupId}' => $parameters['servicegroupId']] ); } /** * @inheritDoc */ public function convertGroupsForPresenter(array $groups): array { return array_map( fn (array $group) => [ 'id' => $group['id'], 'name' => $group['name'], 'configuration_uri' => $this->createForGroup(['servicegroupId' => $group['id']]), ], $groups ); } /** * Create service category configuration redirection uri. * * @param array<string, mixed> $parameters * * @return string|null */ public function createForCategory(array $parameters): ?string { $roles = [ Contact::ROLE_CONFIGURATION_SERVICES_CATEGORIES_READ_WRITE, Contact::ROLE_CONFIGURATION_SERVICES_CATEGORIES_READ, ]; if (! $this->canContactAccessPages($this->contact, $roles)) { return null; } return $this->generateUri( self::URI_SERVICE_CATEGORY_CONFIGURATION, ['{serviceCategoryId}' => $parameters['categoryId']] ); } /** * @inheritDoc */ public function convertCategoriesForPresenter(array $categories): array { return array_map( fn (array $category) => [ 'id' => $category['id'], 'name' => $category['name'], 'configuration_uri' => $this->createForCategory(['categoryId' => $category['id']]), ], $categories ); } /** * @param array<string, int> $parameters * * @return string */ private function generateAcknowledgementEndpoint(array $parameters): string { $acknowledgementFilter = ['limit' => 1]; return $this->generateEndpoint( self::ENDPOINT_SERVICE_ACKNOWLEDGEMENT, array_merge($parameters, $acknowledgementFilter) ); } /** * @param array<string, mixed> $parameters * * @return string|null */ private function generateCheckEndpoint(array $parameters): ?string { return ($this->contact->hasRole(Contact::ROLE_SERVICE_CHECK) || $this->contact->isAdmin()) ? $this->generateEndpoint(self::ENDPOINT_SERVICE_CHECK, $parameters) : null; } /** * @param array<string, mixed> $parameters * * @return string|null */ private function generateForcedCheckEndpoint(array $parameters): ?string { return ($this->contact->hasRole(Contact::ROLE_SERVICE_FORCED_CHECK) || $this->contact->isAdmin()) ? $this->generateEndpoint(self::ENDPOINT_SERVICE_CHECK, $parameters) : null; } /** * @param array<string,int> $parameters * * @return string */ private function generateMetricsByServiceEndpoint(array $parameters): string { return $this->generateEndpoint(self::ENDPOINT_SERVICE_METRICS, $parameters); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Infrastructure/RealTime/Hypermedia/MetaServiceHypermediaProvider.php
centreon/src/Core/Infrastructure/RealTime/Hypermedia/MetaServiceHypermediaProvider.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\Infrastructure\RealTime\Hypermedia; use Centreon\Domain\Contact\Contact; use Core\Domain\RealTime\Model\ResourceTypes\MetaServiceResourceType; class MetaServiceHypermediaProvider extends AbstractHypermediaProvider implements HypermediaProviderInterface { public const ENDPOINT_TIMELINE = 'centreon_application_monitoring_gettimelinebymetaservices'; public const ENDPOINT_TIMELINE_DOWNLOAD = 'centreon_application_monitoring_download_timeline_by_metaservice'; public const ENDPOINT_PERFORMANCE_GRAPH = 'monitoring.metric.getMetaServicePerformanceMetrics'; public const ENDPOINT_STATUS_GRAPH = 'monitoring.metric.getMetaServiceStatusMetrics'; public const ENDPOINT_METRIC_LIST = 'centreon_application_find_meta_service_metrics'; public const ENDPOINT_DETAILS = 'centreon_application_monitoring_resource_details_meta_service'; public const ENDPOINT_SERVICE_DOWNTIME = 'monitoring.downtime.addMetaServiceDowntime'; public const ENDPOINT_METASERVICE_CHECK = 'centreon_application_check_checkMetaService'; public const ENDPOINT_ACKNOWLEDGEMENT = 'centreon_application_acknowledgement_addmetaserviceacknowledgement'; public const ENDPOINT_NOTIFICATION_POLICY = 'configuration.metaservice.notification-policy'; public const URI_CONFIGURATION = '/main.php?p=60204&o=c&meta_id={metaId}'; public const URI_EVENT_LOGS = '/main.php?p=20301&svc={hostId}_{serviceId}'; /** * @inheritDoc */ public function isValidFor(string $resourceType): bool { return $resourceType === MetaServiceResourceType::TYPE_NAME; } /** * @inheritDoc */ public function createForConfiguration(array $parameters): ?string { $roles = [ Contact::ROLE_CONFIGURATION_SERVICES_WRITE, Contact::ROLE_CONFIGURATION_SERVICES_READ, ]; if (! $this->canContactAccessPages($this->contact, $roles)) { return null; } return $this->generateUri(self::URI_CONFIGURATION, ['{metaId}' => $parameters['internalId']]); } /** * @inheritDoc */ public function createForReporting(array $parameters): ?string { return null; } /** * @inheritDoc */ public function createForEventLog(array $parameters): ?string { $urlParams = ['{hostId}' => $parameters['hostId'], '{serviceId}' => $parameters['serviceId']]; return $this->createUrlForEventLog($urlParams); } /** * @inheritDoc */ public function createEndpoints(array $parameters): array { $urlParams = ['metaId' => $parameters['internalId']]; return [ 'details' => $this->generateEndpoint(self::ENDPOINT_DETAILS, $urlParams), 'acknowledgement' => $this->generateAcknowledgementEndpoint($urlParams), 'downtime' => $this->generateDowntimeEndpoint($urlParams), 'timeline' => $this->generateEndpoint(self::ENDPOINT_TIMELINE, $urlParams), 'timeline_download' => $this->generateEndpoint(self::ENDPOINT_TIMELINE_DOWNLOAD, $urlParams), 'status_graph' => $this->generateEndpoint(self::ENDPOINT_STATUS_GRAPH, $urlParams), 'metrics' => $this->generateEndpoint(self::ENDPOINT_METRIC_LIST, $urlParams), 'performance_graph' => $parameters['hasGraphData'] ? $this->generateEndpoint(self::ENDPOINT_PERFORMANCE_GRAPH, $urlParams) : null, 'notification_policy' => $this->generateEndpoint(self::ENDPOINT_NOTIFICATION_POLICY, $urlParams), 'check' => $this->generateCheckEndpoint($urlParams), 'forced_check' => $this->generateForcedCheckEndpoint($urlParams), ]; } /** * @inheritDoc */ public function convertGroupsForPresenter(array $groups): array { return []; } /** * @inheritDoc */ public function convertCategoriesForPresenter(array $categories): array { return []; } /** * @param array<string, int> $parameters * * @return string */ private function generateAcknowledgementEndpoint(array $parameters): string { $acknowledgementFilter = ['limit' => 1]; return $this->generateEndpoint( self::ENDPOINT_ACKNOWLEDGEMENT, array_merge($parameters, $acknowledgementFilter) ); } /** * @param array<string, mixed> $parameters * * @return string|null */ private function generateCheckEndpoint(array $parameters): ?string { return ($this->contact->hasRole(Contact::ROLE_SERVICE_CHECK) || $this->contact->isAdmin()) ? $this->generateEndpoint(self::ENDPOINT_METASERVICE_CHECK, $parameters) : null; } /** * @param array<string, mixed> $parameters * * @return string|null */ private function generateForcedCheckEndpoint(array $parameters): ?string { return ($this->contact->hasRole(Contact::ROLE_SERVICE_FORCED_CHECK) || $this->contact->isAdmin()) ? $this->generateEndpoint(self::ENDPOINT_METASERVICE_CHECK, $parameters) : 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/Infrastructure/RealTime/Hypermedia/UriGenerator.php
centreon/src/Core/Infrastructure/RealTime/Hypermedia/UriGenerator.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\Infrastructure\RealTime\Hypermedia; use Core\Infrastructure\Common\Api\HttpUrlTrait; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; class UriGenerator { use HttpUrlTrait; /** * @param UrlGeneratorInterface $router */ public function __construct(protected UrlGeneratorInterface $router) { } /** * Generates endpoint call URI with parameters. * * @param string $endpoint * @param array<string, mixed> $parameters * * @return string */ public function generateEndpoint(string $endpoint, array $parameters): string { return $this->router->generate($endpoint, $parameters); } /** * Generates a uri where place holders are replaced by their values * Format of the parameters * [ * '{hostId}' => 10, * '{serviceId} => 20, * ... * ]. * * @param string $uri * @param array<string, mixed> $parameters * * @return string */ public function generateUri(string $uri, array $parameters): string { $generatedUri = $this->getBaseUri() . $uri; foreach ($parameters as $placeHolder => $value) { $generatedUri = str_replace($placeHolder, (string) $value, $generatedUri); } return $generatedUri; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Infrastructure/RealTime/Repository/Hostgroup/DbReadHostgroupRepository.php
centreon/src/Core/Infrastructure/RealTime/Repository/Hostgroup/DbReadHostgroupRepository.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\Infrastructure\RealTime\Repository\Hostgroup; use Centreon\Infrastructure\DatabaseConnection; use Centreon\Infrastructure\Repository\AbstractRepositoryDRB; use Core\Application\RealTime\Repository\ReadHostgroupRepositoryInterface; use Core\Domain\RealTime\Model\Hostgroup; class DbReadHostgroupRepository extends AbstractRepositoryDRB implements ReadHostgroupRepositoryInterface { /** * @param DatabaseConnection $db */ public function __construct(DatabaseConnection $db) { $this->db = $db; } /** * @inheritDoc */ public function findAllByHostId(int $hostId): array { return $this->findAll($hostId, null); } /** * @inheritDoc */ public function findAllByHostIdAndAccessGroupIds(int $hostId, array $accessGroupIds): array { $hostgroups = []; if ($accessGroupIds === []) { return $hostgroups; } $aclRequest = ' INNER JOIN `:dbstg`.`centreon_acl` AS acl ON acl.host_id = hhg.host_id AND acl.service_id IS NULL AND acl.group_id IN (' . implode(',', $accessGroupIds) . ') '; return $this->findAll($hostId, $aclRequest); } /** * @param int $hostId * @param string|null $aclRequest * * @return Hostgroup[] */ private function findAll(int $hostId, ?string $aclRequest): array { $request = 'SELECT DISTINCT 1 AS REALTIME, hg.hostgroup_id, hg.name AS `hostgroup_name` FROM `:dbstg`.`hosts_hostgroups` AS hhg INNER JOIN `:dbstg`.`hostgroups` AS hg ON hg.hostgroup_id = hhg.hostgroup_id'; if ($aclRequest !== null) { $request .= $aclRequest; } $request .= ' WHERE hhg.host_id = :hostId ORDER BY hg.name ASC'; $statement = $this->db->prepare($this->translateDbName($request)); $statement->bindValue(':hostId', $hostId, \PDO::PARAM_INT); $statement->execute(); $hostgroups = []; while (($row = $statement->fetch(\PDO::FETCH_ASSOC))) { /** @var array<string,int|string|null> $row */ $hostgroups[] = DbHostgroupFactory::createFromRecord($row); } return $hostgroups; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Infrastructure/RealTime/Repository/Hostgroup/DbHostgroupFactory.php
centreon/src/Core/Infrastructure/RealTime/Repository/Hostgroup/DbHostgroupFactory.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\Infrastructure\RealTime\Repository\Hostgroup; use Core\Domain\RealTime\Model\Hostgroup; class DbHostgroupFactory { /** * @param array<string,int|string|null> $data * * @return Hostgroup */ public static function createFromRecord(array $data): Hostgroup { return new Hostgroup((int) $data['hostgroup_id'], (string) $data['hostgroup_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/Infrastructure/RealTime/Repository/Acknowledgement/DbAcknowledgementFactory.php
centreon/src/Core/Infrastructure/RealTime/Repository/Acknowledgement/DbAcknowledgementFactory.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\Infrastructure\RealTime\Repository\Acknowledgement; use Core\Domain\RealTime\Model\Acknowledgement; use Core\Infrastructure\Common\Repository\DbFactoryUtilitiesTrait; class DbAcknowledgementFactory { use DbFactoryUtilitiesTrait; /** * @param array<string,int|string|null> $data * * @return Acknowledgement */ public static function createFromRecord(array $data): Acknowledgement { $entryTime = (new \DateTime())->setTimestamp((int) $data['entry_time']); /** @var string|null */ $authorName = $data['author']; /** @var string|null */ $comment = $data['comment_data']; return (new Acknowledgement( (int) $data['acknowledgement_id'], (int) $data['host_id'], (int) $data['service_id'], $entryTime ))->setAuthorId((int) $data['author_id']) ->setAuthorName($authorName) ->setSticky((int) $data['sticky'] === 1) ->setPersistentComment((int) $data['persistent_comment'] === 1) ->setNotifyContacts((int) $data['notify_contacts'] === 1) ->setSticky((int) $data['sticky'] === 1) ->setType((int) $data['type']) ->setState((int) $data['state']) ->setInstanceId((int) $data['instance_id']) ->setDeletionTime(self::createDateTimeFromTimestamp((int) $data['deletion_time'])) ->setComment($comment); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Infrastructure/RealTime/Repository/Acknowledgement/DbReadAcknowledgementRepository.php
centreon/src/Core/Infrastructure/RealTime/Repository/Acknowledgement/DbReadAcknowledgementRepository.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\Infrastructure\RealTime\Repository\Acknowledgement; use Centreon\Infrastructure\DatabaseConnection; use Centreon\Infrastructure\Repository\AbstractRepositoryDRB; use Core\Application\RealTime\Repository\ReadAcknowledgementRepositoryInterface; use Core\Domain\RealTime\Model\Acknowledgement; class DbReadAcknowledgementRepository extends AbstractRepositoryDRB implements ReadAcknowledgementRepositoryInterface { /** * @param DatabaseConnection $db */ public function __construct(DatabaseConnection $db) { $this->db = $db; } /** * @inheritDoc */ public function findOnGoingAcknowledgementByHostId(int $hostId): ?Acknowledgement { return $this->findOnGoingAcknowledegement($hostId, 0); } /** * @inheritDoc */ public function findOnGoingAcknowledgementByHostIdAndServiceId(int $hostId, int $serviceId): ?Acknowledgement { return $this->findOnGoingAcknowledegement($hostId, $serviceId); } /** * @param int $hostId * @param int $serviceId * * @return Acknowledgement|null */ private function findOnGoingAcknowledegement(int $hostId, int $serviceId): ?Acknowledgement { $acknowledgement = null; $sql = 'SELECT 1 AS REALTIME, ack.*, contact.contact_id AS author_id FROM `:dbstg`.acknowledgements ack LEFT JOIN `:db`.contact ON contact.contact_alias = ack.author INNER JOIN ( SELECT MAX(acknowledgement_id) AS acknowledgement_id FROM `:dbstg`.acknowledgements ack WHERE ack.host_id = :hostId AND ack.service_id = :serviceId AND ack.deletion_time IS NULL ) ack_max ON ack_max.acknowledgement_id = ack.acknowledgement_id'; $statement = $this->db->prepare($this->translateDbName($sql)); $statement->bindValue(':hostId', $hostId, \PDO::PARAM_INT); $statement->bindValue(':serviceId', $serviceId, \PDO::PARAM_INT); $statement->execute(); if ($row = $statement->fetch(\PDO::FETCH_ASSOC)) { /** @var array<string,int|string|null> $row */ return DbAcknowledgementFactory::createFromRecord($row); } return $acknowledgement; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Infrastructure/RealTime/Repository/MetaService/DbMetaServiceFactory.php
centreon/src/Core/Infrastructure/RealTime/Repository/MetaService/DbMetaServiceFactory.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\Infrastructure\RealTime\Repository\MetaService; use Core\Domain\RealTime\Model\MetaService; use Core\Infrastructure\Common\Repository\DbFactoryUtilitiesTrait; use Core\Infrastructure\RealTime\Repository\Service\DbServiceStatusFactory; class DbMetaServiceFactory { use DbFactoryUtilitiesTrait; /** * @param array<string,int|string|null> $data * * @return MetaService */ public static function createFromRecord(array $data): MetaService { $metaService = new MetaService( (int) $data['id'], (int) $data['host_id'], (int) $data['service_id'], (string) $data['name'], (string) $data['monitoring_server_name'], DbServiceStatusFactory::createFromRecord($data) ); /** @var string|null */ $performanceData = $data['performance_data']; /** @var string|null */ $output = $data['output']; /** @var string|null */ $commandLine = $data['command_line']; $metaService->setPerformanceData($performanceData) ->setOutput($output) ->setCommandLine($commandLine) ->setIsFlapping((int) $data['flapping'] === 1) ->setIsAcknowledged((int) $data['acknowledged'] === 1) ->setIsInDowntime((int) $data['in_downtime'] === 1) ->setPassiveChecks((int) $data['passive_checks'] === 1) ->setActiveChecks((int) $data['active_checks'] === 1) ->setLatency(self::getFloatOrNull($data['latency'])) ->setExecutionTime(self::getFloatOrNull($data['execution_time'])) ->setStatusChangePercentage(self::getFloatOrNull($data['status_change_percentage'])) ->setNotificationEnabled((int) $data['notify'] === 1) ->setNotificationNumber(self::getIntOrNull($data['notification_number'])) ->setLastStatusChange(self::createDateTimeFromTimestamp(is_numeric($data['last_status_change']) ? (int) $data['last_status_change'] : null)) ->setLastNotification(self::createDateTimeFromTimestamp(is_numeric($data['last_notification']) ? (int) $data['last_notification'] : null)) ->setLastCheck(self::createDateTimeFromTimestamp(is_numeric($data['last_check']) ? (int) $data['last_check'] : null)) ->setLastTimeOk(self::createDateTimeFromTimestamp(is_numeric($data['last_time_ok']) ? (int) $data['last_time_ok'] : null)) ->setMaxCheckAttempts(self::getIntOrNull($data['max_check_attempts'])) ->setCheckAttempts(self::getIntOrNull($data['check_attempt'])) ->setHasGraphData((int) $data['has_graph_data'] === 1); $nextCheck = self::createDateTimeFromTimestamp( (int) $data['active_checks'] === 1 ? (int) $data['next_check'] : null ); $metaService->setNextCheck($nextCheck); return $metaService; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Infrastructure/RealTime/Repository/MetaService/DbReadMetaServiceRepository.php
centreon/src/Core/Infrastructure/RealTime/Repository/MetaService/DbReadMetaServiceRepository.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\Infrastructure\RealTime\Repository\MetaService; use Centreon\Infrastructure\DatabaseConnection; use Centreon\Infrastructure\Repository\AbstractRepositoryDRB; use Core\Application\RealTime\Repository\ReadMetaServiceRepositoryInterface; use Core\Domain\RealTime\Model\MetaService; class DbReadMetaServiceRepository extends AbstractRepositoryDRB implements ReadMetaServiceRepositoryInterface { /** * @param DatabaseConnection $db */ public function __construct(DatabaseConnection $db) { $this->db = $db; } /** * @inheritDoc */ public function findMetaServiceById(int $metaId): ?MetaService { return $this->findMetaService($metaId); } /** * @inheritDoc */ public function findMetaServiceByIdAndAccessGroupIds(int $metaId, array $accessGroupIds): ?MetaService { if ($accessGroupIds === []) { return null; } $accessGroupRequest = ' INNER JOIN `:dbstg`.`centreon_acl` AS service_acl ON service_acl.service_id = s.service_id AND service_acl.host_id = s.host_id AND service_acl.group_id IN (' . implode(',', $accessGroupIds) . ') '; return $this->findMetaService($metaId, $accessGroupRequest); } /** * @param int $metaId * @param string|null $accessGroupRequest * * @return MetaService|null */ private function findMetaService(int $metaId, ?string $accessGroupRequest = null): ?MetaService { $request = 'SELECT 1 AS REALTIME, SUBSTRING(s.description, 6) AS `id`, s.host_id, s.service_id, s.display_name AS `name`, s.state AS `status_code`, s.state_type, s.output, s.flapping, s.scheduled_downtime_depth AS `in_downtime`, s.acknowledged, s.perfData AS `performance_data`, s.output, s.command_line, s.notification_number, s.notify, s.last_state_change AS `last_status_change`, s.last_notification, s.latency, s.execution_time, s.percent_state_change AS `status_change_percentage`, s.next_check, s.last_check, s.passive_checks, s.active_checks, s.last_time_ok, s.check_attempt, s.max_check_attempts, i.name AS `monitoring_server_name`, CASE WHEN EXISTS( SELECT i.host_id, i.service_id FROM `:dbstg`.metrics AS m, `:dbstg`.index_data AS i WHERE i.host_id = s.host_id AND i.service_id = s.service_id AND i.id = m.index_id AND m.hidden = "0") THEN 1 ELSE 0 END AS `has_graph_data` FROM `:dbstg`.`services` AS s ' . ($accessGroupRequest ?? '') . ' INNER JOIN `:dbstg`.`hosts` sh ON sh.host_id = s.host_id' . ' INNER JOIN `:dbstg`.`instances` AS i ON i.instance_id = sh.instance_id' . " WHERE s.description = :meta_id AND s.enabled = '1'"; $statement = $this->db->prepare($this->translateDbName($request)); $statement->bindValue(':meta_id', 'meta_' . $metaId, \PDO::PARAM_STR); $statement->execute(); if ($row = $statement->fetch(\PDO::FETCH_ASSOC)) { /** @var array<string,int|string|null> $row */ return DbMetaServiceFactory::createFromRecord($row); } return null; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Infrastructure/RealTime/Repository/Host/DbHostFactory.php
centreon/src/Core/Infrastructure/RealTime/Repository/Host/DbHostFactory.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\Infrastructure\RealTime\Repository\Host; use Core\Domain\RealTime\Model\Host; use Core\Infrastructure\Common\Repository\DbFactoryUtilitiesTrait; use Core\Infrastructure\RealTime\Repository\Icon\DbIconFactory; /** * @phpstan-type _dataHost array{ * host_id: int|string|null, * name: int|string|null, * address: int|string|null, * monitoring_server_name: int|string|null, * timezone: string|null, * performance_data: string|null, * output: string|null, * command_line: string|null, * flapping: int|string|null, * acknowledged: int|string|null, * nb_downtime: int|string|null, * passive_checks: int|string|null, * active_checks: int|string|null, * latency: int|string|null, * execution_time: int|string|null, * status_change_percentage: int|string|null, * notify: int|string|null, * notification_number: int|string|null, * last_status_change: int|string|null, * last_notification: int|string|null, * last_check: int|string|null, * last_time_up: int|string|null, * max_check_attempts: int|string|null, * check_attempt: int|string|null, * alias: string|null, * next_check: int|string|null, * icon_name: string|null, * icon_url: string|null, * } */ class DbHostFactory { use DbFactoryUtilitiesTrait; /** * @param _dataHost $data * * @return Host */ public static function createFromRecord(array $data): Host { $host = new Host( (int) $data['host_id'], (string) $data['name'], (string) $data['address'], (string) $data['monitoring_server_name'], DbHostStatusFactory::createFromRecord($data) ); $host->setTimezone($data['timezone']) ->setPerformanceData($data['performance_data']) ->setOutput($data['output']) ->setCommandLine($data['command_line']) ->setIsFlapping((int) $data['flapping'] === 1) ->setIsAcknowledged((int) $data['acknowledged'] === 1) ->setIsInDowntime((int) $data['nb_downtime'] > 0) ->setPassiveChecks((int) $data['passive_checks'] === 1) ->setActiveChecks((int) $data['active_checks'] === 1) ->setLatency(self::getFloatOrNull($data['latency'])) ->setExecutionTime(self::getFloatOrNull($data['execution_time'])) ->setStatusChangePercentage(self::getFloatOrNull($data['status_change_percentage'])) ->setNotificationEnabled((int) $data['notify'] === 1) ->setNotificationNumber(self::getIntOrNull($data['notification_number'])) ->setLastStatusChange(self::createDateTimeFromTimestamp(is_numeric($data['last_status_change']) ? (int) $data['last_status_change'] : null)) ->setLastNotification(self::createDateTimeFromTimestamp(is_numeric($data['last_notification']) ? (int) $data['last_notification'] : null)) ->setLastCheck(self::createDateTimeFromTimestamp(is_numeric($data['last_check']) ? (int) $data['last_check'] : null)) ->setLastTimeUp(self::createDateTimeFromTimestamp(is_numeric($data['last_time_up']) ? (int) $data['last_time_up'] : null)) ->setMaxCheckAttempts(self::getIntOrNull($data['max_check_attempts'])) ->setCheckAttempts(self::getIntOrNull($data['check_attempt'])) ->setAlias($data['alias']); $nextCheck = self::createDateTimeFromTimestamp( (int) $data['active_checks'] === 1 ? (int) $data['next_check'] : null ); $host->setNextCheck($nextCheck); $host->setIcon(DbIconFactory::createFromRecord($data)); return $host; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Infrastructure/RealTime/Repository/Host/DbHostStatusFactory.php
centreon/src/Core/Infrastructure/RealTime/Repository/Host/DbHostStatusFactory.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\Infrastructure\RealTime\Repository\Host; use Core\Domain\RealTime\Model\HostStatus; class DbHostStatusFactory { /** * @param array<string,int|string|null> $data * * @return HostStatus */ public static function createFromRecord(array $data): HostStatus { $statusType = (int) $data['state_type']; return match ((int) $data['status_code']) { HostStatus::STATUS_CODE_UP => (new HostStatus( HostStatus::STATUS_NAME_UP, HostStatus::STATUS_CODE_UP, $statusType )) ->setOrder(HostStatus::STATUS_ORDER_UP), HostStatus::STATUS_CODE_DOWN => (new HostStatus( HostStatus::STATUS_NAME_DOWN, HostStatus::STATUS_CODE_DOWN, $statusType )) ->setOrder(HostStatus::STATUS_ORDER_DOWN), HostStatus::STATUS_CODE_UNREACHABLE => (new HostStatus( HostStatus::STATUS_NAME_UNREACHABLE, HostStatus::STATUS_CODE_UNREACHABLE, $statusType )) ->setOrder(HostStatus::STATUS_ORDER_UNREACHABLE), HostStatus::STATUS_CODE_PENDING => (new HostStatus( HostStatus::STATUS_NAME_PENDING, HostStatus::STATUS_CODE_PENDING, $statusType )) ->setOrder(HostStatus::STATUS_ORDER_PENDING), default => (new HostStatus( HostStatus::STATUS_NAME_PENDING, HostStatus::STATUS_CODE_PENDING, $statusType )) ->setOrder(HostStatus::STATUS_ORDER_PENDING), }; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Infrastructure/RealTime/Repository/Host/DbReadHostRepository.php
centreon/src/Core/Infrastructure/RealTime/Repository/Host/DbReadHostRepository.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\Infrastructure\RealTime\Repository\Host; use Centreon\Infrastructure\DatabaseConnection; use Centreon\Infrastructure\Repository\AbstractRepositoryDRB; use Core\Application\RealTime\Repository\ReadHostRepositoryInterface; use Core\Domain\RealTime\Model\Host; /** * @phpstan-import-type _dataHost from DbHostFactory */ class DbReadHostRepository extends AbstractRepositoryDRB implements ReadHostRepositoryInterface { /** * @param DatabaseConnection $db */ public function __construct(DatabaseConnection $db) { $this->db = $db; } /** * @inheritDoc */ public function findHostById(int $hostId): ?Host { return $this->findHost($hostId); } /** * @inheritDoc */ public function findHostByIdAndAccessGroupIds(int $hostId, array $accessGroupIds): ?Host { if ($accessGroupIds === []) { return null; } $accessGroupRequest = ' INNER JOIN `:dbstg`.`centreon_acl` AS host_acl ON host_acl.host_id = h.host_id AND host_acl.service_id IS NULL AND host_acl.group_id IN (' . implode(',', $accessGroupIds) . ') '; return $this->findHost($hostId, $accessGroupRequest); } /** * @inheritDoc */ public function isAllowedToFindHostByAccessGroupIds(int $hostId, array $accessGroupIds): bool { if ($accessGroupIds === []) { return false; } $request = ' SELECT COUNT(h.host_id) AS total, 1 AS REALTIME FROM `:dbstg`.`hosts` AS h INNER JOIN `:dbstg`.`centreon_acl` AS host_acl ON host_acl.host_id = h.host_id AND host_acl.group_id IN (' . implode(',', $accessGroupIds) . ') WHERE h.host_id = :host_id AND h.enabled = 1 '; $statement = $this->db->prepare($this->translateDbName($request)); $statement->bindValue(':host_id', $hostId, \PDO::PARAM_INT); $statement->execute(); return $statement->fetchColumn() > 0; } /** * Find host request according to accessgroups or not. * * @param int $hostId * @param string|null $accessGroupRequest * * @return Host|null */ private function findHost(int $hostId, ?string $accessGroupRequest = null): ?Host { $request = "SELECT 1 AS REALTIME, h.host_id, h.name, h.address, h.output, h.alias, h.timezone, h.flapping, h.scheduled_downtime_depth AS `nb_downtime`, h.acknowledged, i.name AS `monitoring_server_name`, h.state AS `status_code`, h.perfData AS `performance_data`, h.output, h.command_line, h.notify, h.notification_number, h.last_state_change AS `last_status_change`, h.last_notification, h.latency, h.execution_time, h.percent_state_change AS `status_change_percentage`, h.next_check, h.last_check, h.passive_checks, h.active_checks, h.last_time_up, host_cvl.value AS `severity_level`, h.icon_image_alt AS `icon_name`, h.icon_image AS `icon_url`, h.check_attempt, h.max_check_attempts, h.state_type FROM `:dbstg`.`hosts` AS h INNER JOIN `:dbstg`.`instances` AS i ON i.instance_id = h.instance_id LEFT JOIN `:dbstg`.`customvariables` AS host_cvl ON host_cvl.host_id = h.host_id AND host_cvl.service_id = 0 AND host_cvl.name = 'CRITICALITY_LEVEL'" . ($accessGroupRequest ?? '') . "WHERE h.host_id = :host_id AND h.enabled = '1' AND h.name NOT LIKE '\_Module_BAM%'"; $statement = $this->db->prepare($this->translateDbName($request)); $statement->bindValue(':host_id', $hostId, \PDO::PARAM_INT); $statement->execute(); if (($row = $statement->fetch(\PDO::FETCH_ASSOC))) { /** @var _dataHost $row */ return DbHostFactory::createFromRecord($row); } return null; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Infrastructure/RealTime/Repository/DataBin/DbReadPerformanceDataRepository.php
centreon/src/Core/Infrastructure/RealTime/Repository/DataBin/DbReadPerformanceDataRepository.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\Infrastructure\RealTime\Repository\DataBin; use Centreon\Infrastructure\DatabaseConnection; use Centreon\Infrastructure\Repository\AbstractRepositoryDRB; use Core\Application\RealTime\Repository\ReadPerformanceDataRepositoryInterface; use Core\Metric\Domain\Model\Metric; use Core\Metric\Domain\Model\MetricValue; use Core\Metric\Domain\Model\PerformanceMetric; use DateTimeInterface; use PDO; class DbReadPerformanceDataRepository extends AbstractRepositoryDRB implements ReadPerformanceDataRepositoryInterface { /** * @param DatabaseConnection $db */ public function __construct(DatabaseConnection $db) { $this->db = $db; } /** * Retrieves raw data_bin with filters. * * @param array<Metric> $metrics * @param DateTimeInterface $startDate * @param DateTimeInterface $endDate * * @return iterable<PerformanceMetric> */ public function findDataByMetricsAndDates( array $metrics, DateTimeInterface $startDate, DateTimeInterface $endDate, ): iterable { $this->db->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false); $this->db->setAttribute(PDO::ATTR_STRINGIFY_FETCHES, true); $query = $this->generateDataBinQuery($metrics); $statement = $this->db->prepare($this->translateDbName($query)); $statement->bindValue(':start', $startDate->getTimestamp(), PDO::PARAM_INT); $statement->bindValue(':end', $endDate->getTimestamp(), PDO::PARAM_INT); $statement->execute(); foreach ($statement->fetchAll(PDO::FETCH_ASSOC) as $dataBin) { yield $this->createPerformanceMetricFromDataBin($dataBin); } $statement->closeCursor(); } /** * Generates SQL query statement to extract metric data from table data_bin. * * @param array<Metric> $metrics * * @return string */ private function generateDataBinQuery(array $metrics): string { $metricIds = []; $subQueryColumns = []; $subQueryPattern = 'AVG(CASE WHEN id_metric = %d THEN `value` end) AS `%s`'; foreach ($metrics as $metric) { $subQueryColumns[] = sprintf($subQueryPattern, $metric->getId(), $metric->getName()); $metricIds[] = $metric->getId(); } $pattern = 'SELECT %s FROM `:dbstg`.data_bin WHERE '; $pattern .= ' ctime >= :start AND ctime < :end AND id_metric IN (%s) GROUP BY ctime'; return sprintf( $pattern, implode(', ', ['ctime', ...$subQueryColumns]), implode(',', $metricIds) ); } /** * @param array<string, int|string> $dataBin */ private function createPerformanceMetricFromDataBin(array $dataBin): PerformanceMetric { $time = (new \DateTimeImmutable())->setTimestamp((int) $dataBin['ctime']); $metricValues = $this->createMetricValues($dataBin); return new PerformanceMetric($time, $metricValues); } /** * @param array<string, mixed> $data * * @return MetricValue[] */ private function createMetricValues(array $data): array { $metricValues = []; foreach ($data as $columnName => $columnValue) { if ($columnName !== 'ctime') { $metricValues[] = new MetricValue($columnName, (float) $columnValue); } } return $metricValues; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Infrastructure/RealTime/Repository/Icon/DbIconFactory.php
centreon/src/Core/Infrastructure/RealTime/Repository/Icon/DbIconFactory.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\Infrastructure\RealTime\Repository\Icon; use Core\Domain\RealTime\Model\Icon; use Core\Infrastructure\RealTime\Repository\Host\DbHostFactory; use Core\Infrastructure\RealTime\Repository\Service\DbServiceFactory; /** * @phpstan-import-type _dataHost from DbHostFactory * @phpstan-import-type _dataService from DbServiceFactory */ class DbIconFactory { /** * @param _dataHost|_dataService $data * * @return Icon|null */ public static function createFromRecord(array $data): ?Icon { if ( $data['icon_name'] === null && $data['icon_url'] === null ) { return null; } return (new Icon()) ->setName($data['icon_name']) ->setUrl($data['icon_url']); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Infrastructure/RealTime/Repository/Downtime/DbReadDowntimeRepository.php
centreon/src/Core/Infrastructure/RealTime/Repository/Downtime/DbReadDowntimeRepository.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\Infrastructure\RealTime\Repository\Downtime; use Centreon\Infrastructure\DatabaseConnection; use Centreon\Infrastructure\Repository\AbstractRepositoryDRB; use Core\Application\RealTime\Repository\ReadDowntimeRepositoryInterface; use Core\Domain\RealTime\Model\Downtime; class DbReadDowntimeRepository extends AbstractRepositoryDRB implements ReadDowntimeRepositoryInterface { /** * @param DatabaseConnection $db */ public function __construct(DatabaseConnection $db) { $this->db = $db; } /** * @inheritDoc */ public function findOnGoingDowntimesByHostId(int $hostId): array { return $this->findOnGoingDowntimes($hostId, 0); } /** * @inheritDoc */ public function findOnGoingDowntimesByHostIdAndServiceId(int $hostId, int $serviceId): array { return $this->findOnGoingDowntimes($hostId, $serviceId); } /** * Find downtimes. * * @param int $hostId * @param int $serviceId * * @return Downtime[] */ private function findOnGoingDowntimes(int $hostId, int $serviceId): array { $downtimes = []; $sql = 'SELECT 1 AS REALTIME, d.*, c.contact_id AS `author_id` FROM `:dbstg`.`downtimes` AS `d` ' . 'LEFT JOIN `:db`.contact AS `c` ON c.contact_alias = d.author ' . 'WHERE d.host_id = :hostId AND d.service_id = :serviceId ' . 'AND d.deletion_time IS NULL AND d.cancelled = 0 AND ((NOW() BETWEEN FROM_UNIXTIME(d.actual_start_time) ' . 'AND FROM_UNIXTIME(d.actual_end_time)) OR ((NOW() > FROM_UNIXTIME(d.actual_start_time) ' . 'AND d.actual_end_time IS NULL))) ' . 'ORDER BY d.entry_time DESC'; $statement = $this->db->prepare($this->translateDbName($sql)); $statement->bindValue(':hostId', $hostId, \PDO::PARAM_INT); $statement->bindValue(':serviceId', $serviceId, \PDO::PARAM_INT); $statement->execute(); while ($row = $statement->fetch(\PDO::FETCH_ASSOC)) { /** @var array<string,int|string|null> $row */ $downtimes[] = DbDowntimeFactory::createFromRecord($row); } return $downtimes; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Infrastructure/RealTime/Repository/Downtime/DbDowntimeFactory.php
centreon/src/Core/Infrastructure/RealTime/Repository/Downtime/DbDowntimeFactory.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\Infrastructure\RealTime\Repository\Downtime; use Core\Domain\RealTime\Model\Downtime; use Core\Infrastructure\Common\Repository\DbFactoryUtilitiesTrait; class DbDowntimeFactory { use DbFactoryUtilitiesTrait; /** * @param array<string,int|string|null> $data * * @return Downtime */ public static function createFromRecord(array $data): Downtime { /** @var string|null */ $authorName = $data['author']; /** @var string|null */ $comment = $data['comment_data']; return (new Downtime((int) $data['downtime_id'], (int) $data['host_id'], (int) $data['service_id'])) ->setAuthorId((int) $data['author_id']) ->setAuthorName($authorName) ->setComment($comment) ->setCancelled((int) $data['cancelled'] === 1) ->setFixed((int) $data['fixed'] === 1) ->setStarted((int) $data['started'] === 1) ->setInstanceId(self::getIntOrNull($data['instance_id'])) ->setEngineDowntimeId(self::getIntOrNull($data['internal_id'])) ->setDuration(self::getIntOrNull($data['duration'])) ->setDeletionTime(self::createDateTimeFromTimestamp((int) $data['deletion_time'])) ->setEndTime(self::createDateTimeFromTimestamp((int) $data['end_time'])) ->setStartTime(self::createDateTimeFromTimestamp((int) $data['start_time'])) ->setActualStartTime(self::createDateTimeFromTimestamp((int) $data['actual_start_time'])) ->setActualEndTime(self::createDateTimeFromTimestamp((int) $data['actual_end_time'])) ->setEntryTime(self::createDateTimeFromTimestamp((int) $data['entry_time'])); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Infrastructure/RealTime/Repository/Servicegroup/DbReadServicegroupRepository.php
centreon/src/Core/Infrastructure/RealTime/Repository/Servicegroup/DbReadServicegroupRepository.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\Infrastructure\RealTime\Repository\Servicegroup; use Centreon\Infrastructure\DatabaseConnection; use Centreon\Infrastructure\Repository\AbstractRepositoryDRB; use Core\Application\RealTime\Repository\ReadServicegroupRepositoryInterface; use Core\Domain\RealTime\Model\Servicegroup; class DbReadServicegroupRepository extends AbstractRepositoryDRB implements ReadServicegroupRepositoryInterface { /** * @param DatabaseConnection $db */ public function __construct(DatabaseConnection $db) { $this->db = $db; } /** * @inheritDoc */ public function findAllByHostIdAndServiceId(int $hostId, int $serviceId): array { return $this->findServicegroups($hostId, $serviceId); } /** * @inheritDoc */ public function findAllByHostIdAndServiceIdAndAccessGroupIds( int $hostId, int $serviceId, array $accessGroupIds, ): array { $servicegroups = []; if ($accessGroupIds === []) { return $servicegroups; } $aclRequest = ' INNER JOIN `:dbstg`.`centreon_acl` AS acl ON acl.host_id = ssg.host_id AND acl.service_id = ssg.service_id AND acl.group_id IN (' . implode(',', $accessGroupIds) . ') '; return $this->findServicegroups($hostId, $serviceId, $aclRequest); } /** * @param int $hostId * @param int $serviceId * @param string|null $aclRequest * * @return Servicegroup[] */ private function findServicegroups(int $hostId, int $serviceId, ?string $aclRequest = null): array { $request = 'SELECT DISTINCT 1 AS REALTIME, sg.servicegroup_id, sg.name AS `servicegroup_name` FROM `:dbstg`.`services_servicegroups` AS ssg INNER JOIN `:dbstg`.`servicegroups` AS sg ON sg.servicegroup_id = ssg.servicegroup_id'; if ($aclRequest !== null) { $request .= $aclRequest; } $request .= ' WHERE ssg.host_id = :hostId AND ssg.service_id = :serviceId ORDER BY sg.name ASC'; $statement = $this->db->prepare($this->translateDbName($request)); $statement->bindValue(':hostId', $hostId, \PDO::PARAM_INT); $statement->bindValue(':serviceId', $serviceId, \PDO::PARAM_INT); $statement->execute(); $servicegroups = []; while (($row = $statement->fetch(\PDO::FETCH_ASSOC))) { $servicegroups[] = DbServicegroupFactory::createFromRecord($row); } return $servicegroups; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Infrastructure/RealTime/Repository/Servicegroup/DbServicegroupFactory.php
centreon/src/Core/Infrastructure/RealTime/Repository/Servicegroup/DbServicegroupFactory.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\Infrastructure\RealTime\Repository\Servicegroup; use Core\Domain\RealTime\Model\Servicegroup; class DbServicegroupFactory { /** * @param array<string, mixed> $data * * @return Servicegroup */ public static function createFromRecord(array $data): Servicegroup { return new Servicegroup((int) $data['servicegroup_id'], $data['servicegroup_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/Infrastructure/RealTime/Repository/FindIndex/DbReadIndexDataRepository.php
centreon/src/Core/Infrastructure/RealTime/Repository/FindIndex/DbReadIndexDataRepository.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\Infrastructure\RealTime\Repository\FindIndex; use Centreon\Infrastructure\DatabaseConnection; use Centreon\Infrastructure\Repository\AbstractRepositoryDRB; use Core\Application\RealTime\Repository\ReadIndexDataRepositoryInterface; use Core\Domain\RealTime\Model\IndexData; use PDO; class DbReadIndexDataRepository extends AbstractRepositoryDRB implements ReadIndexDataRepositoryInterface { /** * @param DatabaseConnection $db */ public function __construct(DatabaseConnection $db) { $this->db = $db; } /** * @inheritDoc */ public function findIndexByHostIdAndServiceId(int $hostId, int $serviceId): int { $query = 'SELECT 1 AS REALTIME, id FROM `:dbstg`.index_data WHERE host_id = :hostId AND service_id = :serviceId'; $statement = $this->db->prepare($this->translateDbName($query)); $statement->bindValue(':hostId', $hostId, PDO::PARAM_INT); $statement->bindValue(':serviceId', $serviceId, PDO::PARAM_INT); $statement->execute(); $row = $statement->fetch(); if (! is_array($row) || ! array_key_exists('id', $row)) { throw new \InvalidArgumentException('Resource not found'); } return (int) $row['id']; } /** * @inheritDoc */ public function findHostNameAndServiceDescriptionByIndex(int $index): ?IndexData { $query = 'SELECT 1 AS REALTIME, host_name as hostName, service_description as serviceDescription '; $query .= ' FROM `:dbstg`.index_data WHERE id = :index'; $statement = $this->db->prepare($this->translateDbName($query)); $statement->bindValue(':index', $index, PDO::PARAM_INT); $statement->execute(); $record = $statement->fetch(); if (! is_array($record)) { return null; } return new IndexData($record['hostName'], $record['serviceDescription']); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Infrastructure/RealTime/Repository/Service/DbServiceFactory.php
centreon/src/Core/Infrastructure/RealTime/Repository/Service/DbServiceFactory.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\Infrastructure\RealTime\Repository\Service; use Core\Domain\RealTime\Model\Service; use Core\Infrastructure\Common\Repository\DbFactoryUtilitiesTrait; use Core\Infrastructure\RealTime\Repository\Icon\DbIconFactory; /** * @phpstan-type _dataService array{ * service_id: int|string|null, * host_id: int|string|null, * description: int|string|null, * performance_data: string|null, * output: string|null, * command_line: string|null, * flapping: int|string|null, * acknowledged: int|string|null, * in_downtime: int|string|null, * passive_checks: int|string|null, * active_checks: int|string|null, * latency: int|string|null, * execution_time: int|string|null, * status_change_percentage: int|string|null, * notify: int|string|null, * notification_number: int|string|null, * last_status_change: int|string|null, * last_status_change: int|string|null, * last_notification: int|string|null, * last_notification: int|string|null, * last_check: int|string|null, * last_check: int|string|null, * last_time_ok: int|string|null, * last_time_ok: int|string|null, * max_check_attempts: int|string|null, * check_attempt: int|string|null, * has_graph_data: int|string|null, * active_checks: int|string|null, * next_check: int|string|null, * icon_name: string|null, * icon_url: string|null, * } */ class DbServiceFactory { use DbFactoryUtilitiesTrait; /** * @param _dataService $data * * @return Service */ public static function createFromRecord(array $data): Service { $service = new Service( (int) $data['service_id'], (int) $data['host_id'], (string) $data['description'], DbServiceStatusFactory::createFromRecord($data) ); $service->setPerformanceData($data['performance_data']) ->setOutput($data['output']) ->setCommandLine($data['command_line']) ->setIsFlapping((int) $data['flapping'] === 1) ->setIsAcknowledged((int) $data['acknowledged'] === 1) ->setIsInDowntime((int) $data['in_downtime'] > 0) ->setPassiveChecks((int) $data['passive_checks'] === 1) ->setActiveChecks((int) $data['active_checks'] === 1) ->setLatency(self::getFloatOrNull($data['latency'])) ->setExecutionTime(self::getFloatOrNull($data['execution_time'])) ->setStatusChangePercentage(self::getFloatOrNull($data['status_change_percentage'])) ->setNotificationEnabled((int) $data['notify'] === 1) ->setNotificationNumber(self::getIntOrNull($data['notification_number'])) ->setLastStatusChange(self::createDateTimeFromTimestamp(is_numeric($data['last_status_change']) ? (int) $data['last_status_change'] : null)) ->setLastNotification(self::createDateTimeFromTimestamp(is_numeric($data['last_notification']) ? (int) $data['last_notification'] : null)) ->setLastCheck(self::createDateTimeFromTimestamp(is_numeric($data['last_check']) ? (int) $data['last_check'] : null)) ->setLastTimeOk(self::createDateTimeFromTimestamp(is_numeric($data['last_time_ok']) ? (int) $data['last_time_ok'] : null)) ->setMaxCheckAttempts(self::getIntOrNull($data['max_check_attempts'])) ->setCheckAttempts(self::getIntOrNull($data['check_attempt'])) ->setHasGraphData((int) $data['has_graph_data'] === 1); $nextCheck = self::createDateTimeFromTimestamp( (int) $data['active_checks'] === 1 ? (int) $data['next_check'] : null ); $service->setNextCheck($nextCheck); $service->setIcon(DbIconFactory::createFromRecord($data)); return $service; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Infrastructure/RealTime/Repository/Service/DbServiceStatusFactory.php
centreon/src/Core/Infrastructure/RealTime/Repository/Service/DbServiceStatusFactory.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\Infrastructure\RealTime\Repository\Service; use Core\Domain\RealTime\Model\ServiceStatus; class DbServiceStatusFactory { /** * @param array<string, mixed> $data * * @return ServiceStatus */ public static function createFromRecord(array $data): ServiceStatus { $statusType = (int) $data['state_type']; return match ((int) $data['status_code']) { ServiceStatus::STATUS_CODE_OK => (new ServiceStatus( ServiceStatus::STATUS_NAME_OK, ServiceStatus::STATUS_CODE_OK, $statusType )) ->setOrder(ServiceStatus::STATUS_ORDER_OK), ServiceStatus::STATUS_CODE_WARNING => (new ServiceStatus( ServiceStatus::STATUS_NAME_WARNING, ServiceStatus::STATUS_CODE_WARNING, $statusType )) ->setOrder(ServiceStatus::STATUS_ORDER_WARNING), ServiceStatus::STATUS_CODE_CRITICAL => (new ServiceStatus( ServiceStatus::STATUS_NAME_CRITICAL, ServiceStatus::STATUS_CODE_CRITICAL, $statusType )) ->setOrder(ServiceStatus::STATUS_ORDER_CRITICAL), ServiceStatus::STATUS_CODE_UNKNOWN => (new ServiceStatus( ServiceStatus::STATUS_NAME_UNKNOWN, ServiceStatus::STATUS_CODE_UNKNOWN, $statusType )) ->setOrder(ServiceStatus::STATUS_ORDER_UNKNOWN), ServiceStatus::STATUS_CODE_PENDING => (new ServiceStatus( ServiceStatus::STATUS_NAME_PENDING, ServiceStatus::STATUS_CODE_PENDING, $statusType )) ->setOrder(ServiceStatus::STATUS_ORDER_PENDING), default => (new ServiceStatus( ServiceStatus::STATUS_NAME_PENDING, ServiceStatus::STATUS_CODE_PENDING, $statusType )) ->setOrder(ServiceStatus::STATUS_ORDER_PENDING), }; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Infrastructure/RealTime/Repository/Service/DbReadServiceRepository.php
centreon/src/Core/Infrastructure/RealTime/Repository/Service/DbReadServiceRepository.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\Infrastructure\RealTime\Repository\Service; use Centreon\Infrastructure\DatabaseConnection; use Centreon\Infrastructure\Repository\AbstractRepositoryDRB; use Core\Application\RealTime\Repository\ReadServiceRepositoryInterface; use Core\Domain\RealTime\Model\Service; /** * @phpstan-import-type _dataService from DbServiceFactory */ class DbReadServiceRepository extends AbstractRepositoryDRB implements ReadServiceRepositoryInterface { /** * @param DatabaseConnection $db */ public function __construct(DatabaseConnection $db) { $this->db = $db; } /** * @inheritDoc */ public function findServiceById(int $hostId, int $serviceId): ?Service { return $this->findService($hostId, $serviceId); } /** * @inheritDoc */ public function findServiceByIdAndAccessGroupIds(int $hostId, int $serviceId, array $accessGroupIds): ?Service { if ($accessGroupIds === []) { return null; } $accessGroupRequest = ' INNER JOIN `:dbstg`.`centreon_acl` AS service_acl ON service_acl.service_id = s.service_id AND service_acl.host_id = s.host_id AND service_acl.group_id IN (' . implode(',', $accessGroupIds) . ') '; return $this->findService($hostId, $serviceId, $accessGroupRequest); } /** * @inheritDoc */ public function isAllowedToFindServiceByAccessGroupIds(int $hostId, int $serviceId, array $accessGroupIds): bool { if ($accessGroupIds === []) { return false; } $request = ' SELECT COUNT(s.service_id) AS total, 1 AS REALTIME FROM `:dbstg`.`services` AS s INNER JOIN `:dbstg`.`centreon_acl` AS service_acl ON service_acl.service_id = s.service_id AND service_acl.host_id = s.host_id AND service_acl.group_id IN (' . implode(',', $accessGroupIds) . ') WHERE s.service_id = :service_id AND s.host_id = :host_id AND s.enabled = 1 '; $statement = $this->db->prepare($this->translateDbName($request)); $statement->bindValue(':service_id', $serviceId, \PDO::PARAM_INT); $statement->bindValue(':host_id', $hostId, \PDO::PARAM_INT); $statement->execute(); return $statement->fetchColumn() > 0; } /** * @param int $hostId * @param int $serviceId * @param string|null $accessGroupRequest * * @return Service|null */ private function findService(int $hostId, int $serviceId, ?string $accessGroupRequest = null): ?Service { $request = "SELECT 1 AS REALTIME, s.service_id, s.host_id, s.description, s.output, s.flapping, s.scheduled_downtime_depth AS `in_downtime`, s.acknowledged, s.state AS `status_code`, s.perfData AS `performance_data`, s.output, s.command_line, s.notification_number, s.notify, s.last_state_change AS `last_status_change`, s.last_notification, s.latency, s.execution_time, s.percent_state_change AS `status_change_percentage`, s.next_check, s.last_check, s.passive_checks, s.active_checks, s.last_time_ok, service_cvl.value AS `severity_level`, s.icon_image_alt AS `icon_name`, s.icon_image AS `icon_url`, s.check_attempt, s.max_check_attempts, s.state_type, CASE WHEN EXISTS( SELECT i.host_id, i.service_id FROM `:dbstg`.metrics AS m, `:dbstg`.index_data AS i WHERE i.host_id = s.host_id AND i.service_id = s.service_id AND i.id = m.index_id AND m.hidden = \"0\") THEN 1 ELSE 0 END AS `has_graph_data` FROM `:dbstg`.`services` AS s LEFT JOIN `:dbstg`.`customvariables` AS service_cvl ON service_cvl.service_id = s.service_id AND service_cvl.name = 'CRITICALITY_LEVEL'" . ($accessGroupRequest ?? '') . "WHERE s.service_id = :service_id AND s.host_id = :host_id AND s.enabled = '1'"; $statement = $this->db->prepare($this->translateDbName($request)); $statement->bindValue(':service_id', $serviceId, \PDO::PARAM_INT); $statement->bindValue(':host_id', $hostId, \PDO::PARAM_INT); $statement->execute(); if ($row = $statement->fetch(\PDO::FETCH_ASSOC)) { /** @var _dataService $row */ return DbServiceFactory::createFromRecord($row); } return null; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Infrastructure/Configuration/NotificationPolicy/Api/FindHostNotificationPolicyController.php
centreon/src/Core/Infrastructure/Configuration/NotificationPolicy/Api/FindHostNotificationPolicyController.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\Infrastructure\Configuration\NotificationPolicy\Api; use Centreon\Application\Controller\AbstractController; use Core\Application\Configuration\NotificationPolicy\UseCase\FindHostNotificationPolicy; use Core\Application\Configuration\NotificationPolicy\UseCase\FindNotificationPolicyPresenterInterface; final class FindHostNotificationPolicyController extends AbstractController { /** * @param int $hostId * @param FindHostNotificationPolicy $useCase * @param FindNotificationPolicyPresenterInterface $presenter * * @return object */ public function __invoke( int $hostId, FindHostNotificationPolicy $useCase, FindNotificationPolicyPresenterInterface $presenter, ): object { /** * Access denied if no rights given to the configuration and realtime for the current user. */ $this->denyAccessUnlessGrantedForApiConfiguration(); $this->denyAccessUnlessGrantedForApiRealtime(); $useCase($hostId, $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/Infrastructure/Configuration/NotificationPolicy/Api/FindNotificationPolicyPresenter.php
centreon/src/Core/Infrastructure/Configuration/NotificationPolicy/Api/FindNotificationPolicyPresenter.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\Infrastructure\Configuration\NotificationPolicy\Api; use Core\Application\Common\UseCase\AbstractPresenter; use Core\Application\Configuration\NotificationPolicy\UseCase\FindNotificationPolicyPresenterInterface; use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface; use Core\Infrastructure\Configuration\NotificationPolicy\Api\Hypermedia\ContactGroupHypermediaCreator; use Core\Infrastructure\Configuration\NotificationPolicy\Api\Hypermedia\ContactHypermediaCreator; class FindNotificationPolicyPresenter extends AbstractPresenter implements FindNotificationPolicyPresenterInterface { /** * @param ContactHypermediaCreator $contactHypermediaCreator * @param ContactGroupHypermediaCreator $contactGroupHypermediaCreator * @param PresenterFormatterInterface $presenterFormatter */ public function __construct( private ContactHypermediaCreator $contactHypermediaCreator, private ContactGroupHypermediaCreator $contactGroupHypermediaCreator, protected PresenterFormatterInterface $presenterFormatter, ) { parent::__construct($presenterFormatter); } /** * @inheritDoc */ public function present(mixed $response): void { $presenterResponse['contacts'] = array_map( fn (array $notifiedContact) => [ 'id' => $notifiedContact['id'], 'name' => $notifiedContact['name'], 'alias' => $notifiedContact['alias'], 'email' => $notifiedContact['email'], 'notifications' => $notifiedContact['notifications'], 'configuration_uri' => $this->contactHypermediaCreator->createContactConfigurationUri( $notifiedContact['id'] ), ], $response->notifiedContacts, ); $presenterResponse['contact_groups'] = array_map( fn (array $notifiedContactGroup) => [ 'id' => $notifiedContactGroup['id'], 'name' => $notifiedContactGroup['name'], 'alias' => $notifiedContactGroup['alias'], 'configuration_uri' => $this->contactGroupHypermediaCreator->createContactGroupConfigurationUri( $notifiedContactGroup['id'] ), ], $response->notifiedContactGroups, ); $presenterResponse['is_notification_enabled'] = $response->isNotificationEnabled; parent::present($presenterResponse); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Infrastructure/Configuration/NotificationPolicy/Api/FindServiceNotificationPolicyController.php
centreon/src/Core/Infrastructure/Configuration/NotificationPolicy/Api/FindServiceNotificationPolicyController.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\Infrastructure\Configuration\NotificationPolicy\Api; use Centreon\Application\Controller\AbstractController; use Core\Application\Configuration\NotificationPolicy\UseCase\FindNotificationPolicyPresenterInterface; use Core\Application\Configuration\NotificationPolicy\UseCase\FindServiceNotificationPolicy; final class FindServiceNotificationPolicyController extends AbstractController { /** * @param int $hostId * @param int $serviceId * @param FindServiceNotificationPolicy $useCase * @param FindNotificationPolicyPresenterInterface $presenter * * @return object */ public function __invoke( int $hostId, int $serviceId, FindServiceNotificationPolicy $useCase, FindNotificationPolicyPresenterInterface $presenter, ): object { /** * Access denied if no rights given to the configuration and realtime for the current user. */ $this->denyAccessUnlessGrantedForApiConfiguration(); $this->denyAccessUnlessGrantedForApiRealtime(); $useCase($hostId, $serviceId, $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/Infrastructure/Configuration/NotificationPolicy/Api/FindMetaServiceNotificationPolicyController.php
centreon/src/Core/Infrastructure/Configuration/NotificationPolicy/Api/FindMetaServiceNotificationPolicyController.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\Infrastructure\Configuration\NotificationPolicy\Api; use Centreon\Application\Controller\AbstractController; use Core\Application\Configuration\NotificationPolicy\UseCase\FindMetaServiceNotificationPolicy; use Core\Application\Configuration\NotificationPolicy\UseCase\FindNotificationPolicyPresenterInterface; final class FindMetaServiceNotificationPolicyController extends AbstractController { /** * @param int $metaId * @param FindMetaServiceNotificationPolicy $useCase * @param FindNotificationPolicyPresenterInterface $presenter * * @return object */ public function __invoke( int $metaId, FindMetaServiceNotificationPolicy $useCase, FindNotificationPolicyPresenterInterface $presenter, ): object { /** * Access denied if no rights given to the configuration and realtime for the current user. */ $this->denyAccessUnlessGrantedForApiConfiguration(); $this->denyAccessUnlessGrantedForApiRealtime(); $useCase($metaId, $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/Infrastructure/Configuration/NotificationPolicy/Api/Hypermedia/ContactGroupHypermediaCreator.php
centreon/src/Core/Infrastructure/Configuration/NotificationPolicy/Api/Hypermedia/ContactGroupHypermediaCreator.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\Infrastructure\Configuration\NotificationPolicy\Api\Hypermedia; use Centreon\Domain\Contact\Contact; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Core\Infrastructure\Common\Api\HttpUrlTrait; class ContactGroupHypermediaCreator { use HttpUrlTrait; private const URI_CONFIGURATION_CONTACT_GROUP = '/main.php?p=60302&o=c&cg_id={contactGroupId}'; /** * @param ContactInterface $contact */ public function __construct( private ContactInterface $contact, ) { } /** * Create the configuration URI to the contact group regarding ACL. * * @param int $contactGroupId * * @return string|null */ public function createContactGroupConfigurationUri(int $contactGroupId): ?string { return ( $this->contact->hasTopologyRole(Contact::ROLE_CONFIGURATION_SERVICES_SERVICE_GROUPS_READ_WRITE) || $this->contact->hasTopologyRole(Contact::ROLE_CONFIGURATION_SERVICES_SERVICE_GROUPS_READ) || $this->contact->isAdmin() ) ? $this->getBaseUri() . str_replace('{contactGroupId}', (string) $contactGroupId, self::URI_CONFIGURATION_CONTACT_GROUP) : 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/Infrastructure/Configuration/NotificationPolicy/Api/Hypermedia/ContactHypermediaCreator.php
centreon/src/Core/Infrastructure/Configuration/NotificationPolicy/Api/Hypermedia/ContactHypermediaCreator.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\Infrastructure\Configuration\NotificationPolicy\Api\Hypermedia; use Centreon\Domain\Contact\Contact; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Core\Infrastructure\Common\Api\HttpUrlTrait; class ContactHypermediaCreator { use HttpUrlTrait; private const URI_CONFIGURATION_CONTACT = '/main.php?p=60301&o=c&contact_id={contactId}'; /** * @param ContactInterface $contact */ public function __construct( private ContactInterface $contact, ) { } /** * Create the configuration URI to the contact regarding ACL. * * @param int $contactId * * @return string|null */ public function createContactConfigurationUri(int $contactId): ?string { return ( $this->contact->hasTopologyRole(Contact::ROLE_CONFIGURATION_CONTACTS_READ_WRITE) || $this->contact->hasTopologyRole(Contact::ROLE_CONFIGURATION_CONTACTS_READ) || $this->contact->isAdmin() ) ? $this->getBaseUri() . str_replace('{contactId}', (string) $contactId, self::URI_CONFIGURATION_CONTACT) : 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/Infrastructure/Configuration/NotificationPolicy/Repository/DbReadHostNotificationRepository.php
centreon/src/Core/Infrastructure/Configuration/NotificationPolicy/Repository/DbReadHostNotificationRepository.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\Infrastructure\Configuration\NotificationPolicy\Repository; use Centreon\Domain\Log\LoggerTrait; use Centreon\Domain\Repository\RepositoryException; use Centreon\Infrastructure\DatabaseConnection; use Core\Application\Configuration\Notification\Repository\ReadHostNotificationRepositoryInterface; use Core\Domain\Configuration\Notification\Model\NotifiedContact; use Core\Domain\Configuration\Notification\Model\NotifiedContactGroup; use Core\Security\AccessGroup\Domain\Model\AccessGroup; class DbReadHostNotificationRepository extends AbstractDbReadNotificationRepository implements ReadHostNotificationRepositoryInterface { use LoggerTrait; /** @var array<int,NotifiedContact[]> */ private array $notifiedContacts = []; /** @var array<int,NotifiedContactGroup[]> */ private array $notifiedContactGroups = []; /** * @param DatabaseConnection $db */ public function __construct( DatabaseConnection $db, ) { $this->db = $db; } /** * @inheritDoc */ public function findNotifiedContactsByIds(int $hostId, array $notifiedContactsIds, array $notifiedContactGroupsIds): array { if (! isset($this->notifiedContacts[$hostId])) { $this->fetchNotifiedContactsAndContactGroups($hostId, $notifiedContactsIds, $notifiedContactGroupsIds); } return $this->notifiedContacts[$hostId]; } /** * @inheritDoc */ public function findNotifiedContactsByIdsAndAccessGroups(int $hostId, array $notifiedContactsIds, array $notifiedContactGroupsIds, array $accessGroups): array { if (! isset($this->notifiedContacts[$hostId])) { $this->fetchNotifiedContactsAndContactGroups($hostId, $notifiedContactsIds, $notifiedContactGroupsIds, $accessGroups); } return $this->notifiedContacts[$hostId]; } /** * @inheritDoc */ public function findNotifiedContactGroupsByIds(int $hostId, array $notifiedContactsIds, array $notifiedContactGroupsIds): array { if (! isset($this->notifiedContactGroups[$hostId])) { $this->fetchNotifiedContactsAndContactGroups($hostId, $notifiedContactsIds, $notifiedContactGroupsIds); } return $this->notifiedContactGroups[$hostId]; } /** * @inheritDoc */ public function findNotifiedContactGroupsByIdsAndAccessGroups(int $hostId, array $notifiedContactsIds, array $notifiedContactGroupsIds, array $accessGroups): array { if (! isset($this->notifiedContactGroups[$hostId])) { $this->fetchNotifiedContactsAndContactGroups($hostId, $notifiedContactsIds, $notifiedContactGroupsIds, $accessGroups); } return $this->notifiedContactGroups[$hostId]; } /** * @inheritDoc */ public function findContactsByHostOrHostTemplate(int $id): array { try { $request = $this->translateDbName( <<<'SQL' SELECT chr.contact_id FROM `:db`.contact_host_relation chr, `:db`.contact WHERE host_host_id = :hostId AND chr.contact_id = contact.contact_id AND contact.contact_activate = '1' SQL ); $statement = $this->db->prepare($request); $statement->bindValue(':hostId', $id, \PDO::PARAM_INT); $statement->execute(); return $statement->fetchAll(\PDO::FETCH_COLUMN); } catch (\PDOException $exception) { $errorMessage = "Error while fetching contacts for host or host template with id {$id} : {$exception->getMessage()}"; $this->error($errorMessage, [ 'id' => $id, 'exception' => [ 'message' => $exception->getMessage(), 'pdo_code' => $exception->getCode(), 'pdo_info' => $exception->errorInfo, 'trace' => $exception->getTraceAsString(), ], ]); throw new RepositoryException(message: $errorMessage, previous: $exception); } } /** * @inheritDoc */ public function findContactGroupsByHostOrHostTemplate(int $id): array { try { $request = $this->translateDbName( <<<'SQL' SELECT contactgroup_cg_id FROM contactgroup_host_relation, contactgroup WHERE host_host_id = :hostId AND contactgroup_cg_id = cg_id AND cg_activate = '1' SQL ); $statement = $this->db->prepare($request); $statement->bindValue(':hostId', $id, \PDO::PARAM_INT); $statement->execute(); return $statement->fetchAll(\PDO::FETCH_COLUMN); } catch (\PDOException $exception) { $errorMessage = "Error while fetching contact groups for host or host template with id {$id} : {$exception->getMessage()}"; $this->error($errorMessage, [ 'id' => $id, 'exception' => [ 'message' => $exception->getMessage(), 'pdo_code' => $exception->getCode(), 'pdo_info' => $exception->errorInfo, 'trace' => $exception->getTraceAsString(), ], ]); throw new RepositoryException(message: $errorMessage, previous: $exception); } } /** * Initialize notified contacts and contactgroups for given host id. * * @param int $hostId * @param array<int, int> $notifiedContactsIds * @param array<int, int> $notifiedContactGroupsIds * @param AccessGroup[] $accessGroups */ private function fetchNotifiedContactsAndContactGroups(int $hostId, array $notifiedContactsIds, array $notifiedContactGroupsIds, array $accessGroups = []): void { if ($accessGroups === []) { $this->notifiedContacts[$hostId] = $this->findContactsByIds($notifiedContactsIds); $this->notifiedContactGroups[$hostId] = $this->findContactGroupsByIds($notifiedContactGroupsIds); } else { $this->notifiedContacts[$hostId] = $this->findContactsByIdsAndAccessGroups( $notifiedContactsIds, $accessGroups ); $this->notifiedContactGroups[$hostId] = $this->findContactGroupsByIdsAndAccessGroups( $notifiedContactGroupsIds, $accessGroups ); } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Infrastructure/Configuration/NotificationPolicy/Repository/LegacyReadServiceNotificationRepository.php
centreon/src/Core/Infrastructure/Configuration/NotificationPolicy/Repository/LegacyReadServiceNotificationRepository.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\Infrastructure\Configuration\NotificationPolicy\Repository; use Centreon\Infrastructure\DatabaseConnection; use Core\Application\Configuration\Notification\Repository\ReadServiceNotificationRepositoryInterface; use Core\Domain\Configuration\Notification\Model\NotifiedContact; use Core\Domain\Configuration\Notification\Model\NotifiedContactGroup; use Core\Security\AccessGroup\Domain\Model\AccessGroup; use Pimple\Container; class LegacyReadServiceNotificationRepository extends AbstractDbReadNotificationRepository implements ReadServiceNotificationRepositoryInterface { /** @var array<int,NotifiedContact[]> */ private array $notifiedContacts = []; /** @var array<int,NotifiedContactGroup[]> */ private array $notifiedContactGroups = []; /** * @param DatabaseConnection $db * @param Container $dependencyInjector */ public function __construct( DatabaseConnection $db, private Container $dependencyInjector, ) { $this->db = $db; } /** * @inheritDoc */ public function findNotifiedContactsById(int $hostId, int $serviceId): array { if (! isset($this->notifiedContacts[$serviceId])) { $this->fetchNotifiedContactsAndContactGroups($hostId, $serviceId); } return $this->notifiedContacts[$serviceId]; } /** * @inheritDoc */ public function findNotifiedContactsByIdAndAccessGroups(int $hostId, int $serviceId, array $accessGroups): array { if (! isset($this->notifiedContacts[$serviceId])) { $this->fetchNotifiedContactsAndContactGroups($hostId, $serviceId, $accessGroups); } return $this->notifiedContacts[$serviceId]; } /** * @inheritDoc */ public function findNotifiedContactGroupsById(int $hostId, int $serviceId): array { if (! isset($this->notifiedContactGroups[$serviceId])) { $this->fetchNotifiedContactsAndContactGroups($hostId, $serviceId); } return $this->notifiedContactGroups[$serviceId]; } /** * @inheritDoc */ public function findNotifiedContactGroupsByIdAndAccessGroups(int $hostId, int $serviceId, array $accessGroups): array { if (! isset($this->notifiedContactGroups[$serviceId])) { $this->fetchNotifiedContactsAndContactGroups($hostId, $serviceId, $accessGroups); } return $this->notifiedContactGroups[$serviceId]; } /** * Initialize notified contacts and contactgroups for given service id. * * @param int $hostId * @param int $serviceId * @param AccessGroup[] $accessGroups */ private function fetchNotifiedContactsAndContactGroups(int $hostId, int $serviceId, array $accessGroups = []): void { /** * Call to Legacy code to get the contacts and contactgroups * that will be notified for the Service regarding global * notification inheritance parameter. */ $serviceInstance = \Service::getInstance($this->dependencyInjector); [ 'contact' => $notifiedContactIds, 'cg' => $notifiedContactGroupIds, ] = $serviceInstance->getCgAndContacts($serviceId); /** * @var array{ * service_use_only_contacts_from_host:string * }|null $service */ $service = $serviceInstance->getServiceFromCache($serviceId); if ( $service !== null && ( $service['service_use_only_contacts_from_host'] === '1' || ( empty($notifiedContactIds) && empty($notifiedContactGroupIds) ) ) ) { $hostInstance = \Host::getInstance($this->dependencyInjector); [ 'contact' => $notifiedContactIds, 'cg' => $notifiedContactGroupIds, ] = $hostInstance->getCgAndContacts($hostId); } if ($accessGroups === []) { $this->notifiedContacts[$serviceId] = $this->findContactsByIds($notifiedContactIds); $this->notifiedContactGroups[$serviceId] = $this->findContactGroupsByIds($notifiedContactGroupIds); } else { $this->notifiedContacts[$serviceId] = $this->findContactsByIdsAndAccessGroups( $notifiedContactIds, $accessGroups ); $this->notifiedContactGroups[$serviceId] = $this->findContactGroupsByIdsAndAccessGroups( $notifiedContactGroupIds, $accessGroups ); } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Infrastructure/Configuration/NotificationPolicy/Repository/DbContactHostNotificationFactory.php
centreon/src/Core/Infrastructure/Configuration/NotificationPolicy/Repository/DbContactHostNotificationFactory.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\Infrastructure\Configuration\NotificationPolicy\Repository; use Core\Domain\Configuration\Notification\Model\HostNotification; use Core\Domain\Configuration\TimePeriod\Model\TimePeriod; class DbContactHostNotificationFactory { /** * @param array<string,int|string|null> $notification * * @return HostNotification */ public static function createFromRecord(array $notification): HostNotification { $timePeriod = new TimePeriod( (int) $notification['host_timeperiod_id'], (string) $notification['host_timeperiod_name'], (string) $notification['host_timeperiod_alias'] ); $hostNotification = new HostNotification($timePeriod); /** @var string|null */ $notificationOptions = $notification['contact_host_notification_options']; $events = $notificationOptions !== null ? explode(',', $notificationOptions) : []; foreach ($events as $event) { $normalizedEvent = self::normalizeHostEvent($event); if ($normalizedEvent === null) { continue; } $hostNotification->addEvent($normalizedEvent); } return $hostNotification; } /** * Convert single char referencing Host event into a string. * * @param string $event * * @return string|null */ private static function normalizeHostEvent(string $event): ?string { return match ($event) { 'd' => HostNotification::EVENT_HOST_DOWN, 'u' => HostNotification::EVENT_HOST_UNREACHABLE, 'r' => HostNotification::EVENT_HOST_RECOVERY, 'f' => HostNotification::EVENT_HOST_FLAPPING, 's' => HostNotification::EVENT_HOST_SCHEDULED_DOWNTIME, default => 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/Infrastructure/Configuration/NotificationPolicy/Repository/DbReadMetaServiceNotificationRepository.php
centreon/src/Core/Infrastructure/Configuration/NotificationPolicy/Repository/DbReadMetaServiceNotificationRepository.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\Infrastructure\Configuration\NotificationPolicy\Repository; use Centreon\Domain\Log\LoggerTrait; use Centreon\Infrastructure\DatabaseConnection; use Centreon\Infrastructure\Repository\AbstractRepositoryDRB; use Core\Application\Configuration\Notification\Repository\ReadMetaServiceNotificationRepositoryInterface; use Core\Common\Infrastructure\Repository\SqlMultipleBindTrait; use Core\Security\AccessGroup\Domain\Model\AccessGroup; class DbReadMetaServiceNotificationRepository extends AbstractRepositoryDRB implements ReadMetaServiceNotificationRepositoryInterface { use LoggerTrait; use SqlMultipleBindTrait; /** * @param DatabaseConnection $db */ public function __construct(DatabaseConnection $db) { $this->db = $db; } /** * @inheritDoc */ public function findNotifiedContactsById(int $metaServiceId): array { $this->info('Fetching contacts from database'); $contacts = []; $request = $this->translateDbName( "SELECT c.contact_id, c.contact_alias, c.contact_name, c.contact_email, c.contact_admin, c.contact_host_notification_options, c.contact_service_notification_options, t1.tp_id as host_timeperiod_id, t1.tp_name as host_timeperiod_name, t1.tp_alias as host_timeperiod_alias, t2.tp_id as service_timeperiod_id, t2.tp_name as service_timeperiod_name, t2.tp_alias as service_timeperiod_alias FROM `:db`.contact c INNER JOIN `:db`.meta_contact cm ON cm.contact_id = c.contact_id AND cm.meta_id = :meta_id INNER JOIN `:db`.timeperiod t1 ON t1.tp_id = c.timeperiod_tp_id INNER JOIN `:db`.timeperiod t2 ON t2.tp_id = c.timeperiod_tp_id2 WHERE c.contact_activate = '1'" ); $statement = $this->db->prepare($request); $statement->bindValue(':meta_id', $metaServiceId, \PDO::PARAM_INT); $statement->execute(); while ($row = $statement->fetch(\PDO::FETCH_ASSOC)) { /** @var array<string,int|string|null> $row */ $contacts[] = DbNotifiedContactFactory::createFromRecord($row); } return $contacts; } /** * @inheritDoc */ public function findNotifiedContactsByIdAndAccessGroups(int $metaServiceId, array $accessGroups): array { $contacts = []; if ($accessGroups === []) { return $contacts; } $accessGroupIds = array_map( static fn (AccessGroup $accessGroup): int => $accessGroup->getId(), $accessGroups ); [$aclBindValues, $aclBindQuery] = $this->createMultipleBindQuery($accessGroupIds, ':access_group_id_'); $request = $this->translateDbName( <<<SQL SELECT c.contact_id, c.contact_alias, c.contact_name, c.contact_email, c.contact_admin, c.contact_host_notification_options, c.contact_service_notification_options, t1.tp_id as host_timeperiod_id, t1.tp_name as host_timeperiod_name, t1.tp_alias as host_timeperiod_alias, t2.tp_id as service_timeperiod_id, t2.tp_name as service_timeperiod_name, t2.tp_alias as service_timeperiod_alias FROM `:db`.contact c INNER JOIN `:db`.meta_contact cm ON cm.contact_id = c.contact_id AND cm.meta_id = :meta_id INNER JOIN `:db`.timeperiod t1 ON t1.tp_id = c.timeperiod_tp_id INNER JOIN `:db`.timeperiod t2 ON t2.tp_id = c.timeperiod_tp_id2 INNER JOIN `:db`.acl_group_contacts_relations agcr ON agcr.contact_contact_id = c.contact_id WHERE c.contact_activate = '1' AND agcr.acl_group_id IN ({$aclBindQuery}) SQL ); $statement = $this->db->prepare($request); foreach ($aclBindValues as $bindParam => $bindValue) { $statement->bindValue($bindParam, $bindValue, \PDO::PARAM_INT); } $statement->bindValue(':meta_id', $metaServiceId, \PDO::PARAM_INT); $statement->execute(); while ($row = $statement->fetch(\PDO::FETCH_ASSOC)) { /** @var array<string,int|string|null> $row */ $contacts[] = DbNotifiedContactFactory::createFromRecord($row); } return $contacts; } /** * @inheritDoc */ public function findNotifiedContactGroupsById(int $metaServiceId): array { $this->info('Fetching contact groups from database'); $contactGroups = []; $request = $this->translateDbName( "SELECT cg.cg_id AS `id`, cg.cg_name AS `name`, cg.cg_alias AS `alias`, cg.cg_activate AS `activated` FROM `:db`.contactgroup cg INNER JOIN `:db`.meta_contactgroup_relation cgm ON cgm.cg_cg_id = cg.cg_id AND cgm.meta_id = :meta_id WHERE cg.cg_activate = '1'" ); $statement = $this->db->prepare($request); $statement->bindValue(':meta_id', $metaServiceId, \PDO::PARAM_INT); $statement->execute(); while ($row = $statement->fetch(\PDO::FETCH_ASSOC)) { /** @var array<string,int|string|null> $row */ $contactGroups[] = DbNotifiedContactGroupFactory::createFromRecord($row); } return $contactGroups; } /** * @inheritDoc */ public function findNotifiedContactGroupsByIdAndAccessGroups(int $metaServiceId, array $accessGroups): array { $contactGroups = []; if ($accessGroups === []) { return $contactGroups; } $accessGroupIds = array_map( static fn (AccessGroup $accessGroup): int => $accessGroup->getId(), $accessGroups ); [$aclBindValues, $aclBindQuery] = $this->createMultipleBindQuery($accessGroupIds, ':access_group_id_'); $request = $this->translateDbName( <<<SQL SELECT cg.cg_id AS `id`, cg.cg_name AS `name`, cg.cg_alias AS `alias`, cg.cg_activate AS `activated` FROM `:db`.contactgroup cg INNER JOIN `:db`.meta_contactgroup_relation cgm ON cgm.cg_cg_id = cg.cg_id AND cgm.meta_id = :meta_id INNER JOIN `:db`.acl_group_contactgroups_relations agcgr ON agcgr.cg_cg_id = cg.cg_id WHERE cg.cg_activate = '1' AND agcgr.acl_group_id IN ({$aclBindQuery}) SQL ); $statement = $this->db->prepare($request); foreach ($aclBindValues as $bindParam => $bindValue) { $statement->bindValue($bindParam, $bindValue, \PDO::PARAM_INT); } $statement->bindValue(':meta_id', $metaServiceId, \PDO::PARAM_INT); $statement->execute(); while ($row = $statement->fetch(\PDO::FETCH_ASSOC)) { /** @var array<string,int|string|null> $row */ $contactGroups[] = DbNotifiedContactGroupFactory::createFromRecord($row); } return $contactGroups; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Infrastructure/Configuration/NotificationPolicy/Repository/DbContactServiceNotificationFactory.php
centreon/src/Core/Infrastructure/Configuration/NotificationPolicy/Repository/DbContactServiceNotificationFactory.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\Infrastructure\Configuration\NotificationPolicy\Repository; use Core\Domain\Configuration\Notification\Model\ServiceNotification; use Core\Domain\Configuration\TimePeriod\Model\TimePeriod; class DbContactServiceNotificationFactory { /** * @param array<string,int|string|null> $notification * * @return ServiceNotification */ public static function createFromRecord(array $notification): ServiceNotification { $timePeriod = new TimePeriod( (int) $notification['service_timeperiod_id'], (string) $notification['service_timeperiod_name'], (string) $notification['service_timeperiod_alias'] ); $serviceNotification = new ServiceNotification($timePeriod); /** @var string|null */ $notificationOptions = $notification['contact_service_notification_options']; $events = $notificationOptions !== null ? explode(',', $notificationOptions) : []; foreach ($events as $event) { $normalizedEvent = self::normalizeServiceEvent($event); if ($normalizedEvent === null) { continue; } $serviceNotification->addEvent($normalizedEvent); } return $serviceNotification; } /** * Convert single char referencing Host event into a string. * * @param string $event * * @return string|null */ private static function normalizeServiceEvent(string $event): ?string { return match ($event) { 'o' => ServiceNotification::EVENT_SERVICE_RECOVERY, 's' => ServiceNotification::EVENT_SERVICE_SCHEDULED_DOWNTIME, 'f' => ServiceNotification::EVENT_SERVICE_FLAPPING, 'w' => ServiceNotification::EVENT_SERVICE_WARNING, 'u' => ServiceNotification::EVENT_SERVICE_UNKNOWN, 'c' => ServiceNotification::EVENT_SERVICE_CRITICAL, default => 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/Infrastructure/Configuration/NotificationPolicy/Repository/DbNotifiedContactGroupFactory.php
centreon/src/Core/Infrastructure/Configuration/NotificationPolicy/Repository/DbNotifiedContactGroupFactory.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\Infrastructure\Configuration\NotificationPolicy\Repository; use Core\Domain\Configuration\Notification\Model\NotifiedContactGroup; class DbNotifiedContactGroupFactory { /** * @param array<string,int|string|null> $contactGroup * * @return NotifiedContactGroup */ public static function createFromRecord(array $contactGroup): NotifiedContactGroup { return new NotifiedContactGroup( (int) $contactGroup['id'], (string) $contactGroup['name'], (string) $contactGroup['alias'], ); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Infrastructure/Configuration/NotificationPolicy/Repository/DbNotifiedContactFactory.php
centreon/src/Core/Infrastructure/Configuration/NotificationPolicy/Repository/DbNotifiedContactFactory.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\Infrastructure\Configuration\NotificationPolicy\Repository; use Core\Domain\Configuration\Notification\Model\NotifiedContact; class DbNotifiedContactFactory { /** * @param array<string,int|string|null> $contact * * @return NotifiedContact */ public static function createFromRecord(array $contact): NotifiedContact { $hostNotification = $contact['host_timeperiod_id'] !== null ? DbContactHostNotificationFactory::createFromRecord($contact) : null; $serviceNotification = $contact['service_timeperiod_id'] !== null ? DbContactServiceNotificationFactory::createFromRecord($contact) : null; return new NotifiedContact( (int) $contact['contact_id'], (string) $contact['contact_name'], (string) $contact['contact_alias'], (string) $contact['contact_email'], $hostNotification, $serviceNotification, ); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Infrastructure/Configuration/NotificationPolicy/Repository/AbstractDbReadNotificationRepository.php
centreon/src/Core/Infrastructure/Configuration/NotificationPolicy/Repository/AbstractDbReadNotificationRepository.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\Infrastructure\Configuration\NotificationPolicy\Repository; use Centreon\Domain\Log\LoggerTrait; use Centreon\Infrastructure\CentreonLegacyDB\StatementCollector; use Centreon\Infrastructure\Repository\AbstractRepositoryDRB; use Core\Common\Infrastructure\Repository\SqlMultipleBindTrait; use Core\Domain\Configuration\Notification\Model\NotifiedContact; use Core\Domain\Configuration\Notification\Model\NotifiedContactGroup; use Core\Security\AccessGroup\Domain\Model\AccessGroup; abstract class AbstractDbReadNotificationRepository extends AbstractRepositoryDRB { use LoggerTrait; use SqlMultipleBindTrait; /** * Find contacts from ids. * * @param int[] $contactIds * * @return NotifiedContact[] */ protected function findContactsByIds(array $contactIds): array { $this->info('Fetching contacts from database'); $contacts = []; if ($contactIds === []) { return $contacts; } $request = $this->translateDbName( 'SELECT c.contact_id, c.contact_alias, c.contact_name, c.contact_email, c.contact_admin, c.contact_host_notification_options, c.contact_service_notification_options, t1.tp_id as host_timeperiod_id, t1.tp_name as host_timeperiod_name, t1.tp_alias as host_timeperiod_alias, t2.tp_id as service_timeperiod_id, t2.tp_name as service_timeperiod_name, t2.tp_alias as service_timeperiod_alias FROM `:db`.contact c LEFT JOIN `:db`.timeperiod t1 ON t1.tp_id = c.timeperiod_tp_id LEFT JOIN `:db`.timeperiod t2 ON t2.tp_id = c.timeperiod_tp_id2' ); $collector = new StatementCollector(); $bindKeys = []; foreach ($contactIds as $index => $contactId) { $key = ":contactId_{$index}"; $bindKeys[] = $key; $collector->addValue($key, $contactId, \PDO::PARAM_INT); } $request .= ' WHERE contact_id IN (' . implode(', ', $bindKeys) . ') AND contact_activate = \'1\''; $statement = $this->db->prepare($request); $collector->bind($statement); $statement->execute(); while ($row = $statement->fetch(\PDO::FETCH_ASSOC)) { /** @var array<string,int|string|null> $row */ $contacts[] = DbNotifiedContactFactory::createFromRecord($row); } return $contacts; } /** * Find contacts from ids and access groups. * * @param int[] $contactIds * @param AccessGroup[] $accessGroups * * @throws \Throwable * * @return NotifiedContact[] */ protected function findContactsByIdsAndAccessGroups(array $contactIds, array $accessGroups): array { $this->info('Fetching contacts from database'); $contacts = []; if ($contactIds === [] || $accessGroups === []) { return $contacts; } $accessGroupIds = array_map( fn ($accessGroup) => $accessGroup->getId(), $accessGroups ); [$contactsBindValues, $contactsBindQuery] = $this->createMultipleBindQuery($contactIds, ':contact_id_'); [$aclBindValues, $aclBindQuery] = $this->createMultipleBindQuery($accessGroupIds, ':access_group_id_'); $request = $this->translateDbName( <<<SQL SELECT DISTINCT c.contact_id, c.contact_alias, c.contact_name, c.contact_email, c.contact_admin, c.contact_host_notification_options, c.contact_service_notification_options, t1.tp_id as host_timeperiod_id, t1.tp_name as host_timeperiod_name, t1.tp_alias as host_timeperiod_alias, t2.tp_id as service_timeperiod_id, t2.tp_name as service_timeperiod_name, t2.tp_alias as service_timeperiod_alias FROM `:db`.contact c LEFT JOIN `:db`.timeperiod t1 ON t1.tp_id = c.timeperiod_tp_id LEFT JOIN `:db`.timeperiod t2 ON t2.tp_id = c.timeperiod_tp_id2 INNER JOIN `:db`.acl_group_contacts_relations agcr ON agcr.contact_contact_id = c.contact_id WHERE contact_id IN ({$contactsBindQuery}) AND agcr.acl_group_id IN ({$aclBindQuery}) AND contact_activate = '1' SQL ); $statement = $this->db->prepare($request); foreach ($contactsBindValues as $bindParam => $bindValue) { $statement->bindValue($bindParam, $bindValue, \PDO::PARAM_INT); } foreach ($aclBindValues as $bindParam => $bindValue) { $statement->bindValue($bindParam, $bindValue, \PDO::PARAM_INT); } $statement->execute(); while ($row = $statement->fetch(\PDO::FETCH_ASSOC)) { /** @var array<string,int|string|null> $row */ $contacts[] = DbNotifiedContactFactory::createFromRecord($row); } return $contacts; } /** * Find contact groups from ids. * * @param int[] $contactGroupIds * * @return NotifiedContactGroup[] */ protected function findContactGroupsByIds(array $contactGroupIds): array { $this->info('Fetching contact groups from database'); $contactGroups = []; if ($contactGroupIds === []) { return $contactGroups; } $collector = new StatementCollector(); $request = $this->translateDbName( 'SELECT cg_id AS `id`, cg_name AS `name`, cg_alias AS `alias`, cg_activate AS `activated` FROM `:db`.contactgroup' ); $bindKeys = []; foreach ($contactGroupIds as $index => $contactGroupId) { $key = ":contactGroupId_{$index}"; $bindKeys[] = $key; $collector->addValue($key, $contactGroupId, \PDO::PARAM_INT); } $request .= ' WHERE cg_id IN (' . implode(', ', $bindKeys) . ')'; $statement = $this->db->prepare($request); $collector->bind($statement); $statement->execute(); while ($row = $statement->fetch(\PDO::FETCH_ASSOC)) { /** @var array<string,int|string|null> $row */ $contactGroups[] = DbNotifiedContactGroupFactory::createFromRecord($row); } return $contactGroups; } /** * Find contact groups from and access groups. * * @param int[] $contactGroupIds * @param AccessGroup[] $accessGroups * * @throws \Throwable * * @return NotifiedContactGroup[] */ protected function findContactGroupsByIdsAndAccessGroups(array $contactGroupIds, array $accessGroups): array { $this->info('Fetching contact groups from database'); $contactGroups = []; if ($contactGroupIds === [] || $accessGroups === []) { return $contactGroups; } $accessGroupIds = array_map( fn ($accessGroup) => $accessGroup->getId(), $accessGroups ); [$cgBindValues, $cgBindQuery] = $this->createMultipleBindQuery($contactGroupIds, ':cg_id_'); [$aclBindValues, $aclBindQuery] = $this->createMultipleBindQuery($accessGroupIds, ':acl_group_id_'); $request = $this->translateDbName( <<<SQL SELECT DISTINCT cg_id AS `id`, cg_name AS `name`, cg_alias AS `alias`, cg_activate AS `activated` FROM `:db`.contactgroup INNER JOIN `:db`.acl_group_contactgroups_relations agcgr ON agcgr.cg_cg_id = contactgroup.cg_id WHERE cg_id IN ({$cgBindQuery}) AND agcgr.acl_group_id IN ({$aclBindQuery}) SQL ); $statement = $this->db->prepare($request); foreach ($cgBindValues as $bindParam => $bindValue) { $statement->bindValue($bindParam, $bindValue, \PDO::PARAM_INT); } foreach ($aclBindValues as $bindParam => $bindValue) { $statement->bindValue($bindParam, $bindValue, \PDO::PARAM_INT); } $statement->execute(); while ($row = $statement->fetch(\PDO::FETCH_ASSOC)) { /** @var array<string,int|string|null> $row */ $contactGroups[] = DbNotifiedContactGroupFactory::createFromRecord($row); } return $contactGroups; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Infrastructure/Configuration/MetaService/Repository/DbMetaServiceFactory.php
centreon/src/Core/Infrastructure/Configuration/MetaService/Repository/DbMetaServiceFactory.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\Infrastructure\Configuration\MetaService\Repository; use Core\Domain\Configuration\Model\MetaService; use Core\Infrastructure\Common\Repository\DbFactoryUtilitiesTrait; class DbMetaServiceFactory { use DbFactoryUtilitiesTrait; /** * @param array<string,int|string|null> $data * * @return MetaService */ public static function createFromRecord(array $data): MetaService { /** @var string|null */ $calculationType = $data['calculation_type']; $calculationType = self::normalizeCalculationType($calculationType); /** @var string|null */ $output = $data['output']; /** @var string|null */ $metric = $data['metric']; /** @var string|null */ $regexSearchServices = $data['regexp_str']; return (new MetaService( (int) $data['id'], (string) $data['name'], $calculationType, (int) $data['meta_selection_mode'], self::normalizeDataSourceType((int) $data['data_source_type']) )) ->setWarningThreshold(self::getIntOrNull($data['warning'])) ->setCriticalThreshold(self::getIntOrNull($data['critical'])) ->setOutput($output) ->setMetric($metric) ->setActivated((int) $data['is_activated'] === 1) ->setRegexpSearchServices($regexSearchServices); } /** * This function will normalize the calculation type coming from the database. * * @param string|null $calculationType * * @return string */ private static function normalizeCalculationType(?string $calculationType): string { return match ($calculationType) { 'AVE' => MetaService::CALCULTATION_TYPE_AVERAGE, 'MIN' => MetaService::CALCULTATION_TYPE_MINIMUM, 'MAX' => MetaService::CALCULTATION_TYPE_MAXIMUM, 'SOM' => MetaService::CALCULTATION_TYPE_SUM, default => MetaService::CALCULTATION_TYPE_AVERAGE, }; } /** * This function will normalize the data source type coming from the database. * * @param int|null $dataSourceType * * @return string */ private static function normalizeDataSourceType(?int $dataSourceType): string { return match ($dataSourceType) { 0 => MetaService::DATA_SOURCE_GAUGE, 1 => MetaService::DATA_SOURCE_COUNTER, 2 => MetaService::DATA_SOURCE_DERIVE, 3 => MetaService::DATA_SOURCE_ABSOLUTE, default => MetaService::DATA_SOURCE_GAUGE, }; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Infrastructure/Configuration/MetaService/Repository/DbReadMetaServiceRepository.php
centreon/src/Core/Infrastructure/Configuration/MetaService/Repository/DbReadMetaServiceRepository.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\Infrastructure\Configuration\MetaService\Repository; use Centreon\Infrastructure\DatabaseConnection; use Centreon\Infrastructure\Repository\AbstractRepositoryDRB; use Core\Application\Configuration\MetaService\Repository\ReadMetaServiceRepositoryInterface; use Core\Common\Domain\TrimmedString; use Core\Domain\Configuration\Model\MetaService; use Core\Domain\Configuration\Model\MetaServiceNamesById; class DbReadMetaServiceRepository extends AbstractRepositoryDRB implements ReadMetaServiceRepositoryInterface { /** * @param DatabaseConnection $db */ public function __construct(DatabaseConnection $db) { $this->db = $db; } /** * @inheritDoc */ public function findNames(int ...$ids): MetaServiceNamesById { $ids = array_unique($ids); $fields = ''; foreach ($ids as $index => $id) { $fields .= ($fields === '' ? '' : ', ') . ':id_' . $index; } $request = <<<SQL SELECT m.meta_id, m.meta_name FROM `:db`.meta_service m WHERE m.meta_id IN ({$fields}) SQL; $statement = $this->db->prepare( $this->translateDbName($request) ); foreach ($ids as $index => $id) { $statement->bindValue(':id_' . $index, $id, \PDO::PARAM_INT); } $statement->setFetchMode(\PDO::FETCH_ASSOC); $statement->execute(); $names = new MetaServiceNamesById(); foreach ($statement as $record) { /** @var array{meta_id:int,meta_name:string} $record */ $names->addName( $record['meta_id'], new TrimmedString($record['meta_name']) ); } return $names; } /** * @inheritDoc */ public function exist(array $metaIds): array { if ($metaIds === []) { return []; } $bindValues = []; foreach ($metaIds as $index => $metaId) { $bindValues[":meta_{$index}"] = $metaId; } $metaIdsList = implode(', ', array_keys($bindValues)); $request = $this->translateDbName( <<<SQL SELECT meta_id FROM `:db`.meta_service WHERE meta_id IN ({$metaIdsList}) SQL ); $statement = $this->db->prepare($request); foreach ($bindValues as $bindKey => $bindValue) { $statement->bindValue($bindKey, $bindValue, \PDO::PARAM_INT); } $statement->setFetchMode(\PDO::FETCH_ASSOC); $statement->execute(); return $statement->fetchAll(\PDO::FETCH_COLUMN); } /** * @inheritDoc */ public function findMetaServiceByIdAndAccessGroupIds(int $metaId, array $accessGroupIds): ?MetaService { if ($accessGroupIds === []) { return null; } $accessGroupRequest = ' INNER JOIN `:db`.`acl_resources_meta_relations` AS armr ON armr.meta_id = ms.meta_id INNER JOIN `:db`.acl_resources res ON armr.acl_res_id = res.acl_res_id INNER JOIN `:db`.acl_res_group_relations argr ON res.acl_res_id = argr.acl_res_id AND argr.acl_group_id IN (' . implode(',', $accessGroupIds) . ') '; return $this->findMetaService($metaId, $accessGroupRequest); } /** * @inheritDoc */ public function findMetaServiceById(int $metaId): ?MetaService { return $this->findMetaService($metaId); } /** * @param int $metaId * @param string|null $accessGroupRequest * * @return MetaService|null */ private function findMetaService(int $metaId, ?string $accessGroupRequest = null): ?MetaService { $request = 'SELECT ms.meta_id AS `id`, ms.meta_name AS `name`, ms.meta_display AS `output`, ms.data_source_type AS `data_source_type`, ms.meta_select_mode AS `meta_selection_mode`, ms.regexp_str, ms.metric, ms.warning, ms.critical, ms.meta_activate AS `is_activated`, ms.calcul_type AS `calculation_type` FROM `:db`.meta_service ms'; $request .= ' WHERE ms.meta_id = :meta_id'; $statement = $this->db->prepare($this->translateDbName($request)); $statement->bindValue(':meta_id', $metaId, \PDO::PARAM_INT); $statement->execute(); if ($row = $statement->fetch(\PDO::FETCH_ASSOC)) { /** @var array<string,int|string|null> $row */ return DbMetaServiceFactory::createFromRecord($row); } return null; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Infrastructure/Configuration/User/Api/FindUsers/FindUsersPresenter.php
centreon/src/Core/Infrastructure/Configuration/User/Api/FindUsers/FindUsersPresenter.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\Infrastructure\Configuration\User\Api\FindUsers; use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface; use Core\Application\Common\UseCase\AbstractPresenter; use Core\Application\Configuration\User\UseCase\FindUsers\FindUsersPresenterInterface; use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface; class FindUsersPresenter extends AbstractPresenter implements FindUsersPresenterInterface { /** * @param RequestParametersInterface $requestParameters * @param PresenterFormatterInterface $presenterFormatter */ public function __construct( private RequestParametersInterface $requestParameters, protected PresenterFormatterInterface $presenterFormatter, ) { parent::__construct($presenterFormatter); } /** * @inheritDoc */ public function present(mixed $data): void { parent::present([ 'result' => $data->users, '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/Infrastructure/Configuration/User/Api/FindUsers/FindUsersController.php
centreon/src/Core/Infrastructure/Configuration/User/Api/FindUsers/FindUsersController.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\Infrastructure\Configuration\User\Api\FindUsers; use Centreon\Application\Controller\AbstractController; use Core\Application\Configuration\User\UseCase\FindUsers\FindUsers; use Core\Application\Configuration\User\UseCase\FindUsers\FindUsersPresenterInterface; final class FindUsersController extends AbstractController { /** * @param FindUsers $findUsers * @param FindUsersPresenterInterface $presenter * * @return object */ public function __invoke( FindUsers $findUsers, FindUsersPresenterInterface $presenter, ): object { $this->denyAccessUnlessGrantedForApiConfiguration(); $findUsers($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/Infrastructure/Configuration/User/Api/PatchUser/PatchUserPresenter.php
centreon/src/Core/Infrastructure/Configuration/User/Api/PatchUser/PatchUserPresenter.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\Infrastructure\Configuration\User\Api\PatchUser; use Core\Application\Common\UseCase\AbstractPresenter; use Core\Application\Configuration\User\UseCase\PatchUser\PatchUserPresenterInterface; class PatchUserPresenter extends AbstractPresenter implements PatchUserPresenterInterface { /** * @param mixed $data */ public function present(mixed $data): void { parent::present($data); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Infrastructure/Configuration/User/Api/PatchUser/PatchUserController.php
centreon/src/Core/Infrastructure/Configuration/User/Api/PatchUser/PatchUserController.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\Infrastructure\Configuration\User\Api\PatchUser; use Centreon\Application\Controller\AbstractController; use Centreon\Domain\Contact\Contact; use Centreon\Domain\Log\LoggerTrait; use Core\Application\Configuration\User\UseCase\PatchUser\PatchUser; use Core\Application\Configuration\User\UseCase\PatchUser\PatchUserPresenterInterface; use Core\Application\Configuration\User\UseCase\PatchUser\PatchUserRequest; use Symfony\Component\HttpFoundation\Request; final class PatchUserController extends AbstractController { use LoggerTrait; /** * @param Request $request * @param PatchUser $useCase * @param PatchUserPresenterInterface $presenter * * @return object */ public function __invoke( Request $request, PatchUser $useCase, PatchUserPresenterInterface $presenter, ): object { $this->denyAccessUnlessGrantedForApiConfiguration(); $this->debug('Validating request body'); $this->validateDataSent($request, __DIR__ . '/PatchUserSchema.json'); /** * @var Contact $currentUser */ $currentUser = $this->getUser(); $useCase($this->createRequest($request, $currentUser->getId()), $presenter); return $presenter->show(); } /** * @param Request $request * @param int $userId * * @return PatchUserRequest */ private function createRequest(Request $request, int $userId): PatchUserRequest { /** @var array{theme?: string, user_interface_density?: string} $requestData */ $requestData = json_decode((string) $request->getContent(), true); $updateUserRequest = new PatchUserRequest(); if ($requestData['theme'] ?? false) { $updateUserRequest->theme = $requestData['theme']; } if ($requestData['user_interface_density'] ?? false) { $updateUserRequest->userInterfaceDensity = $requestData['user_interface_density']; } $updateUserRequest->userId = $userId; return $updateUserRequest; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false