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/Adaptation/Database/Connection/Enum/QueryParameterTypeEnum.php | centreon/src/Adaptation/Database/Connection/Enum/QueryParameterTypeEnum.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Adaptation\Database\Connection\Enum;
/**
* Enum.
*
* @class QueryParameterTypeEnum
*/
enum QueryParameterTypeEnum
{
/**
* Represents the SQL NULL data type.
*/
case NULL;
/**
* Represents the SQL INTEGER data type.
*/
case INTEGER;
/**
* Represents the SQL CHAR, VARCHAR, or other string data type.
*/
case STRING;
/**
* Represents the SQL large object data type.
*/
case LARGE_OBJECT;
/**
* Represents a boolean data type.
*/
case BOOLEAN;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Adaptation/Database/Connection/Enum/ConnectionDriverEnum.php | centreon/src/Adaptation/Database/Connection/Enum/ConnectionDriverEnum.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Adaptation\Database\Connection\Enum;
/**
* Enum.
*
* @class ConnectionDriverEnum
*/
enum ConnectionDriverEnum: string
{
case DRIVER_PDO_MYSQL = 'pdo_mysql';
case DRIVER_PDO_POSTGRESQL = 'pdo_pgsql';
case DRIVER_PDO_SQLITE = 'pdo_sqlite';
case DRIVER_PDO_ORACLE = 'pdo_oci';
case DRIVER_PDO_MICROSOFT_SQL_SERVER = 'pdo_sqlsrv';
case DRIVER_MYSQLI = 'mysqli';
case DRIVER_POSTGRESQL = 'pgsql';
case DRIVER_MICROSOFT_SQL_SERVER = 'sqlsrv';
case DRIVER_SQLITE3 = 'sqlite3';
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Adaptation/Database/Connection/Collection/BatchInsertParameters.php | centreon/src/Adaptation/Database/Connection/Collection/BatchInsertParameters.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Adaptation\Database\Connection\Collection;
use Core\Common\Domain\Collection\ObjectCollection;
/**
* Class.
*
* @class BatchInsertParameters
*
* @extends ObjectCollection<QueryParameters>
*/
class BatchInsertParameters extends ObjectCollection
{
/**
* @return class-string<QueryParameters>
*/
protected function itemClass(): string
{
return QueryParameters::class;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Adaptation/Database/Connection/Collection/QueryParameters.php | centreon/src/Adaptation/Database/Connection/Collection/QueryParameters.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Adaptation\Database\Connection\Collection;
use Adaptation\Database\Connection\Enum\QueryParameterTypeEnum;
use Adaptation\Database\Connection\ValueObject\QueryParameter;
use Core\Common\Domain\Collection\ObjectCollection;
use Core\Common\Domain\Exception\CollectionException;
/**
* Class.
*
* @class QueryParameters
*
* @extends ObjectCollection<QueryParameter>
*/
class QueryParameters extends ObjectCollection
{
/**
* @throws CollectionException
*/
public function getIntQueryParameters(): static
{
return $this->filterOnValue(
fn (QueryParameter $queryParameter): bool => $queryParameter->type === QueryParameterTypeEnum::INTEGER
);
}
/**
* @throws CollectionException
*/
public function getStringQueryParameters(): static
{
return $this->filterOnValue(
fn (QueryParameter $queryParameter): bool => $queryParameter->type === QueryParameterTypeEnum::STRING
);
}
/**
* @throws CollectionException
*/
public function getBoolQueryParameters(): static
{
return $this->filterOnValue(
fn (QueryParameter $queryParameter): bool => $queryParameter->type === QueryParameterTypeEnum::BOOLEAN
);
}
/**
* @throws CollectionException
*/
public function getNullQueryParameters(): static
{
return $this->filterOnValue(
fn (QueryParameter $queryParameter): bool => $queryParameter->type === QueryParameterTypeEnum::NULL
);
}
/**
* @throws CollectionException
*/
public function getLargeObjectQueryParameters(): static
{
return $this->filterOnValue(
fn (QueryParameter $queryParameter): bool => $queryParameter->type === QueryParameterTypeEnum::LARGE_OBJECT
);
}
/**
* @return class-string<QueryParameter>
*/
protected function itemClass(): string
{
return QueryParameter::class;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Adaptation/Database/Connection/ValueObject/QueryParameter.php | centreon/src/Adaptation/Database/Connection/ValueObject/QueryParameter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Adaptation\Database\Connection\ValueObject;
use Adaptation\Database\Connection\Enum\QueryParameterTypeEnum;
use Core\Common\Domain\Exception\ValueObjectException;
use Core\Common\Domain\ValueObject\ValueObjectInterface;
/**
* Class.
*
* @class QueryParameter
*/
final readonly class QueryParameter implements ValueObjectInterface, \Stringable
{
/**
* QueryParameter constructor.
*
* Example: new QueryParameter('name', 'value', QueryParameterTypeEnum::STRING);
*
* @throws ValueObjectException
*/
private function __construct(
public string $name,
public mixed $value,
public ?QueryParameterTypeEnum $type = null,
) {
if (empty($name)) {
throw new ValueObjectException('Name of QueryParameter cannot be empty');
}
if (is_object($value)) {
throw new ValueObjectException('Value of QueryParameter cannot be an object');
}
if ($type === QueryParameterTypeEnum::LARGE_OBJECT && ! is_string($value) && ! is_resource($value)) {
throw new ValueObjectException(sprintf('Value of QueryParameter with type LARGE_OBJECT must be a string or a resource, %s given', gettype($value)));
}
}
public function __toString(): string
{
$type = match ($this->type) {
QueryParameterTypeEnum::STRING => 'string',
QueryParameterTypeEnum::INTEGER => 'int',
QueryParameterTypeEnum::BOOLEAN => 'bool',
QueryParameterTypeEnum::NULL => 'null',
QueryParameterTypeEnum::LARGE_OBJECT => 'largeObject',
default => 'unknown',
};
if (is_object($this->value) && method_exists($this->value, '__toString')) {
$value = (string) $this->value;
} elseif (is_scalar($this->value) || $this->value === null) {
$value = (string) $this->value;
} else {
$value = 'unsupported type';
}
return \sprintf(
'{name:"%s",value:"%s",type:"%s"}',
$this->name,
$value,
$type
);
}
/**
* @throws ValueObjectException
*/
public static function create(string $name, mixed $value, ?QueryParameterTypeEnum $type = null): self
{
return new self($name, $value, $type);
}
/**
* Example : QueryParameter::int('name', 1);
* Null value is not allowed for this type.
*
* @throws ValueObjectException
*/
public static function int(string $name, ?int $value): self
{
if ($value === null) {
return self::null($name);
}
return self::create($name, $value, QueryParameterTypeEnum::INTEGER);
}
/**
* Example : QueryParameter::string('name', 'value');
* Null value is not allowed for this type.
*
* @throws ValueObjectException
*/
public static function string(string $name, ?string $value): self
{
if ($value === null) {
return self::null($name);
}
return self::create($name, $value, QueryParameterTypeEnum::STRING);
}
/**
* Example : QueryParameter::bool('name', true);.
*
* @throws ValueObjectException
*/
public static function bool(string $name, bool $value): self
{
return self::create($name, $value, QueryParameterTypeEnum::BOOLEAN);
}
/**
* Example : QueryParameter::null('name');.
*
* @throws ValueObjectException
*/
public static function null(string $name): self
{
return self::create($name, null, QueryParameterTypeEnum::NULL);
}
/**
* Example : QueryParameter::largeObject('name', 'blob');.
*
* @param string|resource $value
*
* @throws ValueObjectException
*/
public static function largeObject(string $name, mixed $value): self
{
return self::create($name, $value, QueryParameterTypeEnum::LARGE_OBJECT);
}
/**
* @throws ValueObjectException
*/
public function equals(ValueObjectInterface $object): bool
{
if (! $object instanceof self) {
throw new ValueObjectException(sprintf('Expected object of type %s, %s given', self::class, $object::class));
}
return "{$this}" === "{$object}";
}
/**
* @return array<string,mixed>
*/
public function jsonSerialize(): array
{
return [
'name' => $this->name,
'value' => $this->value,
'type' => $this->type,
];
}
public function getName(): string
{
return $this->name;
}
public function getType(): ?QueryParameterTypeEnum
{
return $this->type;
}
public function getValue(): mixed
{
return $this->value;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Adaptation/Database/Connection/Exception/ConnectionException.php | centreon/src/Adaptation/Database/Connection/Exception/ConnectionException.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Adaptation\Database\Connection\Exception;
use Adaptation\Database\Connection\Collection\BatchInsertParameters;
use Adaptation\Database\Connection\Collection\QueryParameters;
use Adaptation\Database\Exception\DatabaseException;
/**
* Class.
*
* @class ConnectionException
*/
class ConnectionException extends DatabaseException
{
public static function notImplemented(string $method): self
{
return new self(
message: "{$method} method not implemented",
code: self::ERROR_CODE_BAD_USAGE
);
}
/**
* @param array<string,mixed> $context
*/
public static function connectionBadUsage(string $message, array $context = []): self
{
return new self(
message: "Bad usage of connection : {$message}",
code: self::ERROR_CODE_BAD_USAGE,
context: $context
);
}
public static function connectionFailed(?\Throwable $previous = null): self
{
$message = 'Error while connecting to the database';
if ($previous instanceof \Throwable && ! empty($previous->getMessage())) {
$message .= " : {$previous->getMessage()}";
}
return new self($message, self::ERROR_CODE_DATABASE, [], $previous);
}
public static function getNativeConnectionFailed(?\Throwable $previous = null): self
{
$message = 'Error while retrieving the native connection';
if ($previous instanceof \Throwable && ! empty($previous->getMessage())) {
$message .= " : {$previous->getMessage()}";
}
return new self(
message: $message,
code: self::ERROR_CODE_DATABASE,
previous: $previous
);
}
public static function getDatabaseNameFailed(?\Throwable $previous = null): self
{
$message = 'Error while retrieving the database name';
if ($previous instanceof \Throwable && ! empty($previous->getMessage())) {
$message .= " : {$previous->getMessage()}";
}
return new self($message, self::ERROR_CODE_DATABASE);
}
public static function getLastInsertFailed(\Throwable $previous): self
{
return new self(
'Error while retrieving the last auto-incremented id inserted.',
code: self::ERROR_CODE_DATABASE,
previous: $previous
);
}
// --------------------------------------- CRUD METHODS -----------------------------------------
public static function notEmptyQuery(): self
{
return new self(
message: 'The query is empty',
code: self::ERROR_CODE_BAD_USAGE
);
}
public static function executeStatementBadFormat(string $message, string $query): self
{
return new self(
message: "Query format is not correct to use executeStatement : {$message}",
code: self::ERROR_CODE_BAD_USAGE,
context: ['query' => $query]
);
}
public static function executeStatementFailed(
\Throwable $previous,
string $query,
?QueryParameters $queryParameters = null,
): self {
return new self(
message: "Error while executing the statement : {$previous->getMessage()}",
code: self::ERROR_CODE_DATABASE,
context: [
'query' => $query,
'query_parameters' => $queryParameters,
],
previous: $previous
);
}
public static function insertQueryBadFormat(string $query): self
{
return new self(
message: "The query need to start by 'INSERT INTO '",
code: self::ERROR_CODE_BAD_USAGE,
context: ['query' => $query]
);
}
public static function insertQueryFailed(
\Throwable $previous,
string $query,
?QueryParameters $queryParameters = null,
): self {
return new self(
message: "Error while executing the insert query : {$previous->getMessage()}",
code: self::ERROR_CODE_DATABASE,
context: [
'query' => $query,
'query_parameters' => $queryParameters,
],
previous: $previous
);
}
public static function batchInsertQueryBadUsage(string $message): self
{
return new self(
message: "Bad usage of batch insert query : {$message}",
code: self::ERROR_CODE_BAD_USAGE
);
}
/**
* @param array<string> $columns
*/
public static function batchInsertQueryFailed(
\Throwable $previous,
string $tableName,
array $columns,
BatchInsertParameters $batchInsertParameters,
string $query = '',
): self {
return new self(
message: "Error while executing the batch insert query : {$previous->getMessage()}",
code: self::ERROR_CODE_DATABASE,
context: [
'table_name' => $tableName,
'columns' => $columns,
'query' => $query,
'batch_insert_parameters' => $batchInsertParameters,
],
previous: $previous
);
}
public static function updateQueryBadFormat(string $query): self
{
return new self(
message: "The query need to start by 'UPDATE '",
code: self::ERROR_CODE_BAD_USAGE,
context: ['query' => $query]
);
}
public static function updateQueryFailed(
\Throwable $previous,
string $query,
?QueryParameters $queryParameters = null,
): self {
return new self(
message: "Error while executing the update query : {$previous->getMessage()}",
code: self::ERROR_CODE_DATABASE,
context: [
'query' => $query,
'query_parameters' => $queryParameters,
],
previous: $previous
);
}
public static function deleteQueryBadFormat(string $query): self
{
return new self(
message: "The query need to start by 'DELETE '",
code: self::ERROR_CODE_BAD_USAGE,
context: ['query' => $query]
);
}
public static function deleteQueryFailed(
\Throwable $previous,
string $query,
?QueryParameters $queryParameters = null,
): self {
return new self(
message: "Error while executing the delete query : {$previous->getMessage()}",
code: self::ERROR_CODE_DATABASE,
context: [
'query' => $query,
'query_parameters' => $queryParameters,
],
previous: $previous
);
}
public static function selectQueryBadFormat(string $query): self
{
return new self(
message: "The query need to start by 'SELECT '",
code: self::ERROR_CODE_BAD_USAGE,
context: ['query' => $query]
);
}
/**
* @param array<string,mixed> $context
*/
public static function selectQueryFailed(
\Throwable $previous,
string $query,
?QueryParameters $queryParameters = null,
array $context = [],
): self {
$context['query'] = $query;
$context['query_parameters'] = $queryParameters;
return new self(
message: "Error while executing the select query : {$previous->getMessage()}",
code: self::ERROR_CODE_DATABASE,
context: $context,
previous: $previous
);
}
public static function fetchNumericQueryFailed(
\Throwable $previous,
string $query,
?QueryParameters $queryParameters = null,
): self {
return new self(
message: "Error while executing fetch numeric query : {$previous->getMessage()}",
code: self::ERROR_CODE_DATABASE,
context: [
'query' => $query,
'query_parameters' => $queryParameters,
],
previous: $previous
);
}
public static function fetchAssociativeQueryFailed(
\Throwable $previous,
string $query,
?QueryParameters $queryParameters = null,
): self {
return new self(
message: "Error while executing fetch associative query : {$previous->getMessage()}",
code: self::ERROR_CODE_DATABASE,
context: [
'query' => $query,
'query_parameters' => $queryParameters,
],
previous: $previous
);
}
public static function fetchOneQueryFailed(
\Throwable $previous,
string $query,
?QueryParameters $queryParameters = null,
): self {
return new self(
message: "Error while executing fetch one query : {$previous->getMessage()}",
code: self::ERROR_CODE_DATABASE,
context: [
'query' => $query,
'query_parameters' => $queryParameters,
],
previous: $previous
);
}
public static function fetchFirstColumnQueryFailed(
\Throwable $previous,
string $query,
?QueryParameters $queryParameters = null,
): self {
return new self(
message: "Error while executing fetch first column query : {$previous->getMessage()}",
code: self::ERROR_CODE_DATABASE,
context: [
'query' => $query,
'query_parameters' => $queryParameters,
],
previous: $previous
);
}
public static function fetchAllNumericQueryFailed(
\Throwable $previous,
string $query,
?QueryParameters $queryParameters = null,
): self {
return new self(
message: "Error while executing fetch all numeric query : {$previous->getMessage()}",
code: self::ERROR_CODE_DATABASE,
context: [
'query' => $query,
'query_parameters' => $queryParameters,
],
previous: $previous
);
}
public static function fetchAllAssociativeQueryFailed(
\Throwable $previous,
string $query,
?QueryParameters $queryParameters = null,
): self {
return new self(
message: "Error while executing fetch all associative query : {$previous->getMessage()}",
code: self::ERROR_CODE_DATABASE,
context: [
'query' => $query,
'query_parameters' => $queryParameters,
],
previous: $previous
);
}
public static function fetchAllKeyValueQueryFailed(
\Throwable $previous,
string $query,
?QueryParameters $queryParameters = null,
): self {
return new self(
message: "Error while executing fetch all key value query : {$previous->getMessage()}",
code: self::ERROR_CODE_DATABASE,
context: [
'query' => $query,
'query_parameters' => $queryParameters,
],
previous: $previous
);
}
public static function fetchAllAssociativeIndexedQueryFailed(
\Throwable $previous,
string $query,
?QueryParameters $queryParameters = null,
): self {
return new self(
message: "Error while executing fetch all associative indexed query : {$previous->getMessage()}",
code: self::ERROR_CODE_DATABASE,
context: [
'query' => $query,
'query_parameters' => $queryParameters,
],
previous: $previous
);
}
public static function iterateNumericQueryFailed(
\Throwable $previous,
string $query,
?QueryParameters $queryParameters = null,
): self {
return new self(
message: "Error while executing iterate numeric query : {$previous->getMessage()}",
code: self::ERROR_CODE_DATABASE,
context: [
'query' => $query,
'query_parameters' => $queryParameters,
],
previous: $previous
);
}
public static function iterateAssociativeQueryFailed(
\Throwable $previous,
string $query,
?QueryParameters $queryParameters = null,
): self {
return new self(
message: "Error while executing iterate associative query : {$previous->getMessage()}",
code: self::ERROR_CODE_DATABASE,
context: [
'query' => $query,
'query_parameters' => $queryParameters,
],
previous: $previous
);
}
public static function iterateColumnQueryFailed(
\Throwable $previous,
string $query,
?QueryParameters $queryParameters = null,
): self {
return new self(
message: "Error while executing iterate first column query : {$previous->getMessage()}",
code: self::ERROR_CODE_DATABASE,
context: [
'query' => $query,
'query_parameters' => $queryParameters,
],
previous: $previous
);
}
public static function iterateKeyValueQueryBadFormat(string $message, string $query): self
{
return new self(
message: "Bad format of iterate key value query : {$message}",
code: self::ERROR_CODE_BAD_USAGE,
context: ['query' => $query]
);
}
public static function iterateKeyValueQueryFailed(
\Throwable $previous,
string $query,
?QueryParameters $queryParameters = null,
): self {
return new self(
message: "Error while executing iterate key value query : {$previous->getMessage()}",
code: self::ERROR_CODE_DATABASE,
context: [
'query' => $query,
'query_parameters' => $queryParameters,
],
previous: $previous
);
}
public static function iterateAssociativeIndexedQueryFailed(
\Throwable $previous,
string $query,
?QueryParameters $queryParameters = null,
): self {
return new self(
message: "Error while executing iterate associative indexed query : {$previous->getMessage()}",
code: self::ERROR_CODE_DATABASE,
context: [
'query' => $query,
'query_parameters' => $queryParameters,
],
previous: $previous
);
}
// ----------------------------------------- TRANSACTIONS -----------------------------------------
public static function setAutoCommitFailed(?\Throwable $exception = null): self
{
$message = 'Error while setting auto commit';
if ($exception instanceof \Throwable && ! empty($exception->getMessage())) {
$message .= " : {$exception->getMessage()}";
}
return new self(
message: $message,
code: self::ERROR_CODE_DATABASE_TRANSACTION,
previous: $exception
);
}
public static function startTransactionFailed(\Throwable $previous): self
{
return new self(
message: "Error while starting a transaction : {$previous->getMessage()}",
code: self::ERROR_CODE_DATABASE_TRANSACTION,
previous: $previous
);
}
public static function commitTransactionFailed(?\Throwable $previous = null): self
{
$message = 'Error during the transaction commit';
if ($previous instanceof \Throwable && ! empty($previous->getMessage())) {
$message .= " : {$previous->getMessage()}";
}
return new self(
message: $message,
code: self::ERROR_CODE_DATABASE_TRANSACTION,
previous: $previous
);
}
public static function rollbackTransactionFailed(?\Throwable $previous = null): self
{
$message = 'Error during the transaction rollback';
if ($previous instanceof \Throwable && ! empty($previous->getMessage())) {
$message .= " : {$previous->getMessage()}";
}
return new self(
message: $message,
code: self::ERROR_CODE_DATABASE_TRANSACTION,
previous: $previous
);
}
// ------------------------------------- UNBUFFERED QUERIES -----------------------------------------
public static function allowUnbufferedQueryFailed(
string $nativeConnectionClass,
string $currentDriverName,
): self {
return new self(
message: "Unbuffered queries not allowed for native connection class '{$nativeConnectionClass}' with this driver : {$currentDriverName}.",
code: self::ERROR_CODE_UNBUFFERED_QUERY,
context: ['native_connection_class' => $nativeConnectionClass, 'current_driver_name' => $currentDriverName]
);
}
public static function startUnbufferedQueryFailed(): self
{
return new self(
message: 'Starting unbuffered queries failed.',
code: self::ERROR_CODE_UNBUFFERED_QUERY
);
}
public static function stopUnbufferedQueryFailed(
string $message,
): self {
return new self(
message: "Stopping unbuffered queries failed : {$message}",
code: self::ERROR_CODE_UNBUFFERED_QUERY
);
}
// ------------------------------------- BASE METHODS -----------------------------------------
public static function closeQueryFailed(\Throwable $previous, string $query): self
{
return new self(
message: "Error while closing the query : {$previous->getMessage()}",
code: self::ERROR_CODE_DATABASE,
context: ['query' => $query],
previous: $previous
);
}
// --------------------------------------- DDL TOOLS -----------------------------------------------
public static function columnExistsFailed(
string $message,
string $tableName,
string $columnName,
?\Exception $previous = null,
): self {
return new self(
message: "Error while checking if column '{$columnName}' exists in table '{$tableName}' : {$message}",
code: self::ERROR_CODE_DATABASE,
context: [
'table_name' => $tableName,
'column_name' => $columnName,
],
previous: $previous
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Adaptation/Database/Connection/Trait/ConnectionTrait.php | centreon/src/Adaptation/Database/Connection/Trait/ConnectionTrait.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Adaptation\Database\Connection\Trait;
use Adaptation\Database\Connection\Collection\BatchInsertParameters;
use Adaptation\Database\Connection\Collection\QueryParameters;
use Adaptation\Database\Connection\Exception\ConnectionException;
use Adaptation\Database\Connection\Model\ConnectionConfig;
use Adaptation\Database\Connection\ValueObject\QueryParameter;
use Adaptation\Database\ExpressionBuilder\Adapter\Dbal\DbalExpressionBuilderAdapter;
use Adaptation\Database\ExpressionBuilder\Exception\ExpressionBuilderException;
use Adaptation\Database\ExpressionBuilder\ExpressionBuilderInterface;
use Adaptation\Database\QueryBuilder\Adapter\Dbal\DbalQueryBuilderAdapter;
use Adaptation\Database\QueryBuilder\Exception\QueryBuilderException;
use Adaptation\Database\QueryBuilder\QueryBuilderInterface;
use Core\Common\Domain\Exception\CollectionException;
use Core\Common\Domain\Exception\ValueObjectException;
/**
* Trait.
*
* @class ConnectionTrait
*/
trait ConnectionTrait
{
/**
* To create an instance of the query builder.
*
* @throws QueryBuilderException
*/
public function createQueryBuilder(): QueryBuilderInterface
{
return DbalQueryBuilderAdapter::createFromConnectionConfig($this->connectionConfig);
}
/**
* To create an instance of the expression builder.
*
* @throws ExpressionBuilderException
*/
public function createExpressionBuilder(): ExpressionBuilderInterface
{
return DbalExpressionBuilderAdapter::createFromConnectionConfig($this->connectionConfig);
}
abstract public function getConnectionConfig(): ConnectionConfig;
/**
* Return the database name if it exists.
*
* @throws ConnectionException
*/
public function getDatabaseName(): ?string
{
try {
$databaseName = $this->fetchFirstColumn('SELECT DATABASE()')[0];
return is_string($databaseName) ? $databaseName : null;
} catch (\Throwable $exception) {
$this->writeDbLog(
message: 'Unable to get database name',
previous: $exception,
);
throw ConnectionException::getDatabaseNameFailed();
}
}
// ----------------------------------------- CUD METHODS -----------------------------------------
/**
* To execute all queries except the queries getting results (SELECT).
*
* Executes an SQL statement with the given parameters and returns the number of affected rows.
*
* Could be used for:
* - DML statements: INSERT, UPDATE, DELETE, etc.
* - DDL statements: CREATE, DROP, ALTER, etc.
* - DCL statements: GRANT, REVOKE, etc.
* - Session control statements: ALTER SESSION, SET, DECLARE, etc.
* - Other statements that don't yield a row set.
*
* @throws ConnectionException
*
* @example $queryParameters = QueryParameters::create([QueryParameter::int('id', 1), QueryParameter::string('name', 'John')]);
* $nbAffectedRows = $db->executeStatement('UPDATE table SET name = :name WHERE id = :id', $queryParameters);
* // $nbAffectedRows = 1
*/
abstract public function executeStatement(string $query, ?QueryParameters $queryParameters = null): int;
/**
* Executes an SQL statement with the given parameters and returns the number of affected rows.
*
* Could be only used for INSERT.
*
* @throws ConnectionException
*
* @example $queryParameters = QueryParameters::create([QueryParameter::int('id', 1), QueryParameter::string('name', 'John')]);
* $nbAffectedRows = $db->insert('INSERT INTO table (id, name) VALUES (:id, :name)', $queryParameters);
* // $nbAffectedRows = 1
*/
public function insert(string $query, ?QueryParameters $queryParameters = null): int
{
try {
// Clean up the query string
$query = mb_ltrim($query);
// Check if the query starts with a valid SQL command
if (preg_match('/^(INSERT INTO|WITH)\b/i', $query) !== 1) {
throw ConnectionException::insertQueryBadFormat($query);
}
return $this->executeStatement($query, $queryParameters);
} catch (\Throwable $exception) {
throw ConnectionException::insertQueryFailed($exception, $query, $queryParameters);
}
}
/**
* Executes an SQL statement with the given parameters and returns the number of affected rows for multiple inserts.
*
* Could be only used for several INSERT.
*
* @param array<string> $columns
*
* @throws ConnectionException
*
* @example $batchInsertParameters = BatchInsertParameters::create([
* QueryParameters::create([QueryParameter::int('id', 1), QueryParameter::string('name', 'John')]),
* QueryParameters::create([QueryParameter::int('id', 2), QueryParameter::string('name', 'Jean')]),
* ]);
* $nbAffectedRows = $db->batchInsert('table', ['id', 'name'], $batchInsertParameters);
* // $nbAffectedRows = 2
*/
public function batchInsert(string $tableName, array $columns, BatchInsertParameters $batchInsertParameters): int
{
try {
if (empty($tableName)) {
throw ConnectionException::batchInsertQueryBadUsage('Table name must not be empty');
}
if ($columns === []) {
throw ConnectionException::batchInsertQueryBadUsage('Columns must not be empty');
}
if ($batchInsertParameters->isEmpty()) {
throw ConnectionException::batchInsertQueryBadUsage('Batch insert parameters must not be empty');
}
$query = "INSERT INTO {$tableName} (" . implode(', ', $columns) . ') VALUES';
$valuesInsert = [];
$queryParametersToInsert = new QueryParameters([]);
$indexQueryParameterToInsert = 1;
/*
* $batchInsertParameters is a collection of QueryParameters, each QueryParameters is a collection of QueryParameter
* We need to iterate over the QueryParameters to build the final query.
* Then, for each QueryParameters, we need to iterate over the QueryParameter to build :
* - to check if the query parameters are not empty (queryParameters)
* - to check if the columns and query parameters have the same length (columns, queryParameters)
* - to rename the parameter name to avoid conflicts with a suffix (indexQueryParameterToInsert)
* - the values block of the query (valuesInsert)
* - the query parameters to insert (queryParametersToInsert)
*/
/** @var QueryParameters $queryParameters */
foreach ($batchInsertParameters->getIterator() as $queryParameters) {
if ($queryParameters->isEmpty()) {
throw ConnectionException::batchInsertQueryBadUsage('Query parameters must not be empty');
}
if (count($columns) !== $queryParameters->length()) {
throw ConnectionException::batchInsertQueryBadUsage('Columns and query parameters must have the same length');
}
$valuesInsertItem = '';
/** @var QueryParameter $queryParameter */
foreach ($queryParameters->getIterator() as $queryParameter) {
if (! empty($valuesInsertItem)) {
$valuesInsertItem .= ', ';
}
$parameterName = "{$queryParameter->getName()}_{$indexQueryParameterToInsert}";
$queryParameterToInsert = QueryParameter::create(
$parameterName,
$queryParameter->getValue(),
$queryParameter->getType()
);
$valuesInsertItem .= ":{$parameterName}";
$queryParametersToInsert->add($queryParameterToInsert->getName(), $queryParameterToInsert);
}
$valuesInsert[] = "({$valuesInsertItem})";
++$indexQueryParameterToInsert;
}
if (count($valuesInsert) === $queryParametersToInsert->length()) {
throw ConnectionException::batchInsertQueryBadUsage('Error while building the final query : values block and query parameters have not the same length');
}
$query .= implode(', ', $valuesInsert);
return $this->executeStatement($query, $queryParametersToInsert);
} catch (\Throwable $exception) {
throw ConnectionException::batchInsertQueryFailed(previous: $exception, tableName: $tableName, columns: $columns, batchInsertParameters: $batchInsertParameters, query: $query ?? '');
}
}
/**
* Executes an SQL statement with the given parameters and returns the number of affected rows.
*
* Could be only used for UPDATE.
*
* @throws ConnectionException
*
* @example $queryParameters = QueryParameters::create([QueryParameter::int('id', 1), QueryParameter::string('name', 'John')]);
* $nbAffectedRows = $db->update('UPDATE table SET name = :name WHERE id = :id', $queryParameters);
* // $nbAffectedRows = 1
*/
public function update(string $query, ?QueryParameters $queryParameters = null): int
{
try {
// Clean up the query string
$query = mb_ltrim($query);
// Check if the query starts with a valid SQL command
if (preg_match('/^(UPDATE|WITH)\b/i', $query) !== 1) {
throw ConnectionException::updateQueryBadFormat($query);
}
return $this->executeStatement($query, $queryParameters);
} catch (\Throwable $exception) {
throw ConnectionException::updateQueryFailed($exception, $query, $queryParameters);
}
}
/**
* Executes an SQL statement with the given parameters and returns the number of affected rows.
*
* Could be only used for DELETE.
*
* @throws ConnectionException
*
* @example $queryParameters = QueryParameters::create([QueryParameter::int('id', 1)]);
* $nbAffectedRows = $db->delete('DELETE FROM table WHERE id = :id', $queryParameters);
* // $nbAffectedRows = 1
*/
public function delete(string $query, ?QueryParameters $queryParameters = null): int
{
try {
// Clean up the query string
$query = mb_ltrim($query);
// Check if the query starts with a valid SQL command
if (preg_match('/^(DELETE|WITH)\b/i', $query) !== 1) {
throw ConnectionException::deleteQueryBadFormat($query);
}
return $this->executeStatement($query, $queryParameters);
} catch (\Throwable $exception) {
throw ConnectionException::deleteQueryFailed($exception, $query, $queryParameters);
}
}
// ----------------------------------------- FETCH METHODS -----------------------------------------
/**
* Prepares and executes an SQL query and returns the result as an array of the first column values.
*
* Could be only used with SELECT.
*
* @throws ConnectionException
*
* @return list<mixed>
*
* @example $queryParameters = QueryParameters::create([QueryParameter::bool('active', true)]);
* $result = $db->fetchFirstColumn('SELECT name FROM table WHERE active = :active', $queryParameters);
* // $result = ['John', 'Jean']
*/
abstract public function fetchFirstColumn(string $query, ?QueryParameters $queryParameters = null): array;
/**
* Prepares and executes an SQL query and returns the result as an array of associative arrays.
*
* Could be only used with SELECT.
*
* @throws ConnectionException
*
* @return array<array<string,mixed>>
*
* @example $queryParameters = QueryParameters::create([QueryParameter::bool('active', true)]);
* $result = $db->fetchAllAssociative('SELECT * FROM table WHERE active = :active', $queryParameters);
* // $result = [['id' => 1, 'name' => 'John', 'surname' => 'Doe'], ['id' => 2, 'name' => 'Jean', 'surname' => 'Dupont']]
*/
abstract public function fetchAllAssociative(string $query, ?QueryParameters $queryParameters = null): array;
/**
* Prepares and executes an SQL query and returns the result as an associative array with the keys mapped
* to the first column and the values being an associative array representing the rest of the columns
* and their values.
*
* Could be only used with SELECT.
*
* @throws ConnectionException
*
* @return array<mixed,array<string,mixed>>
*
* @example $queryParameters = QueryParameters::create([QueryParameter::bool('active', true)]);
* $result = $db->fetchAllAssociativeIndexed('SELECT id, name, surname FROM table WHERE active = :active', $queryParameters);
* // $result = [1 => ['name' => 'John', 'surname' => 'Doe'], 2 => ['name' => 'Jean', 'surname' => 'Dupont']]
*/
public function fetchAllAssociativeIndexed(string $query, ?QueryParameters $queryParameters = null): array
{
try {
$data = [];
foreach ($this->fetchAllAssociative($query, $queryParameters) as $row) {
$data[array_shift($row)] = $row;
}
return $data;
} catch (\Throwable $exception) {
throw ConnectionException::fetchAllAssociativeIndexedQueryFailed($exception, $query, $queryParameters);
}
}
// ----------------------------------------- ITERATE METHODS -----------------------------------------
/**
* Prepares and executes an SQL query and returns the result as an iterator over rows represented as numeric arrays.
*
* Could be only used with SELECT.
*
* @throws ConnectionException
*
* @return \Traversable<int,list<mixed>>
*
* @example $queryParameters = QueryParameters::create([QueryParameter::bool('active', true)]);
* $result = $db->iterateNumeric('SELECT * FROM table WHERE active = :active', $queryParameters);
* foreach ($result as $row) {
* // $row = [0 => 1, 1 => 'John', 2 => 'Doe']
* // $row = [0 => 2, 1 => 'Jean', 2 => 'Dupont']
* }
*/
abstract public function iterateNumeric(string $query, ?QueryParameters $queryParameters = null): \Traversable;
/**
* Prepares and executes an SQL query and returns the result as an iterator over rows represented
* as associative arrays.
*
* Could be only used with SELECT.
*
* @throws ConnectionException
*
* @return \Traversable<int,array<string,mixed>>
*
* @example $queryParameters = QueryParameters::create([QueryParameter::bool('active', true)]);
* $result = $db->iterateAssociative('SELECT * FROM table WHERE active = :active', $queryParameters);
* foreach ($result as $row) {
* // $row = ['id' => 1, 'name' => 'John', 'surname' => 'Doe']
* // $row = ['id' => 2, 'name' => 'Jean', 'surname' => 'Dupont']
* }
*/
abstract public function iterateAssociative(string $query, ?QueryParameters $queryParameters = null): \Traversable;
/**
* Prepares and executes an SQL query and returns the result as an iterator with the keys
* mapped to the first column and the values mapped to the second column.
*
* Could be only used with SELECT.
*
* @throws ConnectionException
*
* @return \Traversable<mixed,mixed>
*
* @example $queryParameters = QueryParameters::create([QueryParameter::bool('active', true)]);
* $result = $db->iterateKeyValue('SELECT name, surname FROM table WHERE active = :active', $queryParameters);
* foreach ($result as $key => $value) {
* // $key = 'John', $value = 'Doe'
* // $key = 'Jean', $value = 'Dupont'
* }
*/
public function iterateKeyValue(string $query, ?QueryParameters $queryParameters = null): \Traversable
{
try {
$this->validateSelectQuery($query);
foreach ($this->iterateNumeric($query, $queryParameters) as $row) {
if (count($row) < 2) {
throw ConnectionException::iterateKeyValueQueryBadFormat('The query must return at least two columns', $query);
}
[$key, $value] = $row;
yield $key => $value;
}
} catch (\Throwable $exception) {
throw ConnectionException::iterateKeyValueQueryFailed($exception, $query, $queryParameters);
}
}
/**
* Prepares and executes an SQL query and returns the result as an iterator with the keys mapped
* to the first column and the values being an associative array representing the rest of the columns
* and their values.
*
* Could be only used with SELECT.
*
* @throws ConnectionException
*
* @return \Traversable<mixed,array<string,mixed>>
*
* @example $queryParameters = QueryParameters::create([QueryParameter::bool('active', true)]);
* $result = $db->iterateAssociativeIndexed('SELECT id, name, surname FROM table WHERE active = :active', $queryParameters);
* foreach ($result as $key => $row) {
* // $key = 1, $row = ['name' => 'John', 'surname' => 'Doe']
* // $key = 2, $row = ['name' => 'Jean', 'surname' => 'Dupont']
* }
*/
public function iterateAssociativeIndexed(string $query, ?QueryParameters $queryParameters = null): \Traversable
{
try {
$this->validateSelectQuery($query);
foreach ($this->iterateAssociative($query, $queryParameters) as $row) {
yield array_shift($row) => $row;
}
} catch (\Throwable $exception) {
throw ConnectionException::iterateAssociativeIndexedQueryFailed($exception, $query, $queryParameters);
}
}
// --------------------------------------- DDL TOOLS -----------------------------------------------
/**
* Check if a column exists in a table.
*
* @throws ConnectionException
*/
public function columnExists(string $dbName, string $tableName, string $columnName): bool
{
if (empty($dbName)) {
throw ConnectionException::columnExistsFailed('Database name must not be empty', $tableName, $columnName);
}
if (empty($tableName)) {
throw ConnectionException::columnExistsFailed('Table name must not be empty', $tableName, $columnName);
}
if (empty($columnName)) {
throw ConnectionException::columnExistsFailed('Column name must not be empty', $tableName, $columnName);
}
$query = <<<'SQL'
SELECT COUNT(*) FROM information_schema.COLUMNS
WHERE TABLE_NAME = :tableName
AND COLUMN_NAME = :columnName
AND TABLE_SCHEMA = :dbName
SQL;
try {
$queryParameters = QueryParameters::create([
QueryParameter::string('tableName', $tableName),
QueryParameter::string('columnName', $columnName),
QueryParameter::string('dbName', $dbName),
]);
$entry = $this->fetchOne($query, $queryParameters);
return is_numeric($entry) && (int) $entry > 0;
} catch (ValueObjectException|CollectionException|ConnectionException $exception) {
throw ConnectionException::columnExistsFailed(
message: 'Failed to query column existence',
tableName: $tableName,
columnName: $columnName,
previous: $exception
);
}
}
// ----------------------------------------- PROTECTED METHODS -----------------------------------------
abstract protected function writeDbLog(
string $message,
array $customContext = [],
string $query = '',
?\Throwable $previous = null,
): void;
// ----------------------------------------- PRIVATE METHODS -----------------------------------------
/**
* @throws ConnectionException
*/
private function validateSelectQuery(string $query): void
{
if (empty($query)) {
throw ConnectionException::notEmptyQuery();
}
// Clean up the query string
$query = mb_ltrim($query);
// Check if the query starts with a valid SQL command
if (preg_match('/^\(*\s*(SELECT|EXPLAIN|SHOW|DESCRIBE|WITH)\b/i', $query) !== 1) {
throw ConnectionException::selectQueryBadFormat($query);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Adaptation/Database/Connection/Adapter/Pdo/Transformer/PdoParameterTypeTransformer.php | centreon/src/Adaptation/Database/Connection/Adapter/Pdo/Transformer/PdoParameterTypeTransformer.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Adaptation\Database\Connection\Adapter\Pdo\Transformer;
use Adaptation\Database\Connection\Enum\QueryParameterTypeEnum;
use Core\Common\Domain\Exception\TransformerException;
/**
* Class.
*
* @class PdoParameterTypeTransformer
*/
abstract readonly class PdoParameterTypeTransformer
{
public static function transformFromQueryParameterType(QueryParameterTypeEnum $queryParameterType): int
{
return match ($queryParameterType) {
QueryParameterTypeEnum::NULL => \PDO::PARAM_NULL,
QueryParameterTypeEnum::INTEGER => \PDO::PARAM_INT,
QueryParameterTypeEnum::STRING => \PDO::PARAM_STR,
QueryParameterTypeEnum::LARGE_OBJECT => \PDO::PARAM_LOB,
QueryParameterTypeEnum::BOOLEAN => \PDO::PARAM_BOOL,
};
}
/**
* @throws TransformerException
*/
public static function reverseToQueryParameterType(int $pdoParameterType): QueryParameterTypeEnum
{
return match ($pdoParameterType) {
\PDO::PARAM_NULL => QueryParameterTypeEnum::NULL,
\PDO::PARAM_INT => QueryParameterTypeEnum::INTEGER,
\PDO::PARAM_STR => QueryParameterTypeEnum::STRING,
\PDO::PARAM_LOB => QueryParameterTypeEnum::LARGE_OBJECT,
\PDO::PARAM_BOOL => QueryParameterTypeEnum::BOOLEAN,
default => throw new TransformerException('Unknown PDO parameter type', ['pdo_parameter_type' => $pdoParameterType]),
};
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Adaptation/Database/Connection/Adapter/Dbal/DbalConnectionAdapter.php | centreon/src/Adaptation/Database/Connection/Adapter/Dbal/DbalConnectionAdapter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Adaptation\Database\Connection\Adapter\Dbal;
use Adaptation\Database\Connection\Adapter\Dbal\Transformer\DbalParametersTransformer;
use Adaptation\Database\Connection\Collection\QueryParameters;
use Adaptation\Database\Connection\ConnectionInterface;
use Adaptation\Database\Connection\Exception\ConnectionException;
use Adaptation\Database\Connection\Model\ConnectionConfig;
use Adaptation\Database\Connection\Trait\ConnectionTrait;
use Centreon\Domain\Log\Logger;
use Core\Common\Domain\Exception\UnexpectedValueException;
use Core\Common\Infrastructure\ExceptionLogger\ExceptionLogger;
use Doctrine\DBAL\Connection as DoctrineDbalConnection;
use Doctrine\DBAL\DriverManager as DoctrineDbalDriverManager;
use Psr\Log\LogLevel;
/**
* Class.
*
* @class DbalConnectionAdapter
*
* @see DoctrineDbalConnection
*/
final class DbalConnectionAdapter implements ConnectionInterface
{
use ConnectionTrait;
/** By default, the queries are buffered. */
private bool $isBufferedQueryActive = true;
/**
* DbalConnectionAdapter constructor.
*/
private function __construct(
private readonly DoctrineDbalConnection $dbalConnection,
private readonly ConnectionConfig $connectionConfig,
) {
}
/**
* Factory.
*
* @throws ConnectionException
*
* @return DbalConnectionAdapter
*/
public static function createFromConfig(ConnectionConfig $connectionConfig): ConnectionInterface
{
$dbalConnectionConfig = [
'dbname' => $connectionConfig->getDatabaseNameConfiguration(),
'user' => $connectionConfig->getUser(),
'password' => $connectionConfig->getPassword(),
'host' => $connectionConfig->getHost(),
'port' => $connectionConfig->getPort(),
'charset' => $connectionConfig->getCharset(),
'driver' => $connectionConfig->getDriver()->value,
];
try {
$dbalConnection = DoctrineDbalDriverManager::getConnection($dbalConnectionConfig);
$dbalConnectionAdapter = new self($dbalConnection, $connectionConfig);
if (! $dbalConnectionAdapter->isConnected()) {
throw new UnexpectedValueException('The connection is not established.');
}
return $dbalConnectionAdapter;
} catch (\Throwable $exception) {
throw ConnectionException::connectionFailed($exception);
}
}
public function getConnectionConfig(): ConnectionConfig
{
return $this->connectionConfig;
}
public function getDbalConnection(): DoctrineDbalConnection
{
return $this->dbalConnection;
}
/**
* To get the used native connection by DBAL (PDO, mysqli, ...).
*
* @throws ConnectionException
*
* @return object|resource
*/
public function getNativeConnection(): mixed
{
try {
return $this->dbalConnection->getNativeConnection();
} catch (\Throwable $exception) {
$this->writeDbLog(
message: 'Unable to get native connection',
previous: $exception
);
throw ConnectionException::getNativeConnectionFailed($exception);
}
}
/**
* Returns the ID of the last inserted row.
* If the underlying driver does not support identity columns, an exception is thrown.
*
* @throws ConnectionException
*/
public function getLastInsertId(): string
{
try {
return (string) $this->dbalConnection->lastInsertId();
} catch (\Throwable $exception) {
$this->writeDbLog(
message: 'Unable to get last insert id',
previous: $exception,
);
throw ConnectionException::getLastInsertFailed($exception);
}
}
/**
* Check if a connection with the database exist.
*/
public function isConnected(): bool
{
try {
return ! empty($this->dbalConnection->getServerVersion());
} catch (\Throwable $exception) {
$this->writeDbLog(
message: 'Unable to check if the connection is established',
previous: $exception,
);
return false;
}
}
/**
* The usage of this method is discouraged. Use prepared statements.
*/
public function quoteString(string $value): string
{
return $this->dbalConnection->quote($value);
}
// ----------------------------------------- CRUD METHODS -----------------------------------------
/**
* To execute all queries except the queries getting results (SELECT).
*
* Executes an SQL statement with the given parameters and returns the number of affected rows.
*
* Could be used for:
* - DML statements: INSERT, UPDATE, DELETE, etc.
* - DDL statements: CREATE, DROP, ALTER, etc.
* - DCL statements: GRANT, REVOKE, etc.
* - Session control statements: ALTER SESSION, SET, DECLARE, etc.
* - Other statements that don't yield a row set.
*
* @throws ConnectionException
*
* @example $queryParameters = QueryParameters::create([QueryParameter::int('id', 1), QueryParameter::string('name', 'John')]);
* $nbAffectedRows = $db->executeStatement('UPDATE table SET name = :name WHERE id = :id', $queryParameters);
* // $nbAffectedRows = 1
*/
public function executeStatement(string $query, ?QueryParameters $queryParameters = null): int
{
try {
if (empty($query)) {
throw ConnectionException::notEmptyQuery();
}
if (str_starts_with($query, 'SELECT') || str_starts_with($query, 'select')) {
throw ConnectionException::executeStatementBadFormat('Cannot use it with a SELECT query', $query);
}
if (! $queryParameters instanceof QueryParameters) {
return (int) $this->dbalConnection->executeStatement($query);
}
[$params, $types] = DbalParametersTransformer::transformFromQueryParameters($queryParameters);
return (int) $this->dbalConnection->executeStatement($query, $params, $types);
} catch (\Throwable $exception) {
$this->writeDbLog(
message: 'Unable to execute statement',
customContext: ['query_parameters' => $queryParameters],
query: $query,
previous: $exception,
);
throw ConnectionException::executeStatementFailed($exception, $query, $queryParameters);
}
}
// --------------------------------------- FETCH METHODS -----------------------------------------
/**
* Prepares and executes an SQL query and returns the first row of the result
* as a numerically indexed array.
*
* Could be only used with SELECT.
*
* @throws ConnectionException
*
* @return array<int, mixed>|false false is returned if no rows are found
*
* @example $queryParameters = QueryParameters::create([QueryParameter::int('id', 1)]);
* $result = $db->fetchNumeric('SELECT * FROM table WHERE id = :id', $queryParameters);
* // $result = [0 => 1, 1 => 'John', 2 => 'Doe']
*/
public function fetchNumeric(string $query, ?QueryParameters $queryParameters = null): false|array
{
try {
$this->validateSelectQuery($query);
if (! $queryParameters instanceof QueryParameters) {
return $this->dbalConnection->fetchNumeric($query);
}
[$params, $types] = DbalParametersTransformer::transformFromQueryParameters($queryParameters);
return $this->dbalConnection->fetchNumeric($query, $params, $types);
} catch (\Throwable $exception) {
$this->writeDbLog(
message: 'Unable to fetch numeric query',
customContext: ['query_parameters' => $queryParameters],
query: $query,
previous: $exception,
);
throw ConnectionException::fetchNumericQueryFailed($exception, $query, $queryParameters);
}
}
/**
* Prepares and executes an SQL query and returns the first row of the result as an associative array.
*
* Could be only used with SELECT.
*
* @throws ConnectionException
*
* @return array<string, mixed>|false false is returned if no rows are found
*
* @example $queryParameters = QueryParameters::create([QueryParameter::int('id', 1)]);
* $result = $db->fetchAssociative('SELECT * FROM table WHERE id = :id', $queryParameters);
* // $result = ['id' => 1, 'name' => 'John', 'surname' => 'Doe']
*/
public function fetchAssociative(string $query, ?QueryParameters $queryParameters = null): false|array
{
try {
$this->validateSelectQuery($query);
if (! $queryParameters instanceof QueryParameters) {
return $this->dbalConnection->fetchAssociative($query);
}
[$params, $types] = DbalParametersTransformer::transformFromQueryParameters($queryParameters);
return $this->dbalConnection->fetchAssociative($query, $params, $types);
} catch (\Throwable $exception) {
$this->writeDbLog(
message: 'Unable to fetch associative query',
customContext: ['query_parameters' => $queryParameters],
query: $query,
previous: $exception,
);
throw ConnectionException::fetchAssociativeQueryFailed($exception, $query, $queryParameters);
}
}
/**
* Prepares and executes an SQL query and returns the value of a single column
* of the first row of the result.
*
* Could be only used with SELECT.
*
* @throws ConnectionException
*
* @return mixed|false false is returned if no rows are found
*
* @example $queryParameters = QueryParameters::create([QueryParameter::string('name', 'John')]);
* $result = $db->fetchOne('SELECT name FROM table WHERE name = :name', $queryParameters);
* // $result = 'John'
*/
public function fetchOne(string $query, ?QueryParameters $queryParameters = null): mixed
{
try {
$this->validateSelectQuery($query);
if (! $queryParameters instanceof QueryParameters) {
return $this->dbalConnection->fetchOne($query);
}
[$params, $types] = DbalParametersTransformer::transformFromQueryParameters($queryParameters);
return $this->dbalConnection->fetchOne($query, $params, $types);
} catch (\Throwable $exception) {
$this->writeDbLog(
message: 'Unable to fetch one query',
customContext: ['query_parameters' => $queryParameters],
query: $query,
previous: $exception,
);
throw ConnectionException::fetchOneQueryFailed($exception, $query, $queryParameters);
}
}
/**
* Prepares and executes an SQL query and returns the result as an array of the first column values.
*
* Could be only used with SELECT.
*
* @throws ConnectionException
*
* @return list<mixed>
*
* @example $queryParameters = QueryParameters::create([QueryParameter::bool('active', true)]);
* $result = $db->fetchFirstColumn('SELECT name FROM table WHERE active = :active', $queryParameters);
* // $result = ['John', 'Jean']
*/
public function fetchFirstColumn(string $query, ?QueryParameters $queryParameters = null): array
{
try {
$this->validateSelectQuery($query);
if (! $queryParameters instanceof QueryParameters) {
return $this->dbalConnection->fetchFirstColumn($query);
}
[$params, $types] = DbalParametersTransformer::transformFromQueryParameters($queryParameters);
return $this->dbalConnection->fetchFirstColumn($query, $params, $types);
} catch (\Throwable $exception) {
$this->writeDbLog(
message: 'Unable to fetch first column query',
customContext: ['query_parameters' => $queryParameters],
query: $query,
previous: $exception,
);
throw ConnectionException::fetchFirstColumnQueryFailed($exception, $query, $queryParameters);
}
}
/**
* Prepares and executes an SQL query and returns the result as an array of numeric arrays.
*
* Could be only used with SELECT.
*
* @throws ConnectionException
*
* @return array<array<int,mixed>>
*
* @example $queryParameters = QueryParameters::create([QueryParameter::bool('active', true)]);
* $result = $db->fetchAllNumeric('SELECT * FROM table WHERE active = :active', $queryParameters);
* // $result = [[0 => 1, 1 => 'John', 2 => 'Doe'], [0 => 2, 1 => 'Jean', 2 => 'Dupont']]
*/
public function fetchAllNumeric(string $query, ?QueryParameters $queryParameters = null): array
{
try {
$this->validateSelectQuery($query);
if (! $queryParameters instanceof QueryParameters) {
return $this->dbalConnection->fetchAllNumeric($query);
}
[$params, $types] = DbalParametersTransformer::transformFromQueryParameters($queryParameters);
return $this->dbalConnection->fetchAllNumeric($query, $params, $types);
} catch (\Throwable $exception) {
$this->writeDbLog(
message: 'Unable to fetch all numeric query',
customContext: ['query_parameters' => $queryParameters],
query: $query,
previous: $exception,
);
throw ConnectionException::fetchAllNumericQueryFailed($exception, $query, $queryParameters);
}
}
/**
* Prepares and executes an SQL query and returns the result as an array of associative arrays.
*
* Could be only used with SELECT.
*
* @throws ConnectionException
*
* @return array<array<string,mixed>>
*
* @example $queryParameters = QueryParameters::create([QueryParameter::bool('active', true)]);
* $result = $db->fetchAllAssociative('SELECT * FROM table WHERE active = :active', $queryParameters);
* // $result = [['id' => 1, 'name' => 'John', 'surname' => 'Doe'], ['id' => 2, 'name' => 'Jean', 'surname' => 'Dupont']]
*/
public function fetchAllAssociative(string $query, ?QueryParameters $queryParameters = null): array
{
try {
$this->validateSelectQuery($query);
if (! $queryParameters instanceof QueryParameters) {
return $this->dbalConnection->fetchAllAssociative($query);
}
[$params, $types] = DbalParametersTransformer::transformFromQueryParameters($queryParameters);
return $this->dbalConnection->fetchAllAssociative($query, $params, $types);
} catch (\Throwable $exception) {
$this->writeDbLog(
message: 'Unable to fetch all associative query',
customContext: ['query_parameters' => $queryParameters],
query: $query,
previous: $exception,
);
throw ConnectionException::fetchAllAssociativeQueryFailed($exception, $query, $queryParameters);
}
}
/**
* Prepares and executes an SQL query and returns the result as an associative array with the keys
* mapped to the first column and the values mapped to the second column.
*
* Could be only used with SELECT.
*
* @throws ConnectionException
*
* @return array<int|string,mixed>
*
* @example $queryParameters = QueryParameters::create([QueryParameter::bool('active', true)]);
* $result = $db->fetchAllKeyValue('SELECT name, surname FROM table WHERE active = :active', $queryParameters);
* // $result = ['John' => 'Doe', 'Jean' => 'Dupont']
*/
public function fetchAllKeyValue(string $query, ?QueryParameters $queryParameters = null): array
{
try {
$this->validateSelectQuery($query);
if (! $queryParameters instanceof QueryParameters) {
return $this->dbalConnection->fetchAllKeyValue($query);
}
[$params, $types] = DbalParametersTransformer::transformFromQueryParameters($queryParameters);
return $this->dbalConnection->fetchAllKeyValue($query, $params, $types);
} catch (\Throwable $exception) {
$this->writeDbLog(
message: 'Unable to fetch all key value query',
customContext: ['query_parameters' => $queryParameters],
query: $query,
previous: $exception,
);
throw ConnectionException::fetchAllKeyValueQueryFailed($exception, $query, $queryParameters);
}
}
// --------------------------------------- ITERATE METHODS -----------------------------------------
/**
* Prepares and executes an SQL query and returns the result as an iterator over rows represented as numeric arrays.
*
* Could be only used with SELECT.
*
* @throws ConnectionException
*
* @return \Traversable<int,list<mixed>>
*
* @example $queryParameters = QueryParameters::create([QueryParameter::bool('active', true)]);
* $result = $db->iterateNumeric('SELECT * FROM table WHERE active = :active', $queryParameters);
* foreach ($result as $row) {
* // $row = [0 => 1, 1 => 'John', 2 => 'Doe']
* // $row = [0 => 2, 1 => 'Jean', 2 => 'Dupont']
* }
*/
public function iterateNumeric(string $query, ?QueryParameters $queryParameters = null): \Traversable
{
try {
$this->validateSelectQuery($query);
if (! $queryParameters instanceof QueryParameters) {
return $this->dbalConnection->iterateNumeric($query);
}
[$params, $types] = DbalParametersTransformer::transformFromQueryParameters($queryParameters);
return $this->dbalConnection->iterateNumeric($query, $params, $types);
} catch (\Throwable $exception) {
throw ConnectionException::iterateNumericQueryFailed($exception, $query, $queryParameters);
}
}
/**
* Prepares and executes an SQL query and returns the result as an iterator over rows represented
* as associative arrays.
*
* Could be only used with SELECT.
*
* @throws ConnectionException
*
* @return \Traversable<int,array<string,mixed>>
*
* @example $queryParameters = QueryParameters::create([QueryParameter::bool('active', true)]);
* $result = $db->iterateAssociative('SELECT * FROM table WHERE active = :active', $queryParameters);
* foreach ($result as $row) {
* // $row = ['id' => 1, 'name' => 'John', 'surname' => 'Doe']
* // $row = ['id' => 2, 'name' => 'Jean', 'surname' => 'Dupont']
* }
*/
public function iterateAssociative(string $query, ?QueryParameters $queryParameters = null): \Traversable
{
try {
$this->validateSelectQuery($query);
if (! $queryParameters instanceof QueryParameters) {
return $this->dbalConnection->iterateAssociative($query);
}
[$params, $types] = DbalParametersTransformer::transformFromQueryParameters($queryParameters);
return $this->dbalConnection->iterateAssociative($query, $params, $types);
} catch (\Throwable $exception) {
throw ConnectionException::iterateAssociativeQueryFailed($exception, $query, $queryParameters);
}
}
/**
* Prepares and executes an SQL query and returns the result as an iterator over the column values.
*
* Could be only used with SELECT.
*
* @throws ConnectionException
*
* @return \Traversable<int,mixed>
*
* @example $queryParameters = QueryParameters::create([QueryParameter::bool('active', true)]);
* $result = $db->iterateFirstColumn('SELECT name FROM table WHERE active = :active', $queryParameters);
* foreach ($result as $value) {
* // $value = 'John'
* // $value = 'Jean'
* }
*/
public function iterateColumn(string $query, ?QueryParameters $queryParameters = null): \Traversable
{
try {
$this->validateSelectQuery($query);
if (! $queryParameters instanceof QueryParameters) {
return $this->dbalConnection->iterateColumn($query);
}
[$params, $types] = DbalParametersTransformer::transformFromQueryParameters($queryParameters);
return $this->dbalConnection->iterateColumn($query, $params, $types);
} catch (\Throwable $exception) {
throw ConnectionException::iterateColumnQueryFailed($exception, $query, $queryParameters);
}
}
// ----------------------------------------- TRANSACTIONS -----------------------------------------
/**
* Returns the current auto-commit mode for this connection.
*
* @return bool true if auto-commit mode is currently enabled for this connection, false otherwise
*
* @see setAutoCommit
*/
public function isAutoCommit(): bool
{
return $this->dbalConnection->isAutoCommit();
}
/**
* Sets auto-commit mode for this connection.
*
* If a connection is in auto-commit mode, then all its SQL statements will be executed and committed as individual
* transactions. Otherwise, its SQL statements are grouped into transactions that are terminated by a call to either
* the method commit or the method rollback. By default, new connections are in auto-commit mode.
*
* NOTE: If this method is called during a transaction and the auto-commit mode is changed, the transaction is
* committed. If this method is called and the auto-commit mode is not changed, the call is a no-op.
*
* @param bool $autoCommit true to enable auto-commit mode; false to disable it
*
* @throws ConnectionException
*/
public function setAutoCommit(bool $autoCommit): void
{
try {
$this->dbalConnection->setAutoCommit($autoCommit);
} catch (\Throwable $exception) {
$this->writeDbLog(
message: 'Unable to set auto commit',
customContext: ['auto_commit' => $autoCommit],
previous: $exception,
);
throw ConnectionException::setAutoCommitFailed($exception);
}
}
/**
* Checks whether a transaction is currently active.
*
* @return bool TRUE if a transaction is currently active, FALSE otherwise
*/
public function isTransactionActive(): bool
{
return $this->dbalConnection->isTransactionActive();
}
/**
* Opens a new transaction. This must be closed by calling one of the following methods:
* {@see commitTransaction} or {@see rollBackTransaction}
*
* Note that it is possible to create nested transactions, but that data will only be written to the database when
* the level 1 transaction is committed.
*
* Similarly, if a rollback occurs in a nested transaction, the level 1 transaction will also be rolled back and
* no data will be updated.
*
* @throws ConnectionException
*/
public function startTransaction(): void
{
try {
// we check if the save points mode is available before run a nested transaction
if ($this->isTransactionActive() && ! $this->dbalConnection->getDatabasePlatform()->supportsSavepoints()) {
throw new ConnectionException('Start nested transaction failed', ConnectionException::ERROR_CODE_DATABASE_TRANSACTION);
}
$this->dbalConnection->beginTransaction();
} catch (\Throwable $exception) {
$this->writeDbLog(
message: 'Unable to start transaction',
previous: $exception,
);
throw ConnectionException::startTransactionFailed($exception);
}
}
/**
* To validate a transaction.
*
* @throws ConnectionException
*/
public function commitTransaction(): bool
{
try {
$this->dbalConnection->commit();
return true;
} catch (\Throwable $exception) {
$this->writeDbLog(
message: 'Unable to commit transaction',
previous: $exception,
);
throw ConnectionException::commitTransactionFailed($exception);
}
}
/**
* To cancel a transaction.
*
* @throws ConnectionException
*/
public function rollBackTransaction(): bool
{
try {
$this->dbalConnection->rollBack();
return true;
} catch (\Throwable $exception) {
$this->writeDbLog(
message: 'Unable to rollback transaction',
previous: $exception,
);
throw ConnectionException::rollbackTransactionFailed($exception);
}
}
// ------------------------------------- UNBUFFERED QUERIES -----------------------------------------
/**
* Checks that the connection instance allows the use of unbuffered queries.
*
* @throws ConnectionException
*/
public function allowUnbufferedQuery(): bool
{
$nativeConnection = $this->getNativeConnection();
if (\is_object($nativeConnection)) {
$driverName = '';
if ($nativeConnection instanceof \PDO) {
$driverNamePdo = $nativeConnection->getAttribute(\PDO::ATTR_DRIVER_NAME);
$driverName = is_string($driverNamePdo) ? 'pdo_' . $driverNamePdo : '';
}
if (empty($driverName) || ! \in_array($driverName, self::DRIVER_ALLOWED_UNBUFFERED_QUERY, true)) {
$this->writeDbLog(
message: 'Unbuffered queries are not allowed with this driver',
customContext: ['driver_name' => $driverName]
);
throw ConnectionException::allowUnbufferedQueryFailed($nativeConnection::class, $driverName);
}
return true;
}
return false;
}
/**
* Prepares a statement to execute a query without buffering. Only works for SELECT queries.
*
* @throws ConnectionException
*/
public function startUnbufferedQuery(): void
{
$this->allowUnbufferedQuery();
$nativeConnection = $this->getNativeConnection();
if ($nativeConnection instanceof \PDO && ! $nativeConnection->setAttribute(\PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false)) {
$this->writeDbLog(message: 'Error while starting an unbuffered query');
throw ConnectionException::startUnbufferedQueryFailed();
}
$this->isBufferedQueryActive = false;
}
/**
* Checks whether an unbuffered query is currently active.
*/
public function isUnbufferedQueryActive(): bool
{
return $this->isBufferedQueryActive === false;
}
/**
* To close an unbuffered query.
*
* @throws ConnectionException
*/
public function stopUnbufferedQuery(): void
{
$nativeConnection = $this->getNativeConnection();
if (! $this->isUnbufferedQueryActive()) {
$this->writeDbLog(
message: 'Error while stopping an unbuffered query, no unbuffered query is currently active'
);
throw ConnectionException::stopUnbufferedQueryFailed('Unbuffered query not active');
}
if ($nativeConnection instanceof \PDO && ! $nativeConnection->setAttribute(\PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true)) {
$this->writeDbLog(message: 'Error while stopping an unbuffered query');
throw ConnectionException::stopUnbufferedQueryFailed('Unbuffered query failed');
}
$this->isBufferedQueryActive = true;
}
// ----------------------------------------- PRIVATE METHODS -----------------------------------------
/**
* Write SQL errors messages.
*
* @param array<string,mixed> $customContext
*/
protected function writeDbLog(
string $message,
array $customContext = [],
string $query = '',
?\Throwable $previous = null,
): void {
// prepare context of the database exception
$context = [
'database_name' => $this->connectionConfig->getDatabaseNameConfiguration(),
'database_connector' => self::class,
'query' => $query,
];
if ($previous instanceof \Throwable) {
ExceptionLogger::create()->log($previous, $context, LogLevel::CRITICAL);
} else {
Logger::create()->critical($message, $context);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Adaptation/Database/Connection/Adapter/Dbal/Transformer/DbalParametersTransformer.php | centreon/src/Adaptation/Database/Connection/Adapter/Dbal/Transformer/DbalParametersTransformer.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Adaptation\Database\Connection\Adapter\Dbal\Transformer;
use Adaptation\Database\Connection\Collection\QueryParameters;
use Adaptation\Database\Connection\ValueObject\QueryParameter;
use Core\Common\Domain\Exception\CollectionException;
use Core\Common\Domain\Exception\TransformerException;
use Core\Common\Domain\Exception\ValueObjectException;
use Doctrine\DBAL\ParameterType as DbalParameterType;
/**
* Class.
*
* @class DbalParametersTransformer
*/
abstract readonly class DbalParametersTransformer
{
/**
* @throws TransformerException
*
* @return array{0: array<string, mixed>, 1: array<string, DbalParameterType>}
*/
public static function transformFromQueryParameters(QueryParameters $queryParameters): array
{
$params = [];
$types = [];
foreach ($queryParameters->getIterator() as $queryParameter) {
// remove : from the key to avoid issues with named parameters, dbal doesn't accept : in the key
$name = $queryParameter->getName();
if (str_starts_with((string) $queryParameter->getName(), ':')) {
$name = mb_substr((string) $queryParameter->getName(), 1);
}
$params[$name] = $queryParameter->getValue();
if ($queryParameter->getType() !== null) {
$types[$name] = DbalParameterTypeTransformer::transformFromQueryParameterType(
$queryParameter->getType()
);
}
}
return [$params, $types];
}
/**
* @param array<string, mixed> $params
* @param array<string, DbalParameterType> $types
*
* @throws TransformerException
*/
public static function reverseToQueryParameters(array $params, array $types): QueryParameters
{
try {
$queryParameters = new QueryParameters();
foreach ($params as $name => $value) {
$type = DbalParameterTypeTransformer::reverseToQueryParameterType(
$types[$name] ?? DbalParameterType::STRING
);
$queryParameter = QueryParameter::create($name, $value, $type);
$queryParameters->add($queryParameter->getName(), $queryParameter);
}
return $queryParameters;
} catch (CollectionException|ValueObjectException $exception) {
throw new TransformerException("Error while reversing to QueryParameters : {$exception->getMessage()}", ['params' => $params, 'types' => $types], $exception);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Adaptation/Database/Connection/Adapter/Dbal/Transformer/DbalParameterTypeTransformer.php | centreon/src/Adaptation/Database/Connection/Adapter/Dbal/Transformer/DbalParameterTypeTransformer.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Adaptation\Database\Connection\Adapter\Dbal\Transformer;
use Adaptation\Database\Connection\Enum\QueryParameterTypeEnum;
use Core\Common\Domain\Exception\TransformerException;
use Doctrine\DBAL\ParameterType as DbalParameterType;
/**
* Class.
*
* @class DbalParameterTypeTransformer
*/
abstract readonly class DbalParameterTypeTransformer
{
public static function transformFromQueryParameterType(QueryParameterTypeEnum $queryParameterTypeEnum): DbalParameterType
{
return match ($queryParameterTypeEnum) {
QueryParameterTypeEnum::STRING => DbalParameterType::STRING,
QueryParameterTypeEnum::INTEGER => DbalParameterType::INTEGER,
QueryParameterTypeEnum::BOOLEAN => DbalParameterType::BOOLEAN,
QueryParameterTypeEnum::NULL => DbalParameterType::NULL,
QueryParameterTypeEnum::LARGE_OBJECT => DbalParameterType::LARGE_OBJECT,
};
}
/**
* @throws TransformerException
*/
public static function reverseToQueryParameterType(DbalParameterType $dbalParameterType): QueryParameterTypeEnum
{
return match ($dbalParameterType) {
DbalParameterType::STRING => QueryParameterTypeEnum::STRING,
DbalParameterType::INTEGER => QueryParameterTypeEnum::INTEGER,
DbalParameterType::BOOLEAN => QueryParameterTypeEnum::BOOLEAN,
DbalParameterType::NULL => QueryParameterTypeEnum::NULL,
DbalParameterType::LARGE_OBJECT => QueryParameterTypeEnum::LARGE_OBJECT,
default => throw new TransformerException('The type of the parameter is not supported by DbalParameterType', ['dbal_parameter_type' => $dbalParameterType]),
};
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Adaptation/Log/LoggerPassword.php | centreon/src/Adaptation/Log/LoggerPassword.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Adaptation\Log;
use Psr\Log\LoggerInterface;
final class LoggerPassword
{
private static ?self $instance = null;
private function __construct(private readonly LoggerInterface $logger)
{
}
public static function create(): self
{
if (! self::$instance instanceof self) {
self::$instance = new self(Logger::create(Enum\LogChannelEnum::PASSWORD));
}
return self::$instance;
}
public function success(int $initiatorId, int $targetId): void
{
$this->logger->info(
'Password change succeeded',
[
'status' => 'success',
'initiator_user_id' => $initiatorId,
'target_user_id' => $targetId,
'ip_address' => $_SERVER['REMOTE_ADDR'] ?? 'unknown',
]
);
}
public function warning(string $reason, int $initiatorId, int $targetId, ?\Throwable $exception = null): void
{
$this->logger->warning(
"Password change failed ({$reason})",
[
'status' => 'failure',
'reason' => mb_strtolower(str_replace(' ', '_', $reason)),
'initiator_user_id' => $initiatorId,
'target_user_id' => $targetId,
'ip_address' => $_SERVER['REMOTE_ADDR'] ?? 'unknown',
'exception' => $exception,
]
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Adaptation/Log/LoggerToken.php | centreon/src/Adaptation/Log/LoggerToken.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Adaptation\Log;
use Psr\Log\LoggerInterface;
final class LoggerToken
{
private static ?self $instance = null;
private function __construct(private readonly LoggerInterface $logger)
{
}
public static function create(): self
{
if (! self::$instance instanceof self) {
self::$instance = new self(Logger::create(Enum\LogChannelEnum::TOKEN));
}
return self::$instance;
}
public function success(
string $event,
int $userId,
?string $tokenType = null,
?string $tokenName = null,
?string $endpoint = null,
?string $httpMethod = null,
): void {
$context = [
'event' => $event,
'status' => 'success',
'datetime' => (new \DateTimeImmutable())->format('Y-m-d H:i:s'),
'user_id' => $userId,
'ip_address' => $_SERVER['REMOTE_ADDR'] ?? 'unknown',
];
if ($tokenName !== null) {
$context['token_name'] = $tokenName;
}
if ($tokenType !== null) {
$context['token_type'] = $tokenType;
}
if ($endpoint !== null) {
$context['endpoint'] = $endpoint;
}
if ($httpMethod !== null) {
$context['http_method'] = $httpMethod;
}
$this->logger->info("Token {$event} succeeded", $context);
}
public function warning(
string $event,
string $reason,
int $userId,
?string $tokenName = null,
?string $tokenType = null,
?\Throwable $exception = null,
): void {
$context = [
'event' => $event,
'status' => 'failure',
'datetime' => (new \DateTimeImmutable())->format('Y-m-d H:i:s'),
'reason' => mb_strtolower(str_replace(' ', '_', $reason)),
'user_id' => $userId,
'ip_address' => $_SERVER['REMOTE_ADDR'] ?? 'unknown',
'exception' => $exception,
];
if ($tokenName !== null) {
$context['token_name'] = $tokenName;
}
if ($tokenType !== null) {
$context['token_type'] = $tokenType;
}
$this->logger->warning("Token {$event} failed", $context);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Adaptation/Log/Logger.php | centreon/src/Adaptation/Log/Logger.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Adaptation\Log;
use Adaptation\Log\Adapter\MonologAdapter;
use Adaptation\Log\Enum\LogChannelEnum;
use Adaptation\Log\Exception\LoggerException;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
final readonly class Logger implements LoggerInterface
{
public const ROTATING_MAX_FILES = 7;
public const DATE_FORMAT = \DateTimeInterface::RFC3339;
private function __construct(private LoggerInterface $logger)
{
}
public static function create(LogChannelEnum $channel): LoggerInterface
{
try {
return new self(MonologAdapter::create($channel));
} catch (LoggerException $e) {
error_log(sprintf('Create logger failed: %s', $e->getMessage()));
return new self(new NullLogger());
}
}
public function emergency(\Stringable|string $message, array $context = []): void
{
$this->logger->emergency($message, $context);
}
public function alert(\Stringable|string $message, array $context = []): void
{
$this->logger->alert($message, $context);
}
public function critical(\Stringable|string $message, array $context = []): void
{
$this->logger->critical($message, $context);
}
public function error(\Stringable|string $message, array $context = []): void
{
$this->logger->error($message, $context);
}
public function warning(\Stringable|string $message, array $context = []): void
{
$this->logger->warning($message, $context);
}
public function notice(\Stringable|string $message, array $context = []): void
{
$this->logger->notice($message, $context);
}
public function info(\Stringable|string $message, array $context = []): void
{
$this->logger->info($message, $context);
}
public function debug(\Stringable|string $message, array $context = []): void
{
$this->logger->debug($message, $context);
}
public function log($level, \Stringable|string $message, array $context = []): void
{
try {
$this->logger->log($level, $message, $context);
} catch (\Throwable $e) {
error_log($e->getMessage());
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Adaptation/Log/Enum/LogChannelEnum.php | centreon/src/Adaptation/Log/Enum/LogChannelEnum.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Adaptation\Log\Enum;
enum LogChannelEnum: string
{
case PASSWORD = 'password';
case TOKEN = 'token';
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Adaptation/Log/Exception/LoggerException.php | centreon/src/Adaptation/Log/Exception/LoggerException.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Adaptation\Log\Exception;
final class LoggerException extends \LogicException
{
public function __construct(string $message, ?\Throwable $previous = null)
{
parent::__construct($message, 0, $previous);
}
public static function channelNotConfigured(string $channel): self
{
return new self(sprintf('The logging channel "%s" is not configured.', $channel));
}
public static function loggerCreationFailed(string $channel, \Throwable $e): self
{
return new self(sprintf('Logger creation failed for this channel "%s".', $channel), $e);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Adaptation/Log/Adapter/MonologAdapter.php | centreon/src/Adaptation/Log/Adapter/MonologAdapter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Adaptation\Log\Adapter;
use Adaptation\Log\Enum\LogChannelEnum;
use Adaptation\Log\Exception\LoggerException;
use Adaptation\Log\Logger;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\StreamHandler;
use Monolog\Level;
use Monolog\Logger as MonologLogger;
use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;
final readonly class MonologAdapter implements LoggerInterface
{
/**
* @throws LoggerException
*/
private function __construct(
private MonologLogger $logger,
private LogChannelEnum $channel,
) {
$this->createLoggerFromChannel();
}
/**
* @throws LoggerException
*/
public static function create(LogChannelEnum $channel): LoggerInterface
{
$logger = new MonologLogger($channel->value);
return new self($logger, $channel);
}
public function emergency(\Stringable|string $message, array $context = []): void
{
$this->logger->emergency($message, $context);
}
public function alert(\Stringable|string $message, array $context = []): void
{
$this->logger->alert($message, $context);
}
public function critical(\Stringable|string $message, array $context = []): void
{
$this->logger->critical($message, $context);
}
public function error(\Stringable|string $message, array $context = []): void
{
$this->logger->error($message, $context);
}
public function warning(\Stringable|string $message, array $context = []): void
{
$this->logger->warning($message, $context);
}
public function notice(\Stringable|string $message, array $context = []): void
{
$this->logger->notice($message, $context);
}
public function info(\Stringable|string $message, array $context = []): void
{
$this->logger->info($message, $context);
}
public function debug(\Stringable|string $message, array $context = []): void
{
$this->logger->debug($message, $context);
}
/**
* @param 'alert'|'critical'|'debug'|'emergency'|'error'|'info'|'notice'|'warning'|Level $level
*
* @throws LoggerException
*/
public function log(mixed $level, \Stringable|string $message, array $context = []): void
{
try {
$this->logger->log($level, $message, $context);
} catch (\InvalidArgumentException $e) {
throw new LoggerException(
message: sprintf('Logging failed: %s', $e->getMessage()),
previous: $e,
);
}
}
/**
* @throws LoggerException
*/
private function createLoggerFromChannel(): void
{
try {
$handler = match ($this->channel) {
LogChannelEnum::PASSWORD => new StreamHandler(
$this->getLogFileFromChannel(LogChannelEnum::PASSWORD),
LogLevel::INFO
),
LogChannelEnum::TOKEN => new StreamHandler(
$this->getLogFileFromChannel(LogChannelEnum::TOKEN),
LogLevel::INFO
),
// TODO if another channel is needed, uncomment the following line
// default => throw LoggerException::channelNotConfigured($this->channel->value),
};
$handler->setFormatter(new LineFormatter(null, Logger::DATE_FORMAT));
$this->logger->pushHandler($handler);
} catch (\InvalidArgumentException $e) {
throw LoggerException::loggerCreationFailed($this->channel->value, $e);
}
}
/**
* Pattern: _CENTREON_LOG_/<APP_ENV>.<channel>.log
* - _CENTREON_LOG_ is defined in the main Centreon configuration file (centreon.conf.php)
* - <APP_ENV> is defined by the current Symfony mode (prod, dev, test)
* - <channel> is the channel name defined in LogChannelEnum
* Example: /var/log/centreon/prod.password.log
*/
private function getLogFileFromChannel(LogChannelEnum $channelEnum): string
{
$appEnv = (isset($_SERVER['APP_ENV']) && is_scalar($_SERVER['APP_ENV']))
? (string) $_SERVER['APP_ENV'] : 'prod';
return sprintf(
'%s/%s.%s.log',
_CENTREON_LOG_,
$appEnv,
(string) $channelEnum->value
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonLegacy/ServiceProvider.php | centreon/src/CentreonLegacy/ServiceProvider.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonLegacy;
use Centreon\Infrastructure\Provider\AutoloadServiceProviderInterface;
use CentreonLegacy\Core\Module;
use CentreonLegacy\Core\Module\License;
use CentreonLegacy\Core\Utils;
use CentreonLegacy\Core\Widget;
use Pimple\Container;
use Pimple\Psr11\ServiceLocator;
use Symfony\Component\Finder\Finder;
class ServiceProvider implements AutoloadServiceProviderInterface
{
public const CONFIGURATION = 'configuration';
public const CENTREON_REST_HTTP = 'centreon.rest.http';
public const CENTREON_LEGACY_UTILS = 'centreon.legacy.utils';
public const CENTREON_LEGACY_MODULE_HEALTHCHECK = 'centreon.legacy.module.healthcheck';
public const CENTREON_LEGACY_MODULE_INFORMATION = 'centreon.legacy.module.information';
public const CENTREON_LEGACY_MODULE_INSTALLER = 'centreon.legacy.module.installer';
public const CENTREON_LEGACY_MODULE_UPGRADER = 'centreon.legacy.module.upgrader';
public const CENTREON_LEGACY_MODULE_REMOVER = 'centreon.legacy.module.remover';
public const CENTREON_LEGACY_MODULE_LICENSE = 'centreon.legacy.module.license';
public const CENTREON_LEGACY_LICENSE = 'centreon.legacy.license';
public const CENTREON_LEGACY_WIDGET_INFORMATION = 'centreon.legacy.widget.information';
public const CENTREON_LEGACY_WIDGET_INSTALLER = 'centreon.legacy.widget.installer';
public const CENTREON_LEGACY_WIDGET_UPGRADER = 'centreon.legacy.widget.upgrader';
public const CENTREON_LEGACY_WIDGET_REMOVER = 'centreon.legacy.widget.remover';
public const SYMFONY_FINDER = 'sf.finder';
/**
* Register CentreonLegacy services.
*
* @param Container $pimple
*/
public function register(Container $pimple): void
{
$pimple[static::CENTREON_LEGACY_UTILS] = function (Container $container): Utils\Utils {
$services = [
'realtime_db',
'configuration_db',
'configuration',
];
$locator = new ServiceLocator($container, $services);
return new Utils\Utils($locator);
};
$pimple[static::SYMFONY_FINDER] = function (Container $container): Finder {
return new Finder();
};
$this->registerConfiguration($pimple);
$this->registerRestHttp($pimple);
$this->registerModule($pimple);
$this->registerWidget($pimple);
}
public static function order(): int
{
return 0;
}
protected function registerConfiguration(Container $pimple)
{
$pimple[static::CONFIGURATION] = function (Container $container): Core\Configuration\Configuration {
global $conf_centreon, $centreon_path;
return new Core\Configuration\Configuration(
$conf_centreon,
$centreon_path,
$container[static::SYMFONY_FINDER]
);
};
}
/**
* @param Container $pimple
*/
protected function registerRestHttp(Container $pimple)
{
$pimple[static::CENTREON_REST_HTTP] = function (Container $container) {
return function ($contentType = 'application/json', $logFile = null) {
// @codeCoverageIgnoreStart
return new \CentreonRestHttp($contentType, $logFile); // @codeCoverageIgnoreEnd
};
};
}
protected function registerModule(Container $pimple)
{
$pimple[static::CENTREON_LEGACY_MODULE_HEALTHCHECK] = function (Container $container): Module\Healthcheck {
$services = [
'configuration',
];
$locator = new ServiceLocator($container, $services);
return new Module\Healthcheck($locator);
};
$pimple[static::CENTREON_LEGACY_MODULE_INFORMATION] = function (Container $container): Module\Information {
$services = [
'finder',
'filesystem',
'configuration_db',
ServiceProvider::CENTREON_LEGACY_UTILS,
ServiceProvider::CENTREON_LEGACY_MODULE_LICENSE,
];
$locator = new ServiceLocator($container, $services);
return new Module\Information($locator);
};
$pimple[static::CENTREON_LEGACY_MODULE_INSTALLER] = $pimple->factory(function (Container $container) {
$services = [
'filesystem',
'configuration_db',
ServiceProvider::CENTREON_LEGACY_UTILS,
ServiceProvider::CENTREON_LEGACY_MODULE_INFORMATION,
];
$locator = new ServiceLocator($container, $services);
$service = function ($moduleName) use ($locator): Module\Installer {
return new Module\Installer($locator, null, $moduleName);
};
return $service;
});
$pimple[static::CENTREON_LEGACY_MODULE_UPGRADER] = $pimple->factory(function (Container $container) {
$services = [
'finder',
'filesystem',
'configuration_db',
ServiceProvider::CENTREON_LEGACY_UTILS,
ServiceProvider::CENTREON_LEGACY_MODULE_INFORMATION,
];
$locator = new ServiceLocator($container, $services);
$service = function ($moduleName, $moduleId) use ($locator): Module\Upgrader {
return new Module\Upgrader($locator, null, $moduleName, null, $moduleId);
};
return $service;
});
$pimple[static::CENTREON_LEGACY_MODULE_REMOVER] = $pimple->factory(function (Container $container) {
$services = [
'filesystem',
'configuration_db',
ServiceProvider::CENTREON_LEGACY_UTILS,
ServiceProvider::CENTREON_LEGACY_MODULE_INFORMATION,
];
$locator = new ServiceLocator($container, $services);
$service = function ($moduleName, $moduleId) use ($locator): Module\Remover {
return new Module\Remover($locator, null, $moduleName, null, $moduleId);
};
return $service;
});
$pimple[static::CENTREON_LEGACY_MODULE_LICENSE] = $pimple->factory(function (Container $container) {
$services = [
ServiceProvider::CENTREON_LEGACY_MODULE_HEALTHCHECK,
];
$locator = new ServiceLocator($container, $services);
return new License($locator);
});
// alias to centreon.legacy.module.license service
$pimple[static::CENTREON_LEGACY_LICENSE] = function (Container $container): License {
return $container[ServiceProvider::CENTREON_LEGACY_MODULE_LICENSE];
};
}
protected function registerWidget(Container $pimple)
{
$pimple[static::CENTREON_LEGACY_WIDGET_INFORMATION] = function (Container $container): Widget\Information {
$services = [
'finder',
'filesystem',
'configuration_db',
ServiceProvider::CENTREON_LEGACY_UTILS,
];
$locator = new ServiceLocator($container, $services);
return new Widget\Information($locator);
};
$pimple[static::CENTREON_LEGACY_WIDGET_INSTALLER] = $pimple->factory(function (Container $container) {
$services = [
'configuration_db',
ServiceProvider::CENTREON_LEGACY_UTILS,
ServiceProvider::CENTREON_LEGACY_WIDGET_INFORMATION,
];
$locator = new ServiceLocator($container, $services);
$service = function ($widgetDirectory) use ($locator): Widget\Installer {
return new Widget\Installer($locator, null, $widgetDirectory, null);
};
return $service;
});
$pimple[static::CENTREON_LEGACY_WIDGET_UPGRADER] = $pimple->factory(function (Container $container) {
$services = [
'configuration_db',
ServiceProvider::CENTREON_LEGACY_UTILS,
ServiceProvider::CENTREON_LEGACY_WIDGET_INFORMATION,
];
$locator = new ServiceLocator($container, $services);
$service = function ($widgetDirectory) use ($locator): Widget\Upgrader {
return new Widget\Upgrader($locator, null, $widgetDirectory, null);
};
return $service;
});
$pimple[static::CENTREON_LEGACY_WIDGET_REMOVER] = $pimple->factory(function (Container $container) {
$services = [
'configuration_db',
ServiceProvider::CENTREON_LEGACY_UTILS,
ServiceProvider::CENTREON_LEGACY_WIDGET_INFORMATION,
];
$locator = new ServiceLocator($container, $services);
$service = function ($widgetDirectory) use ($locator): Widget\Remover {
return new Widget\Remover($locator, null, $widgetDirectory, null);
};
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/CentreonLegacy/Core/Utils/Utils.php | centreon/src/CentreonLegacy/Core/Utils/Utils.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonLegacy\Core\Utils;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\ContainerInterface;
use Psr\Container\NotFoundExceptionInterface;
class Utils
{
/** @var ContainerInterface */
protected $services;
/**
* Construct.
*
* @param ContainerInterface $services
*/
public function __construct(ContainerInterface $services)
{
$this->services = $services;
}
/**
* Require configuration file.
*
* @param string $configurationFile
* @param string $type
*
* @return array
*/
public function requireConfiguration($configurationFile, $type = 'install')
{
$configuration = [];
if ($type == 'install') {
$module_conf = [];
require $configurationFile;
$configuration = $module_conf;
} elseif ($type == 'upgrade') {
$upgrade_conf = [];
require $configurationFile;
$configuration = $upgrade_conf;
}
return $configuration;
}
/**
* @param string $fileName
* @param array $customMacros
* @param mixed $monitoring
*
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
* @throws \Exception
*/
public function executeSqlFile($fileName, $customMacros = [], $monitoring = false): void
{
$dbName = 'configuration_db';
if ($monitoring) {
$dbName = 'realtime_db';
}
if (! file_exists($fileName)) {
throw new \Exception('Cannot execute sql file "' . $fileName . '" : File does not exist.');
}
$file = fopen($fileName, 'r');
$str = '';
$delimiter = ';';
while (! feof($file)) {
$line = fgets($file);
if (! preg_match('/^(--|#)/', $line)) {
if (preg_match('/DELIMITER\s+(\S+)/i', $line, $matches)) {
$delimiter = $matches[1];
continue;
}
$pos = strrpos($line, $delimiter);
$str .= $line;
if ($pos !== false) {
$str = rtrim($this->replaceMacros($str, $customMacros));
if ($delimiter !== ';') {
$str = preg_replace('/' . preg_quote($delimiter, '/') . '$/', '', $str);
}
$this->services->get($dbName)->query($str);
$str = '';
}
}
}
fclose($file);
}
/**
* @param string $fileName
*
* @throws \Exception
*/
public function executePhpFile($fileName): void
{
if (! file_exists($fileName)) {
throw new \Exception('Cannot execute php file "' . $fileName . '" : File does not exist.');
}
// init parameters to be compatible with old module upgrade scripts
$pearDB = $this->services->get('configuration_db');
$pearDBStorage = $this->services->get('realtime_db');
$centreon_path = $this->services->get('configuration')->get('centreon_path');
require_once $fileName;
}
/**
* @param string $content
* @param array $customMacros
*
* @return string
*/
public function replaceMacros($content, $customMacros = [])
{
$macros = [
'DB_CENTREON' => $this->services->get('configuration')->get('db'),
'DB_CENTSTORAGE' => $this->services->get('configuration')->get('dbcstg'),
];
if (count($customMacros)) {
$macros = array_merge($macros, $customMacros);
}
foreach ($macros as $name => $value) {
$value ??= '';
$content = str_replace('@' . $name . '@', $value, $content);
}
return $content;
}
public function xmlIntoArray($path)
{
$xml = simplexml_load_file($path);
return $this->objectIntoArray($xml);
}
/**
* @param array|object $arrObjData
* @param array $skippedKeys
*
* @return string
*/
public function objectIntoArray($arrObjData, $skippedKeys = [])
{
$arrData = [];
if (is_object($arrObjData)) {
$arrObjData = get_object_vars($arrObjData);
}
if (is_array($arrObjData)) {
foreach ($arrObjData as $index => $value) {
if (is_object($value) || is_array($value)) {
$value = self::objectIntoArray($value, $skippedKeys);
}
if (in_array($index, $skippedKeys)) {
continue;
}
$arrData[$index] = $value;
}
}
if ($arrData === []) {
$arrData = '';
}
return $arrData;
}
/**
* @param $endPath
*
* @return bool|string
*/
public function buildPath($endPath)
{
return realpath(__DIR__ . '/../../../../www/' . $endPath);
}
/**
* @param $password
* @param string $algo
*
* @return string
*/
public function encodePass($password, $algo = 'md5'): string
{
/*
* Users passwords must be verified as md5 encrypted
* before they can be encrypted as bcrypt.
*/
if ($algo === 'md5') {
return 'md5__' . md5($password);
}
return password_hash($password, PASSWORD_BCRYPT);
}
/**
* @param $pattern
*/
public function detectPassPattern($pattern)
{
$patternData = explode('__', $pattern);
if (isset($patternData[1])) {
return $patternData[0];
}
return;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonLegacy/Core/Utils/Factory.php | centreon/src/CentreonLegacy/Core/Utils/Factory.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonLegacy\Core\Utils;
use CentreonLegacy\ServiceProvider;
/**
* @deprecated since version 18.10.4
*/
class Factory
{
/** @var \Pimple\Container */
protected $dependencyInjector;
/**
* @param \Pimple\Container $dependencyInjector
*/
public function __construct(\Pimple\Container $dependencyInjector)
{
$this->dependencyInjector = $dependencyInjector;
}
/**
* @return Utils
*/
public function newUtils()
{
return $this->dependencyInjector[ServiceProvider::CENTREON_LEGACY_UTILS];
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonLegacy/Core/Module/Healthcheck.php | centreon/src/CentreonLegacy/Core/Module/Healthcheck.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonLegacy\Core\Module;
use CentreonLegacy\ServiceProvider;
use DateTime;
use Psr\Container\ContainerInterface;
/**
* Check module requirements and health.
*/
class Healthcheck
{
/** @var string Path to the module */
protected $modulePath;
/** @var array|null Collect error messages after check */
protected $messages;
/** @var array|null Collect a custom action after check */
protected $customAction;
/** @var DateTime|null Collect date and time of a license expiration */
protected $licenseExpiration;
/**
* Construct.
*
* @param ContainerInterface $services
*/
public function __construct(ContainerInterface $services)
{
$this->modulePath = $services->get(ServiceProvider::CONFIGURATION)
->getModulePath();
}
/**
* Check module requirements and health.
*
* @param string $module
*
* @throws Exception\HealthcheckNotFoundException
* @throws Exception\HealthcheckCriticalException
* @throws Exception\HealthcheckWarningException
*
* @return bool|null
*/
public function check($module): ?bool
{
// reset messages stack
$this->reset();
if (! preg_match('/^(?!\.)/', $module)) {
throw new Exception\HealthcheckNotFoundException("Incorrect module name {$module}");
}
if (! is_dir($this->modulePath . $module)) {
throw new Exception\HealthcheckNotFoundException("Module did not exist {$this->modulePath} {$module}");
}
$checklistDir = $this->modulePath . $module . '/checklist/';
$warning = false;
$critical = false;
if (file_exists($checklistDir . 'requirements.php')) {
$message = [];
$licenseExpiration = null;
$customAction = null;
$this->getRequirements($checklistDir, $message, $customAction, $warning, $critical, $licenseExpiration);
// Necessary to implement the expiration date column in list modules page
if (! empty($licenseExpiration)) {
$this->licenseExpiration = new DateTime(date(DateTime::W3C, $licenseExpiration));
}
if (! $critical && ! $warning) { // critical: FALSE, warning: FALSE
$this->setCustomAction($customAction);
return true;
}
$this->setMessages($message);
if (! $critical && $warning) { // critical: FALSE, warning: TRUE
throw new Exception\HealthcheckWarningException();
}
// critical: TRUE
throw new Exception\HealthcheckCriticalException();
}
throw new Exception\HealthcheckNotFoundException('The module\'s requirements did not exist');
}
/**
* Made the check method compatible with moduleDependenciesValidator.
*
* @param string $module
*
* @return array|null
*/
public function checkPrepareResponse($module): ?array
{
$result = null;
try {
$this->check($module);
$result = [
'status' => 'ok',
];
if ($this->getCustomAction()) {
$result = array_merge($result, $this->getCustomAction());
}
} catch (Exception\HealthcheckCriticalException $ex) {
$result = [
'status' => 'critical',
];
if ($this->getMessages()) {
$result = array_merge($result, [
'message' => $this->getMessages(),
]);
}
} catch (Exception\HealthcheckWarningException $ex) {
$result = [
'status' => 'warning',
];
if ($this->getMessages()) {
$result = array_merge($result, [
'message' => $this->getMessages(),
]);
}
} catch (Exception\HealthcheckNotFoundException $ex) {
$result = [
'status' => 'notfound',
];
} catch (\Exception $ex) {
$result = [
'status' => 'critical',
'message' => [
'ErrorMessage' => $ex->getMessage(),
'Solution' => '',
],
];
}
if ($this->getLicenseExpiration()) {
$result['licenseExpiration'] = $this->getLicenseExpiration()->getTimestamp();
}
return $result;
}
/**
* Reset collected data after check.
*/
public function reset(): void
{
$this->messages = null;
$this->customAction = null;
$this->licenseExpiration = null;
}
public function getMessages(): ?array
{
return $this->messages;
}
public function getCustomAction(): ?array
{
return $this->customAction;
}
public function getLicenseExpiration(): ?DateTime
{
return $this->licenseExpiration;
}
/**
* Load a file with requirements.
*
* @codeCoverageIgnore
*
* @param string $checklistDir
* @param array $message
* @param array $customAction
* @param bool $warning
* @param bool $critical
* @param int $licenseExpiration
*/
protected function getRequirements(
$checklistDir,
&$message,
&$customAction,
&$warning,
&$critical,
&$licenseExpiration,
) {
global $centreon_path;
require_once $checklistDir . 'requirements.php';
}
protected function setMessages(array $messages)
{
foreach ($messages as $errorMessage) {
$this->messages = [
'ErrorMessage' => $errorMessage['ErrorMessage'],
'Solution' => $errorMessage['Solution'],
];
}
}
protected function setCustomAction(?array $customAction = null)
{
if ($customAction !== null) {
$this->customAction = [
'customAction' => $customAction['action'],
'customActionName' => $customAction['name'],
];
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonLegacy/Core/Module/Module.php | centreon/src/CentreonLegacy/Core/Module/Module.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonLegacy\Core\Module;
use CentreonLegacy\Core\Utils\Utils;
use CentreonLegacy\ServiceProvider;
use Psr\Container\ContainerInterface;
class Module
{
/** @var Information */
protected $informationObj;
/** @var string */
protected $moduleName;
/** @var int */
protected $moduleId;
/** @var Utils */
protected $utils;
/** @var array */
protected $moduleConfiguration;
/** @var ContainerInterface */
protected $services;
/**
* @param ContainerInterface $services
* @param Information $informationObj
* @param string $moduleName
* @param Utils $utils
* @param int $moduleId
*/
public function __construct(
ContainerInterface $services,
?Information $informationObj = null,
$moduleName = '',
?Utils $utils = null,
$moduleId = null,
) {
$this->moduleId = $moduleId;
$this->services = $services;
$this->informationObj = $informationObj ?? $services->get(ServiceProvider::CENTREON_LEGACY_MODULE_INFORMATION);
$this->moduleName = $moduleName;
$this->utils = $utils ?? $services->get(ServiceProvider::CENTREON_LEGACY_UTILS);
$this->moduleConfiguration = $this->informationObj->getConfiguration($this->moduleName);
}
/**
* @param string $moduleName
*
* @return string
*/
public function getModulePath($moduleName = '')
{
return $this->utils->buildPath('/modules/' . $moduleName);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonLegacy/Core/Module/Information.php | centreon/src/CentreonLegacy/Core/Module/Information.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonLegacy\Core\Module;
use CentreonLegacy\Core\Utils\Utils;
use CentreonLegacy\ServiceProvider;
use Psr\Container\ContainerInterface;
class Information
{
/** @var License */
protected $licenseObj;
/** @var ContainerInterface */
protected $services;
/** @var Utils */
protected $utils;
/** @var array */
protected $cachedModulesList = [];
/** @var bool */
protected $hasModulesForUpgrade = false;
/** @var bool */
protected $hasModulesForInstallation = false;
/**
* @param ContainerInterface $services
* @param License $licenseObj
* @param Utils $utils
*/
public function __construct(
ContainerInterface $services,
?License $licenseObj = null,
?Utils $utils = null,
) {
$this->services = $services;
$this->licenseObj = $licenseObj ?? $services->get(ServiceProvider::CENTREON_LEGACY_MODULE_LICENSE);
$this->utils = $utils ?? $services->get(ServiceProvider::CENTREON_LEGACY_UTILS);
}
/**
* Get module configuration from file.
*
* @param string $moduleName
*
* @return array
*/
public function getConfiguration($moduleName)
{
$configurationFile = $this->getModulePath($moduleName) . '/conf.php';
$configuration = $this->utils->requireConfiguration($configurationFile);
return $configuration[$moduleName];
}
/**
* Get module configuration from file.
*
* @param int $moduleId
*
* @return mixed
*/
public function getNameById($moduleId)
{
$query = 'SELECT name '
. 'FROM modules_informations '
. 'WHERE id = :id';
$sth = $this->services->get('configuration_db')->prepare($query);
$sth->bindParam(':id', $moduleId, \PDO::PARAM_INT);
$sth->execute();
$name = null;
if ($row = $sth->fetch()) {
$name = $row['name'];
}
return $name;
}
/**
* Get list of installed modules.
*
* @return array
*/
public function getInstalledList()
{
$query = 'SELECT * '
. 'FROM modules_informations ';
$result = $this->services->get('configuration_db')->query($query);
$modules = $result->fetchAll();
$installedModules = [];
foreach ($modules as $module) {
$installedModules[$module['name']] = $module;
}
return $installedModules;
}
/**
* @param string $moduleName
*
* @return array
*/
public function getInstalledInformation($moduleName)
{
$query = 'SELECT * '
. 'FROM modules_informations '
. 'WHERE name = :name';
$sth = $this->services->get('configuration_db')->prepare($query);
$sth->bindParam(':name', $moduleName, \PDO::PARAM_STR);
$sth->execute();
return $sth->fetch();
}
/**
* Get list of modules (installed or not).
*
* @return array
*/
public function getList()
{
$installedModules = $this->getInstalledList();
$availableModules = $this->getAvailableList();
$modules = [];
foreach ($availableModules as $name => $properties) {
$modules[$name] = $properties;
$modules[$name]['source_available'] = true;
$modules[$name]['is_installed'] = false;
$modules[$name]['upgradeable'] = false;
$modules[$name]['installed_version'] = _('N/A');
$modules[$name]['available_version'] = $modules[$name]['mod_release'];
unset($modules[$name]['release']);
if (isset($installedModules[$name]['mod_release'])) {
$modules[$name]['id'] = $installedModules[$name]['id'];
$modules[$name]['is_installed'] = true;
$modules[$name]['installed_version'] = $installedModules[$name]['mod_release'];
$moduleIsUpgradeable = $this->isUpgradeable(
$modules[$name]['available_version'],
$modules[$name]['installed_version']
);
$modules[$name]['upgradeable'] = $moduleIsUpgradeable;
$this->hasModulesForUpgrade = $moduleIsUpgradeable ?: $this->hasModulesForUpgrade;
}
}
foreach ($installedModules as $name => $properties) {
if (! isset($modules[$name])) {
$modules[$name] = $properties;
$modules[$name]['is_installed'] = true;
$modules[$name]['source_available'] = false;
}
}
$this->hasModulesForInstallation = count($availableModules) > count($installedModules);
$this->cachedModulesList = $modules;
return $modules;
}
/**
* @param string $moduleName
*
* @return string
*/
public function getModulePath($moduleName = '')
{
return $this->utils->buildPath('/modules/' . $moduleName) . '/';
}
public function hasModulesForUpgrade()
{
return $this->hasModulesForUpgrade;
}
public function getUpgradeableList()
{
$list = $this->cachedModulesList === [] ? $this->getList() : $this->cachedModulesList;
return array_filter($list, function ($widget) {
return $widget['upgradeable'];
});
}
public function hasModulesForInstallation()
{
return $this->hasModulesForInstallation;
}
public function getInstallableList()
{
$list = $this->cachedModulesList === [] ? $this->getList() : $this->cachedModulesList;
return array_filter($list, function ($widget) {
return ! $widget['is_installed'];
});
}
/**
* Get list of available modules.
*
* @return array
*/
private function getAvailableList()
{
$list = [];
$modulesPath = $this->getModulePath();
$modules = $this->services->get('finder')->directories()->depth('== 0')->in($modulesPath);
foreach ($modules as $module) {
$moduleName = $module->getBasename();
$modulePath = $modulesPath . $moduleName;
if (! $this->services->get('filesystem')->exists($modulePath . '/conf.php')) {
continue;
}
$configuration = $this->utils->requireConfiguration($modulePath . '/conf.php');
if (! isset($configuration[$moduleName])) {
continue;
}
$licenseFile = $modulePath . '/license/merethis_lic.zl';
$list[$moduleName] = $configuration[$moduleName];
$list[$moduleName]['license_expiration'] = $this->licenseObj->getLicenseExpiration($licenseFile);
}
return $list;
}
/**
* @param string $availableVersion
* @param string $installedVersion
*
* @return bool
*/
private function isUpgradeable($availableVersion, $installedVersion)
{
$comparisonResult = false;
$compare = version_compare($availableVersion, $installedVersion);
if ($compare == 1) {
$comparisonResult = true;
}
return $comparisonResult;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonLegacy/Core/Module/Upgrader.php | centreon/src/CentreonLegacy/Core/Module/Upgrader.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace CentreonLegacy\Core\Module;
use CentreonLog;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Process\Exception\ProcessFailedException;
use Symfony\Component\Process\Process;
class Upgrader extends Module
{
/**
* @return int
*/
public function upgrade()
{
$this->upgradeModuleConfiguration();
$moduleInstalledInformation = $this->informationObj->getInstalledInformation($this->moduleName);
// Process all directories within the /upgrade/ path.
// Entry name should be a version.
$upgradesPath = $this->getModulePath($this->moduleName) . '/upgrade/';
/** @var Finder $upgrades */
$upgrades = $this->services->get('finder');
$upgrades
->directories()
->depth('== 0')
->in($upgradesPath);
$orderedUpgrades = [];
foreach ($upgrades as $upgrade) {
$orderedUpgrades[] = $upgrade->getBasename();
}
usort($orderedUpgrades, 'version_compare');
foreach ($orderedUpgrades as $upgradeName) {
$upgradePath = $upgradesPath . $upgradeName;
if (! preg_match('/^(\d+\.\d+\.\d+)/', $upgradeName, $matches)) {
continue;
}
if (version_compare($moduleInstalledInformation['mod_release'], $upgradeName) >= 0) {
continue;
}
CentreonLog::create()->info(
CentreonLog::TYPE_UPGRADE,
sprintf('Starting upgrade process for %s module', $moduleInstalledInformation['name']),
[
'from' => $moduleInstalledInformation['mod_release'],
'to' => $upgradeName,
]
);
$this->upgradeVersion($upgradeName);
$moduleInstalledInformation['mod_release'] = $upgradeName;
$this->upgradePhpFiles($upgradePath, true);
$this->upgradeSqlFiles($upgradePath);
$this->upgradePhpFiles($upgradePath, false);
}
// finally, upgrade to current version
$this->upgradeVersion($this->moduleConfiguration['mod_release']);
// Clearing symfony cache to properly enable API routes.
$this->clearCache();
return $this->moduleId;
}
private function clearCache(): void
{
$process = new Process(['php', 'bin/console', 'cache:clear']);
$process->setWorkingDirectory(_CENTREON_PATH_);
$process->run();
if (! $process->isSuccessful()) {
throw new ProcessFailedException($process);
}
}
/**
* Upgrade module information except version.
*
* @throws \Exception
*
* @return mixed
*/
private function upgradeModuleConfiguration()
{
$configurationFile = $this->getModulePath($this->moduleName) . '/conf.php';
if (! $this->services->get('filesystem')->exists($configurationFile)) {
throw new \Exception('Module configuration file not found.');
}
$query = 'UPDATE modules_informations SET '
. '`name` = :name , '
. '`rname` = :rname , '
. '`is_removeable` = :is_removeable , '
. '`infos` = :infos , '
. '`author` = :author , '
. '`svc_tools` = :svc_tools , '
. '`host_tools` = :host_tools '
. 'WHERE id = :id';
$sth = $this->services->get('configuration_db')->prepare($query);
$sth->bindValue(':name', $this->moduleConfiguration['name'], \PDO::PARAM_STR);
$sth->bindValue(':rname', $this->moduleConfiguration['rname'], \PDO::PARAM_STR);
$sth->bindValue(':is_removeable', $this->moduleConfiguration['is_removeable'], \PDO::PARAM_STR);
$sth->bindValue(':infos', $this->moduleConfiguration['infos'], \PDO::PARAM_STR);
$sth->bindValue(':author', $this->moduleConfiguration['author'], \PDO::PARAM_STR);
$sth->bindValue(':svc_tools', $this->moduleConfiguration['svc_tools'] ?? '0', \PDO::PARAM_STR);
$sth->bindValue(':host_tools', $this->moduleConfiguration['host_tools'] ?? '0', \PDO::PARAM_STR);
$sth->bindValue(':id', $this->moduleId, \PDO::PARAM_INT);
$sth->execute();
return $this->moduleId;
}
/**
* @param string $version
*
* @return int
*/
private function upgradeVersion($version)
{
$query = 'UPDATE modules_informations SET '
. '`mod_release` = :mod_release '
. 'WHERE id = :id';
$sth = $this->services->get('configuration_db')->prepare($query);
$sth->bindValue(':mod_release', $version, \PDO::PARAM_STR);
$sth->bindValue(':id', $this->moduleId, \PDO::PARAM_INT);
$sth->execute();
return $this->moduleId;
}
/**
* @param string $path
*
* @return bool
*/
private function upgradeSqlFiles($path)
{
$installed = false;
$sqlFile = $path . '/sql/upgrade.sql';
if ($this->services->get('filesystem')->exists($sqlFile)) {
$this->utils->executeSqlFile($sqlFile);
$installed = true;
}
return $installed;
}
/**
* @param string $path
* @param bool $pre
*
* @return bool
*/
private function upgradePhpFiles($path, $pre = false)
{
$installed = false;
$phpFile = $path . '/php/upgrade';
$phpFile = $pre ? $phpFile . '.pre.php' : $phpFile . '.php';
if ($this->services->get('filesystem')->exists($phpFile)) {
$this->utils->executePhpFile($phpFile);
$installed = true;
}
return $installed;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonLegacy/Core/Module/License.php | centreon/src/CentreonLegacy/Core/Module/License.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonLegacy\Core\Module;
use CentreonLegacy\ServiceProvider;
use Psr\Container\ContainerInterface;
/**
* License service provide information about module licenses.
*/
class License extends Module
{
/** @var ContainerInterface */
protected $services;
/**
* Construct.
*
* @param ContainerInterface $services
*/
public function __construct(ContainerInterface $services)
{
$this->services = $services;
}
/**
* Get license expiration date.
*
* @param string $module
*
* @return string
*/
public function getLicenseExpiration($module): ?string
{
$healthcheck = $this->services->get(ServiceProvider::CENTREON_LEGACY_MODULE_HEALTHCHECK);
try {
$healthcheck->check($module);
} catch (\Exception $ex) {
}
if ($expiration = $healthcheck->getLicenseExpiration()) {
return $expiration->format(\DateTime::ISO8601);
}
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/CentreonLegacy/Core/Module/Remover.php | centreon/src/CentreonLegacy/Core/Module/Remover.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonLegacy\Core\Module;
class Remover extends Module
{
/**
* @return bool
*/
public function remove()
{
$this->removePhpFiles(true);
$this->removeSqlFiles();
$this->removePhpFiles(false);
$this->removeModuleConfiguration();
return true;
}
/**
* Remove module information except version.
*
* @throws \Exception
*
* @return mixed
*/
private function removeModuleConfiguration()
{
$configurationFile = $this->getModulePath($this->moduleName) . '/conf.php';
if (! $this->services->get('filesystem')->exists($configurationFile)) {
throw new \Exception('Module configuration file not found.');
}
$query = 'DELETE FROM modules_informations WHERE id = :id ';
$sth = $this->services->get('configuration_db')->prepare($query);
$sth->bindParam(':id', $this->moduleId, \PDO::PARAM_INT);
$sth->execute();
return true;
}
/**
* @return bool
*/
private function removeSqlFiles()
{
$removed = false;
$sqlFile = $this->getModulePath($this->moduleName) . '/sql/uninstall.sql';
if ($this->services->get('filesystem')->exists($sqlFile)) {
$this->utils->executeSqlFile($sqlFile);
$removed = true;
}
return $removed;
}
/**
* Indicates whether or not it is a pre-uninstall.
*
* @param bool $isPreUninstall
*
* @return bool
*/
private function removePhpFiles(bool $isPreUninstall)
{
$removed = false;
$phpFile = $this->getModulePath($this->moduleName)
. '/php/uninstall' . ($isPreUninstall ? '.pre' : '') . '.php';
if ($this->services->get('filesystem')->exists($phpFile)) {
$this->utils->executePhpFile($phpFile);
$removed = true;
}
return $removed;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonLegacy/Core/Module/Factory.php | centreon/src/CentreonLegacy/Core/Module/Factory.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonLegacy\Core\Module;
use CentreonLegacy\ServiceProvider;
/**
* @deprecated since version 18.10.4
*/
class Factory
{
/** @var \Pimple\Container */
protected $dependencyInjector;
/**
* @param \Pimple\Container $dependencyInjector
*/
public function __construct(\Pimple\Container $dependencyInjector)
{
$this->dependencyInjector = $dependencyInjector;
}
/**
* @return Information
*/
public function newInformation()
{
return $this->dependencyInjector[ServiceProvider::CENTREON_LEGACY_MODULE_INFORMATION];
}
/**
* @param string $moduleName
*
* @return Installer
*/
public function newInstaller($moduleName)
{
return $this->dependencyInjector[ServiceProvider::CENTREON_LEGACY_MODULE_INSTALLER]($moduleName);
}
/**
* @param string $moduleName
* @param int $moduleId
*
* @return Upgrader
*/
public function newUpgrader($moduleName, $moduleId)
{
return $this->dependencyInjector[ServiceProvider::CENTREON_LEGACY_MODULE_UPGRADER]($moduleName, $moduleId);
}
/**
* @param string $moduleName
* @param int $moduleId
*
* @return Remover
*/
public function newRemover($moduleName, $moduleId)
{
return $this->dependencyInjector[ServiceProvider::CENTREON_LEGACY_MODULE_REMOVER]($moduleName, $moduleId);
}
/**
* @return License
*/
public function newLicense()
{
return $this->dependencyInjector[ServiceProvider::CENTREON_LEGACY_MODULE_LICENSE];
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonLegacy/Core/Module/Installer.php | centreon/src/CentreonLegacy/Core/Module/Installer.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonLegacy\Core\Module;
class Installer extends Module
{
/**
* @return int
*/
public function install()
{
$id = $this->installModuleConfiguration();
$this->installPhpFiles(true);
$this->installSqlFiles();
$this->installPhpFiles(false);
return $id;
}
/**
* @return bool
*/
public function installSqlFiles()
{
$installed = false;
$sqlFile = $this->getModulePath($this->moduleName) . '/sql/install.sql';
if ($this->services->get('filesystem')->exists($sqlFile)) {
$this->utils->executeSqlFile($sqlFile);
$installed = true;
}
return $installed;
}
/**
* Indicates whether it is a pre-installation.
*
* @param bool $isPreInstallation
*
* @return bool
*/
public function installPhpFiles(bool $isPreInstallation)
{
$installed = false;
$phpFile = $this->getModulePath($this->moduleName)
. '/php/install' . ($isPreInstallation ? '.pre' : '') . '.php';
if ($this->services->get('filesystem')->exists($phpFile)) {
$this->utils->executePhpFile($phpFile);
$installed = true;
}
return $installed;
}
/**
* @throws \Exception
*
* @return int
*/
protected function installModuleConfiguration()
{
$configurationFile = $this->getModulePath($this->moduleName) . '/conf.php';
if (! $this->services->get('filesystem')->exists($configurationFile)) {
throw new \Exception('Module configuration file not found.');
}
$query = 'INSERT INTO modules_informations '
. '(`name` , `rname` , `mod_release` , `is_removeable` , `infos` , `author` , '
. '`svc_tools`, `host_tools`)'
. 'VALUES ( :name , :rname , :mod_release , :is_removeable , :infos , :author , '
. ':svc_tools , :host_tools )';
$sth = $this->services->get('configuration_db')->prepare($query);
$sth->bindParam(':name', $this->moduleConfiguration['name'], \PDO::PARAM_STR);
$sth->bindParam(':rname', $this->moduleConfiguration['rname'], \PDO::PARAM_STR);
$sth->bindParam(':mod_release', $this->moduleConfiguration['mod_release'], \PDO::PARAM_STR);
$sth->bindParam(':is_removeable', $this->moduleConfiguration['is_removeable'], \PDO::PARAM_STR);
$sth->bindParam(':infos', $this->moduleConfiguration['infos'], \PDO::PARAM_STR);
$sth->bindParam(':author', $this->moduleConfiguration['author'], \PDO::PARAM_STR);
$sth->bindParam(':svc_tools', $this->moduleConfiguration['svc_tools'], \PDO::PARAM_STR);
$sth->bindParam(':host_tools', $this->moduleConfiguration['host_tools'], \PDO::PARAM_STR);
$sth->execute();
$queryMax = 'SELECT MAX(id) as id FROM modules_informations';
$result = $this->services->get('configuration_db')->query($queryMax);
$lastId = 0;
if ($row = $result->fetchRow()) {
$lastId = $row['id'];
}
return $lastId;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonLegacy/Core/Module/Exception/HealthcheckNotFoundException.php | centreon/src/CentreonLegacy/Core/Module/Exception/HealthcheckNotFoundException.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonLegacy\Core\Module\Exception;
use RuntimeException;
class HealthcheckNotFoundException extends RuntimeException
{
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonLegacy/Core/Module/Exception/HealthcheckCriticalException.php | centreon/src/CentreonLegacy/Core/Module/Exception/HealthcheckCriticalException.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonLegacy\Core\Module\Exception;
use RuntimeException;
class HealthcheckCriticalException extends RuntimeException
{
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonLegacy/Core/Module/Exception/HealthcheckWarningException.php | centreon/src/CentreonLegacy/Core/Module/Exception/HealthcheckWarningException.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonLegacy\Core\Module\Exception;
use RuntimeException;
class HealthcheckWarningException extends RuntimeException
{
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonLegacy/Core/Configuration/Configuration.php | centreon/src/CentreonLegacy/Core/Configuration/Configuration.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonLegacy\Core\Configuration;
use CentreonModule\Infrastructure\Source\ModuleSource;
use CentreonModule\Infrastructure\Source\WidgetSource;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Yaml\Yaml;
/**
* Service provide configuration data.
*/
class Configuration
{
public const CENTREON_PATH = 'centreon_path';
/** @var array<string,string> the global configuration */
protected $configuration;
/** @var string the centreon path */
protected $centreonPath;
/** @var Finder */
protected $finder;
/**
* @param array<string,string> $configuration the global configuration
* @param string $centreonPath the centreon directory path
* @param Finder $finder
*/
public function __construct(array $configuration, string $centreonPath, Finder $finder)
{
$this->configuration = $this->useAppConstantForConfiguration($configuration);
$this->centreonPath = $centreonPath;
$this->finder = $finder;
}
/**
* Get configuration parameter by key.
*
* @param string $key the key parameter to get
*
* @return string the parameter value
*/
public function get(string $key)
{
$value = null;
// specific case for centreon path which is not stored in $conf_centreon
if ($key === static::CENTREON_PATH) {
$value = $this->centreonPath;
} elseif (isset($this->configuration[$key])) {
$value = $this->configuration[$key];
}
return $value;
}
public function getFinder(): ?Finder
{
return $this->finder;
}
public function getModulePath(): string
{
return $this->centreonPath . ModuleSource::PATH;
}
public function getWidgetPath(): string
{
return $this->centreonPath . WidgetSource::PATH;
}
/**
* Locate all yml files in src/ModuleFolder/config/ and parse them to array.
*
* @param string $moduleFolder
*
* @return array
*/
public function getModuleConfig(string $moduleFolder): array
{
$configVars = [];
$filesIterator = $this->getFinder()
->files()
->name('*.yml')
->depth('== 0')
->in($moduleFolder . '/config');
foreach ($filesIterator as $file) {
$configVars = array_merge($configVars, Yaml::parseFile($file->getPathName()));
}
return $configVars;
}
/**
* Use App Constant if defined instead of global values.
*
* @param array<string,string> $configuration
*
* @return array<string,string>
*/
private function useAppConstantForConfiguration(array $configuration): array
{
foreach (array_keys($configuration) as $parameterName) {
switch ($parameterName) {
case 'user':
$configuration[$parameterName] = defined('user')
? user
: $configuration[$parameterName];
break;
case 'password':
$configuration[$parameterName] = defined('password')
? password
: $configuration[$parameterName];
break;
case 'db':
$configuration[$parameterName] = defined('db')
? db
: $configuration[$parameterName];
break;
case 'dbcstg':
$configuration[$parameterName] = defined('dbcstg')
? dbcstg
: $configuration[$parameterName];
break;
case 'port':
$configuration[$parameterName] = defined('port')
? port
: $configuration[$parameterName];
break;
}
}
return $configuration;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonLegacy/Core/Menu/Menu.php | centreon/src/CentreonLegacy/Core/Menu/Menu.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonLegacy\Core\Menu;
class Menu
{
/** @var \CentreonDB The configuration database connection */
protected $db;
/** @var string|null The query filter for ACL */
protected $acl = null;
/** @var int|null The current topology page */
protected $currentPage = null;
/**
* Constructor.
*
* @param \CentreonDB $db The configuration database connection
* @param \CentreonUser $user The current user
*/
public function __construct($db, $user = null)
{
$this->db = $db;
if (! is_null($user)) {
$this->currentPage = $user->getCurrentPage();
if (! $user->access->admin) {
$this->acl = ' AND topology_page IN (' . $user->access->getTopologyString() . ') ';
}
}
}
/**
* Get all menu (level 1 to 3).
*
* array(
* "p1" => array(
* "label" => "<level_one_label>",
* "url" => "<path_to_php_file>"
* "active" => "<true|false>"
* "color" => "<color_code>"
* "children" => array(
* "_101" => array(
* "label" => "<level_two_label>",
* "url" => "<path_to_php_file>",
* "active" => "<true|false>"
* "children" => array(
* "<group_name>" => array(
* "_10101" => array(
* "label" => "level_three_label",
* "url" => "<path_to_php_file>"
* "active" => "<true|false>"
* )
* )
* )
* )
* )
* )
* )
*
* @return array The menu
*/
public function getMenu()
{
$groups = $this->getGroups();
$query = 'SELECT topology_name, topology_page, topology_url, topology_url_opt, '
. 'topology_group, topology_order, topology_parent, is_react '
. 'FROM topology '
. 'WHERE topology_show = "1" '
. 'AND topology_page IS NOT NULL';
if (! is_null($this->acl)) {
$query .= $this->acl;
}
$query .= ' ORDER BY topology_parent, topology_group, topology_order, topology_page';
$stmt = $this->db->prepare($query);
$stmt->execute();
$currentLevelOne = null;
$currentLevelTwo = null;
$currentLevelThree = null;
if (! is_null($this->currentPage)) {
$currentLevelOne = substr($this->currentPage, 0, 1);
$currentLevelTwo = substr($this->currentPage, 1, 2);
$currentLevelThree = substr($this->currentPage, 2, 2);
}
$menu = [];
while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
$active = false;
if (preg_match('/^(\d)$/', $row['topology_page'], $matches)) { // level 1
if (! is_null($currentLevelOne) && $currentLevelOne == $row['topology_page']) {
$active = true;
}
$menu['p' . $row['topology_page']] = [
'label' => _($row['topology_name']),
'menu_id' => $row['topology_name'],
'url' => $row['topology_url'],
'active' => $active,
'color' => $this->getColor($row['topology_page']),
'children' => [],
'options' => $row['topology_url_opt'],
'is_react' => $row['is_react'],
];
} elseif (preg_match('/^(\d)(\d\d)$/', $row['topology_page'], $matches)) { // level 2
if (! is_null($currentLevelTwo) && $currentLevelTwo == $row['topology_page']) {
$active = true;
}
/**
* Add prefix '_' to prevent json list to be reordered by
* the browser and to keep menu in order.
* This prefix will be remove by front-end.
*/
$menu['p' . $matches[1]]['children']['_' . $row['topology_page']] = [
'label' => _($row['topology_name']),
'url' => $row['topology_url'],
'active' => $active,
'children' => [],
'options' => $row['topology_url_opt'],
'is_react' => $row['is_react'],
];
} elseif (preg_match('/^(\d)(\d\d)(\d\d)$/', $row['topology_page'], $matches)) { // level 3
if (! is_null($currentLevelThree) && $currentLevelThree == $row['topology_page']) {
$active = true;
}
$levelTwo = $matches[1] . $matches[2];
$levelThree = [
'label' => _($row['topology_name']),
'url' => $row['topology_url'],
'active' => $active,
'options' => $row['topology_url_opt'],
'is_react' => $row['is_react'],
];
if (! is_null($row['topology_group']) && isset($groups[$levelTwo][$row['topology_group']])) {
/**
* Add prefix '_' to prevent json list to be reordered by
* the browser and to keep menu in order.
* This prefix will be remove by front-end.
*/
$menu['p' . $matches[1]]['children']['_' . $levelTwo]['children'][$groups[$levelTwo][$row['topology_group']]]['_' . $row['topology_page']] = $levelThree;
} else {
/**
* Add prefix '_' to prevent json list to be reordered by
* the browser and to keep menu in order.
* This prefix will be remove by front-end.
*/
$menu['p' . $matches[1]]['children']['_' . $levelTwo]['children']['Main Menu']['_' . $row['topology_page']] = $levelThree;
}
}
}
$stmt->closeCursor();
return $menu;
}
/**
* Get the list of groups.
*
* @return array The list of groups
*/
public function getGroups()
{
$query = 'SELECT topology_name, topology_parent, topology_group FROM topology '
. 'WHERE topology_show = "1" '
. 'AND topology_page IS NULL '
. 'ORDER BY topology_group, topology_order';
$result = $this->db->query($query);
$groups = [];
while ($row = $result->fetch(\PDO::FETCH_ASSOC)) {
$groups[$row['topology_parent']][$row['topology_group']] = _($row['topology_name']);
}
$result->closeCursor();
return $groups;
}
/**
* Get menu color.
*
* @param int $pageId The page id
*
* @return string color
*/
public function getColor($pageId)
{
switch ($pageId) {
case '1':
$color = '#2B9E93';
break;
case '2':
$color = '#85B446';
break;
case '3':
$color = '#E4932C';
break;
case '5':
$color = '#17387B';
break;
case '6':
$color = '#319ED5';
break;
default:
$color = '#319ED5';
break;
}
return $color;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonLegacy/Core/Install/Information.php | centreon/src/CentreonLegacy/Core/Install/Information.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonLegacy\Core\Install;
class Information
{
/** @var \Pimple\Container */
protected $dependencyInjector;
/**
* @param \Pimple\Container $dependencyInjector
*/
public function __construct(\Pimple\Container $dependencyInjector)
{
$this->dependencyInjector = $dependencyInjector;
}
public function getStep()
{
$step = 1;
$stepFile = __DIR__ . '/../../../../www/install/tmp/step.json';
if ($this->dependencyInjector['filesystem']->exists($stepFile)) {
$content = json_decode(file_get_contents($stepFile), true);
if (isset($content['step'])) {
$step = $content['step'];
}
}
return $step;
}
public function setStep($step): void
{
$stepDir = __DIR__ . '/../../../../www/install/tmp';
if (! $this->dependencyInjector['filesystem']->exists($stepDir)) {
$this->dependencyInjector['filesystem']->mkdir($stepDir);
}
$stepFile = $stepDir . '/step.json';
file_put_contents($stepFile, json_encode([
'step' => $step,
]));
}
public function getStepContent()
{
$content = '';
$step = $this->getStep();
$className = '\CentreonLegacy\Core\Install\Step\Step' . $step;
if (class_exists($className)) {
$stepObj = new $className($this->dependencyInjector);
$content = $stepObj->getContent();
}
return $content;
}
public function previousStepContent()
{
$step = $this->getStep() - 1;
$this->setStep($step);
return $this->getStepContent();
}
public function nextStepContent()
{
$step = $this->getStep() === '6Vault' ? 7 : $this->getStep() + 1;
$this->setStep($step);
return $this->getStepContent();
}
public function vaultStepContent()
{
$this->setStep('6Vault');
return $this->getStepContent();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonLegacy/Core/Install/Factory.php | centreon/src/CentreonLegacy/Core/Install/Factory.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonLegacy\Core\Install;
class Factory
{
/** @var \Pimple\Container */
protected $dependencyInjector;
/**
* @param \Pimple\Container $dependencyInjector
*/
public function __construct(\Pimple\Container $dependencyInjector)
{
$this->dependencyInjector = $dependencyInjector;
}
/**
* @return Information
*/
public function newInformation()
{
return new Information($this->dependencyInjector);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonLegacy/Core/Install/Step/Step5.php | centreon/src/CentreonLegacy/Core/Install/Step/Step5.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonLegacy\Core\Install\Step;
class Step5 extends AbstractStep
{
public function getContent()
{
$installDir = __DIR__ . '/../../../../../www/install';
require_once $installDir . '/steps/functions.php';
$template = getTemplate($installDir . '/steps/templates');
$parameters = $this->getAdminConfiguration();
$template->assign('title', _('Admin information'));
$template->assign('step', 5);
$template->assign('parameters', $parameters);
return $template->fetch('content.tpl');
}
public function setAdminConfiguration($parameters): void
{
$configurationFile = __DIR__ . '/../../../../../www/install/tmp/admin.json';
file_put_contents($configurationFile, json_encode($parameters));
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonLegacy/Core/Install/Step/Step8.php | centreon/src/CentreonLegacy/Core/Install/Step/Step8.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonLegacy\Core\Install\Step;
class Step8 extends AbstractStep
{
public function getContent()
{
$installDir = __DIR__ . '/../../../../../www/install';
require_once $installDir . '/steps/functions.php';
$template = getTemplate($installDir . '/steps/templates');
$modules = $this->getModules();
$widgets = $this->getWidgets();
$template->assign('title', _('Modules installation'));
$template->assign('step', 8);
$template->assign('modules', $modules);
$template->assign('widgets', $widgets);
return $template->fetch('content.tpl');
}
public function getModules()
{
$utilsFactory = new \CentreonLegacy\Core\Utils\Factory($this->dependencyInjector);
$moduleFactory = new \CentreonLegacy\Core\Module\Factory($this->dependencyInjector);
$module = $moduleFactory->newInformation();
return $module->getList();
}
/**
* Get the list of available widgets (installed on the system).
* List filled with the content of the config.xml widget files.
*
* @return array
*/
public function getWidgets()
{
$utilsFactory = new \CentreonLegacy\Core\Utils\Factory($this->dependencyInjector);
$widgetFactory = new \CentreonLegacy\Core\Widget\Factory($this->dependencyInjector);
$widget = $widgetFactory->newInformation();
return $widget->getList();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonLegacy/Core/Install/Step/Step9.php | centreon/src/CentreonLegacy/Core/Install/Step/Step9.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonLegacy\Core\Install\Step;
class Step9 extends AbstractStep
{
public function getContent()
{
$installDir = __DIR__ . '/../../../../../www/install';
require_once $installDir . '/steps/functions.php';
$template = getTemplate($installDir . '/steps/templates');
$backupDir = __DIR__ . '/../../../../../installDir';
$contents = '';
if (! is_dir($backupDir)) {
$contents .= '<br>Warning : The installation directory cannot be move. '
. 'Please create the directory ' . $backupDir . ' '
. 'and give it the rigths to apache user to write.';
}
$template->assign('title', _('Installation finished'));
$template->assign('step', 9);
$template->assign('finish', 1);
$template->assign('blockPreview', 1);
$template->assign('contents', $contents);
return $template->fetch('content.tpl');
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonLegacy/Core/Install/Step/Step4.php | centreon/src/CentreonLegacy/Core/Install/Step/Step4.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonLegacy\Core\Install\Step;
class Step4 extends AbstractStep
{
public function getContent()
{
$installDir = __DIR__ . '/../../../../../www/install';
require_once $installDir . '/steps/functions.php';
$template = getTemplate($installDir . '/steps/templates');
$parameters = $this->getBrokerParameters();
$template->assign('title', _('Broker module information'));
$template->assign('step', 4);
$template->assign('parameters', $parameters);
return $template->fetch('content.tpl');
}
public function getBrokerParameters()
{
$configuration = $this->getBaseConfiguration();
$file = __DIR__ . '/../../../../../www/install/var/brokers/centreon-broker';
$lines = explode("\n", file_get_contents($file));
$parameters = [];
foreach ($lines as $line) {
if (! $line || $line[0] == '#') {
continue;
}
[$key, $label, $required, $paramType, $default] = explode(';', $line);
$val = $default;
$configurationKey = strtolower(str_replace(' ', '_', $key));
if (isset($configuration[$configurationKey])) {
$val = $configuration[$configurationKey];
}
$parameters[$configurationKey] = [
'name' => $configurationKey,
'type' => $paramType,
'label' => $label,
'required' => $required,
'value' => $val,
];
}
return $parameters;
}
public function setBrokerConfiguration($parameters): void
{
$configurationFile = __DIR__ . '/../../../../../www/install/tmp/broker.json';
file_put_contents($configurationFile, json_encode($parameters));
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonLegacy/Core/Install/Step/Step6Vault.php | centreon/src/CentreonLegacy/Core/Install/Step/Step6Vault.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonLegacy\Core\Install\Step;
class Step6Vault extends AbstractStep
{
public function getContent()
{
$installDir = __DIR__ . '/../../../../../www/install';
require_once $installDir . '/steps/functions.php';
$template = getTemplate($installDir . '/steps/templates');
$parameters = $this->getVaultConfiguration();
$template->assign('title', _('Vault information'));
$template->assign('step', 6.1);
$template->assign('parameters', $parameters);
return $template->fetch('content.tpl');
}
public function setVaultConfiguration(array $configuration): void
{
$configurationFile = __DIR__ . '/../../../../../www/install/tmp/vault.json';
file_put_contents($configurationFile, json_encode($configuration));
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonLegacy/Core/Install/Step/Step6.php | centreon/src/CentreonLegacy/Core/Install/Step/Step6.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonLegacy\Core\Install\Step;
class Step6 extends AbstractStep
{
public function getContent()
{
$installDir = __DIR__ . '/../../../../../www/install';
require_once $installDir . '/steps/functions.php';
$template = getTemplate($installDir . '/steps/templates');
$parameters = $this->getDatabaseConfiguration();
$template->assign('title', _('Database information'));
$template->assign('step', 6);
$template->assign('parameters', $parameters);
return $template->fetch('content.tpl');
}
public function setDatabaseConfiguration($parameters): void
{
$configurationFile = __DIR__ . '/../../../../../www/install/tmp/database.json';
file_put_contents($configurationFile, json_encode($parameters));
}
public function setVersion($version): void
{
$configurationFile = __DIR__ . '/../../../../../www/install/tmp/version.json';
file_put_contents($configurationFile, json_encode($version));
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonLegacy/Core/Install/Step/Step1.php | centreon/src/CentreonLegacy/Core/Install/Step/Step1.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonLegacy\Core\Install\Step;
class Step1 extends AbstractStep
{
public function getContent()
{
$installDir = __DIR__ . '/../../../../../www/install';
require_once $installDir . '/steps/functions.php';
$template = getTemplate($installDir . '/steps/templates');
try {
checkPhpPrerequisite();
$this->setConfiguration();
} catch (\Exception $e) {
$template->assign('errorMessage', $e->getMessage());
$template->assign('validate', false);
}
$template->assign('title', _('Welcome to Centreon Setup'));
$template->assign('step', 1);
return $template->fetch('content.tpl');
}
public function setConfiguration(): void
{
$configurationFile = __DIR__ . '/../../../../../www/install/install.conf.php';
if (! $this->dependencyInjector['filesystem']->exists($configurationFile)) {
throw new \Exception('Configuration file "install.conf.php" does not exist.');
}
$conf_centreon = [];
require $configurationFile;
$tmpDir = __DIR__ . '/../../../../../www/install/tmp';
if (! $this->dependencyInjector['filesystem']->exists($tmpDir)) {
$this->dependencyInjector['filesystem']->mkdir($tmpDir);
}
file_put_contents($tmpDir . '/configuration.json', json_encode($conf_centreon));
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonLegacy/Core/Install/Step/Step3.php | centreon/src/CentreonLegacy/Core/Install/Step/Step3.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonLegacy\Core\Install\Step;
class Step3 extends AbstractStep
{
public function getContent()
{
$installDir = __DIR__ . '/../../../../../www/install';
require_once $installDir . '/steps/functions.php';
$template = getTemplate($installDir . '/steps/templates');
$parameters = $this->getEngineParameters();
$template->assign('title', _('Monitoring engine information'));
$template->assign('step', 3);
$template->assign('parameters', $parameters);
return $template->fetch('content.tpl');
}
public function getEngineParameters()
{
$configuration = $this->getBaseConfiguration();
$engineConfiguration = $this->getEngineConfiguration();
$file = __DIR__ . '/../../../../../www/install/var/engines/centreon-engine';
$lines = explode("\n", file_get_contents($file));
$parameters = [];
foreach ($lines as $line) {
if (! $line || $line[0] == '#') {
continue;
}
[$key, $label, $required, $paramType, $default] = explode(';', $line);
$val = $default;
$configurationKey = strtolower(str_replace(' ', '_', $key));
if (isset($engineConfiguration[$configurationKey])) {
$val = $engineConfiguration[$configurationKey];
} elseif (isset($configuration[$configurationKey])) {
$val = $configuration[$configurationKey];
}
$parameters[$configurationKey] = [
'name' => $configurationKey,
'type' => $paramType,
'label' => $label,
'required' => $required,
'value' => $val,
];
}
return $parameters;
}
public function setEngineConfiguration($parameters): void
{
$configurationFile = __DIR__ . '/../../../../../www/install/tmp/engine.json';
file_put_contents($configurationFile, json_encode($parameters));
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonLegacy/Core/Install/Step/Step7.php | centreon/src/CentreonLegacy/Core/Install/Step/Step7.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonLegacy\Core\Install\Step;
class Step7 extends AbstractStep
{
public function getContent()
{
$installDir = __DIR__ . '/../../../../../www/install';
require_once $installDir . '/steps/functions.php';
$template = getTemplate($installDir . '/steps/templates');
$parameters = $this->getDatabaseConfiguration();
$template->assign('title', _('Installation'));
$template->assign('step', 7);
$template->assign('parameters', $parameters);
return $template->fetch('content.tpl');
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonLegacy/Core/Install/Step/Step2.php | centreon/src/CentreonLegacy/Core/Install/Step/Step2.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonLegacy\Core\Install\Step;
class Step2 extends AbstractStep
{
public function getContent()
{
$installDir = __DIR__ . '/../../../../../www/install';
require_once $installDir . '/steps/functions.php';
$template = getTemplate($installDir . '/steps/templates');
$libs = $this->getPhpLib();
$validate = true;
if (count($libs['unloaded'])) {
$validate = false;
}
$template->assign('title', _('Dependency check up'));
$template->assign('step', 2);
$template->assign('libs', $libs);
$template->assign('validate', $validate);
return $template->fetch('content.tpl');
}
private function getPhpLib()
{
$libs = [
'loaded' => [],
'unloaded' => [],
];
$requiredLib = explode(
"\n",
file_get_contents(__DIR__ . '/../../../../../www/install/var/phplib')
);
foreach ($requiredLib as $line) {
if (! $line) {
continue;
}
[$name, $lib] = explode(':', $line);
if (extension_loaded($lib)) {
$libs['loaded'][$name] = $lib . '.so';
} else {
$libs['unloaded'][$name] = $lib . '.so';
}
}
if (! ini_get('date.timezone')) {
$libs['unloaded']['Timezone'] = _('Set the default timezone in php.ini file');
}
return $libs;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonLegacy/Core/Install/Step/AbstractStep.php | centreon/src/CentreonLegacy/Core/Install/Step/AbstractStep.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonLegacy\Core\Install\Step;
use Pimple\Container;
abstract class AbstractStep implements StepInterface
{
protected const TMP_INSTALL_DIR = __DIR__ . '/../../../../../www/install/tmp';
/**
* @param Container $dependencyInjector
*/
public function __construct(protected Container $dependencyInjector)
{
}
/**
* Get base configuration (paths).
*
* @return array<string,string>
*/
public function getBaseConfiguration()
{
return $this->getConfiguration(self::TMP_INSTALL_DIR . '/configuration.json');
}
/**
* Get database access configuration.
*
* @return array<string,string>
*/
public function getDatabaseConfiguration()
{
$configuration = [
'address' => '',
'port' => '',
'root_user' => 'root',
'root_password' => '',
'db_configuration' => 'centreon',
'db_storage' => 'centreon_storage',
'db_user' => 'centreon',
'db_password' => '',
'db_password_confirm' => '',
];
return $this->getConfiguration(self::TMP_INSTALL_DIR . '/database.json', $configuration);
}
/**
* Get admin user configuration.
*
* @return array<string,string>
*/
public function getAdminConfiguration()
{
$configuration = [
'admin_password' => '',
'confirm_password' => '',
'firstname' => '',
'lastname' => '',
'email' => '',
];
return $this->getConfiguration(self::TMP_INSTALL_DIR . '/admin.json', $configuration);
}
public function getVaultConfiguration()
{
$configuration = [
'address' => '',
'port' => '443',
'root_path' => '',
'role_id' => '',
'secret_id' => '',
];
return $this->getConfiguration(self::TMP_INSTALL_DIR . '/vault.json', $configuration);
}
/**
* Get centreon-engine configuration.
*
* @return array<string,string>
*/
public function getEngineConfiguration()
{
return $this->getConfiguration(self::TMP_INSTALL_DIR . '/engine.json');
}
/**
* Get centreon-broker configuration.
*
* @return array<string,string>
*/
public function getBrokerConfiguration()
{
return $this->getConfiguration(self::TMP_INSTALL_DIR . '/broker.json');
}
/**
* Get centreon version.
*
* @return array<string,string>
*/
public function getVersion()
{
return $this->getConfiguration(self::TMP_INSTALL_DIR . '/version.json', '1.0.0');
}
/**
* Get configuration from json file.
*
* @param string $file
* @param array|string $configuration
*
* @return array<int|string,string>|string
*/
private function getConfiguration($file, $configuration = [])
{
if ($this->dependencyInjector['filesystem']->exists($file)) {
$configuration = json_decode(file_get_contents($file), true);
if (is_array($configuration)) {
foreach ($configuration as $key => $configurationValue) {
$configuration[$key] = htmlspecialchars($configurationValue, ENT_QUOTES);
}
} else {
$configuration = htmlspecialchars($configuration, ENT_QUOTES);
}
}
return $configuration;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonLegacy/Core/Install/Step/StepInterface.php | centreon/src/CentreonLegacy/Core/Install/Step/StepInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonLegacy\Core\Install\Step;
interface StepInterface
{
public function getContent();
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonLegacy/Core/Widget/Information.php | centreon/src/CentreonLegacy/Core/Widget/Information.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonLegacy\Core\Widget;
use CentreonLegacy\Core\Utils\Utils;
use CentreonLegacy\ServiceProvider;
use Psr\Container\ContainerInterface;
class Information
{
/** @var ContainerInterface */
protected $services;
/** @var Utils */
protected $utils;
/** @var array */
protected $cachedWidgetsList = [];
/** @var bool */
protected $hasWidgetsForUpgrade = false;
/** @var bool */
protected $hasWidgetsForInstallation = false;
/**
* Construct.
*
* @param ContainerInterface $services
* @param Utils $utils
*/
public function __construct(ContainerInterface $services, ?Utils $utils = null)
{
$this->services = $services;
$this->utils = $utils ?? $services->get(ServiceProvider::CENTREON_LEGACY_UTILS);
}
/**
* Get module configuration from file.
*
* @param string $widgetDirectory the widget directory (usually the widget name)
*
* @throws \Exception
*
* @return array
*/
public function getConfiguration($widgetDirectory)
{
$widgetPath = $this->utils->buildPath('/widgets/' . $widgetDirectory);
if (! $this->services->get('filesystem')->exists($widgetPath . '/configs.xml')) {
throw new \Exception('Cannot get configuration file of widget "' . $widgetDirectory . '"');
}
$conf = $this->utils->xmlIntoArray($widgetPath . '/configs.xml');
if (
$conf['title'] === null
|| $conf['description'] === null
|| $conf['url'] === null
|| $conf['author'] === null
) {
throw new \Exception('Configuration file of widget "' . $widgetDirectory
. '" is invalid: missing at least one required attribute (title/description/url/author)');
}
$conf['directory'] = $widgetDirectory;
$conf['autoRefresh'] ??= 0;
$conf['version'] ??= null;
$conf['email'] ??= null;
$conf['website'] ??= null;
$conf['keywords'] ??= null;
$conf['thumbnail'] ??= null;
return $conf;
}
/**
* @return array
*/
public function getTypes()
{
$types = [];
$query = 'SELECT ft_typename, field_type_id '
. 'FROM widget_parameters_field_type ';
$result = $this->services->get('configuration_db')->query($query);
while ($row = $result->fetchRow()) {
$types[$row['ft_typename']] = [
'id' => $row['field_type_id'],
'name' => $row['ft_typename'],
];
}
return $types;
}
/**
* @param string $name
* @param null|mixed $widgetModelId
*
* @return mixed
*/
public function getParameterIdByName($name, $widgetModelId = null)
{
$query = 'SELECT parameter_id '
. 'FROM widget_parameters '
. 'WHERE parameter_code_name = :name ';
if (! is_null($widgetModelId)) {
$query .= 'AND widget_model_id = :id ';
}
$sth = $this->services->get('configuration_db')->prepare($query);
$sth->bindValue(':name', $name, \PDO::PARAM_STR);
if (! is_null($widgetModelId)) {
$sth->bindValue(':id', $widgetModelId, \PDO::PARAM_INT);
}
$sth->execute();
$id = null;
if ($row = $sth->fetch()) {
$id = $row['parameter_id'];
}
return $id;
}
/**
* @param int $widgetId
*
* @return array
*/
public function getParameters($widgetId)
{
$query = 'SELECT * '
. 'FROM widget_parameters '
. 'WHERE widget_model_id = :id ';
$sth = $this->services->get('configuration_db')->prepare($query);
$sth->bindParam(':id', $widgetId, \PDO::PARAM_INT);
$sth->execute();
$parameters = [];
while ($row = $sth->fetch()) {
$parameters[$row['parameter_code_name']] = $row;
}
return $parameters;
}
/**
* @param string $name
*
* @return int
*/
public function getIdByName($name)
{
$query = 'SELECT widget_model_id '
. 'FROM widget_models '
. 'WHERE directory = :directory';
$sth = $this->services->get('configuration_db')->prepare($query);
$sth->bindParam(':directory', $name, \PDO::PARAM_STR);
$sth->execute();
$id = null;
if ($row = $sth->fetch()) {
$id = $row['widget_model_id'];
}
return $id;
}
/**
* Get list of available modules.
*
* @param string $search
*
* @return array
*/
public function getAvailableList($search = '')
{
$widgetsConf = [];
$widgetsPath = $this->getWidgetPath();
$widgets = $this->services->get('finder')->directories()->depth('== 0')->in($widgetsPath);
foreach ($widgets as $widget) {
$widgetDirectory = $widget->getBasename();
if (! empty($search) && ! stristr($widgetDirectory, $search)) {
continue;
}
$widgetPath = $widgetsPath . $widgetDirectory;
if (! $this->services->get('filesystem')->exists($widgetPath . '/configs.xml')) {
continue;
}
// we use lowercase to avoid problems if directory name have some letters in uppercase
$widgetsConf[strtolower($widgetDirectory)] = $this->getConfiguration($widgetDirectory);
}
return $widgetsConf;
}
/**
* Get list of modules (installed or not).
*
* @return array
*/
public function getList()
{
$installedWidgets = $this->getInstalledList();
$availableWidgets = $this->getAvailableList();
$widgets = [];
foreach ($availableWidgets as $name => $properties) {
$widgets[$name] = $properties;
$widgets[$name]['source_available'] = true;
$widgets[$name]['is_installed'] = false;
$widgets[$name]['upgradeable'] = false;
$widgets[$name]['installed_version'] = _('N/A');
$widgets[$name]['available_version'] = $widgets[$name]['version'];
unset($widgets[$name]['version']);
if (isset($installedWidgets[$name])) {
$widgets[$name]['id'] = $installedWidgets[$name]['widget_model_id'];
$widgets[$name]['is_installed'] = true;
$widgets[$name]['installed_version'] = $installedWidgets[$name]['version'];
$widgetIsUpgradable = $installedWidgets[$name]['is_internal']
? false
: $this->isUpgradeable(
$widgets[$name]['available_version'],
$widgets[$name]['installed_version']
);
$widgets[$name]['upgradeable'] = $widgetIsUpgradable;
$this->hasWidgetsForUpgrade = $widgetIsUpgradable ?: $this->hasWidgetsForUpgrade;
}
}
foreach ($installedWidgets as $name => $properties) {
if (! isset($widgets[$name])) {
$widgets[$name] = $properties;
$widgets[$name]['source_available'] = false;
}
}
$this->hasWidgetsForInstallation = count($availableWidgets) > count($installedWidgets);
$this->cachedWidgetsList = $widgets;
return $widgets;
}
/**
* @param string $widgetName
*
* @return array
*/
public function isInstalled($widgetName)
{
$query = 'SELECT widget_model_id '
. 'FROM widget_models '
. 'WHERE directory = :name';
$sth = $this->services->get('configuration_db')->prepare($query);
$sth->bindParam(':name', $widgetName, \PDO::PARAM_STR);
$sth->execute();
return $sth->fetch();
}
/**
* @param string $widgetName
*
* @return string
*/
public function getWidgetPath($widgetName = '')
{
return $this->utils->buildPath('/widgets/' . $widgetName) . '/';
}
public function hasWidgetsForUpgrade()
{
return $this->hasWidgetsForUpgrade;
}
public function getUpgradeableList()
{
$list = $this->cachedWidgetsList === [] ? $this->getList() : $this->cachedWidgetsList;
return array_filter($list, function ($widget) {
return $widget['upgradeable'];
});
}
public function hasWidgetsForInstallation()
{
return $this->hasWidgetsForInstallation;
}
public function getInstallableList()
{
$list = $this->cachedWidgetsList === [] ? $this->getList() : $this->cachedWidgetsList;
return array_filter($list, function ($widget) {
return ! $widget['is_installed'];
});
}
/**
* Get list of installed widgets.
*
* @return array
*/
private function getInstalledList()
{
$query = 'SELECT * '
. 'FROM widget_models ';
$result = $this->services->get('configuration_db')->query($query);
$widgets = $result->fetchAll();
$installedWidgets = [];
foreach ($widgets as $widget) {
// we use lowercase to avoid problems if directory name have some letters in uppercase
$installedWidgets[strtolower($widget['directory'])] = $widget;
$installedWidgets[strtolower($widget['directory'])]['is_internal'] = $widget['is_internal'] === 1;
}
return $installedWidgets;
}
/**
* @param string $availableVersion
* @param string $installedVersion
*
* @return bool
*/
private function isUpgradeable($availableVersion, $installedVersion)
{
$compare = version_compare($availableVersion, $installedVersion);
return (bool) ($compare == 1);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonLegacy/Core/Widget/Upgrader.php | centreon/src/CentreonLegacy/Core/Widget/Upgrader.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonLegacy\Core\Widget;
class Upgrader extends Installer
{
/**
* @throws \Exception
*
* @return bool
*/
public function upgrade()
{
if (! $this->informationObj->isInstalled($this->widgetName)) {
throw new \Exception('Widget "' . $this->widgetName . '" is not installed.');
}
try {
$id = $this->upgradeConfiguration();
$this->upgradePreferences($id);
$upgraded = true;
} catch (\Exception $e) {
$upgraded = false;
}
return $upgraded;
}
/**
* @throws \Exception
*
* @return int
*/
protected function upgradeConfiguration()
{
$query = 'UPDATE widget_models SET '
. 'title = :title, '
. 'description = :description, '
. 'url = :url, '
. 'version = :version, '
. 'author = :author, '
. 'email = :email, '
. 'website = :website, '
. 'keywords = :keywords, '
. 'thumbnail = :thumbnail, '
. 'autoRefresh = :autoRefresh '
. 'WHERE directory = :directory ';
$sth = $this->services->get('configuration_db')->prepare($query);
$sth->bindParam(':title', $this->widgetConfiguration['title'], \PDO::PARAM_STR);
$sth->bindParam(':description', $this->widgetConfiguration['description'], \PDO::PARAM_STR);
$sth->bindParam(':url', $this->widgetConfiguration['url'], \PDO::PARAM_STR);
$sth->bindParam(':version', $this->widgetConfiguration['version'], \PDO::PARAM_STR);
$sth->bindParam(':author', $this->widgetConfiguration['author'], \PDO::PARAM_STR);
$sth->bindParam(':email', $this->widgetConfiguration['email'], \PDO::PARAM_STR);
$sth->bindParam(':website', $this->widgetConfiguration['website'], \PDO::PARAM_STR);
$sth->bindParam(':keywords', $this->widgetConfiguration['keywords'], \PDO::PARAM_STR);
$sth->bindParam(':thumbnail', $this->widgetConfiguration['thumbnail'], \PDO::PARAM_STR);
$sth->bindParam(':autoRefresh', $this->widgetConfiguration['autoRefresh'], \PDO::PARAM_INT);
$sth->bindParam(':directory', $this->widgetConfiguration['directory'], \PDO::PARAM_STR);
if (! $sth->execute()) {
throw new \Exception('Cannot upgrade widget "' . $this->widgetName . '".');
}
return $this->informationObj->getIdByName($this->widgetName);
}
/**
* @param int $id
* @param array $parameters
* @param array $preference
*/
protected function updateParameters($id, $parameters, $preference)
{
$query = 'UPDATE widget_parameters SET '
. 'field_type_id = :field_type_id, '
. 'parameter_name = :parameter_name, '
. 'default_value = :default_value, '
. 'parameter_order = :parameter_order, '
. 'require_permission = :require_permission, '
. 'header_title = :header_title '
. 'WHERE widget_model_id = :widget_model_id '
. 'AND parameter_code_name = :parameter_code_name ';
$sth = $this->services->get('configuration_db')->prepare($query);
$sth->bindParam(':field_type_id', $parameters['type']['id'], \PDO::PARAM_INT);
$sth->bindParam(':parameter_name', $parameters['label'], \PDO::PARAM_STR);
$sth->bindParam(':default_value', $parameters['defaultValue'], \PDO::PARAM_STR);
$sth->bindParam(':parameter_order', $parameters['order'], \PDO::PARAM_STR);
$sth->bindParam(':require_permission', $parameters['requirePermission'], \PDO::PARAM_STR);
$sth->bindParam(':header_title', $parameters['header'], \PDO::PARAM_STR);
$sth->bindParam(':widget_model_id', $id, \PDO::PARAM_INT);
$sth->bindParam(':parameter_code_name', $parameters['name'], \PDO::PARAM_STR);
$sth->execute();
$lastId = $this->informationObj->getParameterIdByName($parameters['name'], $id);
$this->deleteParameterOptions($lastId);
switch ($parameters['type']['name']) {
case 'list':
case 'sort':
$this->installMultipleOption($lastId, $preference);
break;
case 'range':
$this->installRangeOption($lastId, $parameters);
break;
}
}
/**
* @param int $id
*/
protected function deleteParameter($id)
{
$query = 'DELETE FROM widget_parameters '
. 'WHERE parameter_id = :id ';
$sth = $this->services->get('configuration_db')->prepare($query);
$sth->bindParam(':id', $id, \PDO::PARAM_INT);
$sth->execute();
}
/**
* @param int $id
*/
protected function deleteParameterOptions($id)
{
$query = 'DELETE FROM widget_parameters_multiple_options '
. 'WHERE parameter_id = :id ';
$sth = $this->services->get('configuration_db')->prepare($query);
$sth->bindParam(':id', $id, \PDO::PARAM_INT);
$sth->execute();
$query = 'DELETE FROM widget_parameters_range '
. 'WHERE parameter_id = :id ';
$sth = $this->services->get('configuration_db')->prepare($query);
$sth->bindParam(':id', $id, \PDO::PARAM_INT);
$sth->execute();
}
/**
* @param int $widgetId
*
* @throws \Exception
*/
private function upgradePreferences($widgetId): void
{
if (! isset($this->widgetConfiguration['preferences'])) {
return;
}
$types = $this->informationObj->getTypes();
$existingParams = $this->informationObj->getParameters($widgetId);
$insertedParameters = [];
foreach ($this->widgetConfiguration['preferences'] as $preferences) {
if (! is_array($preferences)) {
continue;
}
$order = 1;
if (isset($preferences['@attributes'])) {
$preferences = [$preferences['@attributes']];
}
foreach ($preferences as $preference) {
$attr = $preference['@attributes'];
if (! isset($types[$attr['type']])) {
throw new \Exception('Unknown type : ' . $attr['type'] . ' found in configuration file');
}
$attr['requirePermission'] ??= 0;
$attr['defaultValue'] ??= '';
$attr['header'] = (isset($attr['header']) && $attr['header'] != '') ? $attr['header'] : null;
$attr['order'] = $order;
$attr['type'] = $types[$attr['type']];
if (! isset($existingParams[$attr['name']])) {
$this->installParameters($widgetId, $attr, $preference);
} else {
$this->updateParameters($widgetId, $attr, $preference);
}
$insertedParameters[] = $attr['name'];
$order++;
}
}
foreach ($existingParams as $name => $attributes) {
if (! in_array($name, $insertedParameters)) {
$this->deleteParameter($attributes['parameter_id']);
}
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonLegacy/Core/Widget/Widget.php | centreon/src/CentreonLegacy/Core/Widget/Widget.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonLegacy\Core\Widget;
use CentreonLegacy\Core\Utils\Utils;
use CentreonLegacy\ServiceProvider;
use Psr\Container\ContainerInterface;
class Widget
{
/** @var Information */
protected $informationObj;
/** @var string */
protected $widgetName;
/** @var Utils */
protected $utils;
/** @var array */
protected $widgetConfiguration;
/** @var ContainerInterface */
protected $services;
/**
* Construct.
*
* @param ContainerInterface $services
* @param Information $informationObj
* @param string $widgetName
* @param Utils $utils
*/
public function __construct(
ContainerInterface $services,
?Information $informationObj = null,
$widgetName = '',
?Utils $utils = null,
) {
$this->services = $services;
$this->informationObj = $informationObj ?? $services->get(ServiceProvider::CENTREON_LEGACY_WIDGET_INFORMATION);
$this->widgetName = $widgetName;
$this->utils = $utils ?? $services->get(ServiceProvider::CENTREON_LEGACY_UTILS);
$this->widgetConfiguration = $this->informationObj->getConfiguration($this->widgetName);
}
/**
* @param string $widgetName
*
* @return string
*/
public function getWidgetPath($widgetName = '')
{
return $this->utils->buildPath('/widgets/' . $widgetName);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonLegacy/Core/Widget/Remover.php | centreon/src/CentreonLegacy/Core/Widget/Remover.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonLegacy\Core\Widget;
class Remover extends Widget
{
/**
* @return bool
*/
public function remove()
{
$query = 'DELETE FROM widget_models '
. 'WHERE directory = :directory '
. 'AND is_internal = FALSE ';
$sth = $this->services->get('configuration_db')->prepare($query);
$sth->bindParam(':directory', $this->widgetName, \PDO::PARAM_STR);
return $sth->execute() ? true : false;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonLegacy/Core/Widget/Factory.php | centreon/src/CentreonLegacy/Core/Widget/Factory.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonLegacy\Core\Widget;
use CentreonLegacy\ServiceProvider;
/**
* @deprecated since version 18.10.4
*/
class Factory
{
/** @var \Pimple\Container */
protected $dependencyInjector;
/**
* @param \Pimple\Container $dependencyInjector
*/
public function __construct(\Pimple\Container $dependencyInjector)
{
$this->dependencyInjector = $dependencyInjector;
}
/**
* @return Information
*/
public function newInformation()
{
return $this->dependencyInjector[ServiceProvider::CENTREON_LEGACY_WIDGET_INFORMATION];
}
/**
* @param string $widgetDirectory
*
* @return Installer
*/
public function newInstaller($widgetDirectory)
{
return $this->dependencyInjector[ServiceProvider::CENTREON_LEGACY_WIDGET_INSTALLER]($widgetDirectory);
}
/**
* @param string $widgetDirectory
*
* @return Upgrader
*/
public function newUpgrader($widgetDirectory)
{
return $this->dependencyInjector[ServiceProvider::CENTREON_LEGACY_WIDGET_UPGRADER]($widgetDirectory);
}
/**
* @param string $widgetDirectory
*
* @return Remover
*/
public function newRemover($widgetDirectory)
{
return $this->dependencyInjector[ServiceProvider::CENTREON_LEGACY_WIDGET_REMOVER]($widgetDirectory);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonLegacy/Core/Widget/Installer.php | centreon/src/CentreonLegacy/Core/Widget/Installer.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonLegacy\Core\Widget;
class Installer extends Widget
{
/**
* @throws \Exception
*
* @return int
*/
public function install()
{
if ($this->informationObj->isInstalled($this->widgetName)) {
throw new \Exception('Widget "' . $this->widgetName . '" is already installed.');
}
$id = $this->installConfiguration();
$this->installPreferences($id);
return $id;
}
/**
* @return int
*/
protected function installConfiguration()
{
$query = 'INSERT INTO widget_models '
. '(title, description, url, version, is_internal, directory, author, '
. 'email, website, keywords, thumbnail, autoRefresh) '
. 'VALUES (:title, :description, :url, :version, :is_internal, :directory, :author, '
. ':email, :website, :keywords, :thumbnail, :autoRefresh) ';
$sth = $this->services->get('configuration_db')->prepare($query);
$sth->bindValue(':title', $this->widgetConfiguration['title'], \PDO::PARAM_STR);
$sth->bindValue(':description', $this->widgetConfiguration['description'], \PDO::PARAM_STR);
$sth->bindValue(':url', $this->widgetConfiguration['url'], \PDO::PARAM_STR);
$sth->bindValue(':version', $this->widgetConfiguration['version'], \PDO::PARAM_STR);
$sth->bindValue(':is_internal', $this->widgetConfiguration['version'] === null, \PDO::PARAM_BOOL);
$sth->bindValue(':directory', $this->widgetConfiguration['directory'], \PDO::PARAM_STR);
$sth->bindValue(':author', $this->widgetConfiguration['author'], \PDO::PARAM_STR);
$sth->bindValue(':email', $this->widgetConfiguration['email'], \PDO::PARAM_STR);
$sth->bindValue(':website', $this->widgetConfiguration['website'], \PDO::PARAM_STR);
$sth->bindValue(':keywords', $this->widgetConfiguration['keywords'], \PDO::PARAM_STR);
$sth->bindValue(':thumbnail', $this->widgetConfiguration['thumbnail'], \PDO::PARAM_STR);
$sth->bindValue(':autoRefresh', $this->widgetConfiguration['autoRefresh'], \PDO::PARAM_INT);
$sth->execute();
return $this->informationObj->getIdByName($this->widgetName);
}
/**
* @param int $id
*
* @throws \Exception
*/
protected function installPreferences($id)
{
if (! isset($this->widgetConfiguration['preferences'])) {
return;
}
$types = $this->informationObj->getTypes();
foreach ($this->widgetConfiguration['preferences'] as $preferences) {
if (! is_array($preferences)) {
continue;
}
$order = 1;
if (isset($preferences['@attributes'])) {
$preferences = [$preferences['@attributes']];
}
foreach ($preferences as $preference) {
$attr = $preference['@attributes'];
if (! isset($types[$attr['type']])) {
throw new \Exception('Unknown type : ' . $attr['type'] . ' found in configuration file');
}
$attr['requirePermission'] ??= 0;
$attr['defaultValue'] ??= '';
$attr['header'] = (isset($attr['header']) && $attr['header'] != '') ? $attr['header'] : null;
$attr['order'] = $order;
$attr['type'] = $types[$attr['type']];
$this->installParameters($id, $attr, $preference);
$order++;
}
}
}
/**
* @param int $id
* @param array $parameters
* @param array $preference
*/
protected function installParameters($id, $parameters, $preference)
{
$query = 'INSERT INTO widget_parameters '
. '(widget_model_id, field_type_id, parameter_name, parameter_code_name, '
. 'default_value, parameter_order, require_permission, header_title) '
. 'VALUES '
. '(:widget_model_id, :field_type_id, :parameter_name, :parameter_code_name, '
. ':default_value, :parameter_order, :require_permission, :header_title) ';
$sth = $this->services->get('configuration_db')->prepare($query);
$sth->bindParam(':widget_model_id', $id, \PDO::PARAM_INT);
$sth->bindParam(':field_type_id', $parameters['type']['id'], \PDO::PARAM_INT);
$sth->bindParam(':parameter_name', $parameters['label'], \PDO::PARAM_STR);
$sth->bindParam(':parameter_code_name', $parameters['name'], \PDO::PARAM_STR);
$sth->bindParam(':default_value', $parameters['defaultValue'], \PDO::PARAM_STR);
$sth->bindParam(':parameter_order', $parameters['order'], \PDO::PARAM_STR);
$sth->bindParam(':require_permission', $parameters['requirePermission'], \PDO::PARAM_STR);
$sth->bindParam(':header_title', $parameters['header'], \PDO::PARAM_STR);
$sth->execute();
$lastId = $this->informationObj->getParameterIdByName($parameters['name'], $id);
switch ($parameters['type']['name']) {
case 'list':
case 'sort':
$this->installMultipleOption($lastId, $preference);
break;
case 'range':
$this->installRangeOption($lastId, $parameters);
break;
}
}
/**
* @param int $paramId
* @param array $preference
*/
protected function installMultipleOption($paramId, $preference)
{
if (! isset($preference['option'])) {
return;
}
$query = 'INSERT INTO widget_parameters_multiple_options '
. '(parameter_id, option_name, option_value) VALUES '
. '(:parameter_id, :option_name, :option_value) ';
$sth = $this->services->get('configuration_db')->prepare($query);
foreach ($preference['option'] as $option) {
$opt = $option['@attributes'] ?? $option;
$sth->bindParam(':parameter_id', $paramId, \PDO::PARAM_INT);
$sth->bindParam(':option_name', $opt['label'], \PDO::PARAM_STR);
$sth->bindParam(':option_value', $opt['value'], \PDO::PARAM_STR);
$sth->execute();
}
}
/**
* @param int $paramId
* @param array $parameters
*/
protected function installRangeOption($paramId, $parameters)
{
$query = 'INSERT INTO widget_parameters_range (parameter_id, min_range, max_range, step) '
. 'VALUES (:parameter_id, :min_range, :max_range, :step) ';
$sth = $this->services->get('configuration_db')->prepare($query);
$sth->bindParam(':parameter_id', $paramId, \PDO::PARAM_INT);
$sth->bindParam(':min_range', $parameters['min'], \PDO::PARAM_INT);
$sth->bindParam(':max_range', $parameters['max'], \PDO::PARAM_INT);
$sth->bindParam(':step', $parameters['step'], \PDO::PARAM_INT);
$sth->execute();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/EventSubscriber/UpdateEventSubscriber.php | centreon/src/EventSubscriber/UpdateEventSubscriber.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace EventSubscriber;
use Centreon\Domain\Log\LoggerTrait;
use Core\Platform\Application\Repository\ReadVersionRepositoryInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class UpdateEventSubscriber implements EventSubscriberInterface
{
use LoggerTrait;
private const MINIMAL_INSTALLED_VERSION = '22.04.0';
/**
* @param ReadVersionRepositoryInterface $readVersionRepository
*/
public function __construct(
private ReadVersionRepositoryInterface $readVersionRepository,
) {
}
/**
* @inheritDoc
*/
public static function getSubscribedEvents(): array
{
if (! file_exists(_CENTREON_ETC_ . DIRECTORY_SEPARATOR . 'centreon.conf.php')) {
return [];
}
return [
KernelEvents::REQUEST => [
['validateCentreonWebVersionOrFail', 35],
],
];
}
/**
* validate centreon web installed version when update endpoint is called.
*
* @param RequestEvent $event
*
* @throws \Exception
*/
public function validateCentreonWebVersionOrFail(RequestEvent $event): void
{
$this->debug('Checking if route matches updates endpoint');
if (
$event->getRequest()->getMethod() === Request::METHOD_PATCH
&& preg_match(
'#^.*/api/(?:latest|beta|v[0-9]+|v[0-9]+\.[0-9]+)/platform/updates$#',
$event->getRequest()->getPathInfo(),
)
) {
$this->debug('Getting Centreon web current version');
$currentVersion = $this->readVersionRepository->findCurrentVersion();
if ($currentVersion === null) {
$errorMessage
= _('Centreon database schema does not seem to be installed.')
. ' '
. _('Please use Web UI to install Centreon.');
$this->error($errorMessage);
throw new \Exception(_($errorMessage));
}
$this->debug(
sprintf(
'Comparing installed version %s to required version %s',
$currentVersion,
self::MINIMAL_INSTALLED_VERSION,
),
);
if (version_compare($currentVersion, self::MINIMAL_INSTALLED_VERSION, '<')) {
$errorMessage = sprintf(
_('Centreon database schema version is "%s" ("%s" required).')
. ' '
. _('Please use Web UI to update Centreon.'),
$currentVersion,
self::MINIMAL_INSTALLED_VERSION,
);
$this->debug($errorMessage);
throw new \Exception(_($errorMessage));
}
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/EventSubscriber/CentreonEventSubscriber.php | centreon/src/EventSubscriber/CentreonEventSubscriber.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace EventSubscriber;
use Centreon\Application\ApiPlatform;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Entity\EntityCreator;
use Centreon\Domain\Entity\EntityValidator;
use Centreon\Domain\Exception\EntityNotFoundException;
use Centreon\Domain\RequestParameters\{Interfaces\RequestParametersInterface,
RequestParameters,
RequestParametersException};
use Centreon\Domain\VersionHelper;
use Core\Common\Domain\Exception\RepositoryException;
use Core\Common\Infrastructure\ExceptionLogger\ExceptionLogger;
use Psr\Log\LogLevel;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\{ExceptionEvent, RequestEvent, ResponseEvent};
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Core\{Exception\AccessDeniedException};
use Symfony\Component\Validator\Exception\ValidationFailedException;
/**
* We defined an event subscriber on the kernel event request to create a
* RequestParameters class according to query parameters and then used in the services
* or repositories.
*
* This class is automatically calls by Symfony through the dependency injector
* and because it's defined as a service.
*/
class CentreonEventSubscriber implements EventSubscriberInterface
{
/**
* If no API header name has been defined in the configuration,
* this name will be used by default.
*/
public const DEFAULT_API_HEADER_NAME = 'version';
/**
* @param RequestParametersInterface $requestParameters
* @param Security $security
* @param ApiPlatform $apiPlatform
* @param ContactInterface $contact
* @param ExceptionLogger $exceptionLogger
* @param string $apiVersionLatest
* @param string $apiHeaderName
* @param string $translationPath
*/
public function __construct(
readonly private RequestParametersInterface $requestParameters,
readonly private Security $security,
readonly private ApiPlatform $apiPlatform,
readonly private ContactInterface $contact,
readonly private ExceptionLogger $exceptionLogger,
readonly private string $apiVersionLatest,
readonly private string $apiHeaderName,
readonly private string $translationPath,
) {
}
/**
* Returns an array of event names this subscriber wants to listen to.
*
* @return mixed[] The event names to listen to
*/
public static function getSubscribedEvents(): array
{
return [
KernelEvents::REQUEST => [
['initRequestParameters', 9],
['defineApiVersionInAttributes', 33],
['initUser', 7],
],
KernelEvents::RESPONSE => [
['addApiVersion', 10],
],
KernelEvents::EXCEPTION => [
['onKernelException', 10],
],
];
}
/**
* Use to update the api version into all responses.
*
* @param ResponseEvent $event
*
* @throws InvalidArgumentException
*/
public function addApiVersion(ResponseEvent $event): void
{
$event->getResponse()->headers->add([$this->apiHeaderName => $this->apiVersionLatest]);
}
/**
* Initializes the RequestParameters instance for later use in the service or repositories.
*
* @param RequestEvent $request
*
* @throws \Exception
*/
public function initRequestParameters(RequestEvent $request): void
{
$query = $request->getRequest()->query->all();
$limit = filter_var(
$query[RequestParameters::NAME_FOR_LIMIT] ?? RequestParameters::DEFAULT_LIMIT,
FILTER_VALIDATE_INT
);
if ($limit === false) {
throw RequestParametersException::integer(RequestParameters::NAME_FOR_LIMIT);
}
$this->requestParameters->setLimit($limit);
$page = filter_var(
$query[RequestParameters::NAME_FOR_PAGE] ?? RequestParameters::DEFAULT_PAGE,
FILTER_VALIDATE_INT
);
if ($page === false) {
throw RequestParametersException::integer(RequestParameters::NAME_FOR_PAGE);
}
$this->requestParameters->setPage($page);
if (isset($query[RequestParameters::NAME_FOR_SORT])) {
$this->requestParameters->setSort($query[RequestParameters::NAME_FOR_SORT]);
}
if (isset($query[RequestParameters::NAME_FOR_SEARCH])) {
$this->requestParameters->setSearch($query[RequestParameters::NAME_FOR_SEARCH]);
} else {
// Create search by using parameters in query
$reservedFields = [
RequestParameters::NAME_FOR_LIMIT,
RequestParameters::NAME_FOR_PAGE,
RequestParameters::NAME_FOR_SEARCH,
RequestParameters::NAME_FOR_SORT,
RequestParameters::NAME_FOR_TOTAL,
];
$search = [];
foreach ($query as $parameterName => $parameterValue) {
if (
in_array($parameterName, $reservedFields, true)
|| $parameterName !== 'filter'
|| ! is_array($parameterValue)
) {
continue;
}
foreach ($parameterValue as $subParameterName => $subParameterValues) {
if (str_contains($subParameterValues, '|')) {
$subParameterValues = explode('|', urldecode($subParameterValues));
foreach ($subParameterValues as $value) {
$search[RequestParameters::AGGREGATE_OPERATOR_OR][] = [$subParameterName => $value];
}
} else {
$search[RequestParameters::AGGREGATE_OPERATOR_AND][$subParameterName]
= urldecode($subParameterValues);
}
}
}
if ($json = json_encode($search)) {
$this->requestParameters->setSearch($json);
}
}
/**
* Add extra parameters.
*/
$reservedFields = [
RequestParameters::NAME_FOR_LIMIT,
RequestParameters::NAME_FOR_PAGE,
RequestParameters::NAME_FOR_SEARCH,
RequestParameters::NAME_FOR_SORT,
RequestParameters::NAME_FOR_TOTAL,
'filter',
];
foreach ($request->getRequest()->query->all() as $parameter => $value) {
if (! in_array($parameter, $reservedFields, true)) {
$this->requestParameters->addExtraParameter(
$parameter,
$value
);
}
}
}
/**
* We retrieve the API version from url to put it in the attributes to allow
* the kernel to use it in routing conditions.
*
* @param RequestEvent $event
*
* @throws InvalidArgumentException
*/
public function defineApiVersionInAttributes(RequestEvent $event): void
{
$event->getRequest()->attributes->set('version.latest', $this->apiVersionLatest);
$event->getRequest()->attributes->set('version.is_latest', false);
$event->getRequest()->attributes->set('version.is_beta', false);
$event->getRequest()->attributes->set('version.not_beta', true);
$uri = $event->getRequest()->getRequestUri();
if (preg_match('/\/api\/([^\/]+)/', $uri, $matches)) {
$requestApiVersion = $matches[1];
if ($requestApiVersion[0] === 'v') {
$requestApiVersion = mb_substr($requestApiVersion, 1);
$requestApiVersion = VersionHelper::regularizeDepthVersion(
$requestApiVersion,
1
);
}
if (
$requestApiVersion === 'latest'
|| VersionHelper::compare($requestApiVersion, $this->apiVersionLatest, VersionHelper::EQUAL)
) {
$event->getRequest()->attributes->set('version.is_latest', true);
$requestApiVersion = $this->apiVersionLatest;
}
if ($requestApiVersion === 'beta') {
$event->getRequest()->attributes->set('version.is_beta', true);
$event->getRequest()->attributes->set('version.not_beta', false);
}
/**
* Used for the routing conditions.
*
* @todo We need to use an other name because after routing,
* its value is overwritten by the value of the 'version' property from uri
*/
$event->getRequest()->attributes->set('version', $requestApiVersion);
// Used for controllers
$event->getRequest()->attributes->set('version_number', $requestApiVersion);
$this->apiPlatform->setVersion($requestApiVersion);
}
}
/**
* Used to manage exceptions outside controllers.
*
* @param ExceptionEvent $event
*
* @throws \InvalidArgumentException
*/
public function onKernelException(ExceptionEvent $event): void
{
$flagController = 'Controller';
$errorIsBeforeController = true;
// We detect if the exception occurred before the kernel called the controller
foreach ($event->getThrowable()->getTrace() as $trace) {
if (
array_key_exists('class', $trace)
&& mb_strlen($trace['class']) > mb_strlen($flagController)
&& mb_substr($trace['class'], -mb_strlen($flagController)) === $flagController
) {
$errorIsBeforeController = false;
break;
}
}
/**
* If Yes and exception code !== 403 (Forbidden access),
* we create a custom error message.
* If we don't do that, an HTML error will appear.
*/
if ($errorIsBeforeController) {
$message = $event->getThrowable()->getMessage();
if ($event->getThrowable()->getCode() >= Response::HTTP_INTERNAL_SERVER_ERROR) {
$errorCode = $event->getThrowable()->getCode();
$statusCode = Response::HTTP_INTERNAL_SERVER_ERROR;
} elseif ($event->getThrowable()->getCode() === Response::HTTP_FORBIDDEN) {
$errorCode = $event->getThrowable()->getCode();
$statusCode = Response::HTTP_FORBIDDEN;
} elseif (
$event->getThrowable() instanceof NotFoundHttpException
|| $event->getThrowable() instanceof MethodNotAllowedHttpException
) {
$errorCode = Response::HTTP_NOT_FOUND;
$statusCode = Response::HTTP_NOT_FOUND;
} elseif ($event->getThrowable()->getPrevious() instanceof ValidationFailedException) {
$message = '';
foreach ($event->getThrowable()->getPrevious()->getViolations() as $violation) {
$message .= $violation->getPropertyPath() . ': ' . $violation->getMessage() . "\n";
}
if ($event->getThrowable() instanceof HttpException) {
$errorCode = $event->getThrowable()->getStatusCode();
$statusCode = $event->getThrowable()->getStatusCode();
} else {
$statusCode = Response::HTTP_INTERNAL_SERVER_ERROR;
$errorCode = $statusCode;
}
} elseif ($event->getThrowable() instanceof HttpException) {
$errorCode = $event->getThrowable()->getStatusCode();
$statusCode = $event->getThrowable()->getStatusCode();
if (
$statusCode === Response::HTTP_UNPROCESSABLE_ENTITY
&& empty($event->getThrowable()->getMessage())
) {
$message = 'The data sent does not comply with the defined validation constraints';
}
} else {
$errorCode = $event->getThrowable()->getCode();
$statusCode = $event->getThrowable()->getCode()
?: Response::HTTP_INTERNAL_SERVER_ERROR;
}
// Manage exception outside controllers
$event->setResponse(
new Response(
json_encode([
'code' => $errorCode,
'message' => $message,
]),
(int) $statusCode
)
);
} else {
$errorCode = $event->getThrowable()->getCode() > 0
? $event->getThrowable()->getCode()
: Response::HTTP_INTERNAL_SERVER_ERROR;
$httpCode = ($event->getThrowable()->getCode() >= 100 && $event->getThrowable()->getCode() < 600)
? (int) $event->getThrowable()->getCode()
: Response::HTTP_INTERNAL_SERVER_ERROR;
if ($event->getThrowable() instanceof EntityNotFoundException) {
$errorMessage = json_encode([
'code' => Response::HTTP_NOT_FOUND,
'message' => $event->getThrowable()->getMessage(),
]);
$httpCode = Response::HTTP_NOT_FOUND;
} elseif ($event->getThrowable() instanceof \JMS\Serializer\Exception\ValidationFailedException) {
$errorMessage = json_encode([
'code' => $errorCode,
'message' => EntityValidator::formatErrors(
$event->getThrowable()->getConstraintViolationList(),
true
),
]);
} elseif (
$event->getThrowable() instanceof \PDOException
|| $event->getThrowable() instanceof RepositoryException
) {
$errorMessage = json_encode([
'code' => $errorCode,
'message' => 'An error has occurred in a repository',
]);
} elseif ($event->getThrowable() instanceof AccessDeniedException) {
$errorCode = $event->getThrowable()->getCode();
$errorMessage = json_encode([
'code' => $errorCode,
'message' => $event->getThrowable()->getMessage(),
]);
} elseif ($event->getThrowable()::class === \Exception::class) {
$errorMessage = json_encode([
'code' => $errorCode,
'message' => 'Internal error',
]);
} else {
$errorMessage = json_encode([
'code' => $errorCode,
'message' => $event->getThrowable()->getMessage(),
]);
}
$event->setResponse(
new Response($errorMessage, (int) $httpCode)
);
}
$this->logException($event->getThrowable());
}
/**
* Set contact if he is logged in.
* @param RequestEvent $event
*/
public function initUser(RequestEvent $event): void
{
/** @var ?Contact $user */
$user = $this->security->getUser();
if ($user === null) {
return;
}
$request = $event->getRequest();
if ($user->getLang() === 'browser') {
$locale = $this->guessLocale($request);
$user->setLocale($locale);
}
EntityCreator::setContact($user);
$this->initLanguage($user);
$this->initGlobalContact($user);
}
/**
* Guess the locale to use according to the provided Accept-Language header (sent by browser or http client)
*
* @todo improve this by moving the logic in a dedicated service
* @todo improve the array of supported locales by INJECTING them instead
* @param Request $request
*/
private function guessLocale(Request $request): string
{
$preferredLanguage = $request->getPreferredLanguage(['fr-FR', 'en-US', 'es-ES', 'pr-BR', 'pt-PT', 'de-DE']);
// Reformating is necessary as the standard format uses "-" and we decided to store "_"
$locale = $preferredLanguage ? str_replace('-', '_', $preferredLanguage) : 'en_US';
// Also Safari has its own format "fr-fr" instead of "fr-FR" hence the strtoupper
return substr($locale, 0, -2) . strtoupper(substr($locale, -2));
}
/**
* Used to log the message according to the code and type of exception.
*
* @param \Throwable $exception
*/
private function logException(\Throwable $exception): void
{
if (! $exception instanceof HttpExceptionInterface || $exception->getCode() >= 500) {
$level = LogLevel::CRITICAL;
} else {
$level = LogLevel::ERROR;
}
$this->exceptionLogger->log(
throwable: $exception,
context: ['internal_error' => $exception],
level: $level
);
}
/**
* Init language to manage translation.
*
* @param ContactInterface $user
*/
private function initLanguage(ContactInterface $user): void
{
$lang = $user->getLocale() . '.' . Contact::DEFAULT_CHARSET;
putenv('LANG=' . $lang);
setlocale(LC_ALL, $lang);
bindtextdomain('messages', $this->translationPath);
bind_textdomain_codeset('messages', Contact::DEFAULT_CHARSET);
textdomain('messages');
}
/**
* Initialise the contact that will be used as the Service.
* This will not change the user identified during authentication.
*
* @param ContactInterface $user Local contact with information to be used
*/
private function initGlobalContact(ContactInterface $user): void
{
if (! $this->contact instanceof Contact) {
return;
}
$this->contact->setId($user->getId())
->setName($user->getName())
->setAlias($user->getAlias())
->setEmail($user->getEmail())
->setTemplateId($user->getTemplateId())
->setIsActive($user->isActive())
->setAdmin($user->isAdmin())
->setTimezone($user->getTimezone())
->setLocale($user->getLocale())
->setRoles($user->getRoles())
->setTopologyRules($user->getTopologyRules())
->setAccessToApiRealTime($user->hasAccessToApiRealTime())
->setAccessToApiConfiguration($user->hasAccessToApiConfiguration())
->setLang($user->getLang())
->setAllowedToReachWeb($user->isAllowedToReachWeb())
->setToken($user->getToken())
->setEncodedPassword($user->getEncodedPassword())
->setTimezoneId($user->getTimezoneId())
->setDefaultPage($user->getDefaultPage())
->setUseDeprecatedPages($user->isUsingDeprecatedPages())
->setUseDeprecatedCustomViews($user->isUsingDeprecatedCustomViews())
->setTheme($user->getTheme() ?? 'light')
->setUserInterfaceDensity($user->getUserInterfaceDensity());
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/EventSubscriber/FeatureFlagEventSubscriber.php | centreon/src/EventSubscriber/FeatureFlagEventSubscriber.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace EventSubscriber;
use Core\Common\Infrastructure\FeatureFlags;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
/**
* This event subscriber is dedicated for the Feature Flag system.
*
* @see FeatureFlags
*/
class FeatureFlagEventSubscriber implements EventSubscriberInterface
{
/**
* @param FeatureFlags $featureFlags
*/
public function __construct(
private readonly FeatureFlags $featureFlags,
) {
}
/**
* Returns an array of event names this subscriber wants to listen to.
*
* @return mixed[] The event names to listen to
*/
public static function getSubscribedEvents(): array
{
return [
KernelEvents::REQUEST => [
['defineFeaturesInAttributes', 40],
],
];
}
/**
* We inject in the request a TRUE attribute for each enabled feature of the feature flags system.
*
* @param RequestEvent $event
*/
public function defineFeaturesInAttributes(RequestEvent $event): void
{
foreach ($this->featureFlags->getEnabled() as $name) {
$event->getRequest()->attributes->set('feature.' . $name, true);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonUser/ServiceProvider.php | centreon/src/CentreonUser/ServiceProvider.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonUser;
use Centreon\Infrastructure\Provider\AutoloadServiceProviderInterface;
use CentreonUser\Application\Webservice;
use Pimple\Container;
class ServiceProvider implements AutoloadServiceProviderInterface
{
/**
* {@inheritDoc}
*/
public function register(Container $pimple): void
{
// register Timeperiod webservice
$pimple[\Centreon\ServiceProvider::CENTREON_WEBSERVICE]
->add(Webservice\TimeperiodWebservice::class);
}
/**
* {@inheritDoc}
*/
public static function order(): int
{
return 51;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonUser/Application/Webservice/TimeperiodWebservice.php | centreon/src/CentreonUser/Application/Webservice/TimeperiodWebservice.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonUser\Application\Webservice;
use Centreon\Infrastructure\Webservice;
use Centreon\ServiceProvider;
use CentreonUser\Application\Serializer;
use CentreonUser\Domain\Repository;
/**
* @OA\Tag(name="centreon_timeperiod", description="Resource for authorized access")
*/
class TimeperiodWebservice extends Webservice\WebServiceAbstract implements Webservice\WebserviceAutorizeRestApiInterface
{
use Webservice\DependenciesTrait;
/**
* {@inheritDoc}
*/
public static function getName(): string
{
return 'centreon_timeperiod';
}
/**
* {@inheritDoc}
*
* @return array<ServiceProvider::CENTREON_PAGINATION>
*/
public static function dependencies(): array
{
return [
ServiceProvider::CENTREON_PAGINATION,
];
}
/**
* @OA\Get(
* path="/external.php?object=centreon_timeperiod&action=list",
* description="Get list of timeperiods",
* tags={"centreon_timeperiod"},
* security={{"Session": {}}},
*
* @OA\Parameter(
* in="query",
* name="object",
*
* @OA\Schema(
* type="string",
* enum={"centreon_timeperiod"},
* ),
* description="the name of the API object class",
* required=true
* ),
*
* @OA\Parameter(
* in="query",
* name="action",
*
* @OA\Schema(
* type="string",
* enum={"list"}
* ),
* description="the name of the action in the API class",
* required=true
* ),
*
* @OA\Parameter(
* in="query",
* name="search",
*
* @OA\Schema(
* type="string"
* ),
* description="filter the list by name of the entity"
* ),
*
* @OA\Parameter(
* in="query",
* name="searchByIds",
*
* @OA\Schema(
* type="string"
* ),
* description="filter by IDs for more than one separate them with a comma sign"
* ),
*
* @OA\Parameter(
* in="query",
* name="offset",
*
* @OA\Schema(
* type="integer"
* ),
* description="the argument specifies the offset of the first row to return"
* ),
*
* @OA\Parameter(
* in="query",
* name="limit",
*
* @OA\Schema(
* type="integer"
* ),
* description="maximum entities in the list"
* ),
*
* @OA\Response(
* response="200",
* description="OK",
*
* @OA\JsonContent(
*
* @OA\Property(
* property="entities",
* type="array",
*
* @OA\Items(ref="#/components/schemas/TimeperiodEntity")
* ),
*
* @OA\Property(
* property="pagination",
* ref="#/components/schemas/Pagination"
* )
* )
* )
* )
*
* Get list of timeperiods
*
* @throws \RestBadRequestException
*
* @return \Centreon\Application\DataRepresenter\Response
*/
public function getList()
{
// extract post payload
$request = $this->query();
$limit = isset($request['limit']) ? (int) $request['limit'] : null;
$offset = isset($request['offset']) ? (int) $request['offset'] : null;
$sortField = $request['sortf'] ?? null;
$sortOrder = $request['sorto'] ?? 'ASC';
$filters = [];
if (isset($request['search']) && $request['search']) {
$filters['search'] = $request['search'];
}
if (isset($request['searchByIds']) && $request['searchByIds']) {
$filters['ids'] = explode(',', $request['searchByIds']);
}
$pagination = $this->services->get(ServiceProvider::CENTREON_PAGINATION);
$pagination->setRepository(Repository\TimeperiodRepository::class);
$pagination->setContext(Serializer\Timeperiod\ListContext::context());
$pagination->setFilters($filters);
$pagination->setLimit($limit);
$pagination->setOffset($offset);
$pagination->setOrder($sortField, $sortOrder);
return $pagination->getResponse();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonUser/Application/Serializer/Timeperiod/ListContext.php | centreon/src/CentreonUser/Application/Serializer/Timeperiod/ListContext.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonUser\Application\Serializer\Timeperiod;
use Centreon\Application\Serializer\SerializerContextInterface;
use CentreonUser\Domain\Entity\Timeperiod;
/**
* @OA\Schema(
* schema="TimeperiodEntity",
*
* @OA\Property(property="id", type="integer"),
* @OA\Property(property="name", type="string"),
* @OA\Property(property="alias", type="string")
* )
*
* Serialize Timeperiod entity for list
*/
class ListContext implements SerializerContextInterface
{
/**
* {@inheritDoc}
*/
public static function context(): array
{
return [
static::GROUPS => [
Timeperiod::SERIALIZER_GROUP_LIST,
],
];
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonUser/Domain/Entity/Timeperiod.php | centreon/src/CentreonUser/Domain/Entity/Timeperiod.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonUser\Domain\Entity;
use Centreon\Infrastructure\CentreonLegacyDB\Mapping;
use PDO;
use Symfony\Component\Serializer\Annotation as Serializer;
/**
* Timeperiod entity.
*
* @codeCoverageIgnore
*/
class Timeperiod implements Mapping\MetadataInterface
{
public const SERIALIZER_GROUP_LIST = 'timeperiod-list';
public const TABLE = 'timeperiod';
public const ENTITY_IDENTIFICATOR_COLUMN = 'tp_id';
/** @var int an identification of entity */
#[Serializer\Groups([Timeperiod::SERIALIZER_GROUP_LIST])]
private $id;
/** @var string */
#[Serializer\Groups([Timeperiod::SERIALIZER_GROUP_LIST])]
private $name;
/** @var string */
#[Serializer\Groups([Timeperiod::SERIALIZER_GROUP_LIST])]
private $alias;
/**
* {@inheritDoc}
*/
public static function loadMetadata(Mapping\ClassMetadata $metadata): void
{
$metadata->setTableName(static::TABLE)
->add('id', 'tp_id', PDO::PARAM_INT, null, true)
->add('name', 'tp_name', PDO::PARAM_STR)
->add('alias', 'tp_alias', PDO::PARAM_STR);
}
/**
* @param int $id
*/
public function setId(?int $id = null): void
{
$this->id = $id;
}
/**
* @return int|null
*/
public function getId(): ?int
{
return $this->id;
}
/**
* @param string $name
*/
public function setName(?string $name = null): void
{
$this->name = $name;
}
/**
* @return string|null
*/
public function getName(): ?string
{
return $this->name;
}
/**
* @param string $alias
*/
public function setAlias(?string $alias = null): void
{
$this->alias = $alias;
}
/**
* @return string|null
*/
public function getAlias(): ?string
{
return $this->alias;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonUser/Domain/Entity/Contact.php | centreon/src/CentreonUser/Domain/Entity/Contact.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonUser\Domain\Entity;
/**
* Contact entity.
*
* @codeCoverageIgnore
*
* @todo describe properties of this entity
*/
class Contact
{
public const TABLE = 'contact';
public const ENTITY_IDENTIFICATOR_COLUMN = 'contact_id';
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonUser/Domain/Repository/ContactRepository.php | centreon/src/CentreonUser/Domain/Repository/ContactRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonUser\Domain\Repository;
use Centreon\Domain\Repository\Traits\CheckListOfIdsTrait;
use Centreon\Infrastructure\CentreonLegacyDB\ServiceEntityRepository;
use CentreonUser\Domain\Entity\Contact;
class ContactRepository extends ServiceEntityRepository
{
use CheckListOfIdsTrait;
/**
* Check list of IDs.
*
* @param int[] $ids
*
* @return bool
*/
public function checkListOfIds(array $ids): bool
{
return $this->checkListOfIdsTrait($ids, Contact::TABLE, Contact::ENTITY_IDENTIFICATOR_COLUMN);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonUser/Domain/Repository/TimeperiodRepository.php | centreon/src/CentreonUser/Domain/Repository/TimeperiodRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace CentreonUser\Domain\Repository;
use Centreon\Domain\Repository\Traits\CheckListOfIdsTrait;
use Centreon\Infrastructure\CentreonLegacyDB\Interfaces\PaginationRepositoryInterface;
use Centreon\Infrastructure\CentreonLegacyDB\StatementCollector;
use Centreon\Infrastructure\DatabaseConnection;
use CentreonUser\Domain\Entity\Timeperiod;
use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB;
class TimeperiodRepository extends AbstractRepositoryRDB implements PaginationRepositoryInterface
{
use CheckListOfIdsTrait;
/** @var int */
private int $resultCountForPagination = 0;
/**
* @param DatabaseConnection $db
*/
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* {@inheritDoc}
*/
public static function entityClass(): string
{
return Timeperiod::class;
}
/**
* Check list of IDs.
*
* @param int[] $ids
*
* @return bool
*/
public function checkListOfIds(array $ids): bool
{
return $this->checkListOfIdsTrait(
$ids,
Timeperiod::TABLE,
Timeperiod::ENTITY_IDENTIFICATOR_COLUMN
);
}
/**
* {@inheritDoc}
*/
public function getPaginationList($filters = null, ?int $limit = null, ?int $offset = null, $ordering = []): array
{
$sql = 'SELECT SQL_CALC_FOUND_ROWS `tp_id`, `tp_name`, `tp_alias` '
. 'FROM `:db`.`timeperiod`';
$collector = new StatementCollector();
$isWhere = false;
if ($filters !== null) {
if ($filters['search'] ?? false) {
$sql .= ' WHERE (`tp_name` LIKE :search OR `tp_alias` LIKE :search)';
$collector->addValue(':search', "%{$filters['search']}%");
$isWhere = true;
}
if (
array_key_exists('ids', $filters)
&& is_array($filters['ids'])
&& $filters['ids'] !== []
) {
$idsListKey = [];
foreach ($filters['ids'] as $x => $id) {
$key = ":id{$x}";
$idsListKey[] = $key;
$collector->addValue($key, $id, \PDO::PARAM_INT);
unset($x, $id);
}
$sql .= $isWhere ? ' AND' : ' WHERE';
$sql .= ' `tp_id` IN (' . implode(',', $idsListKey) . ')';
}
}
if (! empty($ordering['field'])) {
$sql .= ' ORDER BY `' . $ordering['field'] . '` ' . $ordering['order'];
}
if ($limit !== null) {
$sql .= ' LIMIT :limit';
$collector->addValue(':limit', $limit, \PDO::PARAM_INT);
if ($offset !== null) {
$sql .= ' OFFSET :offset';
$collector->addValue(':offset', $offset, \PDO::PARAM_INT);
}
}
$statement = $this->db->prepare($this->translateDbName($sql));
$collector->bind($statement);
$statement->execute();
$foundRecords = $this->db->query('SELECT FOUND_ROWS()');
if ($foundRecords !== false && ($total = $foundRecords->fetchColumn()) !== false) {
$this->resultCountForPagination = $total;
}
$result = [];
while ($record = $statement->fetch(\PDO::FETCH_ASSOC)) {
$result[] = $this->createTimeperiodFromArray($record);
}
return $result;
}
/**
* {@inheritDoc}
*/
public function getPaginationListTotal(): int
{
return $this->resultCountForPagination;
}
/**
* @param array<string, mixed> $data
*
* @return Timeperiod
*/
private function createTimeperiodFromArray(array $data): Timeperiod
{
$timeperiod = new Timeperiod();
$timeperiod->setId((int) $data['tp_id']);
$timeperiod->setName($data['tp_name']);
$timeperiod->setAlias($data['tp_alias']);
return $timeperiod;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Utility/ULIDGenerator.php | centreon/src/Utility/ULIDGenerator.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Utility;
use Symfony\Component\Uid\Ulid;
use Utility\Interfaces\StringGeneratorInterface;
class ULIDGenerator implements StringGeneratorInterface
{
/**
* @inheritDoc
*/
public function generateForQueryParameter(): string
{
return (new Ulid())->toBase58();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Utility/EnvironmentFileManager.php | centreon/src/Utility/EnvironmentFileManager.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Utility;
class EnvironmentFileManager
{
public const DEFAULT_ENVIRONMENT_FILE = '.env';
public const APP_ENV_PROD = 'prod';
/** @var array<string, int|float|bool|string> */
private array $variables = [];
private ?string $currentEnvironnementFile = null;
private string $environmentMode;
/**
* @param string $environmentFilePath
*/
public function __construct(private string $environmentFilePath)
{
$this->environmentFilePath = $this->addDirectorySeparatorIfNeeded($this->environmentFilePath);
$this->environmentMode = (isset($_SERVER['APP_ENV']) && is_scalar($_SERVER['APP_ENV']))
? (string) $_SERVER['APP_ENV']
: 'prod';
}
/**
* @param string $environmentFile
*
* @throws \Exception
*/
public function load(string $environmentFile = self::DEFAULT_ENVIRONMENT_FILE): void
{
$this->currentEnvironnementFile = $environmentFile;
$filePath = $this->environmentFilePath . $environmentFile;
if (! file_exists($filePath)) {
throw new \Exception(sprintf("The environment file '%s' does not exist", $environmentFile));
}
$file = fopen($filePath, 'r');
if (! $file) {
throw new \Exception(sprintf('Impossible to open file \'%s\'', $filePath));
}
try {
while (($line = fgets($file, 1024)) !== false) {
$line = trim($line);
if (str_contains($line, '=')) {
[$key, $value] = explode('=', $line, 2);
$this->add($key, $value);
}
}
} finally {
fclose($file);
}
}
/**
* @param string $key
* @param int|float|bool|string $value
*/
public function add(string $key, int|float|bool|string $value): void
{
if ($key[0] === '#') { // The commented line will be ignored
return;
}
if (is_string($value)) {
$value = trim($value);
if ($value === 'true' || $value === 'false') {
$value = filter_var($value, FILTER_VALIDATE_BOOLEAN);
}
}
if (is_numeric($value)) {
if (str_starts_with($key, 'IS_') && ((string) $value === '0' || (string) $value === '1')) {
$value = (bool) $value;
} elseif (preg_match('/^-?\d+\.\d+/', (string) $value)) {
$value = (float) $value;
} else {
$value = (int) $value;
}
}
$this->variables[trim($key)] = $value;
}
public function clear(): void
{
$this->variables = [];
}
/**
* @param string $key
*/
public function delete(string $key): void
{
unset($this->variables[$key]);
}
/**
* @return array<string, int|float|bool|string>
*/
public function getAll(): array
{
return $this->variables;
}
/**
* @param string $key
*
* @return int|float|bool|string|null
*/
public function get(string $key): int|float|bool|string|null
{
return $this->variables[$key] ?? null;
}
/**
* @param string|null $environmentFile
*
* @throws \Exception
*/
public function save(?string $environmentFile = null): void
{
$this->checkEnvironmentFileDefined($environmentFile);
$filePath = $this->environmentFilePath . $this->currentEnvironnementFile;
$file = fopen($filePath, 'w');
if (! $file) {
throw new \Exception(sprintf('Impossible to open file \'%s\'', $filePath));
}
try {
foreach ($this->variables as $key => $value) {
if (is_bool($value)) {
$value = $value ? 1 : 0;
}
$successWriteFile = fwrite($file, sprintf("%s=%s\n", $key, $value));
if ($successWriteFile === false) {
throw new \Exception(sprintf('Impossible to write file \'%s\'', $filePath));
}
}
} finally {
fclose($file);
}
// If the environment is dev or test, we do not create the local file named .env.local.php to avoid overriding
// the local environment variables with .env.local
if (! $this->isProdEnvironment()) {
return;
}
// Create the local environment file only if the environment is prod
$variables = var_export($this->variables, true);
$content = <<<CONTENT
<?php
// This file was generated by Centreon
return {$variables};
CONTENT;
$successWriteFile = file_put_contents($filePath . '.local.php', $content);
if ($successWriteFile === false) {
throw new \Exception(sprintf('Impossible to write file \'%s.local.php\'', $filePath));
}
}
public function isProdEnvironment(): bool
{
return $this->environmentMode === self::APP_ENV_PROD;
}
/**
* @param string|null $environmentFile
*
* @throws \Exception
*/
private function checkEnvironmentFileDefined(?string $environmentFile = null): void
{
$environmentFile ??= $this->currentEnvironnementFile;
if ($environmentFile === null) {
throw new \Exception('No environment file defined');
}
}
/**
* Add the directory separator at the end of the path if it does not exist.
*
* /dir1/dir2 => /dir1/dir2/
*
* @param string $path
*
* @return string
*/
private function addDirectorySeparatorIfNeeded(string $path): string
{
if ($path === '' || $path[-1] !== DIRECTORY_SEPARATOR) {
return $path . DIRECTORY_SEPARATOR;
}
return $path;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Utility/SqlConcatenator.php | centreon/src/Utility/SqlConcatenator.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Utility;
/**
* This is *NOT* a SQL Builder.
* This is a *String Builder* dedicated to SQL queries we named "Concatenator" to be explicit.
*
* > See it like a SQL "mutable string".
* > No more, no less : only string concatenations.
*
* The aim is to facilitate string manipulations for SQL queries.
* *DO NOT USE* for simple queries where a basic string is preferable.
*
* This class should very probably not have any evolution at all in the future !
*/
final class SqlConcatenator implements \Stringable
{
private const SEPARATOR_JOINS = ' ';
private const SEPARATOR_CONDITIONS = ' AND ';
private const SEPARATOR_EXPRESSIONS = ', ';
private const PREFIX_SELECT = 'SELECT ';
private const PREFIX_FROM = 'FROM ';
private const PREFIX_WHERE = 'WHERE ';
private const PREFIX_GROUP_BY = 'GROUP BY ';
private const PREFIX_HAVING = 'HAVING ';
private const PREFIX_ORDER_BY = 'ORDER BY ';
private const PREFIX_LIMIT = 'LIMIT ';
/** @var bool */
private bool $withNoCache = false;
/** @var bool */
private bool $withCalcFoundRows = false;
/** @var array<string|\Stringable> */
private array $select = [];
/** @var string|\Stringable */
private string|\Stringable $from = '';
/** @var array<string|\Stringable> */
private array $joins = [];
/** @var array<string|\Stringable> */
private array $where = [];
/** @var array<string|\Stringable> */
private array $groupBy = [];
/** @var array<string|\Stringable> */
private array $having = [];
/** @var array<string|\Stringable> */
private array $orderBy = [];
/** @var string|\Stringable */
private string|\Stringable $limit = '';
/** @var array<string, array{mixed, int}> */
private array $bindValues = [];
/** @var array<string, string> */
private array $bindArrayReplacements = [];
public function __toString(): string
{
return $this->concatAll();
}
/**
* @param bool $bool
*
* @return $this
*/
public function withCalcFoundRows(bool $bool): self
{
$this->withCalcFoundRows = $bool;
return $this;
}
/**
* @param bool $bool
*
* @return $this
*/
public function withNoCache(bool $bool): self
{
$this->withNoCache = $bool;
return $this;
}
/**
* @param string|\Stringable ...$expressions
*
* @return $this
*/
public function defineSelect(string|\Stringable ...$expressions): self
{
$this->select = $this->trimPrefix(self::PREFIX_SELECT, ...$expressions);
return $this;
}
/**
* @param string|\Stringable ...$expressions
*
* @return $this
*/
public function appendSelect(string|\Stringable ...$expressions): self
{
$this->select = array_merge($this->select, $this->trimPrefix(self::PREFIX_SELECT, ...$expressions));
return $this;
}
/**
* @param string|\Stringable $table
*
* @return $this
*/
public function defineFrom(string|\Stringable $table): self
{
$this->from = $this->trimPrefix(self::PREFIX_FROM, $table)[0];
return $this;
}
/**
* @param string|\Stringable ...$joins
*
* @return $this
*/
public function defineJoins(string|\Stringable ...$joins): self
{
$this->joins = $joins;
return $this;
}
/**
* @param string|\Stringable ...$joins
*
* @return $this
*/
public function appendJoins(string|\Stringable ...$joins): self
{
$this->joins = array_merge($this->joins, $joins);
return $this;
}
/**
* @param string|\Stringable ...$conditions
*
* @return $this
*/
public function defineWhere(string|\Stringable ...$conditions): self
{
$this->where = $this->trimPrefix(self::PREFIX_WHERE, ...$conditions);
return $this;
}
/**
* @param string|\Stringable ...$conditions
*
* @return $this
*/
public function appendWhere(string|\Stringable ...$conditions): self
{
$this->where = array_merge($this->where, $this->trimPrefix(self::PREFIX_WHERE, ...$conditions));
return $this;
}
/**
* @param string|\Stringable ...$expressions
*
* @return $this
*/
public function defineGroupBy(string|\Stringable ...$expressions): self
{
$this->groupBy = $this->trimPrefix(self::PREFIX_GROUP_BY, ...$expressions);
return $this;
}
/**
* @param string|\Stringable ...$expressions
*
* @return $this
*/
public function appendGroupBy(string|\Stringable ...$expressions): self
{
$this->groupBy = array_merge($this->groupBy, $this->trimPrefix(self::PREFIX_GROUP_BY, ...$expressions));
return $this;
}
/**
* @param string|\Stringable ...$expressions
*
* @return $this
*/
public function defineHaving(string|\Stringable ...$expressions): self
{
$this->having = $this->trimPrefix(self::PREFIX_HAVING, ...$expressions);
return $this;
}
/**
* @param string|\Stringable ...$conditions
*
* @return $this
*/
public function appendHaving(string|\Stringable ...$conditions): self
{
$this->having = array_merge($this->having, $this->trimPrefix(self::PREFIX_HAVING, ...$conditions));
return $this;
}
/**
* @param string|\Stringable ...$expressions
*
* @return $this
*/
public function defineOrderBy(string|\Stringable ...$expressions): self
{
$this->orderBy = $this->trimPrefix(self::PREFIX_ORDER_BY, ...$expressions);
return $this;
}
/**
* @param string|\Stringable ...$expressions
*
* @return $this
*/
public function appendOrderBy(string|\Stringable ...$expressions): self
{
$this->orderBy = array_merge($this->orderBy, $this->trimPrefix(self::PREFIX_ORDER_BY, ...$expressions));
return $this;
}
/**
* @param string|\Stringable $limit
*
* @return $this
*/
public function defineLimit(string|\Stringable $limit): self
{
$this->limit = $this->trimPrefix(self::PREFIX_LIMIT, $limit)[0];
return $this;
}
/**
* This method serve only to store bind values in an easy way close to the sql strings.
*
* @param string $param
* @param mixed $value
* @param int $type
*
* @return $this
*/
public function storeBindValue(string $param, mixed $value, int $type = \PDO::PARAM_STR): self
{
$param = ':' . ltrim($param, ':');
$this->bindValues[$param] = [$value, $type];
return $this;
}
/**
* This method serve only to store bind values in an easy way close to the sql strings.
*
* @param string $param
* @param list<int|string> $values
* @param int $type
*
* @return $this
*/
public function storeBindValueMultiple(string $param, array $values, int $type = \PDO::PARAM_STR): self
{
// reindex the array to avoid problems with index bindings
$values = array_values($values);
$param = ':' . ltrim($param, ':');
$names = [];
for ($num = 1, $count = \count($values); $num <= $count; $num++) {
$names[] = $name = "{$param}_{$num}";
$this->bindValues[$name] = [$values[$num - 1], $type];
}
$this->bindArrayReplacements[$param] = implode(', ', $names);
return $this;
}
/**
* Empty the bindValues array.
*
* @return $this
*/
public function clearBindValues(): self
{
$this->bindValues = [];
$this->bindArrayReplacements = [];
return $this;
}
/**
* @return array<string, array{mixed, int}> Format: $param => [$value, $type]
*/
public function retrieveBindValues(): array
{
return $this->bindValues;
}
/**
* Helper method which bind all values stored here into a statement.
*
* @param \PDOStatement $statement
*/
public function bindValuesToStatement(\PDOStatement $statement): void
{
foreach ($this->retrieveBindValues() as $param => [$value, $type]) {
$statement->bindValue($param, $value, $type);
}
}
/**
* @return string
*/
public function concatAll(): string
{
$sql = rtrim(
$this->concatSelect()
. $this->concatFrom()
. $this->concatJoins()
. $this->concatWhere()
. $this->concatGroupBy()
. $this->concatHaving()
. $this->concatOrderBy()
. $this->concatLimit()
);
return $this->bindArrayReplacements($sql);
}
/**
* @return string
*/
public function concatForUnion(): string
{
$sql = rtrim(
$this->concatSelect()
. $this->concatFrom()
. $this->concatJoins()
. $this->concatWhere()
. $this->concatGroupBy()
. $this->concatHaving()
. $this->concatOrderBy()
);
return $this->bindArrayReplacements($sql);
}
/**
* @param string $sql
*
* @return string
*/
private function bindArrayReplacements(string $sql): string
{
if ($this->bindArrayReplacements === []) {
return $sql;
}
$patterns = array_map(
static fn (string $name): string => '!' . preg_quote($name, '!') . '\b!',
array_keys($this->bindArrayReplacements)
);
return (string) preg_replace($patterns, $this->bindArrayReplacements, $sql);
}
/**
* @return string
*/
private function concatSelect(): string
{
if ($this->select === []) {
return '';
}
$noCache = $this->withNoCache ? 'SQL_NO_CACHE ' : '';
$calcFoundRows = $this->withCalcFoundRows ? 'SQL_CALC_FOUND_ROWS ' : '';
return self::PREFIX_SELECT . $noCache . $calcFoundRows
. implode(self::SEPARATOR_EXPRESSIONS, $this->select) . ' ';
}
/**
* @return string
*/
private function concatFrom(): string
{
$from = (string) $this->from;
return $from === '' ? ''
: self::PREFIX_FROM . $this->from . ' ';
}
/**
* @return string
*/
private function concatJoins(): string
{
return $this->joins === [] ? ''
: implode(self::SEPARATOR_JOINS, $this->joins) . ' ';
}
/**
* @return string
*/
private function concatWhere(): string
{
return $this->where === [] ? ''
: self::PREFIX_WHERE . implode(self::SEPARATOR_CONDITIONS, $this->where) . ' ';
}
/**
* @return string
*/
private function concatGroupBy(): string
{
return $this->groupBy === [] ? ''
: self::PREFIX_GROUP_BY . implode(self::SEPARATOR_EXPRESSIONS, $this->groupBy) . ' ';
}
/**
* @return string
*/
private function concatHaving(): string
{
return $this->having === [] ? ''
: self::PREFIX_HAVING . implode(self::SEPARATOR_CONDITIONS, $this->having) . ' ';
}
/**
* @return string
*/
private function concatOrderBy(): string
{
return $this->orderBy === [] ? ''
: self::PREFIX_ORDER_BY . implode(self::SEPARATOR_EXPRESSIONS, $this->orderBy) . ' ';
}
/**
* @return string
*/
private function concatLimit(): string
{
return $this->limit === '' ? ''
: self::PREFIX_LIMIT . $this->limit;
}
/**
* We remove spaces and prefix in front of the string, and we skip empty string values.
*
* @param string $prefix
* @param string|\Stringable ...$strings
*
* @return array<string|\Stringable>
*/
private function trimPrefix(string $prefix, string|\Stringable ...$strings): array
{
$regex = "!^\s*" . preg_quote(trim($prefix), '!') . "\s+!i";
$sanitized = [];
foreach ($strings as $string) {
if ($string instanceof \Stringable) {
$sanitized[] = $string;
} elseif ($string !== '') {
$sanitized[] = (string) preg_replace($regex, '', $string);
}
}
return $sanitized;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Utility/StringConverter.php | centreon/src/Utility/StringConverter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Utility;
class StringConverter
{
/**
* Convert a string in camel case format to snake case.
*
* @param string $camelCaseName Name in camelCase format
*
* @return string Returns the name converted in snake case format
*/
public static function convertCamelCaseToSnakeCase(string $camelCaseName): string
{
return mb_strtolower((string) preg_replace('/(?<!^)[A-Z]/', '_$0', $camelCaseName));
}
/**
* Convert a string in snake case format to camel case.
*
* @param string $snakeCaseName Name in snake format
*
* @return string Returns the name converted in camel case format
*/
public static function convertSnakeCaseToCamelCase(string $snakeCaseName): string
{
return lcfirst(str_replace('_', '', ucwords($snakeCaseName, '_')));
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Utility/UUIDGenerator.php | centreon/src/Utility/UUIDGenerator.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Utility;
use Symfony\Component\Uid\Uuid;
use Utility\Interfaces\UUIDGeneratorInterface;
class UUIDGenerator implements UUIDGeneratorInterface
{
/**
* @inheritDoc
*/
public function generateV4(): string
{
return (string) Uuid::v4();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Utility/Interfaces/StringGeneratorInterface.php | centreon/src/Utility/Interfaces/StringGeneratorInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Utility\Interfaces;
interface StringGeneratorInterface
{
/**
* Generate a string compatible for a URL Query Parameter usage.
*
* @return string
*/
public function generateForQueryParameter(): string;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Utility/Interfaces/UUIDGeneratorInterface.php | centreon/src/Utility/Interfaces/UUIDGeneratorInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Utility\Interfaces;
interface UUIDGeneratorInterface
{
/**
* Generate a UUID Version 4.
*
* @return string
*/
public function generateV4(): string;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Utility/Difference/DifferenceInterface.php | centreon/src/Utility/Difference/DifferenceInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Utility\Difference;
/**
* @template T
*/
interface DifferenceInterface
{
/**
* @param array<T> $before
* @param array<T> $after
*/
public function __construct(array $before, array $after);
/**
* @return array<T>
*/
public function getAdded(): array;
/**
* @return array<T>
*/
public function getRemoved(): array;
/**
* @return array<T>
*/
public function getCommon(): array;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Utility/Difference/BasicDifference.php | centreon/src/Utility/Difference/BasicDifference.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Utility\Difference;
/**
* Only for INT or STRING : basic.
*
* Note: indexes are preserved, up to you to use them or not.
*
* @template T of int|string
*
* @implements DifferenceInterface<T>
*/
final class BasicDifference implements DifferenceInterface
{
/**
* @param array<T> $before
* @param array<T> $after
*/
public function __construct(private readonly array $before, private readonly array $after)
{
}
/**
* @return array<T>
*/
public function getAdded(): array
{
return array_diff($this->after, $this->before);
}
/**
* @return array<T>
*/
public function getRemoved(): array
{
return array_diff($this->before, $this->after);
}
/**
* @return array<T>
*/
public function getCommon(): array
{
return array_intersect($this->before, $this->after);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Utility/Difference/TupleDifference.php | centreon/src/Utility/Difference/TupleDifference.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Utility\Difference;
/**
* Only for TUPLE = array of INT or STRING.
*
* Note: indexes are preserved, up to you to use them or not.
*
* @template T of array<int|string>
*
* @implements DifferenceInterface<T>
*/
final class TupleDifference implements DifferenceInterface
{
/** @var array<string> */
private array $beforeSerialized = [];
/** @var array<string> */
private array $afterSerialized = [];
/**
* @param array<T> $before
* @param array<T> $after
*/
public function __construct(private readonly array $before, private readonly array $after)
{
foreach ($this->before as $key => $value) {
$this->beforeSerialized[$key] = serialize($value);
}
foreach ($this->after as $key => $value) {
$this->afterSerialized[$key] = serialize($value);
}
}
/**
* @return array<T>
*/
public function getAdded(): array
{
$diff = array_diff($this->afterSerialized, $this->beforeSerialized);
$added = [];
foreach ($diff as $key => $value) {
$added[$key] = $this->after[$key];
}
return $added;
}
/**
* @return array<T>
*/
public function getRemoved(): array
{
$diff = array_diff($this->beforeSerialized, $this->afterSerialized);
$removed = [];
foreach ($diff as $key => $value) {
$removed[$key] = $this->before[$key];
}
return $removed;
}
/**
* @return array<T>
*/
public function getCommon(): array
{
$diff = array_intersect($this->beforeSerialized, $this->afterSerialized);
$common = [];
foreach ($diff as $key => $value) {
$common[$key] = $this->before[$key];
}
return $common;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/Kernel.php | centreon/src/App/Kernel.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace App;
use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\ErrorHandler\Debug;
use Symfony\Component\HttpKernel\Kernel as BaseKernel;
/**
* Legacy Kernel.
*/
class Kernel extends BaseKernel
{
use MicroKernelTrait;
private static ?Kernel $instance = null;
/** @var string cache path */
private string $cacheDir = '/var/cache/centreon/symfony';
/** @var string Log path */
private string $logDir = '/var/log/centreon/symfony';
/**
* Kernel constructor.
*/
public function __construct(string $environment, bool $debug)
{
parent::__construct($environment, $debug);
if (\defined('_CENTREON_LOG_')) {
$this->logDir = _CENTREON_LOG_ . '/symfony';
}
if (\defined('_CENTREON_CACHEDIR_')) {
$this->cacheDir = _CENTREON_CACHEDIR_ . '/symfony';
}
}
public static function createForWeb(): self
{
if (! self::$instance instanceof self) {
include_once \dirname(__DIR__, 2) . '/config/bootstrap.php';
if (isset($_SERVER['APP_DEBUG']) && $_SERVER['APP_DEBUG'] === '1') {
umask(0000);
Debug::enable();
} else {
$_SERVER['APP_DEBUG'] = '0';
}
$env = (isset($_SERVER['APP_ENV']) && is_scalar($_SERVER['APP_ENV']))
? (string) $_SERVER['APP_ENV']
: 'prod';
self::$instance = new self($env, (bool) $_SERVER['APP_DEBUG']);
self::$instance->boot();
}
return self::$instance;
}
/**
* @return iterable<mixed>
*/
public function registerBundles(): iterable
{
$contents = require $this->getProjectDir() . '/config/bundles.php';
if (! is_array($contents)) {
return;
}
foreach ($contents as $class => $envs) {
if ((is_array($envs) && (($envs[$this->environment] ?? $envs['all'] ?? false)))) {
yield new $class();
}
}
}
public function getProjectDir(): string
{
return \dirname(__DIR__, 2);
}
public function getCacheDir(): string
{
return $this->cacheDir;
}
public function getLogDir(): string
{
return $this->logDir;
}
protected function build(ContainerBuilder $container): void
{
$class = 'CentreonAnomalyDetection\DependencyInjection\TagIndicatorPass';
if (class_exists($class)) {
/** @var CompilerPassInterface $compilerPass */
$compilerPass = new $class();
$container->addCompilerPass($compilerPass);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/ActivityLogging/Domain/Event/LogActivityEventHandler.php | centreon/src/App/ActivityLogging/Domain/Event/LogActivityEventHandler.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace App\ActivityLogging\Domain\Event;
use App\ActivityLogging\Domain\Aggregate\ActionEnum;
use App\ActivityLogging\Domain\Aggregate\Actor;
use App\ActivityLogging\Domain\Aggregate\ActorId;
use App\ActivityLogging\Domain\Factory\ActivityLogFactoryInterface;
use App\ActivityLogging\Domain\Repository\ActivityLogRepository;
use App\Shared\Domain\Aggregate\AggregateRoot;
use App\Shared\Domain\Event\AggregateCreated;
use App\Shared\Domain\Event\AsEventHandler;
use Psr\Container\ContainerInterface;
use Symfony\Component\DependencyInjection\Attribute\AutowireLocator;
#[AsEventHandler]
final readonly class LogActivityEventHandler
{
public function __construct(
private ActivityLogRepository $repository,
#[AutowireLocator('activity_logging.activity_log_factory')]
private ContainerInterface $activityLogFactories,
) {
}
public function __invoke(AggregateCreated $event): void
{
if (! $this->activityLogFactories->has($event->aggregate::class)) {
throw new \LogicException(\sprintf('There is no "%s" for "%s", did you add a service with "activity_logging.activity_log_factory" tag?', ActivityLogFactoryInterface::class, $event->aggregate::class));
}
/** @var ActivityLogFactoryInterface<AggregateRoot> $factory */
$factory = $this->activityLogFactories->get($event->aggregate::class);
$activityLog = $factory->create(
action: ActionEnum::Add,
aggregate: $event->aggregate,
firedBy: new Actor(id: new ActorId($event->creatorId)),
firedAt: $event->firedAt(),
);
$this->repository->add($activityLog);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/ActivityLogging/Domain/Aggregate/TargetName.php | centreon/src/App/ActivityLogging/Domain/Aggregate/TargetName.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace App\ActivityLogging\Domain\Aggregate;
use Webmozart\Assert\Assert;
final readonly class TargetName
{
public function __construct(
public string $value,
) {
Assert::lengthBetween($value, 1, 255);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/ActivityLogging/Domain/Aggregate/ActorId.php | centreon/src/App/ActivityLogging/Domain/Aggregate/ActorId.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace App\ActivityLogging\Domain\Aggregate;
use Webmozart\Assert\Assert;
final readonly class ActorId
{
public function __construct(
public int $value,
) {
Assert::positiveInteger($value);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/ActivityLogging/Domain/Aggregate/ActivityLogId.php | centreon/src/App/ActivityLogging/Domain/Aggregate/ActivityLogId.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace App\ActivityLogging\Domain\Aggregate;
use Webmozart\Assert\Assert;
final readonly class ActivityLogId
{
public function __construct(
public int $value,
) {
Assert::positiveInteger($value);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/ActivityLogging/Domain/Aggregate/ActivityLog.php | centreon/src/App/ActivityLogging/Domain/Aggregate/ActivityLog.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace App\ActivityLogging\Domain\Aggregate;
use App\Shared\Domain\Exception\MissingIdException;
final class ActivityLog
{
/**
* @param array<string, string> $details
*/
public function __construct(
private ?ActivityLogId $id,
public readonly ActionEnum $action,
public readonly Actor $actor,
public readonly Target $target,
public readonly array $details = [],
public readonly \DateTimeImmutable $performedAt = new \DateTimeImmutable(),
) {
}
public function id(): ActivityLogId
{
if (! $this->id instanceof ActivityLogId) {
throw new MissingIdException(self::class);
}
return $this->id;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/ActivityLogging/Domain/Aggregate/TargetId.php | centreon/src/App/ActivityLogging/Domain/Aggregate/TargetId.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace App\ActivityLogging\Domain\Aggregate;
use Webmozart\Assert\Assert;
final readonly class TargetId
{
public function __construct(
public int $value,
) {
Assert::positiveInteger($value);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/ActivityLogging/Domain/Aggregate/TargetTypeEnum.php | centreon/src/App/ActivityLogging/Domain/Aggregate/TargetTypeEnum.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace App\ActivityLogging\Domain\Aggregate;
enum TargetTypeEnum: string
{
case Host = 'Host';
case ServiceCategory = 'ServiceCategory';
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/ActivityLogging/Domain/Aggregate/ActionEnum.php | centreon/src/App/ActivityLogging/Domain/Aggregate/ActionEnum.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace App\ActivityLogging\Domain\Aggregate;
enum ActionEnum: string
{
case Add = 'Add';
case Remove = 'Remove';
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/ActivityLogging/Domain/Aggregate/Actor.php | centreon/src/App/ActivityLogging/Domain/Aggregate/Actor.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace App\ActivityLogging\Domain\Aggregate;
final readonly class Actor
{
public function __construct(
public ActorId $id,
) {
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/ActivityLogging/Domain/Aggregate/Target.php | centreon/src/App/ActivityLogging/Domain/Aggregate/Target.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace App\ActivityLogging\Domain\Aggregate;
final readonly class Target
{
public function __construct(
public TargetId $id,
public TargetName $name,
public TargetTypeEnum $type,
) {
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/ActivityLogging/Domain/Repository/ActivityLogRepository.php | centreon/src/App/ActivityLogging/Domain/Repository/ActivityLogRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace App\ActivityLogging\Domain\Repository;
use App\ActivityLogging\Domain\Aggregate\ActivityLog;
use App\ActivityLogging\Domain\Aggregate\ActivityLogId;
interface ActivityLogRepository
{
public function add(ActivityLog $activityLog): void;
public function count(): int;
public function find(ActivityLogId $id): ?ActivityLog;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/ActivityLogging/Domain/Factory/ServiceCategoryActivityLogFactory.php | centreon/src/App/ActivityLogging/Domain/Factory/ServiceCategoryActivityLogFactory.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace App\ActivityLogging\Domain\Factory;
use App\ActivityLogging\Domain\Aggregate\ActionEnum;
use App\ActivityLogging\Domain\Aggregate\ActivityLog;
use App\ActivityLogging\Domain\Aggregate\Actor;
use App\ActivityLogging\Domain\Aggregate\Target;
use App\ActivityLogging\Domain\Aggregate\TargetId;
use App\ActivityLogging\Domain\Aggregate\TargetName;
use App\ActivityLogging\Domain\Aggregate\TargetTypeEnum;
use App\MonitoringConfiguration\Domain\Aggregate\ServiceCategory\ServiceCategory;
use App\Shared\Domain\Aggregate\AggregateRoot;
use Symfony\Component\DependencyInjection\Attribute\AsTaggedItem;
/**
* @implements ActivityLogFactoryInterface<ServiceCategory>
*/
#[AsTaggedItem(index: ServiceCategory::class)]
final readonly class ServiceCategoryActivityLogFactory implements ActivityLogFactoryInterface
{
public function create(ActionEnum $action, AggregateRoot $aggregate, Actor $firedBy, \DateTimeImmutable $firedAt): ActivityLog
{
$target = new Target(
id: new TargetId($aggregate->id()->value),
name: new TargetName($aggregate->name->value),
type: TargetTypeEnum::ServiceCategory,
);
$details = [
'sc_activate' => $aggregate->activated ? '1' : '0',
'sc_name' => $aggregate->name->value,
'sc_alias' => $aggregate->alias->value,
];
return new ActivityLog(
id: null,
action: $action,
actor: $firedBy,
target: $target,
performedAt: $firedAt,
details: $details,
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/ActivityLogging/Domain/Factory/ActivityLogFactoryInterface.php | centreon/src/App/ActivityLogging/Domain/Factory/ActivityLogFactoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace App\ActivityLogging\Domain\Factory;
use App\ActivityLogging\Domain\Aggregate\ActionEnum;
use App\ActivityLogging\Domain\Aggregate\ActivityLog;
use App\ActivityLogging\Domain\Aggregate\Actor;
use App\Shared\Domain\Aggregate\AggregateRoot;
use Symfony\Component\DependencyInjection\Attribute\AutoconfigureTag;
/**
* @template T of AggregateRoot
*/
#[AutoconfigureTag('activity_logging.activity_log_factory')]
interface ActivityLogFactoryInterface
{
/**
* @param T $aggregate
*/
public function create(ActionEnum $action, AggregateRoot $aggregate, Actor $firedBy, \DateTimeImmutable $firedAt): ActivityLog;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/ActivityLogging/Infrastructure/Doctrine/DoctrineActivityLogRepository.php | centreon/src/App/ActivityLogging/Infrastructure/Doctrine/DoctrineActivityLogRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace App\ActivityLogging\Infrastructure\Doctrine;
use App\ActivityLogging\Domain\Aggregate\ActionEnum;
use App\ActivityLogging\Domain\Aggregate\ActivityLog;
use App\ActivityLogging\Domain\Aggregate\ActivityLogId;
use App\ActivityLogging\Domain\Aggregate\Actor;
use App\ActivityLogging\Domain\Aggregate\ActorId;
use App\ActivityLogging\Domain\Aggregate\Target;
use App\ActivityLogging\Domain\Aggregate\TargetId;
use App\ActivityLogging\Domain\Aggregate\TargetName;
use App\ActivityLogging\Domain\Aggregate\TargetTypeEnum;
use App\ActivityLogging\Domain\Repository\ActivityLogRepository;
use App\Shared\Infrastructure\Dbal\DbalRepository;
use Doctrine\DBAL\Connection;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
/**
* @phpstan-type RowTypeAlias = array{action_log_id: int, action_log_date: int, object_id: int, object_name: string, object_type: string, action_type: string, log_contact_id: int, field_name: string|null, field_value: string|null}
*/
final readonly class DoctrineActivityLogRepository extends DbalRepository implements ActivityLogRepository
{
private const TABLE_NAME = 'log_action';
private const DETAIL_TABLE_NAME = 'log_action_modification';
private const TARGET_TYPE_VALUE_MAP = [
TargetTypeEnum::ServiceCategory->value => 'servicecategories',
];
private const ACTION_VALUE_MAP = [
ActionEnum::Add->value => 'a',
];
public function __construct(
#[Autowire(service: 'doctrine.dbal.realtime_connection')]
private Connection $connection,
) {
}
public function add(ActivityLog $activityLog): void
{
$qb = $this->connection->createQueryBuilder();
$targetType = self::TARGET_TYPE_VALUE_MAP[$activityLog->target->type->value];
$action = self::ACTION_VALUE_MAP[$activityLog->action->value];
$qb->insert(self::TABLE_NAME)
->values([
'action_log_date' => ':performedAt',
'object_id' => ':targetId',
'object_name' => ':targetName',
'object_type' => ':targetType',
'action_type' => ':action',
'log_contact_id' => ':actorId',
])
->setParameter('performedAt', $activityLog->performedAt->getTimestamp())
->setParameter('targetId', $activityLog->target->id->value)
->setParameter('targetName', $activityLog->target->name->value)
->setParameter('targetType', $targetType)
->setParameter('action', $action)
->setParameter('actorId', $activityLog->actor->id->value)
->executeStatement();
$id = (int) $this->connection->lastInsertId();
if ($id === 0) {
throw new \RuntimeException(sprintf('Unable to retrieve last insert ID for "%s".', self::TABLE_NAME));
}
$this->setId($activityLog, new ActivityLogId($id));
foreach ($activityLog->details as $name => $value) {
$qb->insert(self::DETAIL_TABLE_NAME)
->values([
'action_log_id' => ':logId',
'field_name' => ':name',
'field_value' => ':value',
])
->setParameter('logId', $id)
->setParameter('name', $name)
->setParameter('value', $value)
->executeStatement();
}
}
public function find(ActivityLogId $id): ?ActivityLog
{
$qb = $this->connection->createQueryBuilder();
$qb->select('l.action_log_id', 'l.action_log_date', 'l.object_id', 'l.object_name', 'l.object_type', 'l.action_type', 'l.log_contact_id', 'd.field_name', 'd.field_value')
->from(self::TABLE_NAME, 'l')
->leftJoin('l', self::DETAIL_TABLE_NAME, 'd', 'l.action_log_id = d.action_log_id')
->where('l.action_log_id = :id')
->setParameter('id', $id->value);
/** @var list<RowTypeAlias> $rows */
$rows = $qb->executeQuery()->fetchAllAssociative();
if ($rows === []) {
return null;
}
return $this->createActivityLog($rows);
}
public function count(): int
{
$qb = $this->connection->createQueryBuilder();
$qb->select('count(1)')
->from(self::TABLE_NAME)
->setMaxResults(1);
/** @var int|false $count */
$count = $qb->executeQuery()->fetchOne();
return $count ?: 0;
}
/**
* @param non-empty-array<RowTypeAlias> $rows
*/
private function createActivityLog(array $rows): ActivityLog
{
$details = [];
foreach ($rows as $row) {
if ($row['field_name'] !== null && $row['field_value'] !== null) {
$details[$row['field_name']] = $row['field_value'];
}
}
$row = $rows[0];
$targetType = array_flip(self::TARGET_TYPE_VALUE_MAP)[$row['object_type']] ?? null;
if ($targetType === null) {
throw new \RuntimeException(sprintf('There is no "%s" associated to "%s", try to updated %s::TARGET_TYPE_VALUE_MAP.', TargetTypeEnum::class, $row['object_type'], self::class));
}
$action = array_flip(self::ACTION_VALUE_MAP)[$row['action_type']] ?? null;
if ($action === null) {
throw new \RuntimeException(sprintf('There is no "%s" associated to "%s", try to updated %s::ACTION_VALUE_MAP.', ActionEnum::class, $row['action_type'], self::class));
}
return new ActivityLog(
id: new ActivityLogId($row['action_log_id']),
action: ActionEnum::from($action),
actor: new Actor(
id: new ActorId($row['log_contact_id']),
),
target: new Target(
id: new TargetId($row['object_id']),
name: new TargetName($row['object_name']),
type: TargetTypeEnum::from($targetType),
),
performedAt: (new \DateTimeImmutable('@' . $row['action_log_date']))->setTimezone(new \DateTimeZone(date_default_timezone_get())),
details: $details,
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/MonitoringConfiguration/Application/Command/CreateServiceCategoryCommandHandler.php | centreon/src/App/MonitoringConfiguration/Application/Command/CreateServiceCategoryCommandHandler.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace App\MonitoringConfiguration\Application\Command;
use App\MonitoringConfiguration\Domain\Aggregate\ServiceCategory\ServiceCategory;
use App\MonitoringConfiguration\Domain\Event\ServiceCategoryCreated;
use App\MonitoringConfiguration\Domain\Exception\ServiceCategoryAlreadyExistsException;
use App\MonitoringConfiguration\Domain\Repository\ServiceCategoryRepository;
use App\Shared\Application\Command\AsCommandHandler;
use App\Shared\Domain\Event\EventBus;
#[AsCommandHandler]
final readonly class CreateServiceCategoryCommandHandler
{
public function __construct(
private ServiceCategoryRepository $repository,
private EventBus $eventBus,
) {
}
public function __invoke(CreateServiceCategoryCommand $command): ServiceCategory
{
$serviceCategory = new ServiceCategory(
id: null,
name: $command->name,
alias: $command->alias,
activated: $command->activated,
);
if ($this->repository->findOneByName($serviceCategory->name) instanceof ServiceCategory) {
throw new ServiceCategoryAlreadyExistsException(['name' => $serviceCategory->name->value]);
}
$this->repository->add($serviceCategory);
// Ensure the repository assigned an ID
$serviceCategory->id();
$this->eventBus->fire(new ServiceCategoryCreated($serviceCategory, $command->creatorId));
return $serviceCategory;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/MonitoringConfiguration/Application/Command/CreateServiceCategoryCommand.php | centreon/src/App/MonitoringConfiguration/Application/Command/CreateServiceCategoryCommand.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace App\MonitoringConfiguration\Application\Command;
use App\MonitoringConfiguration\Domain\Aggregate\ServiceCategory\ServiceCategoryName;
final readonly class CreateServiceCategoryCommand
{
public function __construct(
public ServiceCategoryName $name,
public ServiceCategoryName $alias,
public bool $activated,
public int $creatorId,
) {
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/MonitoringConfiguration/Domain/Event/ServiceCategoryCreated.php | centreon/src/App/MonitoringConfiguration/Domain/Event/ServiceCategoryCreated.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace App\MonitoringConfiguration\Domain\Event;
use App\Shared\Domain\Event\AggregateCreated;
final readonly class ServiceCategoryCreated extends AggregateCreated
{
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/MonitoringConfiguration/Domain/Exception/ServiceCategoryAlreadyExistsException.php | centreon/src/App/MonitoringConfiguration/Domain/Exception/ServiceCategoryAlreadyExistsException.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace App\MonitoringConfiguration\Domain\Exception;
use App\Shared\Domain\Exception\AggregateAlreadyExistsException;
final class ServiceCategoryAlreadyExistsException extends AggregateAlreadyExistsException
{
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/MonitoringConfiguration/Domain/Exception/OptionDoesNotExistException.php | centreon/src/App/MonitoringConfiguration/Domain/Exception/OptionDoesNotExistException.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace App\MonitoringConfiguration\Domain\Exception;
use App\Shared\Domain\Exception\AggregateDoesNotExistException;
final class OptionDoesNotExistException extends AggregateDoesNotExistException
{
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/MonitoringConfiguration/Domain/Aggregate/Poller/PollerId.php | centreon/src/App/MonitoringConfiguration/Domain/Aggregate/Poller/PollerId.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace App\MonitoringConfiguration\Domain\Aggregate\Poller;
use App\Shared\Domain\Aggregate\AggregateRootId;
final readonly class PollerId extends AggregateRootId
{
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/MonitoringConfiguration/Domain/Aggregate/Poller/PollerName.php | centreon/src/App/MonitoringConfiguration/Domain/Aggregate/Poller/PollerName.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace App\MonitoringConfiguration\Domain\Aggregate\Poller;
use Webmozart\Assert\Assert;
final readonly class PollerName
{
public function __construct(
public string $value,
) {
Assert::lengthBetween($value, 1, 255);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/MonitoringConfiguration/Domain/Aggregate/Poller/Poller.php | centreon/src/App/MonitoringConfiguration/Domain/Aggregate/Poller/Poller.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace App\MonitoringConfiguration\Domain\Aggregate\Poller;
use App\MonitoringConfiguration\Domain\Aggregate\GlobalMacro\GlobalMacro;
use App\Shared\Domain\Aggregate\AggregateRoot;
use App\Shared\Domain\Collection;
final class Poller extends AggregateRoot
{
/**
* @param Collection<GlobalMacro> $globalMacros
*/
public function __construct(
?PollerId $id,
public readonly PollerName $name,
public readonly Collection $globalMacros,
) {
parent::__construct($id);
}
public function addGlobalMacro(GlobalMacro $globalMacro): void
{
if ($this->globalMacros->contains($globalMacro)) {
return;
}
$this->globalMacros->add($globalMacro);
$globalMacro->addPoller($this);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/MonitoringConfiguration/Domain/Aggregate/ServiceCategory/ServiceCategoryName.php | centreon/src/App/MonitoringConfiguration/Domain/Aggregate/ServiceCategory/ServiceCategoryName.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace App\MonitoringConfiguration\Domain\Aggregate\ServiceCategory;
use Webmozart\Assert\Assert;
final readonly class ServiceCategoryName
{
public function __construct(
public string $value,
) {
Assert::lengthBetween($value, 1, 255);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/MonitoringConfiguration/Domain/Aggregate/ServiceCategory/ServiceCategoryId.php | centreon/src/App/MonitoringConfiguration/Domain/Aggregate/ServiceCategory/ServiceCategoryId.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace App\MonitoringConfiguration\Domain\Aggregate\ServiceCategory;
use App\Shared\Domain\Aggregate\AggregateRootId;
final readonly class ServiceCategoryId extends AggregateRootId
{
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/MonitoringConfiguration/Domain/Aggregate/ServiceCategory/ServiceCategory.php | centreon/src/App/MonitoringConfiguration/Domain/Aggregate/ServiceCategory/ServiceCategory.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace App\MonitoringConfiguration\Domain\Aggregate\ServiceCategory;
use App\Shared\Domain\Aggregate\AggregateRoot;
final class ServiceCategory extends AggregateRoot
{
public function __construct(
?ServiceCategoryId $id,
public readonly ServiceCategoryName $name,
public readonly ServiceCategoryName $alias,
public readonly bool $activated,
) {
parent::__construct($id);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/App/MonitoringConfiguration/Domain/Aggregate/GlobalMacro/GlobalMacroExpression.php | centreon/src/App/MonitoringConfiguration/Domain/Aggregate/GlobalMacro/GlobalMacroExpression.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace App\MonitoringConfiguration\Domain\Aggregate\GlobalMacro;
use Webmozart\Assert\Assert;
final readonly class GlobalMacroExpression
{
public function __construct(
public string $value,
) {
Assert::lengthBetween($value, 1, 255);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.