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-open-tickets/www/modules/centreon-open-tickets/php/clear_cache.php
centreon-open-tickets/www/modules/centreon-open-tickets/php/clear_cache.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ use App\Kernel; use Symfony\Bundle\FrameworkBundle\Console\Application; use Symfony\Component\Console\Input\ArgvInput; use Symfony\Component\Console\Output\BufferedOutput; use Symfony\Component\Console\Output\OutputInterface; $extractErrorMessage = function (BufferedOutput $output): ?string { $rawMessage = $output->fetch(); $messages = explode("\n", $rawMessage); $filteredMessages = []; foreach ($messages as $rawMessage) { if (! empty(trim($rawMessage))) { $filteredMessages[] = $rawMessage; } } if ($filteredMessages !== []) { if (str_starts_with(strtolower($filteredMessages[0]), 'in')) { array_shift($filteredMessages); } return implode('<br/>', $filteredMessages); } return null; }; if (! class_exists(Application::class)) { throw new RuntimeException('You need to add "symfony/framework-bundle" as a Composer dependency.'); } require _CENTREON_PATH_ . '/config/bootstrap.php'; $kernel = new Kernel($_SERVER['APP_ENV'], (bool) $_SERVER['APP_DEBUG']); $application = new Application($kernel); $application->setAutoExit(false); $consoleOutput = new BufferedOutput(); $consoleOutput->setVerbosity(OutputInterface::VERBOSITY_QUIET | OutputInterface::OUTPUT_RAW); $input = new ArgvInput(['', 'cache:clear']); $code = $application->run($input, $consoleOutput); if (! is_null($message = $extractErrorMessage($consoleOutput))) { throw new Exception($message); }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon-open-tickets/www/modules/centreon-open-tickets/php/install.php
centreon-open-tickets/www/modules/centreon-open-tickets/php/install.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ require __DIR__ . '/clear_cache.php';
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/.php-cs-fixer.conf.php
centreon/.php-cs-fixer.conf.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); return [ 'legacy' => [ 'files' => [ '.env.local.php', 'bootstrap.php', 'container.php', 'tests/php/bootstrap.php', 'tests/php/polyfill.php', ], 'directories' => [ 'api', 'config', 'cron', 'lib', 'libinstall', 'packaging', 'src/Centreon', 'src/CentreonCommand', 'src/CentreonLegacy', 'src/CentreonModule', 'src/CentreonNotification', 'src/CentreonRemote', 'src/CentreonUser', 'src/EventSubscriber', 'src/Security', 'src/Utility', 'tools', 'www', 'tests/php/Centreon', 'tests/php/CentreonLegacy', 'tests/php/CentreonRemote', 'tests/php/mock', 'tests/php/Security', 'tests/php/Utility', 'tests/php/www', ], 'skip' => [ 'centreon.config.php', // Exclude the config file because it is generated by the installer ], ], 'core' => [ 'files' => [ 'src/Centreon/Infrastructure/DatabaseConnection.php', ], 'directories' => [ 'src/Core', 'tests/php/Core', ], 'skip' => [], ], 'new' => [ 'files' => [ '.php-cs-fixer.conf.php', '.php-cs-fixer.diff.php', '.php-cs-fixer.core.php', '.php-cs-fixer.legacy.php', '.php-cs-fixer.new.php', 'castor.php', 'rector.conf.php', 'rector.core.php', 'rector.diff.php', 'rector.legacy.php', 'rector.new.php', ], 'directories' => [ 'config.new', 'src/Adaptation', 'src/App', 'tests/php/Adaptation', 'tests/php/App', ], 'skip' => [], ], ];
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/castor.php
centreon/castor.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); use Castor\Attribute\AsRawTokens; use Castor\Attribute\AsTask; use function Castor\context; use function Castor\run; #[AsTask(description: 'Fix coding style')] function cs(bool $dryRun = false): void { $command = ['vendor/bin/php-cs-fixer', 'fix', '--config', '.php-cs-fixer.new.php']; if ($dryRun) { $command[] = '--dry-run'; } run($command, context: context()->withEnvironment(['PHP_CS_FIXER_IGNORE_ENV' => true])); } #[AsTask(description: 'Analyze code')] function stan(): void { $command = ['vendor/bin/phpstan', 'analyze', '--configuration', 'phpstan.new.neon']; run($command, context: context()->withEnvironment(['XDEBUG_MODE' => 'off'])); } #[AsTask(description: 'Run dependency analysis')] function dep(): void { run(['vendor/bin/deptrac', 'analyze', '--config-file', 'deptrac_bc.yaml', '--cache-file', '.deptrac_bc.cache', '--fail-on-uncovered', '--report-uncovered']); run(['vendor/bin/deptrac', 'analyze', '--config-file', 'deptrac_hexa.yaml', '--cache-file', '.deptrac_hexa.cache', '--fail-on-uncovered', '--report-uncovered']); } #[AsTask(description: 'Test the application')] function test(?string $filter = null, ?string $group = null): void { $command = ['vendor/bin/simple-phpunit', '--configuration', 'phpunit.new.xml']; if ($filter) { $command = [...$command, '--filter', $filter]; } if ($group) { $command = [...$command, '--group', $group]; } run($command); } #[AsTask(description: 'Run CI locally')] function ci(): void { cs(dryRun: true); stan(); dep(); test(); } #[AsTask(description: 'Run a Symfony Console command')] function console(#[AsRawTokens] array $args = []): void { run(['bin/console.new', ...$args]); }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/.php-cs-fixer.diff.php
centreon/.php-cs-fixer.diff.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); use Tools\PhpCsFixer\Command\RunCsFixerOnDiffCommand; use Tools\PhpCsFixer\Command\RunCsFixerOnDiffCommandHandler; require_once __DIR__ . '/../php-tools/vendor/autoload.php'; $pathsConfig = require_once __DIR__ . '/.php-cs-fixer.conf.php'; $args = $_SERVER['argv'] ?? []; $runCsFixerOnDiffCommand = new RunCsFixerOnDiffCommand( moduleName: 'centreon', sections: ['legacy', 'core', 'new'], pathsConfig: $pathsConfig, args: $args ); $runCsFixerOnDiffCommandHandler = new RunCsFixerOnDiffCommandHandler(); $runCsFixerOnDiffCommandHandler->run($runCsFixerOnDiffCommand);
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/.php-cs-fixer.core.php
centreon/.php-cs-fixer.core.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); use PhpCsFixer\Finder; $csFixerConfig = require_once __DIR__ . '/../php-tools/php-cs-fixer/config/base.strict.php'; $pathsConfig = require_once __DIR__ . '/.php-cs-fixer.conf.php'; $finder = Finder::create() ->in($pathsConfig['core']['directories']) ->append($pathsConfig['core']['files']) ->notPath($pathsConfig['core']['skip']); return $csFixerConfig ->setFinder($finder) ->setCacheFile('.php-cs-fixer.core.cache');
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/.php-cs-fixer.legacy.php
centreon/.php-cs-fixer.legacy.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); use PhpCsFixer\Finder; $csFixerConfig = require_once __DIR__ . '/../php-tools/php-cs-fixer/config/base.unstrict.php'; $pathsConfig = require_once __DIR__ . '/.php-cs-fixer.conf.php'; $finder = Finder::create() ->in($pathsConfig['legacy']['directories']) ->append($pathsConfig['legacy']['files']) ->notPath($pathsConfig['legacy']['skip']); return $csFixerConfig ->setFinder($finder) ->setCacheFile('.php-cs-fixer.legacy.cache');
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/rector.new.php
centreon/rector.new.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); $rectorConfig = require_once __DIR__ . '/../php-tools/rector/config/base.strict.php'; $pathsConfig = require_once __DIR__ . '/rector.conf.php'; return $rectorConfig ->withCache(__DIR__ . '/var/cache/rector.new') ->withPaths($pathsConfig['new']['paths']) ->withSkip($pathsConfig['new']['skip']);
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/rector.diff.php
centreon/rector.diff.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); use Tools\Rector\Command\RunRectorOnDiffCommand; use Tools\Rector\Command\RunRectorOnDiffCommandHandler; require_once __DIR__ . '/../php-tools/vendor/autoload.php'; $pathsConfig = require_once __DIR__ . '/rector.conf.php'; $args = $_SERVER['argv'] ?? []; $runRectorOnDiffCommand = new RunRectorOnDiffCommand( moduleName: 'centreon', sections: ['legacy', 'core', 'new'], pathsConfig: $pathsConfig, args: $args ); $runRectorOnDiffCommandHandler = new RunRectorOnDiffCommandHandler(); $runRectorOnDiffCommandHandler->run($runRectorOnDiffCommand);
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/rector.legacy.php
centreon/rector.legacy.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); $rectorConfig = require_once __DIR__ . '/../php-tools/rector/config/base.unstrict.php'; $pathsConfig = require_once __DIR__ . '/rector.conf.php'; return $rectorConfig ->withCache(__DIR__ . '/var/cache/rector.legacy') ->withPaths($pathsConfig['legacy']['paths']) ->withSkip($pathsConfig['legacy']['skip']);
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/.php-cs-fixer.new.php
centreon/.php-cs-fixer.new.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); use PhpCsFixer\Finder; $csFixerConfig = require_once __DIR__ . '/../php-tools/php-cs-fixer/config/base.strict.php'; $pathsConfig = require_once __DIR__ . '/.php-cs-fixer.conf.php'; $finder = Finder::create() ->in($pathsConfig['new']['directories']) ->append($pathsConfig['new']['files']) ->notPath($pathsConfig['new']['skip']); $rules = $csFixerConfig->getRules(); return $csFixerConfig ->setRules($rules) ->setFinder($finder) ->setCacheFile('.php-cs-fixer.new.cache');
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/rector.core.php
centreon/rector.core.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); $rectorConfig = require_once __DIR__ . '/../php-tools/rector/config/base.unstrict.php'; $pathsConfig = require_once __DIR__ . '/rector.conf.php'; return $rectorConfig ->withCache(__DIR__ . '/var/cache/rector.core') ->withPaths($pathsConfig['core']['paths']) ->withSkip($pathsConfig['core']['skip']);
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/.env.local.php
centreon/.env.local.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ return [ 'APP_ENV' => 'prod', 'APP_SECRET' => '%APP_SECRET%', ];
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/rector.conf.php
centreon/rector.conf.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); use Rector\Php81\Rector\Property\ReadOnlyPropertyRector; return [ 'legacy' => [ 'paths' => [ // directories 'api/', 'config/', 'cron/', 'lib/', 'libinstall/', 'packaging/', 'src/', 'tests/php/', 'tools/', 'www/', // files 'bootstrap.php', 'container.php', ], 'skip' => [ // directories 'www/class/centreon-clapi/', 'src/Adaptation', 'src/App', 'src/Core', 'tests/php/Adaptation', 'tests/php/App', 'tests/php/Core', ], ], 'core' => [ 'paths' => [ // directories 'src/Core/', 'tests/php/Core/', ], 'skip' => [], ], 'new' => [ 'paths' => [ // directories 'src/Adaptation/', 'src/App/', 'tests/php/Adaptation/', 'tests/php/App/', // files '.env.local.php', '.php-cs-fixer.conf.php', '.php-cs-fixer.core.php', '.php-cs-fixer.diff.php', '.php-cs-fixer.legacy.php', '.php-cs-fixer.new.php', 'rector.conf.php', 'rector.core.php', 'rector.diff.php', 'rector.legacy.php', 'rector.new.php', ], 'skip' => [ // because id are only able to be set by object construction, rector // tries to set it as readonly. But in repositories, we set the id using // reflection (to protect the domain). Therefore the id property cannot be // readonly. ReadOnlyPropertyRector::class => __DIR__ . '/src/App/*/Domain/Aggregate/*', ], ], ];
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/bootstrap.php
centreon/bootstrap.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ set_include_path(implode(PATH_SEPARATOR, [realpath(__DIR__ . '/www/class'), realpath(__DIR__ . '/www/lib'), get_include_path()])); // Centreon Autoload spl_autoload_register(function ($sClass): void { $fileName = lcfirst($sClass); $fileNameType1 = __DIR__ . '/www/class/' . $fileName . '.class.php'; $fileNameType2 = __DIR__ . '/www/class/' . $fileName . '.php'; if (file_exists($fileNameType1)) { require_once $fileNameType1; } elseif (file_exists($fileNameType2)) { require_once $fileNameType2; } }); function loadDependencyInjector() { global $dependencyInjector; return $dependencyInjector; } // require composer file $loader = require __DIR__ . '/vendor/autoload.php'; Doctrine\Common\Annotations\AnnotationRegistry::registerLoader([$loader, 'loadClass']); // Retrieving Symfony environment variables for legacy code (APIv1,...) (new Symfony\Component\Dotenv\Dotenv())->bootEnv(__DIR__ . '/.env'); require_once __DIR__ . '/container.php';
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/container.php
centreon/container.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ // Creating container use Pimple\Container; global $dependencyInjector; $dependencyInjector = Centreon\LegacyContainer::getInstance(); // Define Centreon Configuration Database Connection $dependencyInjector['configuration_db'] = function ($c) { return new CentreonDB('centreon'); }; // Define Centreon Realtime Database Connection $dependencyInjector['realtime_db'] = function ($c) { return new CentreonDB('centstorage'); }; // Define Centreon Rest Http Client $dependencyInjector['rest_http'] = function ($c) { return new CentreonRestHttp(); }; // Define filesystem $dependencyInjector['filesystem'] = function ($c) { return new Symfony\Component\Filesystem\Filesystem(); }; // Utils $dependencyInjector['utils'] = function ($c) use ($dependencyInjector) { return $dependencyInjector[CentreonLegacy\ServiceProvider::CENTREON_LEGACY_UTILS]; }; // Define finder $dependencyInjector['finder'] = $dependencyInjector->factory(function ($c) { return new Symfony\Component\Finder\Finder(); }); // Define Language translator $dependencyInjector['translator'] = $dependencyInjector->factory(function ($c) { global $centreon; $translator = new CentreonLang(_CENTREON_PATH_, $centreon); $translator->bindLang(); $translator->bindLang('help'); return $translator; }); $dependencyInjector['path.files_generation'] = _CENTREON_PATH_ . '/filesGeneration/'; // Defines the web service that will transform the translation files into one json file $dependencyInjector[CentreonI18n::class] = function ($container) { require_once _CENTREON_PATH_ . '/www/api/class/centreon_i18n.class.php'; $lang = getenv('LANG'); if ($lang === false) { // Initialize the language translator $container['translator']; $lang = getenv('LANG'); } if (! str_contains($lang, '.UTF-8')) { $lang .= '.UTF-8'; } $translationFile = _CENTREON_PATH_ . "www/locale/{$lang}/LC_MESSAGES/messages.ser"; $translation = new CentreonI18n(); $translation->setFilesGenerationPath($translationFile); return $translation; }; // Dynamically register service provider Centreon\Infrastructure\Provider\AutoloadServiceProvider::register($dependencyInjector); // Centreon configuration files $configFiles = $dependencyInjector['finder'] ->files() ->name('*.config.php') ->depth('== 0') ->in(__DIR__ . '/config'); foreach ($configFiles as $configFile) { $configFileName = $configFile->getBasename(); require __DIR__ . '/config/' . $configFileName; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/packaging/src/install.conf.php
centreon/packaging/src/install.conf.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ $conf_centreon['centreon_dir'] = '/usr/share/centreon/'; $conf_centreon['centreon_etc'] = '/etc/centreon/'; $conf_centreon['centreon_dir_www'] = '/usr/share/centreon/www/'; $conf_centreon['centreon_dir_rrd'] = '/var/lib/centreon'; $conf_centreon['centreon_log'] = '/var/log/centreon'; $conf_centreon['centreon_cachedir'] = '/var/cache/centreon/'; $conf_centreon['centreon_varlib'] = '/var/lib/centreon'; $conf_centreon['centreon_group'] = 'centreon'; $conf_centreon['centreon_user'] = 'centreon'; $conf_centreon['rrdtool_dir'] = '/usr/bin/rrdtool'; $conf_centreon['apache_user'] = '@WEB_USER@'; $conf_centreon['apache_group'] = '@WEB_USER@'; $conf_centreon['mail'] = '/bin/mail'; $conf_centreon['broker_user'] = 'centreon-broker'; $conf_centreon['broker_group'] = 'centreon-broker'; $conf_centreon['broker_etc'] = '/etc/centreon-broker'; $conf_centreon['monitoring_user'] = 'centreon-engine'; $conf_centreon['monitoring_group'] = 'centreon-engine'; $conf_centreon['monitoring_etc'] = '/etc/centreon-engine'; $conf_centreon['monitoring_binary'] = '/usr/sbin/centengine'; $conf_centreon['monitoring_varlog'] = '/var/log/centreon-engine'; $conf_centreon['plugin_dir'] = '/usr/lib64/nagios/plugins'; $conf_centreon['centreon_engine_connectors'] = '/usr/lib64/centreon-connector'; $conf_centreon['centreon_engine_lib'] = '/usr/lib64/centreon-engine'; $conf_centreon['centreon_plugins'] = '/usr/lib/centreon/plugins';
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/packaging/src/centreon.conf.php
centreon/packaging/src/centreon.conf.php
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tools/update_centreon_storage_logs.php
centreon/tools/update_centreon_storage_logs.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ /** * The goal of this script is to manage the removal of the log_id column from * the centreon_storage.logs table */ ini_set('max_execution_time', 0); require_once realpath(__DIR__ . '/../config/centreon.config.php'); require_once _CENTREON_PATH_ . '/www/class/centreonDB.class.php'; define('TEMP_DIRECTORY', '/tmp/'); // Indicates whether Broker is running at startup of this script $isBrokerAlreadyStarted = isBrokerRunning(); // Indicates whether this is a migration recovery $isMigrationRecovery = false; $fileInfos = pathinfo(__FILE__); $lockFileName = $fileInfos['filename'] . '.lock'; /** * Path for the temporary files */ $temporaryPath = null; /** * Check if the directory exist and add the character / at the end if it not exist * * @param string &$temporaryPath Path to check * * @throws Exception */ function checkTemporaryDirectory(&$temporaryPath) { if (is_dir($temporaryPath) === false) { throw new Exception( 'This path for temporary files (' . $temporaryPath . ') does not exist' ); } if (! str_ends_with($temporaryPath, '/')) { $temporaryPath .= '/'; } } /** * Ask question and wait response of type yes/no * * @param string $question Question to ask * @param bool $trueByDefault * @return bool Return TRUE if response is y or Y otherwise FALSE */ function askYesOrNoQuestion($question, $trueByDefault = true) { $defaultResponse = $trueByDefault ? 'Y' : 'N'; printf('%s [%s] ', $question, $defaultResponse); $handle = fopen('php://stdin', 'r'); $response = trim(fgets($handle)); $response = $response ?: $defaultResponse; fclose($handle); return strtolower($response) === 'y'; } /** * Ask question. The echo of keyboard can be disabled * * @param string $question Question to ask * @param bool $hidden Set to TRUE to disable the echo of keyboard * @return string Return the response */ function askQuestion($question, $hidden = false) { if ($hidden) { system('stty -echo'); } printf('%s', $question); $handle = fopen('php://stdin', 'r'); $response = trim(fgets($handle)); fclose($handle); if ($hidden) { system('stty echo'); } printf("\n"); return $response; } /** * Show message in the standard output * * @param string $message Message to show * @param bool $showStep Set to true if you want showing steps */ $logs = function ($message, $showStep = true) use (&$currentStep, &$partitionName): void { if ($showStep && $currentStep) { if (! empty($partitionName)) { printf( "[%s] [%s - STEP %d] %s\n", date('Y-m-d H:i:s'), $partitionName, $currentStep, $message ); } else { printf( "[%s] [STEP %d] %s\n", date('Y-m-d H:i:s'), $currentStep, $message ); } } else { printf("[%s] %s\n", date('Y-m-d H:i:s'), $message); } }; /** * Show message but without showing the partition name and step * * @param string $message Message to show */ function mySysLog($message) { global $logs; $logs($message, false); } /** * Stop the Centreon Broker process * * @return int Return status of the Broker stop */ function stopBroker() { exec('systemctl stop cbd', $output, $status); return $output === [] ? $status : -1; } /** * Start the Centreon Broker process * * @return int Return status of the Broker start */ function startBroker() { exec('systemctl start cbd', $output, $status); return $output === [] ? $status : -1; } /** * Indicate if broker is running * * @return bool Return TRUE if Broker is running */ function isBrokerRunning() { exec('systemctl status cbd', $output, $status); return ((int) $status) === 0; } /** * Get all partitions that are not empty * * @param PDO $db * @param mixed $isMigrationRecovery * @return array Return a list of partition name [0 => partition1, 1 => partition2, ...) */ function getNotEmptyPartitions($db, $isMigrationRecovery = false) { $tableName = $isMigrationRecovery ? 'logs_old' : 'logs'; $result = $db->query( 'SELECT PARTITION_NAME FROM INFORMATION_SCHEMA.PARTITIONS ' . "WHERE TABLE_NAME='{$tableName}'" ); $partitions = []; while (($row = $result->fetch(PDO::FETCH_ASSOC))) { $partitions[] = $row['PARTITION_NAME']; } ksort($partitions); $partitions = array_flip($partitions); foreach (array_keys($partitions) as $partition) { $countResult = $db->query( "SELECT COUNT(*) AS is_empty FROM ( SELECT ctime FROM {$tableName} PARTITION ({$partition}) LIMIT 0,1 ) AS s" ); $result = $countResult->fetchAll(PDO::FETCH_ASSOC); $isEmptyPartition = $result[0]['is_empty'] === 0; if ($isEmptyPartition) { unset($partitions[$partition]); } } return array_flip($partitions); } /** * Indicates whether we are in compatible mode. * The compatible mode should be used when the partition selection option is * not available. The compatible mode only applies to old database engines whose * versions are less than MariaDb 10 or MySQL 5.6 * * @param PDO $db * @return bool Return TRUE if in compatible mode */ function isInCompatibleMode(PDO $db) { $statement = $db->query('SELECT VERSION() AS version'); $result = $statement->fetchAll(PDO::FETCH_ASSOC); [$version, $dbType] = explode('-', $result[0]['version']); [$majorVersion, $minorVersion, $revision] = explode('.', $version); if ($dbType === 'MariaDB' && $majorVersion >= 10) { return false; } return ! ($dbType === 'standard' && $majorVersion >= 5 && $minorVersion >= 6); } $loadDataInfileQuery = <<<'QUERY' LOAD DATA INFILE '{{DATA_FILE}}' INTO TABLE logs FIELDS TERMINATED BY ',' ENCLOSED BY '"' ESCAPED BY '\\' LINES TERMINATED BY '\n' (log_id, ctime, @host_id, host_name, instance_name, @issue_id, msg_type, notification_cmd, notification_contact, output, retry, @service_description, @service_id, status, type) set host_id = if(@host_id = '', NULL, @host_id), issue_id = if(@issue_id = '', NULL, @issue_id), service_id = if(@service_id = '', NULL, @service_id), service_description = if(@service_description = '', NULL, @service_description) QUERY; $mainExplanation = <<<TEXT Before starting, we inform you that we will create a new %s.logs table and rename the older. Then, we will copy the data from the old table into the new one.\n\n TEXT; $mainExplanation = sprintf($mainExplanation, dbcstg); $recoveryExplanation = <<<TEXT Recovery mode. We consider that the old 'logs' table has already been renamed and the new one has been created. Now we will continue to copy the data from the old table to the new one.\n\n TEXT; $dbUser = 'root'; $currentStep = 1; try { // We load start parameters if ($argc > 1) { foreach ($argv as $parameter) { if (str_starts_with($parameter, '--password=')) { [, $dbPassword] = explode('=', $parameter); } elseif ($parameter === '--no-keep') { $shouldDeleteOldData = true; } elseif ($parameter === '--keep') { $shouldDeleteOldData = false; } elseif (str_starts_with($parameter, '--continue')) { $firstRecoveryPartitionName = ''; if (str_contains($parameter, '=')) { [, $firstRecoveryPartitionName] = explode('=', $parameter); } $isMigrationRecovery = true; } elseif (str_starts_with($parameter, '--temporary-path=')) { [, $temporaryPath] = explode('=', $parameter); } } } if (is_null($temporaryPath)) { $temporaryPath = TEMP_DIRECTORY; // We check if the default directory for temporary files exists if (is_dir(TEMP_DIRECTORY) === false) { $temporaryPath = __DIR__; } $pathDirectory = askQuestion( "Please to give the directory for temporary files [{$temporaryPath}]\n", false ); $temporaryPath = empty($pathDirectory) ? $temporaryPath : $pathDirectory; } checkTemporaryDirectory($temporaryPath); if (! isset($shouldDeleteOldData)) { // We display explanations according to the recovery mode printf($isMigrationRecovery ? $recoveryExplanation : $mainExplanation); // We ask to user if he want to keep old data otherwise we will delete the old logs table $shouldDeleteOldData = askYesOrNoQuestion( "Do you want to delete the partition data from the old log table after each copy?\n" . 'If not, be careful with your disk space: ', false ); } // We check if the database connection port is set, otherwise we request it. if (defined('port')) { $dbPort = port; } else { $port = askQuestion('Please enter the port of the Centreon database: '); if (! is_numeric($port)) { throw new Exception("The port given ({$port}) is not valid"); } $dbPort = (int) $port; } // We check if the database connection host is set, otherwise we request it. if (defined('hostCentstorage')) { $dbHost = hostCentstorage; } else { $dbHost = askQuestion('Please enter the host or IP address of the Centreon database: '); } if (! isset($dbPassword)) { // We need a root access $dbPassword = askQuestion('Please enter the root password of database: ', true); } // We create a .lock file to avoid to start this script while it is already running if (file_exists($lockFileName)) { mySysLog('Process ' . __FILE__ . ' already running'); exit(); } touch($lockFileName); // Connection to database $dsn = sprintf( 'mysql:dbname=%s;host=%s;port=%d', dbcstg, $dbHost, $dbPort ); $db = new PDO($dsn, $dbUser, $dbPassword); $db->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false); $db->setAttribute(PDO::ATTR_AUTOCOMMIT, false); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // We will process partitions that are not empty $partitions = getNotEmptyPartitions($db, $isMigrationRecovery); // If we are in the migration recovery mode, we do not create/alter the database if (! $isMigrationRecovery) { /* * First we check if this update is necessary by checking if the log_id * column is present */ $statement = $db->prepare( "SELECT COUNT(*) AS is_present FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = :db_storage AND TABLE_NAME = 'logs' AND COLUMN_NAME = 'log_id'" ); $statement->bindValue(':db_storage', dbcstg, PDO::PARAM_STR); $statement->execute(); $result = $statement->fetchAll(PDO::FETCH_ASSOC); $shouldBeContinue = $result[0]['is_present'] == '1'; if (! $shouldBeContinue) { throw new Exception('The current log table does not have the log_id column'); } // For consistency consideration, we stop broker before creating the new table if ($isBrokerAlreadyStarted) { $logs('For consistency consideration, we stop broker before creating the new table'); if (stopBroker() !== 0 && isBrokerRunning() === true) { throw new Exception('Error stopping Broker'); } } else { $logs('Broker is not started, no need to stop it'); } $currentStep++; // We create the new logs table and rename the older $logs('We create the new logs table and rename the older'); $db->query('CREATE TABLE logs_new LIKE logs'); $currentStep++; // Next we change the column log_id from the new logs table into BIGINT $logs('Next we modify the log_id column of the new logs table with the type BIGINT'); $db->query('ALTER TABLE logs_new MODIFY log_id BIGINT(20) NOT NULL AUTO_INCREMENT'); $currentStep++; // Finally we rename the current table 'logs' to 'logs_old' $logs("Finally we rename the current table 'logs' to 'logs_old'"); $db->query('ALTER TABLE logs RENAME TO logs_old'); $currentStep++; // And we rename the new table 'logs_new' to 'logs' $logs("And we rename the new table 'logs_new' to 'logs'"); $db->query('ALTER TABLE logs_new RENAME TO logs'); $currentStep++; // We start Broker if it was previously started if ($isBrokerAlreadyStarted) { // Now we can restart Broker $logs('Now we can restart Broker'); if (startBroker() !== 0 && isBrokerRunning() === false) { throw new Exception('Error starting Broker'); } } else { $logs('Broker was not started at the beginning of this script, we do not start it'); } $currentStep++; } elseif (! empty($partitions) && empty($firstRecoveryPartitionName)) { /** * Migration recovery mode */ // If the partition name is not defined, we get the first not empty partition name $firstRecoveryPartitionName = array_slice($partitions, 0, 1)[0]; } $isInCompatibleMode = isInCompatibleMode($db); $globalStep = $currentStep; $partitionOfTheDay = (new DateTime())->format('\pYmd'); // Now we can copy old data to the new logs table only for non-empty partitions foreach ($partitions as $partitionName) { // If the name of the first recovery partition is defined, we will start copying from it if (isset($firstRecoveryPartitionName) && $firstRecoveryPartitionName !== $partitionName) { continue; } if (isset($firstRecoveryPartitionName) && $firstRecoveryPartitionName === $partitionName) { unset($firstRecoveryPartitionName); } $currentStep = 1; // We copy data from old table into temporary csv file for the current partition $logs("Copying records from old table into csv file for the partition {$partitionName}"); $pathPartition = TEMP_DIRECTORY . $partitionName . '.csv'; if (! $fp = fopen($pathPartition, 'w')) { throw new Exception("Error creating the temporary csv file {$pathPartition}"); } if ($isInCompatibleMode) { $date = new DateTime(); $date->setDate( (int) substr($partitionName, 1, 4), (int) substr($partitionName, 5, 2), (int) substr($partitionName, 7, 2) ); $date->setTime(0, 0, 0); $end = (int) $date->format('U'); $date->setTime(-24, 0, 0); $start = (int) $date->format('U'); $result = $db->query("SELECT * FROM logs_old WHERE ctime >= {$start} AND ctime < {$end}"); } else { $result = $db->query("SELECT * FROM logs_old PARTITION ({$partitionName})"); } $nbrRecords = 0; while ($row = $result->fetch(PDO::FETCH_ASSOC)) { fputcsv($fp, $row); $nbrRecords++; } fclose($fp); $currentStep++; // We copy data from the csv partition file into the new table 'logs' $logs("Copying of {$nbrRecords} records from the csv file {$partitionName} into the new table"); $query = str_replace('{{DATA_FILE}}', realpath($pathPartition), $loadDataInfileQuery); if ($db->beginTransaction()) { // LOAD DATA INFILE ... $db->query($query); $currentStep++; // We delete the temporary csv file if (unlink($pathPartition)) { $logs("We delete the temporary csv file {$partitionName}"); $currentStep++; // If asked, we delete the old data from the old logs table if ($shouldDeleteOldData) { $logs("We delete the old data from the partition {$partitionName} of the old log table"); $db->query("DELETE FROM logs_old PARTITION ({$partitionName})"); } else { $logs("We do not delete the old data from the partition {$partitionName} of the old logs table"); } $db->commit(); } else { $db->rollBack(); throw new Exception("Error deleting the temporary csv file {$partitionName}"); } } else { throw new Exception('Error getting a database transaction'); } } $currentStep = $globalStep; $partitionName = null; // If asked, we delete the old log table if ($shouldDeleteOldData) { $logs('We delete the old logs table'); $db->query('DROP TABLE logs_old'); } else { $logs('We do not delete the old log table'); } } catch (Exception $ex) { mySysLog("ERROR: {$ex->getMessage()}"); } if (file_exists($lockFileName)) { unlink($lockFileName); } mySysLog(sprintf('End of %s', __FILE__));
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonCommand/ServiceProvider.php
centreon/src/CentreonCommand/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 CentreonCommand; use Centreon\Infrastructure\Provider\AutoloadServiceProviderInterface; use CentreonCommand\Application\Webservice; use Pimple\Container; class ServiceProvider implements AutoloadServiceProviderInterface { /** * {@inheritDoc} */ public function register(Container $pimple): void { // register Command webservice $pimple[\Centreon\ServiceProvider::CENTREON_WEBSERVICE] ->add(Webservice\CommandWebservice::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/CentreonCommand/Application/Webservice/CommandWebservice.php
centreon/src/CentreonCommand/Application/Webservice/CommandWebservice.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 CentreonCommand\Application\Webservice; use Centreon\Infrastructure\Webservice; use Centreon\ServiceProvider; use CentreonCommand\Application\Serializer; use CentreonCommand\Domain\Entity\Command; use CentreonCommand\Domain\Repository; /** * @OA\Tag(name="centreon_command", description="Resource for authorized access") */ class CommandWebservice extends Webservice\WebServiceAbstract implements Webservice\WebserviceAutorizeRestApiInterface { use Webservice\DependenciesTrait; /** * {@inheritDoc} */ public static function getName(): string { return 'centreon_command'; } /** * {@inheritDoc} * * @return array<ServiceProvider::CENTREON_PAGINATION> */ public static function dependencies(): array { return [ ServiceProvider::CENTREON_PAGINATION, ]; } /** * @OA\Get( * path="/external.php?object=centreon_command&action=list", * description="Get list of commands", * tags={"centreon_command"}, * security={{"Session": {}}}, * * @OA\Parameter( * in="query", * name="object", * * @OA\Schema( * type="string", * enum={"centreon_command"}, * ), * 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\Parameter( * in="query", * name="type", * * @OA\Schema( * type="string", * enum={"notification", "check", "misc", "discovery"}, * ), * description="filter by type" * ), * * @OA\Response( * response="200", * description="OK", * * @OA\JsonContent( * * @OA\Property( * property="entities", * type="array", * * @OA\Items(ref="#/components/schemas/CommandEntity") * ), * * @OA\Property( * property="pagination", * ref="#/components/schemas/Pagination" * ) * ) * ) * ) * * Get list of commands * * @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; $filters = []; if (isset($request['search']) && $request['search']) { $filters['search'] = $request['search']; } if (isset($request['searchByIds']) && $request['searchByIds']) { $filters['ids'] = explode(',', $request['searchByIds']); } if (isset($request['type']) && $request['type']) { $typeId = Command::getTypeIdFromName($request['type']); if ($typeId !== null) { $filters['type'] = $typeId; } unset($typeId); } $pagination = $this->services->get(ServiceProvider::CENTREON_PAGINATION); $pagination->setRepository(Repository\CommandRepository::class); $pagination->setContext(Serializer\Command\ListContext::context()); $pagination->setFilters($filters); $pagination->setLimit($limit); $pagination->setOffset($offset); return $pagination->getResponse(); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonCommand/Application/Serializer/Command/ListContext.php
centreon/src/CentreonCommand/Application/Serializer/Command/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 CentreonCommand\Application\Serializer\Command; use Centreon\Application\Serializer\SerializerContextInterface; use CentreonCommand\Domain\Entity\Command; /** * @OA\Schema( * schema="CommandEntity", * * @OA\Property(property="id", type="integer"), * @OA\Property(property="name", type="string") * ) * * Serialize Command entity for list */ class ListContext implements SerializerContextInterface { /** * {@inheritDoc} */ public static function context(): array { return [ static::GROUPS => [ Command::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/CentreonCommand/Domain/Entity/Command.php
centreon/src/CentreonCommand/Domain/Entity/Command.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ namespace CentreonCommand\Domain\Entity; use Symfony\Component\Serializer\Annotation as Serializer; /** * Command entity. * * @codeCoverageIgnore */ class Command { public const SERIALIZER_GROUP_LIST = 'command-list'; public const TABLE = 'command'; public const TYPE_NOTIFICATION = 1; public const TYPE_CHECK = 2; public const TYPE_MISC = 3; public const TYPE_DISCOVERY = 4; /** @var int an identification of entity */ #[Serializer\Groups([Command::SERIALIZER_GROUP_LIST])] private $id; /** @var string */ #[Serializer\Groups([Command::SERIALIZER_GROUP_LIST])] private $name; /** * @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; } /** * Convert type from string to integer. * * @param string $name * * @return int|null */ public static function getTypeIdFromName(?string $name = null): ?int { switch ($name) { case 'notification': return static::TYPE_NOTIFICATION; case 'check': return static::TYPE_CHECK; case 'misc': return static::TYPE_MISC; case 'discovery': return static::TYPE_DISCOVERY; } 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/CentreonCommand/Domain/Repository/CommandRepository.php
centreon/src/CentreonCommand/Domain/Repository/CommandRepository.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 CentreonCommand\Domain\Repository; use Centreon\Infrastructure\CentreonLegacyDB\Interfaces\PaginationRepositoryInterface; use Centreon\Infrastructure\CentreonLegacyDB\StatementCollector; use Centreon\Infrastructure\DatabaseConnection; use CentreonCommand\Domain\Entity\Command; use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB; class CommandRepository extends AbstractRepositoryRDB implements PaginationRepositoryInterface { /** @var int */ private int $resultCountForPagination = 0; /** * @param DatabaseConnection $db */ public function __construct(DatabaseConnection $db) { $this->db = $db; } /** * {@inheritDoc} */ public function getPaginationList( $filters = null, ?int $limit = null, ?int $offset = null, $ordering = [], ): array { $sql = 'SELECT SQL_CALC_FOUND_ROWS `command_id` AS `id`, `command_name` AS `name` ' . 'FROM `' . Command::TABLE . '`'; $collector = new StatementCollector(); $sql .= ' WHERE `command_activate` = :active'; $collector->addValue(':active', true, \PDO::PARAM_STR); if ($filters !== null) { if (array_key_exists('search', $filters) && $filters['search']) { $sql .= ' AND `command_name` LIKE :search'; $collector->addValue(':search', "%{$filters['search']}%"); } if (array_key_exists('ids', $filters) && is_array($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 .= ' AND `command_id` IN (' . implode(',', $idsListKey) . ')'; } if (array_key_exists('type', $filters) && $filters['type']) { $sql .= ' AND `command_type` LIKE :type'; $collector->addValue(':type', "%{$filters['type']}%"); } } $sql .= ' ORDER BY `command_name` ASC'; 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); } } $stmt = $this->db->prepare($sql); $collector->bind($stmt); $stmt->execute(); $foundRecords = $this->db->query('SELECT FOUND_ROWS()'); if ($foundRecords !== false && ($total = $foundRecords->fetchColumn()) !== false) { $this->resultCountForPagination = $total; } $stmt->setFetchMode(\PDO::FETCH_CLASS, Command::class); return $stmt->fetchAll(); } /** * {@inheritDoc} */ public function getPaginationListTotal(): int { return $this->resultCountForPagination; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonNotification/ServiceProvider.php
centreon/src/CentreonNotification/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 CentreonNotification; use Centreon\Infrastructure\Provider\AutoloadServiceProviderInterface; use CentreonNotification\Application\Webservice; use Pimple\Container; class ServiceProvider implements AutoloadServiceProviderInterface { /** * {@inheritDoc} */ public function register(Container $pimple): void { // register Excalaton webservice $pimple[\Centreon\ServiceProvider::CENTREON_WEBSERVICE] ->add(Webservice\EscalationWebservice::class); } /** * {@inheritDoc} */ public static function order(): int { return 50; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonNotification/Application/Webservice/EscalationWebservice.php
centreon/src/CentreonNotification/Application/Webservice/EscalationWebservice.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 CentreonNotification\Application\Webservice; use Centreon\Infrastructure\Webservice; use Centreon\ServiceProvider; use CentreonNotification\Application\Serializer; use CentreonNotification\Domain\Repository; /** * @OA\Tag(name="centreon_escalation", description="Resource for authorized access") */ class EscalationWebservice extends Webservice\WebServiceAbstract implements Webservice\WebserviceAutorizeRestApiInterface { use Webservice\DependenciesTrait; /** * Name of web service object. * * @return string */ public static function getName(): string { return 'centreon_escalation'; } /** * {@inheritDoc} * * @return array<ServiceProvider::CENTREON_PAGINATION> */ public static function dependencies(): array { return [ ServiceProvider::CENTREON_PAGINATION, ]; } /** * @OA\Get( * path="/external.php?object=centreon_escalation&action=list", * description="Get list of escalations", * tags={"centreon_escalation"}, * security={{"Session": {}}}, * * @OA\Parameter( * in="query", * name="object", * * @OA\Schema( * type="string", * enum={"centreon_escalation"}, * ), * 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/EscalationEntity") * ), * * @OA\Property( * property="pagination", * ref="#/components/schemas/Pagination" * ) * ) * ) * ) * * Get list of escalations * * @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; $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\EscalationRepository::class); $pagination->setContext(Serializer\Escalation\ListContext::context()); $pagination->setFilters($filters); $pagination->setLimit($limit); $pagination->setOffset($offset); return $pagination->getResponse(); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonNotification/Application/Serializer/Escalation/ListContext.php
centreon/src/CentreonNotification/Application/Serializer/Escalation/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 CentreonNotification\Application\Serializer\Escalation; use Centreon\Application\Serializer\SerializerContextInterface; use CentreonNotification\Domain\Entity\Escalation; /** * @OA\Schema( * schema="EscalationEntity", * * @OA\Property(property="id", type="integer"), * @OA\Property(property="name", type="string") * ) * * Serialize Escalation entity for list */ class ListContext implements SerializerContextInterface { /** * {@inheritDoc} */ public static function context(): array { return [ static::GROUPS => [ Escalation::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/CentreonNotification/Domain/Entity/Escalation.php
centreon/src/CentreonNotification/Domain/Entity/Escalation.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 CentreonNotification\Domain\Entity; use Centreon\Infrastructure\CentreonLegacyDB\Mapping; use PDO; use Symfony\Component\Serializer\Annotation as Serializer; /** * Escalation entity. * * @codeCoverageIgnore */ class Escalation implements Mapping\MetadataInterface { public const SERIALIZER_GROUP_LIST = 'escalation-list'; /** * Use class metadata instead calling of this constant. * * <example> * $this->repository->getClassMetadata()->getTableName() * </example> */ public const TABLE = 'escalation'; /** * Use class metadata instead calling of this constant. * * <example> * $this->repository->getClassMetadata()->getTableName() * </example> */ public const ENTITY_IDENTIFICATOR_COLUMN = 'esc_id'; /** @var int an identification of entity */ #[Serializer\Groups([Escalation::SERIALIZER_GROUP_LIST])] private $id; /** @var string escalation name */ #[Serializer\Groups([Escalation::SERIALIZER_GROUP_LIST])] private $name; /** * {@inheritDoc} */ public static function loadMetadata(Mapping\ClassMetadata $metadata): void { $metadata->setTableName(static::TABLE) ->add('id', 'esc_id', PDO::PARAM_INT, null, true) ->add('name', 'esc_name', 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; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonNotification/Domain/Repository/DependencyRepository.php
centreon/src/CentreonNotification/Domain/Repository/DependencyRepository.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 CentreonNotification\Domain\Repository; use Centreon\Infrastructure\CentreonLegacyDB\StatementCollector; use Centreon\Infrastructure\DatabaseConnection; use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB; class DependencyRepository extends AbstractRepositoryRDB { /** * @param DatabaseConnection $db */ public function __construct(DatabaseConnection $db) { $this->db = $db; } /** * Remove dependency by ID. * * @param int $id */ public function removeById(int $id): void { $request = <<<'SQL' DELETE FROM `:db`.`dependency` WHERE dep_id = :dependencyId SQL; $collector = new StatementCollector(); $collector->addValue(':dependencyId', $id); $statement = $this->db->prepare($this->translateDbName($request)); $collector->bind($statement); $statement->execute(); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonNotification/Domain/Repository/EscalationRepository.php
centreon/src/CentreonNotification/Domain/Repository/EscalationRepository.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 CentreonNotification\Domain\Repository; use Centreon\Domain\Repository\Traits\CheckListOfIdsTrait; use Centreon\Infrastructure\CentreonLegacyDB\Interfaces\PaginationRepositoryInterface; use Centreon\Infrastructure\CentreonLegacyDB\StatementCollector; use Centreon\Infrastructure\DatabaseConnection; use CentreonNotification\Domain\Entity\Escalation; use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB; class EscalationRepository 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 Escalation::class; } /** * Check list of IDs. * * @param int[] $ids * * @return bool */ public function checkListOfIds(array $ids): bool { return $this->checkListOfIdsTrait( $ids, Escalation::TABLE, Escalation::ENTITY_IDENTIFICATOR_COLUMN ); } /** * {@inheritDoc} */ public function getPaginationList($filters = null, ?int $limit = null, ?int $offset = null, $ordering = []): array { $sql = 'SELECT SQL_CALC_FOUND_ROWS `esc_id`, `esc_name` FROM `:db`.escalation'; $collector = new StatementCollector(); $isWhere = false; if ($filters !== null) { if ($filters['search'] ?? false) { $sql .= ' WHERE `esc_name` 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 .= ' `esc_id` IN (' . implode(',', $idsListKey) . ')'; } } $sql .= ' ORDER BY `esc_name` ASC'; 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; } $results = []; while ($record = $statement->fetch(\PDO::FETCH_ASSOC)) { $results[] = $this->createEscalationFromArray($record); } return $results; } /** * {@inheritDoc} */ public function getPaginationListTotal(): int { return $this->resultCountForPagination; } private function createEscalationFromArray(array $data): Escalation { $escalation = new Escalation(); $escalation->setId((int) $data['esc_id']); $escalation->setName($data['esc_name']); return $escalation; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonRemote/ServiceProvider.php
centreon/src/CentreonRemote/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 CentreonRemote; use Centreon\Infrastructure\Provider\AutoloadServiceProviderInterface; use Centreon\Infrastructure\Service\CentcoreCommandService; use CentreonRemote\Application\Clapi; use CentreonRemote\Application\Webservice; use CentreonRemote\Domain\Service\ConfigurationWizard\LinkedPollerConfigurationService; use CentreonRemote\Domain\Service\ConfigurationWizard\PollerConfigurationRequestBridge; use CentreonRemote\Domain\Service\ConfigurationWizard\PollerConnectionConfigurationService; use CentreonRemote\Domain\Service\ConfigurationWizard\RemoteConnectionConfigurationService; use CentreonRemote\Domain\Service\InformationsService; use CentreonRemote\Domain\Service\NotifyMasterService; use CentreonRemote\Domain\Service\TaskService; use CentreonRemote\Infrastructure\Service\PollerInteractionService; use ConfigGenerateRemote\Generate; use Curl\Curl; use Pimple\Container; use Pimple\Psr11\ServiceLocator; class ServiceProvider implements AutoloadServiceProviderInterface { public const CENTREON_NOTIFYMASTER = 'centreon.notifymaster'; public const CENTREON_TASKSERVICE = 'centreon.taskservice'; public const CENTREON_REMOTE_POLLER_INTERACTION_SERVICE = 'centreon_remote.poller_interaction_service'; public const CENTREON_REMOTE_INFORMATIONS_SERVICE = 'centreon_remote.informations_service'; public const CENTREON_REMOTE_REMOTE_CONNECTION_SERVICE = 'centreon_remote.remote_connection_service'; public const CENTREON_REMOTE_POLLER_CONNECTION_SERVICE = 'centreon_remote.poller_connection_service'; public const CENTREON_REMOTE_POLLER_CONFIG_SERVICE = 'centreon_remote.poller_config_service'; public const CENTREON_REMOTE_POLLER_CONFIG_BRIDGE = 'centreon_remote.poller_config_bridge'; public const CENTREON_REMOTE_EXPORT = 'centreon_remote.export'; public const CENTREON_REMOTE_EXPORTER_CACHE = 'centreon_remote.exporter.cache'; public const CENTREON_REMOTE_EXPORTER = 'centreon_remote.exporter'; /** * Register Centreon Remote services. * * @param Container $pimple */ public function register(Container $pimple): void { $pimple->extend( \Centreon\ServiceProvider::YML_CONFIG, function (array $cc, Container $pimple) { return $pimple[\CentreonLegacy\ServiceProvider::CONFIGURATION]->getModuleConfig(__DIR__); } ); $pimple[\Centreon\ServiceProvider::CENTREON_WEBSERVICE] ->add(Webservice\CentreonRemoteServer::class) ->add(Webservice\CentreonConfigurationRemote::class) ->add(Webservice\CentreonConfigurationTopology::class) ->add(Webservice\CentreonTaskService::class) ->add(Webservice\CentreonAclWebservice::class); $pimple[\Centreon\ServiceProvider::CENTREON_CLAPI]->add(Clapi\CentreonRemoteServer::class); $pimple[\Centreon\ServiceProvider::CENTREON_CLAPI]->add(Clapi\CentreonWorker::class); $pimple[static::CENTREON_NOTIFYMASTER] = function (Container $pimple): NotifyMasterService { $service = new NotifyMasterService($pimple[\Centreon\ServiceProvider::CENTREON_DB_MANAGER]); $service->setCurl(new Curl()); return $service; }; $pimple[static::CENTREON_TASKSERVICE] = function (Container $pimple): TaskService { $service = new TaskService( $pimple[\Centreon\ServiceProvider::CENTREON_DB_MANAGER], new CentcoreCommandService() ); $service->setCentreonRestHttp($pimple['rest_http']); return $service; }; $pimple[static::CENTREON_REMOTE_POLLER_INTERACTION_SERVICE] = function (Container $pimple): PollerInteractionService { return new PollerInteractionService($pimple); }; $pimple[static::CENTREON_REMOTE_INFORMATIONS_SERVICE] = function (Container $pimple): InformationsService { return new InformationsService($pimple); }; $pimple[static::CENTREON_REMOTE_REMOTE_CONNECTION_SERVICE] = function (Container $pimple): RemoteConnectionConfigurationService { return new RemoteConnectionConfigurationService( $pimple[\Centreon\ServiceProvider::CENTREON_DB_MANAGER]->getAdapter('configuration_db'), ); }; $pimple[static::CENTREON_REMOTE_POLLER_CONNECTION_SERVICE] = function (Container $pimple): PollerConnectionConfigurationService { $service = new PollerConnectionConfigurationService( $pimple[\Centreon\ServiceProvider::CENTREON_DB_MANAGER]->getAdapter('configuration_db'), ); $service->setBrokerRepository($pimple[\Centreon\ServiceProvider::CENTREON_BROKER_REPOSITORY]); $service->setBrokerConfigurationService($pimple['centreon.broker_configuration_service']); return $service; }; $pimple[static::CENTREON_REMOTE_POLLER_CONFIG_SERVICE] = function (Container $pimple): LinkedPollerConfigurationService { $service = new LinkedPollerConfigurationService( $pimple[\Centreon\ServiceProvider::CENTREON_DB_MANAGER]->getAdapter('configuration_db') ); $service->setBrokerRepository($pimple[\Centreon\ServiceProvider::CENTREON_BROKER_REPOSITORY]); $service->setBrokerConfigurationService($pimple['centreon.broker_configuration_service']); $service->setPollerInteractionService( $pimple[ServiceProvider::CENTREON_REMOTE_POLLER_INTERACTION_SERVICE] ); $service->setTaskService($pimple[ServiceProvider::CENTREON_TASKSERVICE]); return $service; }; $pimple[static::CENTREON_REMOTE_POLLER_CONFIG_BRIDGE] = function (Container $pimple): PollerConfigurationRequestBridge { return new PollerConfigurationRequestBridge($pimple); }; $pimple[static::CENTREON_REMOTE_EXPORT] = function (Container $container): Infrastructure\Service\ExportService { $services = [ ServiceProvider::CENTREON_REMOTE_EXPORTER_CACHE, ServiceProvider::CENTREON_REMOTE_EXPORTER, \Centreon\ServiceProvider::CENTREON_DB_MANAGER, 'centreon.acl', ]; $locator = new ServiceLocator($container, $services); return new Infrastructure\Service\ExportService($locator); }; $pimple[static::CENTREON_REMOTE_EXPORTER_CACHE] = function (): Infrastructure\Service\ExporterCacheService { return new Infrastructure\Service\ExporterCacheService(); }; $pimple[static::CENTREON_REMOTE_EXPORTER] = function (): Infrastructure\Service\ExporterService { return new Infrastructure\Service\ExporterService(); }; // -----------// // Exporters // -----------// // Configuration $pimple[static::CENTREON_REMOTE_EXPORTER]->add( Domain\Exporter\ConfigurationExporter::class, function () use ($pimple) { $service = new Domain\Exporter\ConfigurationExporter($pimple); $generateService = new Generate($pimple); $service->setGenerateService($generateService); return $service; } ); } /** * inheritDoc. */ public static function order(): int { return 20; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonRemote/Application/Webservice/CentreonRemoteServer.php
centreon/src/CentreonRemote/Application/Webservice/CentreonRemoteServer.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 CentreonRemote\Application\Webservice; /** * @OA\Tag(name="centreon_remote_server", description="") */ class CentreonRemoteServer extends CentreonWebServiceAbstract { /** * Name of web service object. * * @return string */ public static function getName(): string { return 'centreon_remote_server'; } /** * @OA\Post( * path="/external.php?object=centreon_remote_server&action=addToWaitList", * description="Add remote Centreon instance in waiting list", * tags={"centreon_remote_server"}, * * @OA\Parameter( * in="query", * name="object", * * @OA\Schema( * type="string", * enum={"centreon_remote_server"}, * default="centreon_remote_server" * ), * description="the name of the API object class", * required=true * ), * * @OA\Parameter( * in="query", * name="action", * * @OA\Schema( * type="string", * enum={"addToWaitList"}, * default="addToWaitList" * ), * description="the name of the action in the API class", * required=true * ), * * @OA\RequestBody( * required=true, * * @OA\JsonContent( * required={ * "app_key", * "version" * }, * * @OA\Property( * property="app_key", * type="string", * description="the unique app key of the Centreon instance" * ), * @OA\Property( * property="version", * type="string", * description="the app version Centreon instance" * ) * ) * ), * * @OA\Response( * response=200, * description="Empty string", * * @OA\JsonContent( * * @OA\Property(type="string") * ) * ) * ) * * Add remote Centreon instance in waiting list * * @throws \RestBadRequestException * @throws \RestConflictException * * @return string */ public function postAddToWaitList(): string { $ip = $_SERVER['REMOTE_ADDR'] ?? null; /** * Check mandatory parameters and request arguments. */ if (! $ip) { throw new \RestBadRequestException('Can not access your address.'); } if ( ! isset($_POST['version']) || ! $_POST['version'] || empty($version = filter_var($_POST['version'], FILTER_SANITIZE_FULL_SPECIAL_CHARS)) ) { throw new \RestBadRequestException('Please send \'version\' in the request.'); } $filterOptions = ['options' => ['min_range' => 1, 'max_range' => 65535]]; if ( ! isset($_POST['http_port']) || ! $_POST['http_port'] || false === ($httpPort = filter_var($_POST['http_port'], FILTER_VALIDATE_INT, $filterOptions)) ) { throw new \RestBadRequestException('Inconsistent \'http port\' in the request.'); } $noCheckCertificate = ($_POST['no_check_certificate'] === '1' ? '1' : '0'); $httpScheme = ($_POST['http_method'] === 'https' ? 'https' : 'http'); $statement = $this->pearDB->prepare('SELECT COUNT(id) as count FROM `remote_servers` WHERE `ip` = :ip'); $statement->bindValue(':ip', $ip, \PDO::PARAM_STR); $statement->execute(); $result = $statement->fetch(); if ((bool) $result['count']) { throw new \RestConflictException('Address already in wait list.'); } try { $createdAt = date('Y-m-d H:i:s'); $insertQuery = 'INSERT INTO `remote_servers` (`ip`, `version`, `is_connected`, `created_at`, `http_method`, `http_port`, `no_check_certificate`) VALUES (:ip, :version, 0, :created_at, :http_method, :http_port, :no_check_certificate )'; $insert = $this->pearDB->prepare($insertQuery); $insert->bindValue(':ip', $ip, \PDO::PARAM_STR); $insert->bindValue(':version', $version, \PDO::PARAM_STR); $insert->bindValue(':created_at', $createdAt, \PDO::PARAM_STR); $insert->bindValue(':http_method', $httpScheme, \PDO::PARAM_STR); $insert->bindValue(':http_port', $httpPort, \PDO::PARAM_INT); $insert->bindValue(':no_check_certificate', $noCheckCertificate, \PDO::PARAM_STR); $insert->execute(); } catch (\Exception $e) { throw new \RestBadRequestException('There was an error while saving the data.'); } return ''; } /** * Authorize to access to the action. * * @param string $action The action name * @param \CentreonUser $user The current user * @param bool $isInternal If the api is call in internal * * @return bool If the user has access to the action */ public function authorize($action, $user, $isInternal = false) { return true; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonRemote/Application/Webservice/CentreonConfigurationRemote.php
centreon/src/CentreonRemote/Application/Webservice/CentreonConfigurationRemote.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 CentreonRemote\Application\Webservice; use Centreon\Domain\Entity\Task; use Centreon\Domain\PlatformTopology\Model\PlatformPending; use CentreonRemote\Application\Validator\WizardConfigurationRequestValidator; use CentreonRemote\Domain\Value\ServerWizardIdentity; /** * @OA\Tag(name="centreon_configuration_remote", description="") */ class CentreonConfigurationRemote extends CentreonWebServiceAbstract { /** * Name of web service object. * * @return string */ public static function getName(): string { return 'centreon_configuration_remote'; } /** * @OA\Post( * path="/internal.php?object=centreon_configuration_remote&action=getWaitList", * description="Get remotes servers waitlist", * tags={"centreon_configuration_remote"}, * security={{"Session": {}}}, * * @OA\Parameter( * in="query", * name="object", * * @OA\Schema( * type="string", * enum={"centreon_configuration_remote"}, * default="centreon_configuration_remote" * ), * description="the name of the API object class", * required=true * ), * * @OA\Parameter( * in="query", * name="action", * * @OA\Schema( * type="string", * enum={"getWaitList"}, * default="getWaitList" * ), * description="the name of the action in the API class", * required=true * ), * * @OA\Response( * response=200, * description="JSON with the IPs inside the waitlist", * * @OA\JsonContent( * * @OA\Property(property="ip", type="string"), * @OA\Property(property="version", type="string") * ) * ) * ) * * Get remotes servers waitlist * * @return array<int, array<mixed>> */ public function postGetWaitList(): array { $statement = $this->pearDB->query(" SELECT id, address as ip, name as server_name FROM `platform_topology` WHERE `type` = 'remote' AND pending = '1' "); return $statement->fetchAll(); } /** * Get Pollers servers waitlist. * * @return array<int, array<mixed>> */ public function postGetPollerWaitList(): array { $statement = $this->pearDB->query(" SELECT id, address as ip, name as server_name FROM `platform_topology` WHERE `type` = 'poller' AND pending = '1' "); return $statement->fetchAll(); } /** * @OA\Get( * path="/internal.php?object=centreon_configuration_remote&action=list", * description="Get list with connected remotes", * tags={"centreon_configuration_remote"}, * security={{"Session": {}}}, * * @OA\Parameter( * in="query", * name="object", * * @OA\Schema( * type="string", * enum={"centreon_configuration_remote"}, * default="centreon_configuration_remote" * ), * description="the name of the API object class", * required=true * ), * * @OA\Parameter( * in="query", * name="action", * * @OA\Schema( * type="string", * enum={"getRemotesList"}, * default="getRemotesList" * ), * description="the name of the action in the API class", * required=true * ), * * @OA\Response( * response=200, * description="JSON with the IPs of connected remotes", * * @OA\JsonContent( * * @OA\Property(property="id", type="string"), * @OA\Property(property="ip", type="string"), * @OA\Property(property="name", type="string") * ) * ) * ) * * Get list with connected remotes * * @return array<int, array<mixed>> * * @example [['id' => 'poller id', 'ip' => 'poller ip address', 'name' => 'poller name']] */ public function getList(): array { $list = []; foreach ($this->postGetRemotesList() as $row) { $row['id'] = (int) $row['id']; $list[] = $row; } return $list; } /** * @OA\Post( * path="/internal.php?object=centreon_configuration_remote&action=getRemotesList", * description="Get list with connected remotes", * tags={"centreon_configuration_remote"}, * security={{"Session": {}}}, * * @OA\Parameter( * in="query", * name="object", * * @OA\Schema( * type="string", * enum={"centreon_configuration_remote"}, * default="centreon_configuration_remote" * ), * description="the name of the API object class", * required=true * ), * * @OA\Parameter( * in="query", * name="action", * * @OA\Schema( * type="string", * enum={"getRemotesList"}, * default="getRemotesList" * ), * description="the name of the action in the API class", * required=true * ), * * @OA\Response( * response=200, * description="JSON with the IPs of connected remotes", * * @OA\JsonContent( * * @OA\Property(property="id", type="string"), * @OA\Property(property="ip", type="string"), * @OA\Property(property="name", type="string") * ) * ) * ) * * Get list with connected remotes * * @return array<int, array<mixed>> * * @example [['id' => 'poller id', 'ip' => 'poller ip address', 'name' => 'poller name']] */ public function postGetRemotesList(): array { $query = 'SELECT ns.id, ns.ns_ip_address as ip, ns.name FROM nagios_server as ns ' . 'JOIN remote_servers as rs ON rs.server_id = ns.id ' . 'WHERE rs.is_connected = 1'; $statement = $this->pearDB->query($query); return $statement->fetchAll(); } /** * @OA\Post( * path="/internal.php?object=centreon_configuration_remote&action=linkCentreonRemoteServer", * description="Link centreon remote server", * tags={"centreon_configuration_remote"}, * security={{"Session": {}}}, * * @OA\Parameter( * in="query", * name="object", * * @OA\Schema( * type="string", * enum={"centreon_configuration_remote"}, * default="centreon_configuration_remote" * ), * description="the name of the API object class", * required=true * ), * * @OA\Parameter( * in="query", * name="action", * * @OA\Schema( * type="string", * enum={"linkCentreonRemoteServer"}, * default="linkCentreonRemoteServer" * ), * description="the name of the action in the API class", * required=true * ), * * @OA\RequestBody( * required=true, * * @OA\JsonContent( * required={ * "manage_broker_configuration", * "server_ip", * "centreon_central_ip", * "server_name" * }, * * @OA\Property( * property="manage_broker_configuration", * type="string", * description="if broker configuration of poller should be managed" * ), * @OA\Property( * property="server_ip", * type="string", * description="the remote server ip address" * ), * @OA\Property( * property="centreon_central_ip", * type="string", * description="the centreon central ip address" * ), * @OA\Property( * property="server_name", * type="string", * description="the remote centreon instance name" * ), * @OA\Property( * property="open_broker_flow", * type="string", * description="if the connection should be made with open broker flow" * ), * @OA\Property( * property="db_user", * type="string", * description="database username" * ), * @OA\Property( * property="db_password", * type="string", * description="database password" * ), * @OA\Property( * property="server_type", * type="string", * description="type of server - remote or poller" * ), * @OA\Property( * property="centreon_folder", * type="string", * description="path to the centreon web folder on the remote machine" * ), * @OA\Property( * property="linked_pollers", * type="string", * description="pollers to link with the new remote" * ), * @OA\Property( * property="linked_remote_master", * type="string", * description="remote to manage the new poller" * ), * @OA\Property( * property="linked_remote_slaves", * type="string", * description="additional remotes which receive data from the new poller" * ) * ) * ), * * @OA\Response( * response=200, * description="JSON", * * @OA\JsonContent( * * @OA\Property(property="success", type="boolean"), * @OA\Property(property="task_id", type="integer") * ) * ) * ) * * Link centreon remote server * * @throws \RestBadRequestException * @throws \Exception * * @return array<string,bool|int|string|null> * * @example ['success' => true, 'task_id' => 'task id'] * @example ['error' => true, 'message' => 'error message'] */ public function postLinkCentreonRemoteServer(): array { global $pearDB; // retrieve post values to be used in other classes $_POST = json_decode(file_get_contents('php://input'), true); $openBrokerFlow = isset($this->arguments['open_broker_flow']) && $this->arguments['open_broker_flow'] === true; $centreonPath = $this->arguments['centreon_folder'] ?? '/centreon/'; $noCheckCertificate = isset($this->arguments['no_check_certificate']) && $this->arguments['no_check_certificate'] === true; $noProxy = isset($this->arguments['no_proxy']) && $this->arguments['no_proxy'] === true; $serverWizardIdentity = new ServerWizardIdentity(); $isRemoteConnection = $serverWizardIdentity->requestConfigurationIsRemote(); $configurationServiceName = $isRemoteConnection ? 'centreon_remote.remote_connection_service' : 'centreon_remote.poller_connection_service'; // validate form fields WizardConfigurationRequestValidator::validate(); $pollerConfigurationService = $this->getDi()['centreon_remote.poller_config_service']; $serverConfigurationService = $this->getDi()[$configurationServiceName]; $pollerConfigurationBridge = $this->getDi()['centreon_remote.poller_config_bridge']; // extract HTTP method and port from form or database if registered $serverIP = parse_url($this->arguments['server_ip'], PHP_URL_HOST) ?: $this->arguments['server_ip']; $serverName = substr($this->arguments['server_name'], 0, 40); // Check IPv6, IPv4 and FQDN format if ( ! filter_var($serverIP, FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME) && ! filter_var($serverIP, FILTER_VALIDATE_IP) ) { return ['error' => true, 'message' => 'Invalid IP address']; } $dbAdapter = $this->getDi()['centreon.db-manager']->getAdapter('configuration_db'); /** * Avoid Ip duplication. */ $statement = $this->pearDB->prepare( 'SELECT COUNT(*) as `total` FROM `nagios_server` WHERE `ns_ip_address` = :serverIp' ); $statement->bindValue(':serverIp', $serverIP, \PDO::PARAM_STR); $statement->execute(); $isInNagios = $statement->fetch(\PDO::FETCH_ASSOC); if ((int) $isInNagios['total'] > 0) { throw new \Exception(_('This IP Address already exist')); } $sql = 'SELECT * FROM `remote_servers` WHERE `ip` = ?'; $dbAdapter->query($sql, [$serverIP]); $hasIpInTable = (bool) $dbAdapter->count(); if (! $hasIpInTable) { $httpMethod = parse_url($this->arguments['server_ip'], PHP_URL_SCHEME) ?: 'http'; $httpPort = parse_url($this->arguments['server_ip'], PHP_URL_PORT) ?: ''; } else { $result = $dbAdapter->results(); $remoteData = reset($result); $httpMethod = $remoteData->http_method; $httpPort = $remoteData->http_port; } $serverConfigurationService->setCentralIp($this->arguments['centreon_central_ip']); $serverConfigurationService->setServerIp($serverIP); $serverConfigurationService->setName($serverName); $serverConfigurationService->setOnePeerRetention($openBrokerFlow); // set linked pollers $pollerConfigurationBridge->collectDataFromRequest(); // set additional Remote Servers $pollerConfigurationBridge->collectDataFromAdditionalRemoteServers(); // if it's a remote server, set database connection information and check if bam is installed if ($isRemoteConnection) { $serverConfigurationService->setDbUser($this->arguments['db_user']); $serverConfigurationService->setDbPassword($this->arguments['db_password']); if ( $serverWizardIdentity->checkBamOnRemoteServer( $httpMethod . '://' . $serverIP . ':' . $httpPort . '/' . trim($centreonPath, '/'), $noCheckCertificate, $noProxy ) ) { $serverConfigurationService->shouldInsertBamBrokers(); } } // Add configuration of the new server in the database (poller, engine, broker...) try { // If server not linked to a poller, then it is linked to central server if (! $pollerConfigurationBridge->hasPollersForUpdating()) { $serverConfigurationService->isLinkedToCentralServer(); } $serverId = $serverConfigurationService->insert(); } catch (\Exception $e) { return ['error' => true, 'message' => $e->getMessage()]; } $taskId = null; // if it is remote server wizard, create an export task and link pollers to it if needed if ($isRemoteConnection) { $remoteServer = $pollerConfigurationBridge->getPollerFromId($serverId); // set basic parameters to export task $params = [ 'server' => $remoteServer->getId(), 'pollers' => [], 'remote_ip' => $serverIP, 'centreon_path' => $centreonPath, 'http_method' => $httpMethod, 'http_port' => $httpPort, 'no_check_certificate' => $noCheckCertificate, 'no_proxy' => $noProxy, ]; // If you want to link pollers to a remote if ($pollerConfigurationBridge->hasPollersForUpdating()) { $pollers = $pollerConfigurationBridge->getLinkedPollersSelectedForUpdate(); $pollerConfigurationService->linkPollersToParentPoller($pollers, $remoteServer); foreach ($pollers as $poller) { $params['pollers'][] = $poller->getId(); } } // Create export task $taskId = $this->createExportTask($params); // add server to the list of remote servers in database (table remote_servers) $this->addServerToListOfRemotes( (int) $serverId, $serverIP, $centreonPath, $httpMethod, $httpPort, $noCheckCertificate, $noProxy ); $this->setCentreonInstanceAsCentral(); $this->updateServerInPlatformTopology([ 'type' => PlatformPending::TYPE_REMOTE, 'server_name' => $serverName, 'nagios_id' => $serverId, 'address' => $serverIP, 'children_pollers' => $pollers ?? null, ]); // if it is poller wizard and poller is linked to another poller/remote server (instead of central) } elseif ($pollerConfigurationBridge->hasPollersForUpdating()) { $pollers = [$pollerConfigurationBridge->getPollerFromId($serverId)]; $parentPoller = $pollerConfigurationBridge->getLinkedPollersSelectedForUpdate()[0]; $pollerConfigurationService->linkPollersToParentPoller($pollers, $parentPoller); // add broker output to forward data to additional remote server and link in db $additionalRemotes = $pollerConfigurationBridge->getAdditionalRemoteServers(); $pollerConfigurationService->linkPollerToAdditionalRemoteServers($pollers[0], $additionalRemotes); $this->updateServerInPlatformTopology([ 'type' => PlatformPending::TYPE_POLLER, 'server_name' => $serverName, 'nagios_id' => $serverId, 'address' => $serverIP, 'parent' => $parentPoller->getId(), ]); } else { $this->updateServerInPlatformTopology([ 'type' => PlatformPending::TYPE_POLLER, 'server_name' => $serverName, 'nagios_id' => $serverId, 'address' => $serverIP, ]); } // Update session to reload ACL $sid = session_id(); $statement = $pearDB->prepareQuery( <<<'SQL' UPDATE session SET update_acl = '1' WHERE session_id = :sessionId SQL ); $pearDB->executePreparedQuery($statement, ['sessionId' => $sid]); return ['success' => true, 'task_id' => $taskId]; } /** * Authorize to access to the action. * * @param string $action The action name * @param \CentreonUser $user The current user * @param bool $isInternal If the api is call in internal * * @return bool If the user has access to the action */ public function authorize($action, $user, $isInternal = false): bool { if (parent::authorize($action, $user, $isInternal)) { return true; } return $user->hasAccessRestApiConfiguration(); } /** * Add server ip in table of remote servers. * * @param int $serverId the poller id * @param string $serverIP the IP of the server * @param string $centreonPath the path to access to Centreon * @param string $httpMethod the method to access to server (HTTP/HTTPS) * @param string $httpPort the port to access to the server * @param bool $noCheckCertificate to do not check SSL CA * @param bool $noProxy to do not use configured proxy */ private function addServerToListOfRemotes( int $serverId, string $serverIP, string $centreonPath, string $httpMethod, string $httpPort, bool $noCheckCertificate, bool $noProxy, ): void { $currentDate = date('Y-m-d H:i:s'); $statement = $this->pearDB->prepare('SELECT 1 FROM `remote_servers` WHERE `server_id` = :server_id'); $statement->bindValue(':server_id', $serverId, \PDO::PARAM_INT); $statement->execute(); $remoteAlreadyExists = (bool) $statement->rowCount(); if ($remoteAlreadyExists) { $updateStatement = $this->pearDB->prepare( 'UPDATE `remote_servers` SET `is_connected` = 1, `connected_at` = :connected_at, `centreon_path` = :centreon_path, `no_check_certificate` = :no_check_certificate, `no_proxy` = :no_proxy, `ip_address` = :ip_address WHERE `server_id` = :server_id' ); $updateStatement->bindValue(':connected_at', $currentDate, \PDO::PARAM_STR); $updateStatement->bindValue(':centreon_path', $centreonPath, \PDO::PARAM_STR); $updateStatement->bindValue(':no_check_certificate', $noCheckCertificate ? '1' : '0', \PDO::PARAM_STR); $updateStatement->bindValue(':no_proxy', $noProxy ? '1' : '0', \PDO::PARAM_STR); $updateStatement->bindValue(':ip_address', $serverIP, \PDO::PARAM_STR); $updateStatement->bindValue(':server_id', $serverId, \PDO::PARAM_INT); $updateStatement->execute(); } else { $insertStatement = $this->pearDB->prepare( 'INSERT INTO `remote_servers` (`ip`, `version`, `is_connected`, `created_at`, `connected_at`, `centreon_path`, `http_method`, `http_port`, `no_check_certificate`, `no_proxy`, `server_id`) VALUES (:ip_address, "", 1, :created_at, :connected_at, :centreon_path, :http_method, :http_port, :no_check_certificate, :no_proxy, :server_id)' ); $insertStatement->bindValue(':ip_address', $serverIP, \PDO::PARAM_STR); $insertStatement->bindValue(':created_at', $currentDate, \PDO::PARAM_STR); $insertStatement->bindValue(':connected_at', $currentDate, \PDO::PARAM_STR); $insertStatement->bindValue(':centreon_path', $centreonPath, \PDO::PARAM_STR); $insertStatement->bindValue(':http_method', $httpMethod, \PDO::PARAM_STR); $insertStatement->bindValue(':http_port', $httpPort ?: null, \PDO::PARAM_INT); $insertStatement->bindValue(':no_check_certificate', $noCheckCertificate ? '1' : '0', \PDO::PARAM_STR); $insertStatement->bindValue(':no_proxy', $noProxy ? '1' : '0', \PDO::PARAM_STR); $insertStatement->bindValue(':server_id', $serverId, \PDO::PARAM_INT); $insertStatement->execute(); } } /** * Set current centreon instance as central. */ private function setCentreonInstanceAsCentral(): void { $dbAdapter = $this->getDi()[\Centreon\ServiceProvider::CENTREON_DB_MANAGER]->getAdapter('configuration_db'); $sql = "SELECT * FROM `informations` WHERE `key` = 'isCentral'"; $dbAdapter->query($sql); $hasInfoRecord = (bool) $dbAdapter->count(); if ($hasInfoRecord) { $sql = "UPDATE `informations` SET `value` = 'yes' WHERE `key` = 'isCentral'"; $dbAdapter->query($sql); } else { $data = [ 'key' => 'isCentral', 'value' => 'yes', ]; $dbAdapter->insert('informations', $data); } } /** * Create New Task for export. * * @param array<string,mixed> $params * * @return bool|int */ private function createExportTask(array $params) { return $this->getDi()['centreon.taskservice']->addTask(Task::TYPE_EXPORT, ['params' => $params]); } /** * @param array<string,mixed> $topologyInformation * * @throws \Exception */ private function updateServerInPlatformTopology(array $topologyInformation): void { /** * Get platform_topology id. */ $statement = $this->pearDB->prepare( 'SELECT id, server_id as nagios_id FROM `platform_topology` WHERE address = :address' ); $statement->bindValue(':address', $topologyInformation['address'], \PDO::PARAM_STR); $statement->execute(); $server = $statement->fetch(\PDO::FETCH_ASSOC); if (isset($server['nagios_id'])) { throw new \Exception(_('This server is already registered')); } if (! empty($topologyInformation['parent'])) { $statement = $this->pearDB->prepare('SELECT id FROM platform_topology WHERE server_id = :serverId'); $statement->bindValue(':serverId', (int) $topologyInformation['parent'], \PDO::PARAM_INT); $statement->execute(); $parent = $statement->fetch(\PDO::FETCH_ASSOC); } else { // Get Central ID $statement = $this->pearDB->query("SELECT id FROM `platform_topology` WHERE type = 'central'"); $parent = $statement->fetch(\PDO::FETCH_ASSOC); if (empty($parent['id'])) { throw new \Exception(_('No Central in topology,please edit it from Configuration > Pollers menu')); } } /** * If the server is already registered in platform_topology Update else insert. */ $insertedPlatform = []; if (! empty($server['id'])) { $statement = $this->pearDB->prepare( "UPDATE `platform_topology` SET `name` = :name, parent_id = :parentId, server_id = :nagiosId, pending = '0' WHERE id = :topologyId" ); $statement->bindValue(':name', $topologyInformation['server_name'], \PDO::PARAM_STR); $statement->bindValue(':parentId', (int) $parent['id'], \PDO::PARAM_INT); $statement->bindValue(':nagiosId', $topologyInformation['nagios_id'], \PDO::PARAM_INT); $statement->bindValue(':topologyId', (int) $server['id'], \PDO::PARAM_INT); $statement->execute(); } else { $statement = $this->pearDB->prepare( "INSERT INTO `platform_topology` (`address`,`name`,`type`,`parent_id`,`server_id`, `pending`) VALUES (:address, :name, :type, :parentId, :serverId, '0')" ); $statement->bindValue(':address', $topologyInformation['address'], \PDO::PARAM_STR); $statement->bindValue(':name', $topologyInformation['server_name'], \PDO::PARAM_STR); $statement->bindValue(':type', $topologyInformation['type'], \PDO::PARAM_STR); $statement->bindValue(':parentId', (int) $parent['id'], \PDO::PARAM_INT); $statement->bindValue(':serverId', $topologyInformation['nagios_id'], \PDO::PARAM_INT); $statement->execute(); /** * Get the new registered platform IP. */ $statement = $this->pearDB->prepare('SELECT MAX(id) as last_id FROM `platform_topology`'); $statement->execute(); $insertedPlatform = $statement->fetch(\PDO::FETCH_ASSOC); } /** * If it's a remote with attached poller. Update their parent id. */ if (! empty($topologyInformation['children_pollers'])) { $statement = $this->pearDB->prepare( "UPDATE `platform_topology` SET parent_id = :parentId, `pending` = '0' WHERE server_id = :pollerId" ); foreach ($topologyInformation['children_pollers'] as $poller) { $statement->bindValue( ':parentId', isset($insertedPlatform['last_id']) ? (int) $insertedPlatform['last_id'] : (int) $server['id'], \PDO::PARAM_INT ); $statement->bindValue(':pollerId', (int) $poller->getId(), \PDO::PARAM_INT); $statement->execute(); } } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonRemote/Application/Webservice/CentreonTaskService.php
centreon/src/CentreonRemote/Application/Webservice/CentreonTaskService.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 CentreonRemote\Application\Webservice; use Centreon\Domain\Entity\Task; /** * @OA\Tag(name="centreon_task_service", description="") */ class CentreonTaskService extends CentreonWebServiceAbstract { /** * Name of web service object. * * @return string */ public static function getName(): string { return 'centreon_task_service'; } /** * @OA\Post( * path="/internal.php?object=centreon_task_service&action=getTaskStatus", * description="Get Status of task", * tags={"centreon_task_service"}, * * @OA\Parameter( * in="query", * name="object", * * @OA\Schema( * type="string", * enum={"centreon_task_service"}, * default="centreon_task_service" * ), * description="the name of the API object class", * required=true * ), * * @OA\Parameter( * in="query", * name="action", * * @OA\Schema( * type="string", * enum={"getTaskStatus"}, * default="getTaskStatus" * ), * description="the name of the action in the API class", * required=true * ), * * @OA\RequestBody( * required=true, * * @OA\JsonContent( * required={ * "task_id" * }, * * @OA\Property( * property="task_id", * type="string", * description="Id of the task you want to get status of" * ) * ) * ), * * @OA\Response( * response=200, * description="JSON", * * @OA\JsonContent( * * @OA\Property(property="success", type="boolean"), * @OA\Property(property="status", type="string") * ) * ) * ) * * Get Status of task * * @throws \RestBadRequestException * * @return array<string,bool|string> * * @example ['success' => true, 'status' => 'status of the task'] */ public function postGetTaskStatus(): array { if (! isset($this->arguments['task_id'])) { throw new \RestBadRequestException('Missing argument task_id'); } $result = $this->getDi()['centreon.taskservice']->getStatus($this->arguments['task_id']); return ['success' => true, 'status' => $result]; } /** * Find task status by parent id (used on remote server). * * @throws \RestBadRequestException * * @return array<string,bool|string> * * @example ['success' => true, 'status' => 'status of the task'] */ public function postGetTaskStatusByParent(): array { if (! isset($this->arguments['parent_id'])) { throw new \RestBadRequestException('Missing argument parent_id'); } $result = $this->getDi()['centreon.taskservice']->getStatusByParent($this->arguments['parent_id']); return ['success' => true, 'status' => $result]; } /** * Authorize to access to the action. * * @param string $action The action name * @param \CentreonUser $user The current user * @param bool $isInternal If the api is call in internal * * @return bool If the user has access to the action */ public function authorize($action, $user, $isInternal = false): bool { return true; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonRemote/Application/Webservice/CentreonWebServiceAbstract.php
centreon/src/CentreonRemote/Application/Webservice/CentreonWebServiceAbstract.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 CentreonRemote\Application\Webservice; use Centreon\Infrastructure\Webservice\WebServiceAbstract; /** * @deprecated */ abstract class CentreonWebServiceAbstract extends WebServiceAbstract { }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonRemote/Application/Webservice/CentreonAclWebservice.php
centreon/src/CentreonRemote/Application/Webservice/CentreonAclWebservice.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 CentreonRemote\Application\Webservice; use Centreon\Domain\Repository\TopologyRepository; /** * @OA\Tag(name="centreon_acl_webservice", description="") */ class CentreonAclWebservice extends CentreonWebServiceAbstract { /** * Name of web service object. * * @return string */ public static function getName(): string { return 'centreon_acl_webservice'; } /** * @OA\Get( * path="/internal.php?object=centreon_acl_webservice&action=getCurrentAcl", * description="Get list of ACLs", * tags={"centreon_acl_webservice"}, * * @OA\Parameter( * in="query", * name="object", * * @OA\Schema( * type="string", * enum={"centreon_acl_webservice"}, * default="centreon_acl_webservice" * ), * description="the name of the API object class", * required=true * ), * * @OA\Parameter( * in="query", * name="action", * * @OA\Schema( * type="string", * enum={"getCurrentAcl"}, * default="getCurrentAcl" * ), * description="the name of the action in the API class", * required=true * ), * * @OA\Response( * response="200", * description="OK", * * @OA\MediaType( * mediaType="application/json", * * @OA\Schema(type="array", items={"type": "string"}) * ) * ) * ) * * @return array<int,string|null> */ public function getGetCurrentAcl() { $user = $_SESSION['centreon']->user; if (empty($user)) { return []; } return $this->getDi()[\Centreon\ServiceProvider::CENTREON_DB_MANAGER] ->getRepository(TopologyRepository::class) ->getReactTopologiesPerUserWithAcl($user); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonRemote/Application/Webservice/CentreonConfigurationTopology.php
centreon/src/CentreonRemote/Application/Webservice/CentreonConfigurationTopology.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 CentreonRemote\Application\Webservice; /** * @OA\Tag(name="centreon_configuration_topology", description="") */ class CentreonConfigurationTopology extends CentreonWebServiceAbstract { /** * Name of web service object. * * @return string */ public static function getName(): string { return 'centreon_configuration_topology'; } /** * @OA\Post( * path="/internal.php?object=centreon_configuration_topology&action=getTopologyData", * description="Get data for topology_id", * tags={"centreon_configuration_topology"}, * security={{"Session": {}}}, * * @OA\Parameter( * in="query", * name="object", * * @OA\Schema( * type="string", * enum={"centreon_configuration_topology"}, * default="centreon_configuration_topology" * ), * description="the name of the API object class", * required=true * ), * * @OA\Parameter( * in="query", * name="action", * * @OA\Schema( * type="string", * enum={"getTopologyData"}, * default="getTopologyData" * ), * description="the name of the action in the API class", * required=true * ), * * @OA\RequestBody( * required=true, * * @OA\JsonContent( * required={ * "topology_id" * }, * * @OA\Property( * property="topology_id", * type="string", * description="the ID of the topology page" * ) * ) * ), * * @OA\Response( * response=200, * description="JSON with topology data", * * @OA\JsonContent( * * @OA\Property(property="url", type="string"), * @OA\Property(property="is_react", type="boolean") * ) * ) * ) * * Get data for topology_id * * @throws \RestBadRequestException * * @return array<string,string|bool> */ public function postGetTopologyData() { if (! isset($_POST['topology_id']) || ! $_POST['topology_id']) { throw new \RestBadRequestException('You need to send \'topology_id\' in the request.'); } $topologyID = (int) $_POST['topology_id']; $statement = $this->pearDB->prepare( 'SELECT `topology_url`, `is_react` FROM `topology` WHERE `topology_id` = :id' ); $statement->execute([':id' => $topologyID]); $result = $statement->fetch(); if (! $result) { throw new \RestBadRequestException('No topology found.'); } return [ 'url' => $result['topology_url'], 'is_react' => (bool) $result['is_react'], ]; } /** * Authorize to access to the action. * * @param string $action The action name * @param \CentreonUser $user The current user * @param bool $isInternal If the api is call in internal * * @return bool If the user has access to the action */ public function authorize($action, $user, $isInternal = false) { if (parent::authorize($action, $user, $isInternal)) { return true; } return $user->hasAccessRestApiConfiguration(); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonRemote/Application/Clapi/CentreonRemoteServer.php
centreon/src/CentreonRemote/Application/Clapi/CentreonRemoteServer.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 CentreonRemote\Application\Clapi; use Centreon\Domain\Repository\InformationsRepository; use Centreon\Domain\Repository\TopologyRepository; use Centreon\Infrastructure\Service\CentreonClapiServiceInterface; use Pimple\Container; /** * Class to manage remote server with clapi (enable, disable, import). */ class CentreonRemoteServer implements CentreonClapiServiceInterface { /** * @var Container * todo: extract only services we need to avoid using whole container */ private $di; public function __construct(Container $di) { $this->di = $di; } public static function getName(): string { return (new \ReflectionClass(self::class))->getShortName(); } /** * Clapi command to enable remote server. * * @param string $parametersString parameters string made of * a comma separated list of hosts/urls/ip adresses representing the central, * a boolean to enable/disable certificate check to contact the central, * the method to use to contact the remote (http or https), * the http port to use to contact the remote, * a boolean to enable/disable certificate check to contact the remote, * a boolean to enable/disable the use of proxy to contact the central * * @return int|void */ public function enableRemote(string $parametersString) { // Set default value $noCheckCertificate = false; $data = [ 'remoteHttpMethod' => 'http', 'remoteHttpPort' => null, 'remoteNoCheckCertificate' => false, ]; $urlString = ''; $noProxy = ''; // Check CLAPI $options = explode(';', $parametersString); if (count($options) === 6) { $urlString = $options[0]; $noCheckCertificate = $options[1]; $data['remoteHttpMethod'] = $options[2]; $data['remoteHttpPort'] = $options[3]; $data['remoteNoCheckCertificate'] = $options[4]; $noProxy = $options[5]; } elseif (count($options) > 1) { echo 'Expecting 6 parameters, received ' . count($options) . "\n"; return 1; } // Extract host from URI $hostList = []; $pattern_extract_host = '/^[htps:\/]*([a-z0-9.-]+)[:0-9]*$/'; $urlList = explode(',', $urlString); foreach ($urlList as $url) { if (preg_match($pattern_extract_host, $url, $matches)) { $hostList[] = $matches[1]; } } echo "Starting Centreon Remote enable process:\n"; echo 'Limiting Menu Access... '; $result = $this->getDi()[\Centreon\ServiceProvider::CENTREON_DB_MANAGER] ->getRepository(TopologyRepository::class) ->disableMenus(); echo (($result) ? 'Success' : 'Fail') . "\n"; echo 'Limiting Actions... '; $this->getDi()[\Centreon\ServiceProvider::CENTREON_DB_MANAGER] ->getRepository(InformationsRepository::class) ->toggleRemote('yes'); echo "Done\n"; echo 'Authorizing Master... '; $this->getDi()[\Centreon\ServiceProvider::CENTREON_DB_MANAGER] ->getRepository(InformationsRepository::class) ->authorizeMaster( implode(',', $hostList) ); echo "Done\n"; echo "Set 'remote' instance type... "; system( "sed -i -r 's/(\\\$instance_mode?\s+=?\s+\")([a-z]+)(\";)/\\1remote\\3/' " . _CENTREON_ETC_ . '/conf.pm' ); echo "Done\n"; echo "Notifying Master...\n"; $result = ''; foreach ($urlList as $host) { echo " Trying host '{$host}'... "; $result = $this->getDi()['centreon.notifymaster']->pingMaster( $host, $data, $noCheckCertificate, $noProxy ); if (! empty($result['status']) && $result['status'] == 'success') { echo "Success\n"; break; } printf("Fail [Details: %s]\n", $result['details']); } echo "Centreon Remote enabling finished.\n"; } /** * Clapi command to disable remote server. */ public function disableRemote(): void { echo "Starting Centreon Remote disable process:\n"; echo 'Restoring Menu Access... '; $result = $this->getDi()[\Centreon\ServiceProvider::CENTREON_DB_MANAGER] ->getRepository(TopologyRepository::class) ->enableMenus(); echo ($result) ? 'Success' : 'Fail' . "\n"; echo 'Restoring Actions... '; $this->getDi()[\Centreon\ServiceProvider::CENTREON_DB_MANAGER] ->getRepository(InformationsRepository::class) ->toggleRemote('no'); echo 'Done' . "\n"; echo "Restore 'central' instance type... "; system( "sed -i -r 's/(\\\$instance_mode?\s+=?\s+\")([a-z]+)(\";)/\\1central\\3/' " . _CENTREON_ETC_ . '/conf.pm' ); echo "Done\n"; echo "Centreon Remote disabling finished.\n"; } /** * Import files which are stored in import directory. */ public function import(): void { echo date('Y-m-d H:i:s') . " - INFO - Starting Centreon Remote import process...\n"; try { $this->getDi()['centreon_remote.export']->import(); echo date('Y-m-d H:i:s') . " - INFO - Import succeed\n"; } catch (\Exception $e) { echo date('Y-m-d H:i:s') . " - ERROR - Import failed\n"; echo date('Y-m-d H:i:s') . ' - ERROR - Error message: ' . $e->getMessage() . "\n"; } echo date('Y-m-d H:i:s') . " - INFO - Centreon Remote import process finished.\n"; } public function getDi(): Container { return $this->di; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonRemote/Application/Clapi/CentreonWorker.php
centreon/src/CentreonRemote/Application/Clapi/CentreonWorker.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 CentreonRemote\Application\Clapi; use Centreon\Domain\Entity\Command; use Centreon\Domain\Entity\Task; use Centreon\Domain\Repository\TaskRepository; use Centreon\Infrastructure\Service\CentcoreCommandService; use Centreon\Infrastructure\Service\CentreonClapiServiceInterface; use CentreonRemote\Infrastructure\Export\ExportCommitment; use Pimple\Container; /** * Manage worker queue with centcore (import/export tasks...). */ class CentreonWorker implements CentreonClapiServiceInterface { /** @var Container */ private $di; public function __construct(Container $di) { $this->di = $di; } /** * Get Class name. * * @throws \ReflectionException * * @return string */ public static function getName(): string { return (new \ReflectionClass(self::class))->getShortName(); } /** * Process task queue for import/export. */ public function processQueue(): void { // check export tasks in database and execute these $this->processExportTasks(); // check import tasks in database and execute these $this->processImportTasks(); } /** * Worker method to create task for import on remote. * * @param int $taskId the task id to create on the remote server */ public function createRemoteTask(int $taskId): void { // find task parameters (type, status, params...) $task = $this->getDi()[\Centreon\ServiceProvider::CENTREON_DB_MANAGER] ->getRepository(TaskRepository::class) ->findOneById($taskId); /** * create import task on remote. */ $serializedParams = htmlspecialchars($task->getParams()); if (empty($serializedParams)) { throw new \Exception('Invalid Parameters'); } $taskParams = unserialize($serializedParams); if (! array_key_exists('params', $taskParams)) { throw new \Exception('Missing parameters: params'); } $params = $taskParams['params']; $centreonPath = trim($params['centreon_path'], '/'); $centreonPath = $centreonPath ?: '/centreon'; $url = $params['http_method'] ? $params['http_method'] . '://' : ''; $url .= $params['remote_ip']; $url .= $params['http_port'] ? ':' . $params['http_port'] : ''; $url .= "/{$centreonPath}/api/external.php?object=centreon_task_service&action=AddImportTaskWithParent"; try { $curl = new \CentreonRestHttp(); $res = $curl->call( $url, 'POST', ['parent_id' => $task->getId()], [], false, $params['no_check_certificate'], $params['no_proxy'] ); } catch (\Exception $e) { echo date('Y-m-d H:i:s') . ' - ERROR - Error while creating parent task on ' . $url . ".\n"; echo date('Y-m-d H:i:s') . ' - ERROR - Error message: ' . $e->getMessage() . "\n"; } } public function getDi(): Container { return $this->di; } /** * Execute export tasks which are store in task table. */ private function processExportTasks(): void { $tasks = $this->getDi()[\Centreon\ServiceProvider::CENTREON_DB_MANAGER] ->getRepository(TaskRepository::class) ->findExportTasks() ?? []; echo date('Y-m-d H:i:s') . ' - INFO - Checking for pending export tasks: ' . count($tasks) . " task(s) found.\n"; foreach (array_values($tasks) as $task) { echo date('Y-m-d H:i:s') . ' - INFO - Processing task #' . $task->getId() . "...\n"; // mark task as being worked on $this->getDi()['centreon.taskservice']->updateStatus($task->getId(), Task::STATE_PROGRESS); $serializedParams = htmlspecialchars($task->getParams(), ENT_NOQUOTES); if (empty($serializedParams)) { throw new \Exception('Invalid Parameters'); } $taskParams = unserialize($serializedParams); if (! array_key_exists('params', $taskParams)) { throw new \Exception('Missing parameters: params'); } $params = $taskParams['params']; $commitment = new ExportCommitment($params['server'], $params['pollers']); try { $this->getDi()['centreon_remote.export']->export($commitment); $this->getDi()['centreon.taskservice']->updateStatus($task->getId(), Task::STATE_COMPLETED); /** * move export file. */ $cmd = new Command(); $compositeKey = $params['server'] . ':' . $task->getId(); $cmd->setCommandLine(Command::COMMAND_TRANSFER_EXPORT_FILES . $compositeKey); $cmdService = new CentcoreCommandService(); $cmdWritten = $cmdService->sendCommand($cmd); echo date('Y-m-d H:i:s') . ' - INFO - Task #' . $task->getId() . " completed.\n"; } catch (\Exception $e) { echo date('Y-m-d H:i:s') . ' - ERROR - Task #' . $task->getId() . " failed.\n"; echo date('Y-m-d H:i:s') . ' - ERROR - Error message: ' . $e->getMessage() . "\n"; $this->getDi()['centreon.taskservice']->updateStatus($task->getId(), Task::STATE_FAILED); } } echo date('Y-m-d H:i:s') . " - INFO - Worker cycle completed.\n"; } /** * Execute import tasks which are store in task table. */ private function processImportTasks(): void { $tasks = $this->getDi()[\Centreon\ServiceProvider::CENTREON_DB_MANAGER] ->getRepository(TaskRepository::class) ->findImportTasks() ?? []; echo date('Y-m-d H:i:s') . ' - INFO - Checking for pending import tasks: ' . count($tasks) . " task(s) found.\n"; foreach ($tasks as $x => $task) { echo date('Y-m-d H:i:s') . ' - INFO - Processing task #' . $task->getId() . ' (parent ID #' . $task->getParentId() . ")...\n"; // mark task as being worked on $this->getDi()['centreon.taskservice']->updateStatus($task->getId(), Task::STATE_PROGRESS); try { $this->getDi()['centreon_remote.export']->import(); $this->getDi()['centreon.taskservice']->updateStatus($task->getId(), Task::STATE_COMPLETED); echo date('Y-m-d H:i:s') . ' - INFO - Task #' . $task->getId() . " completed.\n"; } catch (\Exception $e) { echo date('Y-m-d H:i:s') . ' - ERROR - Task #' . $task->getId() . " failed.\n"; echo date('Y-m-d H:i:s') . ' - ERROR - Error message: ' . $e->getMessage() . "\n"; $this->getDi()['centreon.taskservice']->updateStatus($task->getId(), Task::STATE_FAILED); } } echo date('Y-m-d H:i:s') . " - INFO - Worker cycle completed.\n"; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonRemote/Application/Validator/WizardConfigurationRequestValidator.php
centreon/src/CentreonRemote/Application/Validator/WizardConfigurationRequestValidator.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 CentreonRemote\Application\Validator; use CentreonRemote\Domain\Value\ServerWizardIdentity; /** * class to validate poller wizard forms. */ class WizardConfigurationRequestValidator { /** * validate arguments sent from poller/remote server wizard. * * @throws \RestBadRequestException */ public static function validate(): void { (new self())->validateServerPostData(); } /** * validate post arguments. * * @throws \RestBadRequestException */ public function validateServerPostData(): void { $isRemoteConnection = (new ServerWizardIdentity())->requestConfigurationIsRemote(); $this->validateServerGeneralFields(); // if it is a remote server, validate specific fields (like database connection parameters) if ($isRemoteConnection) { $this->validateRemoteSpecificFields(); } } /** * validate general form fields which are in poller wizard and remote server wizard. * * @throws \RestBadRequestException */ private function validateServerGeneralFields(): void { $missingParameterMessage = "You need to send '%s' in the request."; if (! isset($_POST['server_name']) || ! $_POST['server_name']) { throw new \RestBadRequestException( sprintf(_($missingParameterMessage), 'server_name') ); } if (! isset($_POST['server_ip']) || ! $_POST['server_ip']) { throw new \RestBadRequestException( sprintf(_($missingParameterMessage), 'server_ip') ); } if (! isset($_POST['centreon_central_ip']) || ! $_POST['centreon_central_ip']) { throw new \RestBadRequestException( sprintf(_($missingParameterMessage), 'centreon_central_ip') ); } } /** * validate form fields which are specific to remote server wizard. * * @throws \RestBadRequestException */ private function validateRemoteSpecificFields(): void { $missingParameterMessage = "You need to send '%s' in the request."; if (! isset($_POST['db_user']) || ! $_POST['db_user']) { throw new \RestBadRequestException( sprintf(_($missingParameterMessage), 'db_user') ); } if (! isset($_POST['db_password']) || ! $_POST['db_password']) { throw new \RestBadRequestException( sprintf(_($missingParameterMessage), 'db_password') ); } if (! isset($_POST['centreon_folder']) || ! $_POST['centreon_folder']) { throw new \RestBadRequestException( sprintf(_($missingParameterMessage), 'centreon_folder') ); } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonRemote/Domain/Exporter/ConfigurationExporter.php
centreon/src/CentreonRemote/Domain/Exporter/ConfigurationExporter.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 CentreonRemote\Domain\Exporter; use CentreonRemote\Infrastructure\Export\ExportManifest; use CentreonRemote\Infrastructure\Service\ExporterServiceAbstract; use ConfigGenerateRemote\Manifest; class ConfigurationExporter extends ExporterServiceAbstract { public const NAME = 'configuration'; private const MEDIA_PATH = _CENTREON_PATH_ . 'www/img/media'; /** @var \ConfigGenerateRemote\Generate */ private $generateService; /** * Set generate service. * * @param \ConfigGenerateRemote\Generate $generateService */ public function setGenerateService(\ConfigGenerateRemote\Generate $generateService): void { $this->generateService = $generateService; } /** * Export data. * * @param int $remoteId * * @return mixed[] */ public function export(int $remoteId): array { // create path $this->createPath(); $this->generateService->configRemoteServerFromId($remoteId, 'user'); return Manifest::getInstance($this->dependencyInjector)->getManifest(); } /** * Import data. * * @param ExportManifest $manifest */ public function import(ExportManifest $manifest): void { // skip if no data if (! is_dir($this->getPath())) { return; } $db = $this->db->getAdapter('configuration_db'); // get tables $stmt = $db->getCentreonDBInstance()->query('SHOW TABLES'); $tables = []; while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) { foreach ($row as $name) { $tables[$name] = 1; } } // start transaction $db->beginTransaction(); try { $truncated = []; // allow insert records without foreign key checks $db->query('SET FOREIGN_KEY_CHECKS=0;'); $import = $manifest->get('import'); foreach ($import['data'] as $data) { $exportPathFile = $this->getFile($data['filename']); $size = filesize($exportPathFile); echo date('Y-m-d H:i:s') . " - INFO - Loading '" . $exportPathFile . "' ({$size}).\n"; if ($size > 0 && ! isset($tables[$data['table']])) { echo date('Y-m-d H:i:s') . " - ERROR - cannot import table '" . $data['table'] . "': not exist.\n"; continue; } if (! isset($truncated[$data['table']]) && isset($tables[$data['table']])) { // empty table $db->query('DELETE FROM `' . $data['table'] . '`'); $db->query('ALTER TABLE `' . $data['table'] . '` AUTO_INCREMENT = 1'); $truncated[$data['table']] = 1; } // insert data if ($size > 0) { $db->loadDataInfile( $exportPathFile, $data['table'], $import['infile_clauses']['fields_clause'], $import['infile_clauses']['lines_clause'], $data['columns'] ); } } // restore foreign key checks $db->query('SET FOREIGN_KEY_CHECKS=1;'); // commit transaction $db->commit(); } catch (\ErrorException $e) { // rollback changes $db->rollBack(); echo date('Y-m-d H:i:s') . " - ERROR - Loading failed.\n"; } // media copy $exportPathMedia = $this->commitment->getPath() . '/media'; $mediaPath = self::MEDIA_PATH; $this->recursiveCopy($exportPathMedia, $mediaPath); } public static function order(): int { return 40; } /** * @return string */ public static function getName(): string { return static::NAME; } /** * Copy directory recursively. * * @param string $src * @param string $dst */ private function recursiveCopy($src, $dst): void { $dir = opendir($src); @mkdir($dst, $this->commitment->getFilePermission(), true); while (($file = readdir($dir))) { if (($file != '.') && ($file != '..')) { if (is_dir($src . '/' . $file)) { $this->recursiveCopy($src . '/' . $file, $dst . '/' . $file); } else { echo date('Y-m-d H:i:s') . " - INFO - Copying '" . $src . '/' . $file . "'.\n"; copy($src . '/' . $file, $dst . '/' . $file); chmod($dst . '/' . $file, $this->commitment->getFilePermission()); } } } closedir($dir); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonRemote/Domain/Value/ServerWizardIdentity.php
centreon/src/CentreonRemote/Domain/Value/ServerWizardIdentity.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 CentreonRemote\Domain\Value; use Curl\Curl; /** * Check wizard type. */ class ServerWizardIdentity { /** * check wizard type (remote server / poller). * * @return bool true if it is remote server wizard */ public function requestConfigurationIsRemote(): bool { return isset($_POST['server_type']) && $_POST['server_type'] == 'remote'; } /** * check wizard type (remote server / poller). * * @return bool true if it is poller wizard */ public function requestConfigurationIsPoller(): bool { return ! static::requestConfigurationIsRemote(); } /** * check if bam is installed on remote server. * * @param string $centreonUrl URL of Centreon of the remote server * @param bool $noCheckCertificate do not check peer SSL certificat * @param bool $noProxy don't use configured proxy * * @return bool if bam is installed on remote server */ public function checkBamOnRemoteServer( string $centreonUrl, bool $noCheckCertificate = false, bool $noProxy = false, ): bool { $centreonUrl .= '/api/external.php?object=centreon_modules_webservice&action=getBamModuleInfo'; try { $curl = new Curl(); if ($noCheckCertificate) { $curl->setOpt(CURLOPT_SSL_VERIFYPEER, false); } if ($noProxy) { $curl->setOpt(CURLOPT_PROXY, false); } $curl->post($centreonUrl); if ($curl->error) { return false; } } catch (\ErrorException $e) { return false; } $data = json_decode($curl->response, true) ?: []; return array_key_exists('enabled', $data) && $data['enabled']; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonRemote/Domain/Value/PollerServer.php
centreon/src/CentreonRemote/Domain/Value/PollerServer.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 CentreonRemote\Domain\Value; class PollerServer { /** @var int the poller id */ private $id; /** @var string the poller name */ private $name; /** @var string the poller ip address */ private $ip; /** * @return int */ public function getId(): int { return $this->id; } /** * @param int $id */ public function setId($id): void { $this->id = $id; } /** * Get poller name. * * @return string the poller name */ public function getName(): string { return $this->name; } /** * Set poller name. * * @param string $name the poller name */ public function setName(string $name): void { $this->name = $name; } /** * @return string */ public function getIp(): string { return $this->ip; } /** * @param string $ip */ public function setIp($ip): void { $this->ip = $ip; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonRemote/Domain/Resources/RemoteConfig/CfgNagiosBrokerModule.php
centreon/src/CentreonRemote/Domain/Resources/RemoteConfig/CfgNagiosBrokerModule.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 CentreonRemote\Domain\Resources\RemoteConfig; /** * Get broker configuration template. */ class CfgNagiosBrokerModule { /** * Get template configuration. * * @todo move it as yml * * @param int $configID the broker config id * @param string $pollerName the poller name * * @return array<int, array<string,string|int>> the configuration template */ public static function getConfiguration(int $configID, string $pollerName): array { $pollerName = strtolower(str_replace(' ', '-', $pollerName)); return [ [ 'cfg_nagios_id' => $configID, 'broker_module' => '/usr/lib64/centreon-engine/externalcmd.so', ], ]; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonRemote/Domain/Resources/RemoteConfig/CfgNagiosLogger.php
centreon/src/CentreonRemote/Domain/Resources/RemoteConfig/CfgNagiosLogger.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 CentreonRemote\Domain\Resources\RemoteConfig; use CentreonRemote\Domain\Resources\DefaultConfig\CfgNagiosLogger as DefaultLoggerCfg; /** * Get broker configuration template. */ class CfgNagiosLogger { /** * Get template configuration. * * @param int $nagiosId * * @return array<string,string|int> */ public static function getConfiguration(int $nagiosId): array { $cfg = DefaultLoggerCfg::getConfiguration(); $cfg['cfg_nagios_id'] = $nagiosId; return $cfg; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonRemote/Domain/Resources/RemoteConfig/CfgCentreonBrokerInfo.php
centreon/src/CentreonRemote/Domain/Resources/RemoteConfig/CfgCentreonBrokerInfo.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 CentreonRemote\Domain\Resources\RemoteConfig; use CentreonRemote\Domain\Resources\RemoteConfig\BrokerInfo\InputBroker; use CentreonRemote\Domain\Resources\RemoteConfig\BrokerInfo\InputRrd; use CentreonRemote\Domain\Resources\RemoteConfig\BrokerInfo\OutputForwardMaster; use CentreonRemote\Domain\Resources\RemoteConfig\BrokerInfo\OutputModuleMaster; use CentreonRemote\Domain\Resources\RemoteConfig\BrokerInfo\OutputRrd; use CentreonRemote\Domain\Resources\RemoteConfig\BrokerInfo\OutputRrdMaster; use CentreonRemote\Domain\Resources\RemoteConfig\BrokerInfo\OutputUnifiedSql; /** * Get broker configuration template. */ class CfgCentreonBrokerInfo { /** * Get template configuration. * * @todo move it as yml * * @param string $serverName the poller name * @param string|null $dbUser the database user * @param string|null $dbPassword the database password * * @return array<string, array<string, array<int, array<string>>>> the configuration template */ public static function getConfiguration(string $serverName, $dbUser, $dbPassword): array { $serverName = strtolower(str_replace(' ', '-', $serverName)); return [ 'central-broker' => [ 'broker' => InputBroker::getConfiguration(), 'output_rrd' => OutputRrdMaster::getConfiguration(), 'output_forward' => OutputForwardMaster::getConfiguration(), 'output_unified_sql' => OutputUnifiedSql::getConfiguration($dbUser, $dbPassword), ], 'central-module' => [ 'output' => OutputModuleMaster::getConfiguration(), ], 'central-rrd' => [ 'input' => InputRrd::getConfiguration(), 'output' => OutputRrd::getConfiguration(), ], ]; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonRemote/Domain/Resources/RemoteConfig/CfgNagios.php
centreon/src/CentreonRemote/Domain/Resources/RemoteConfig/CfgNagios.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 CentreonRemote\Domain\Resources\RemoteConfig; /** * Get broker configuration template. */ class CfgNagios { /** * Get template configuration. * * @todo move it as yml * * @param string $name the poller name * @param int $serverID the poller id * * @return array<string,string|int|null> the configuration template */ public static function getConfiguration(string $name, int $serverID): array { $configName = strtolower(str_replace(' ', '-', $name)); return [ 'nagios_name' => $name, 'use_timezone' => null, 'log_file' => '/var/log/centreon-engine/centengine.log', 'cfg_dir' => '/etc/centreon-engine/', 'status_file' => '/var/log/centreon-engine/status.dat', 'status_update_interval' => '60', 'enable_notifications' => '1', 'execute_service_checks' => '1', 'accept_passive_service_checks' => '1', 'execute_host_checks' => '1', 'accept_passive_host_checks' => '1', 'enable_event_handlers' => '1', 'check_external_commands' => '1', 'external_command_buffer_slots' => '4096', 'command_check_interval' => '1s', 'command_file' => '/var/lib/centreon-engine/rw/centengine.cmd', 'retain_state_information' => '1', 'state_retention_file' => '/var/log/centreon-engine/retention.dat', 'retention_update_interval' => '60', 'use_retained_program_state' => '1', 'use_retained_scheduling_info' => '0', 'use_syslog' => '0', 'log_notifications' => '1', 'log_service_retries' => '1', 'log_host_retries' => '1', 'log_event_handlers' => '1', 'log_initial_states' => '1', 'log_external_commands' => '1', 'log_passive_checks' => '1', 'global_host_event_handler' => null, 'global_service_event_handler' => null, 'sleep_time' => '0.5', 'service_inter_check_delay_method' => 's', 'Host_inter_check_delay_method' => 's', 'service_interleave_factor' => 's', 'max_concurrent_checks' => '0', 'max_service_check_spread' => '15', 'max_host_check_spread' => '15', 'check_result_reaper_frequency' => '5', 'auto_reschedule_checks' => '0', 'auto_rescheduling_interval' => '30', 'auto_rescheduling_window' => '180', 'enable_flap_detection' => '1', 'low_service_flap_threshold' => '25.0', 'high_service_flap_threshold' => '50.0', 'low_host_flap_threshold' => '25.0', 'high_host_flap_threshold' => '50.0', 'soft_state_dependencies' => '0', 'service_check_timeout' => '60', 'host_check_timeout' => '30', 'event_handler_timeout' => '30', 'notification_timeout' => '30', 'check_for_orphaned_services' => '1', 'check_for_orphaned_hosts' => '1', 'check_service_freshness' => '0', 'service_freshness_check_interval' => null, 'freshness_check_interval' => null, 'check_host_freshness' => '0', 'host_freshness_check_interval' => null, 'date_format' => 'euro', 'illegal_object_name_chars' => "~!$%^&*\"|'<>?,()=", 'illegal_macro_output_chars' => "`~$^&\"|'<>", 'use_regexp_matching' => '0', 'use_true_regexp_matching' => '0', 'admin_email' => 'admin@localhost', 'admin_pager' => 'admin@localhost', 'nagios_comment' => 'Centreon Engine config file for a polling instance', 'nagios_activate' => '1', 'event_broker_options' => '-1', 'nagios_server_id' => $serverID, 'enable_predictive_host_dependency_checks' => '1', 'enable_predictive_service_dependency_checks' => '1', 'host_down_disable_service_checks' => '1', 'cached_host_check_horizon' => '15', 'cached_service_check_horizon' => '15', 'enable_environment_macros' => '0', 'additional_freshness_latency' => '15', 'debug_file' => '/var/log/centreon-engine/centengine.debug', 'debug_level' => '0', 'debug_level_opt' => '0', 'debug_verbosity' => '1', 'max_debug_file_size' => '1000000000', 'cfg_file' => 'centengine.cfg', 'log_pid' => '1', 'logger_version' => 'log_v2_enabled', 'broker_module_cfg_file' => "/etc/centreon-broker/{$configName}-module.json", ]; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonRemote/Domain/Resources/RemoteConfig/CfgCentreonBroker.php
centreon/src/CentreonRemote/Domain/Resources/RemoteConfig/CfgCentreonBroker.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 CentreonRemote\Domain\Resources\RemoteConfig; /** * Get broker configuration template. */ class CfgCentreonBroker { /** * Get template configuration. * * @todo move it as yml * * @param int $serverID the poller id * @param string $pollerName the poller name * * @return array<string, array<string, int|string>> the configuration template */ public static function getConfiguration(int $serverID, string $pollerName): array { $configName = strtolower(str_replace(' ', '-', $pollerName)); return [ 'broker' => [ 'config_name' => "{$configName}-broker", 'config_filename' => "{$configName}-broker.json", 'config_write_timestamp' => '0', 'config_write_thread_id' => '0', 'config_activate' => '1', 'ns_nagios_server' => $serverID, 'event_queue_max_size' => '100000', 'command_file' => '', 'cache_directory' => '/var/lib/centreon-broker', 'log_directory' => '/var/log/centreon-broker', 'stats_activate' => '1', 'daemon' => '1', ], 'module' => [ 'config_name' => "{$configName}-module", 'config_filename' => "{$configName}-module.json", 'config_write_timestamp' => '0', 'config_write_thread_id' => '0', 'config_activate' => '1', 'ns_nagios_server' => $serverID, 'event_queue_max_size' => '100000', 'command_file' => '', 'cache_directory' => '/var/lib/centreon-engine', 'log_directory' => '/var/log/centreon-broker', 'stats_activate' => '1', 'daemon' => '0', ], 'rrd' => [ 'config_name' => "{$configName}-rrd", 'config_filename' => "{$configName}-rrd.json", 'config_write_timestamp' => '0', 'config_write_thread_id' => '0', 'config_activate' => '1', 'ns_nagios_server' => $serverID, 'event_queue_max_size' => '100000', 'command_file' => '', 'cache_directory' => '/var/lib/centreon-broker', 'log_directory' => '/var/log/centreon-broker', 'stats_activate' => '1', 'daemon' => '1', ], ]; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonRemote/Domain/Resources/RemoteConfig/BamBrokerCfgInfo.php
centreon/src/CentreonRemote/Domain/Resources/RemoteConfig/BamBrokerCfgInfo.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 CentreonRemote\Domain\Resources\RemoteConfig; /** * Get broker configuration template. */ class BamBrokerCfgInfo { /** * Get template configuration. * * @todo move it as yml * * @param string $dbPassword the centreon database password * * @return array<string, array<int, string[]>> the configuration template */ public static function getConfiguration(string $dbPassword): array { return [ 'monitoring' => [ [ 'config_key' => 'name', 'config_value' => 'poller-bam-monitoring', 'config_group' => 'output', 'config_group_id' => '4', 'grp_level' => '0', ], [ 'config_key' => 'cache', 'config_value' => 'yes', 'config_group' => 'output', 'config_group_id' => '4', 'grp_level' => '0', ], [ 'config_key' => 'command_file', 'config_value' => '/var/lib/centreon-engine/rw/centengine.cmd', 'config_group' => 'output', 'config_group_id' => '4', 'grp_level' => '0', ], [ 'config_key' => 'db_host', 'config_value' => 'localhost', 'config_group' => 'output', 'config_group_id' => '4', 'grp_level' => '0', ], [ 'config_key' => 'db_name', 'config_value' => 'centreon', 'config_group' => 'output', 'config_group_id' => '4', 'grp_level' => '0', ], [ 'config_key' => 'db_password', 'config_value' => $dbPassword, 'config_group' => 'output', 'config_group_id' => '4', 'grp_level' => '0', ], [ 'config_key' => 'db_user', 'config_value' => 'centreon', 'config_group' => 'output', 'config_group_id' => '4', 'grp_level' => '0', ], [ 'config_key' => 'db_port', 'config_value' => '3306', 'config_group' => 'output', 'config_group_id' => '4', 'grp_level' => '0', ], [ 'config_key' => 'db_type', 'config_value' => 'mysql', 'config_group' => 'output', 'config_group_id' => '4', 'grp_level' => '0', ], [ 'config_key' => 'queries_per_transaction', 'config_value' => '0', 'config_group' => 'output', 'config_group_id' => '4', 'grp_level' => '0', ], [ 'config_key' => 'read_timeout', 'config_value' => '', 'config_group' => 'output', 'config_group_id' => '4', 'grp_level' => '0', ], [ 'config_key' => 'retry_interval', 'config_value' => '', 'config_group' => 'output', 'config_group_id' => '4', 'grp_level' => '0', ], [ 'config_key' => 'storage_db_name', 'config_value' => '', 'config_group' => 'output', 'config_group_id' => '4', 'grp_level' => '0', ], [ 'config_key' => 'type', 'config_value' => 'bam', 'config_group' => 'output', 'config_group_id' => '4', 'grp_level' => '0', ], [ 'config_key' => 'blockId', 'config_value' => '1_34', 'config_group' => 'output', 'config_group_id' => '4', 'grp_level' => '0', ], ], 'reporting' => [ [ 'config_key' => 'name', 'config_value' => 'poller-bam-reporting', 'config_group' => 'output', 'config_group_id' => '5', 'grp_level' => '0', ], [ 'config_key' => 'filters', 'config_value' => '', 'config_group' => 'output', 'config_group_id' => '5', 'grp_level' => '0', ], [ 'config_key' => 'category', 'config_value' => 'bam', 'config_group' => 'output', 'config_group_id' => '5', 'grp_level' => '0', ], [ 'config_key' => 'db_host', 'config_value' => 'localhost', 'config_group' => 'output', 'config_group_id' => '5', 'grp_level' => '0', ], [ 'config_key' => 'db_name', 'config_value' => 'centreon_storage', 'config_group' => 'output', 'config_group_id' => '5', 'grp_level' => '0', ], [ 'config_key' => 'db_password', 'config_value' => $dbPassword, 'config_group' => 'output', 'config_group_id' => '5', 'grp_level' => '0', ], [ 'config_key' => 'db_user', 'config_value' => 'centreon', 'config_group' => 'output', 'config_group_id' => '5', 'grp_level' => '0', ], [ 'config_key' => 'db_port', 'config_value' => '3306', 'config_group' => 'output', 'config_group_id' => '5', 'grp_level' => '0', ], [ 'config_key' => 'db_type', 'config_value' => 'mysql', 'config_group' => 'output', 'config_group_id' => '5', 'grp_level' => '0', ], [ 'config_key' => 'queries_per_transaction', 'config_value' => '0', 'config_group' => 'output', 'config_group_id' => '5', 'grp_level' => '0', ], [ 'config_key' => 'read_timeout', 'config_value' => '', 'config_group' => 'output', 'config_group_id' => '5', 'grp_level' => '0', ], [ 'config_key' => 'retry_interval', 'config_value' => '', 'config_group' => 'output', 'config_group_id' => '5', 'grp_level' => '0', ], [ 'config_key' => 'type', 'config_value' => 'bam_bi', 'config_group' => 'output', 'config_group_id' => '5', 'grp_level' => '0', ], [ 'config_key' => 'blockId', 'config_value' => '1_35', 'config_group' => 'output', 'config_group_id' => '5', 'grp_level' => '0', ], ], ]; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonRemote/Domain/Resources/RemoteConfig/NagiosServer.php
centreon/src/CentreonRemote/Domain/Resources/RemoteConfig/NagiosServer.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 CentreonRemote\Domain\Resources\RemoteConfig; /** * Get broker configuration template. */ class NagiosServer { // ZMQ enum value public const ZMQ = '1'; /** * Get template configuration. * * @todo move it as yml * * @param string $name the poller name * @param string $ip the poller ip address * * @return array<string,int|string> the configuration template */ public static function getConfiguration(string $name, string $ip): array { return [ 'name' => $name, 'localhost' => '0', 'is_default' => '0', 'ns_ip_address' => $ip, 'ns_activate' => '1', 'ns_status' => '0', 'engine_start_command' => 'service centengine start', 'engine_stop_command' => 'service centengine stop', 'engine_restart_command' => 'service centengine restart', 'engine_reload_command' => 'service centengine reload', 'nagios_bin' => '/usr/sbin/centengine', 'nagiostats_bin' => '/usr/sbin/centenginestats', 'nagios_perfdata' => '/var/log/centreon-engine/service-perfdata', 'centreonbroker_cfg_path' => '/etc/centreon-broker', 'centreonbroker_module_path' => '/usr/share/centreon/lib/centreon-broker', 'centreonconnector_path' => '/usr/lib64/centreon-connector', 'ssh_port' => 22, 'gorgone_communication_type' => self::ZMQ, 'gorgone_port' => 5556, 'init_script_centreontrapd' => 'centreontrapd', 'snmp_trapd_path_conf' => '/etc/snmp/centreon_traps/', 'centreonbroker_logs_path' => '/var/log/centreon-broker/', ]; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonRemote/Domain/Resources/RemoteConfig/InputFlowOnePeerRetention.php
centreon/src/CentreonRemote/Domain/Resources/RemoteConfig/InputFlowOnePeerRetention.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 CentreonRemote\Domain\Resources\RemoteConfig; use Centreon\Domain\Entity\CfgCentreonBrokerInfo; /** * Configuration if input flow of central broker to get data from the remote poller. */ class InputFlowOnePeerRetention { /** * Get template configuration. * * @todo move it as yml * * @param string $pollerName the poller name * @param string $pollerIP the poller ip address * * @return CfgCentreonBrokerInfo[] the configuration template */ public static function getConfiguration(string $pollerName, string $pollerIP): array { return [ new CfgCentreonBrokerInfo('name', "connection-to-{$pollerName}"), new CfgCentreonBrokerInfo('port', '5669'), new CfgCentreonBrokerInfo('retry_interval', '15'), new CfgCentreonBrokerInfo('buffering_timeout', '0'), new CfgCentreonBrokerInfo('host', $pollerIP), new CfgCentreonBrokerInfo('protocol', 'bbdo'), new CfgCentreonBrokerInfo('tls', 'no'), new CfgCentreonBrokerInfo('failover', ''), new CfgCentreonBrokerInfo('private_key', ''), new CfgCentreonBrokerInfo('public_cert', ''), new CfgCentreonBrokerInfo('ca_certificate', ''), new CfgCentreonBrokerInfo('negotiation', 'yes'), new CfgCentreonBrokerInfo('one_peer_retention_mode', 'no'), new CfgCentreonBrokerInfo('compression', 'no'), new CfgCentreonBrokerInfo('compression_level', ''), new CfgCentreonBrokerInfo('compression_buffer', ''), new CfgCentreonBrokerInfo('type', 'ipv4'), new CfgCentreonBrokerInfo('blockId', '2_3'), ]; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonRemote/Domain/Resources/RemoteConfig/BrokerInfo/OutputRrd.php
centreon/src/CentreonRemote/Domain/Resources/RemoteConfig/BrokerInfo/OutputRrd.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 CentreonRemote\Domain\Resources\RemoteConfig\BrokerInfo; /** * Get broker configuration template. */ class OutputRrd { /** * Get template configuration. * * @todo move it as yml * * @return array<int, string[]> the configuration template */ public static function getConfiguration(): array { return [ [ 'config_key' => 'name', 'config_value' => 'central-rrd-master-output', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'metrics_path', 'config_value' => '/var/lib/centreon/metrics/', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'failover', 'config_value' => '', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'status_path', 'config_value' => '/var/lib/centreon/status/', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'retry_interval', 'config_value' => '15', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'buffering_timeout', 'config_value' => '0', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'path', 'config_value' => '', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'port', 'config_value' => '', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'write_metrics', 'config_value' => 'yes', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'write_status', 'config_value' => 'yes', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'store_in_data_bin', 'config_value' => 'yes', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'insert_in_index_data', 'config_value' => '1', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'type', 'config_value' => 'rrd', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'blockId', 'config_value' => '1_13', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], ]; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonRemote/Domain/Resources/RemoteConfig/BrokerInfo/InputBroker.php
centreon/src/CentreonRemote/Domain/Resources/RemoteConfig/BrokerInfo/InputBroker.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 CentreonRemote\Domain\Resources\RemoteConfig\BrokerInfo; /** * Get broker configuration template. */ class InputBroker { /** * Get template configuration. * * @todo move it as yml * * @return array<int, string[]> the configuration template */ public static function getConfiguration(): array { return [ [ 'config_key' => 'name', 'config_value' => 'central-broker-master-input', 'config_group' => 'input', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'port', 'config_value' => '5669', 'config_group' => 'input', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'host', 'config_value' => '', 'config_group' => 'input', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'failover', 'config_value' => '', 'config_group' => 'input', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'retry_interval', 'config_value' => '15', 'config_group' => 'input', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'buffering_timeout', 'config_value' => '0', 'config_group' => 'input', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'protocol', 'config_value' => 'bbdo', 'config_group' => 'input', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'tls', 'config_value' => 'auto', 'config_group' => 'input', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'private_key', 'config_value' => '', 'config_group' => 'input', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'public_cert', 'config_value' => '', 'config_group' => 'input', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'ca_certificate', 'config_value' => '', 'config_group' => 'input', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'negotiation', 'config_value' => 'yes', 'config_group' => 'input', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'one_peer_retention_mode', 'config_value' => 'no', 'config_group' => 'input', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'compression', 'config_value' => 'auto', 'config_group' => 'input', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'compression_level', 'config_value' => '', 'config_group' => 'input', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'compression_buffer', 'config_value' => '', 'config_group' => 'input', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'type', 'config_value' => 'ipv4', 'config_group' => 'input', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'blockId', 'config_value' => '2_3', 'config_group' => 'input', 'config_group_id' => '0', 'grp_level' => '0', ], ]; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonRemote/Domain/Resources/RemoteConfig/BrokerInfo/OutputCentral.php
centreon/src/CentreonRemote/Domain/Resources/RemoteConfig/BrokerInfo/OutputCentral.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 CentreonRemote\Domain\Resources\RemoteConfig\BrokerInfo; /** * Get broker configuration template. */ class OutputCentral { /** * Get template configuration. * * @todo move it as yml * * @return array<int, string[]> the configuration template */ public static function getConfiguration(): array { return [ [ 'config_key' => 'name', 'config_value' => 'Central-Output', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'port', 'config_value' => '5669', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'host', 'config_value' => 'localhost', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'failover', 'config_value' => '', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'retry_interval', 'config_value' => '', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'buffering_timeout', 'config_value' => '', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'protocol', 'config_value' => 'bbdo', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'tls', 'config_value' => 'no', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'private_key', 'config_value' => '', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'public_cert', 'config_value' => '', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'ca_certificate', 'config_value' => '', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'negotiation', 'config_value' => 'yes', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'one_peer_retention_mode', 'config_value' => 'no', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'compression', 'config_value' => 'no', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'compression_level', 'config_value' => '', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'compression_buffer', 'config_value' => '', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'type', 'config_value' => 'ipv4', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'blockId', 'config_value' => '1_3', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], ]; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonRemote/Domain/Resources/RemoteConfig/BrokerInfo/OutputForwardMaster.php
centreon/src/CentreonRemote/Domain/Resources/RemoteConfig/BrokerInfo/OutputForwardMaster.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 CentreonRemote\Domain\Resources\RemoteConfig\BrokerInfo; /** * Get broker configuration template. */ class OutputForwardMaster { /** * Get template configuration. * * @todo move it as yml * * @return array<int, string[]> the configuration template */ public static function getConfiguration(): array { return [ [ 'config_key' => 'name', 'config_value' => 'forward-to-master', 'config_group' => 'output', 'config_group_id' => '3', 'grp_level' => '0', ], [ 'config_key' => 'port', 'config_value' => '5669', 'config_group' => 'output', 'config_group_id' => '3', 'grp_level' => '0', ], [ 'config_key' => 'host', 'config_value' => '', 'config_group' => 'output', 'config_group_id' => '3', 'grp_level' => '0', ], [ 'config_key' => 'failover', 'config_value' => '', 'config_group' => 'output', 'config_group_id' => '3', 'grp_level' => '0', ], [ 'config_key' => 'retry_interval', 'config_value' => '', 'config_group' => 'output', 'config_group_id' => '3', 'grp_level' => '0', ], [ 'config_key' => 'buffering_timeout', 'config_value' => '', 'config_group' => 'output', 'config_group_id' => '3', 'grp_level' => '0', ], [ 'config_key' => 'protocol', 'config_value' => 'bbdo', 'config_group' => 'output', 'config_group_id' => '3', 'grp_level' => '0', ], [ 'config_key' => 'tls', 'config_value' => 'no', 'config_group' => 'output', 'config_group_id' => '3', 'grp_level' => '0', ], [ 'config_key' => 'private_key', 'config_value' => '', 'config_group' => 'output', 'config_group_id' => '3', 'grp_level' => '0', ], [ 'config_key' => 'public_cert', 'config_value' => '', 'config_group' => 'output', 'config_group_id' => '3', 'grp_level' => '0', ], [ 'config_key' => 'ca_certificate', 'config_value' => '', 'config_group' => 'output', 'config_group_id' => '3', 'grp_level' => '0', ], [ 'config_key' => 'negotiation', 'config_value' => 'yes', 'config_group' => 'output', 'config_group_id' => '3', 'grp_level' => '0', ], [ 'config_key' => 'one_peer_retention_mode', 'config_value' => 'no', 'config_group' => 'output', 'config_group_id' => '3', 'grp_level' => '0', ], [ 'config_key' => 'compression', 'config_value' => 'no', 'config_group' => 'output', 'config_group_id' => '3', 'grp_level' => '0', ], [ 'config_key' => 'compression_level', 'config_value' => '', 'config_group' => 'output', 'config_group_id' => '3', 'grp_level' => '0', ], [ 'config_key' => 'compression_buffer', 'config_value' => '', 'config_group' => 'output', 'config_group_id' => '3', 'grp_level' => '0', ], [ 'config_key' => 'type', 'config_value' => 'ipv4', 'config_group' => 'output', 'config_group_id' => '3', 'grp_level' => '0', ], [ 'config_key' => 'blockId', 'config_value' => '1_3', 'config_group' => 'output', 'config_group_id' => '3', 'grp_level' => '0', ], [ 'config_key' => 'filters', 'config_value' => '', 'config_group' => 'output', 'config_group_id' => '3', 'grp_level' => '0', 'subgrp_id' => '1', ], [ 'config_key' => 'category', 'config_value' => 'neb', 'config_group' => 'output', 'config_group_id' => '3', 'grp_level' => '1', 'parent_grp_id' => '1', ], ]; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonRemote/Domain/Resources/RemoteConfig/BrokerInfo/OutputRrdMaster.php
centreon/src/CentreonRemote/Domain/Resources/RemoteConfig/BrokerInfo/OutputRrdMaster.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 CentreonRemote\Domain\Resources\RemoteConfig\BrokerInfo; /** * Get broker configuration template. */ class OutputRrdMaster { /** * Get template configuration. * * @todo move it as yml * * @return array<int, string[]> the configuration template */ public static function getConfiguration(): array { return [ [ 'config_key' => 'name', 'config_value' => 'centreon-broker-master-rrd', 'config_group' => 'output', 'config_group_id' => '1', 'grp_level' => '0', ], [ 'config_key' => 'port', 'config_value' => '5670', 'config_group' => 'output', 'config_group_id' => '1', 'grp_level' => '0', ], [ 'config_key' => 'host', 'config_value' => 'localhost', 'config_group' => 'output', 'config_group_id' => '1', 'grp_level' => '0', ], [ 'config_key' => 'failover', 'config_value' => '', 'config_group' => 'output', 'config_group_id' => '1', 'grp_level' => '0', ], [ 'config_key' => 'retry_interval', 'config_value' => '15', 'config_group' => 'output', 'config_group_id' => '1', 'grp_level' => '0', ], [ 'config_key' => 'buffering_timeout', 'config_value' => '0', 'config_group' => 'output', 'config_group_id' => '1', 'grp_level' => '0', ], [ 'config_key' => 'protocol', 'config_value' => 'bbdo', 'config_group' => 'output', 'config_group_id' => '1', 'grp_level' => '0', ], [ 'config_key' => 'tls', 'config_value' => 'no', 'config_group' => 'output', 'config_group_id' => '1', 'grp_level' => '0', ], [ 'config_key' => 'private_key', 'config_value' => '', 'config_group' => 'output', 'config_group_id' => '1', 'grp_level' => '0', ], [ 'config_key' => 'public_cert', 'config_value' => '', 'config_group' => 'output', 'config_group_id' => '1', 'grp_level' => '0', ], [ 'config_key' => 'ca_certificate', 'config_value' => '', 'config_group' => 'output', 'config_group_id' => '1', 'grp_level' => '0', ], [ 'config_key' => 'negotiation', 'config_value' => 'yes', 'config_group' => 'output', 'config_group_id' => '1', 'grp_level' => '0', ], [ 'config_key' => 'one_peer_retention_mode', 'config_value' => 'no', 'config_group' => 'output', 'config_group_id' => '1', 'grp_level' => '0', ], [ 'config_key' => 'compression', 'config_value' => 'no', 'config_group' => 'output', 'config_group_id' => '1', 'grp_level' => '0', ], [ 'config_key' => 'compression_level', 'config_value' => '', 'config_group' => 'output', 'config_group_id' => '1', 'grp_level' => '0', ], [ 'config_key' => 'compression_buffer', 'config_value' => '', 'config_group' => 'output', 'config_group_id' => '1', 'grp_level' => '0', ], [ 'config_key' => 'type', 'config_value' => 'ipv4', 'config_group' => 'output', 'config_group_id' => '1', 'grp_level' => '0', ], [ 'config_key' => 'blockId', 'config_value' => '1_3', 'config_group' => 'output', 'config_group_id' => '1', 'grp_level' => '0', ], ]; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonRemote/Domain/Resources/RemoteConfig/BrokerInfo/OutputUnifiedSql.php
centreon/src/CentreonRemote/Domain/Resources/RemoteConfig/BrokerInfo/OutputUnifiedSql.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 CentreonRemote\Domain\Resources\RemoteConfig\BrokerInfo; /** * Get broker configuration template. */ class OutputUnifiedSql { /** * Get template configuration. * * @todo move it as yml * * @param string|null $dbUser the database user * @param string|null $dbPassword the database password * * @return array<int, string[]> the configuration template */ public static function getConfiguration($dbUser, $dbPassword): array { return [ [ 'config_key' => 'name', 'config_value' => 'central-broker-master-unified-sql', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'db_type', 'config_value' => 'mysql', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'retry_interval', 'config_value' => '15', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'buffering_timeout', 'config_value' => '0', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'db_host', 'config_value' => 'localhost', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'db_port', 'config_value' => '3306', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'db_user', 'config_value' => $dbUser, 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'db_password', 'config_value' => $dbPassword, 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'db_name', 'config_value' => 'centreon_storage', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'queries_per_transaction', 'config_value' => '', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'read_timeout', 'config_value' => '', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'interval', 'config_value' => '60', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'length', 'config_value' => '15552000', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'rebuild_check_interval', 'config_value' => '', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'store_in_data_bin', 'config_value' => 'yes', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'insert_in_index_data', 'config_value' => '1', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'failover', 'config_value' => '', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'cleanup_check_interval', 'config_value' => '', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'instance_timeout', 'config_value' => '', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'type', 'config_value' => 'unified_sql', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'blockId', 'config_value' => '1_34', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], ]; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonRemote/Domain/Resources/RemoteConfig/BrokerInfo/OutputStatus.php
centreon/src/CentreonRemote/Domain/Resources/RemoteConfig/BrokerInfo/OutputStatus.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 CentreonRemote\Domain\Resources\RemoteConfig\BrokerInfo; /** * Get broker configuration template. */ class OutputStatus { /** * Get template configuration. * * @todo move it as yml * * @return array<int, string[]> the configuration template */ public static function getConfiguration(): array { return [ [ 'config_key' => 'name', 'config_value' => 'Status-Master', 'config_group' => 'output', 'config_group_id' => '1', 'grp_level' => '0', ], [ 'config_key' => 'retry_interval', 'config_value' => '', 'config_group' => 'output', 'config_group_id' => '1', 'grp_level' => '0', ], [ 'config_key' => 'buffering_timeout', 'config_value' => '', 'config_group' => 'output', 'config_group_id' => '1', 'grp_level' => '0', ], [ 'config_key' => 'failover', 'config_value' => '', 'config_group' => 'output', 'config_group_id' => '1', 'grp_level' => '0', ], [ 'config_key' => 'db_type', 'config_value' => 'mysql', 'config_group' => 'output', 'config_group_id' => '1', 'grp_level' => '0', ], [ 'config_key' => 'db_host', 'config_value' => 'localhost', 'config_group' => 'output', 'config_group_id' => '1', 'grp_level' => '0', ], [ 'config_key' => 'db_port', 'config_value' => '3306', 'config_group' => 'output', 'config_group_id' => '1', 'grp_level' => '0', ], [ 'config_key' => 'db_user', 'config_value' => 'centreon', 'config_group' => 'output', 'config_group_id' => '1', 'grp_level' => '0', ], [ 'config_key' => 'db_password', 'config_value' => 'FDuM1710', 'config_group' => 'output', 'config_group_id' => '1', 'grp_level' => '0', ], [ 'config_key' => 'db_name', 'config_value' => 'centreon_storage', 'config_group' => 'output', 'config_group_id' => '1', 'grp_level' => '0', ], [ 'config_key' => 'queries_per_transaction', 'config_value' => '400', 'config_group' => 'output', 'config_group_id' => '1', 'grp_level' => '0', ], [ 'config_key' => 'read_timeout', 'config_value' => '5', 'config_group' => 'output', 'config_group_id' => '1', 'grp_level' => '0', ], [ 'config_key' => 'cleanup_check_interval', 'config_value' => '', 'config_group' => 'output', 'config_group_id' => '1', 'grp_level' => '0', ], [ 'config_key' => 'instance_timeout', 'config_value' => '', 'config_group' => 'output', 'config_group_id' => '1', 'grp_level' => '0', ], [ 'config_key' => 'filters', 'config_value' => '', 'config_group' => 'output', 'config_group_id' => '1', 'grp_level' => '0', ], [ 'config_key' => 'category', 'config_value' => 'neb', 'config_group' => 'output', 'config_group_id' => '1', 'grp_level' => '1', ], [ 'config_key' => 'category', 'config_value' => 'correlation', 'config_group' => 'output', 'config_group_id' => '1', 'grp_level' => '1', ], [ 'config_key' => 'type', 'config_value' => 'sql', 'config_group' => 'output', 'config_group_id' => '1', 'grp_level' => '0', ], [ 'config_key' => 'blockId', 'config_value' => '1_16', 'config_group' => 'output', 'config_group_id' => '1', 'grp_level' => '0', ], ]; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonRemote/Domain/Resources/RemoteConfig/BrokerInfo/OutputModuleMaster.php
centreon/src/CentreonRemote/Domain/Resources/RemoteConfig/BrokerInfo/OutputModuleMaster.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 CentreonRemote\Domain\Resources\RemoteConfig\BrokerInfo; /** * Get broker configuration template. */ class OutputModuleMaster { /** * Get template configuration. * * @todo move it as yml * * @return array<int, string[]> the configuration template */ public static function getConfiguration(): array { return [ [ 'config_key' => 'name', 'config_value' => 'central-module-master-output', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'port', 'config_value' => '5669', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'host', 'config_value' => 'localhost', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'failover', 'config_value' => '', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'retry_interval', 'config_value' => '15', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'buffering_timeout', 'config_value' => '0', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'protocol', 'config_value' => 'bbdo', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'tls', 'config_value' => 'no', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'private_key', 'config_value' => '', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'public_cert', 'config_value' => '', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'ca_certificate', 'config_value' => '', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'negotiation', 'config_value' => 'yes', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'one_peer_retention_mode', 'config_value' => 'no', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'compression', 'config_value' => 'no', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'compression_level', 'config_value' => '', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'compression_buffer', 'config_value' => '', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'type', 'config_value' => 'ipv4', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'blockId', 'config_value' => '1_3', 'config_group' => 'output', 'config_group_id' => '0', 'grp_level' => '0', ], ]; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonRemote/Domain/Resources/RemoteConfig/BrokerInfo/InputRrd.php
centreon/src/CentreonRemote/Domain/Resources/RemoteConfig/BrokerInfo/InputRrd.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 CentreonRemote\Domain\Resources\RemoteConfig\BrokerInfo; /** * Get broker configuration template. */ class InputRrd { /** * Get template configuration. * * @todo move it as yml * * @return array<int, string[]> the configuration template */ public static function getConfiguration(): array { return [ [ 'config_key' => 'name', 'config_value' => 'central-rrd-master-input', 'config_group' => 'input', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'port', 'config_value' => '5670', 'config_group' => 'input', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'host', 'config_value' => '', 'config_group' => 'input', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'failover', 'config_value' => '', 'config_group' => 'input', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'retry_interval', 'config_value' => '15', 'config_group' => 'input', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'buffering_timeout', 'config_value' => '0', 'config_group' => 'input', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'protocol', 'config_value' => 'bbdo', 'config_group' => 'input', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'tls', 'config_value' => 'auto', 'config_group' => 'input', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'private_key', 'config_value' => '', 'config_group' => 'input', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'public_cert', 'config_value' => '', 'config_group' => 'input', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'ca_certificate', 'config_value' => '', 'config_group' => 'input', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'negotiation', 'config_value' => 'yes', 'config_group' => 'input', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'one_peer_retention_mode', 'config_value' => 'no', 'config_group' => 'input', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'compression', 'config_value' => 'auto', 'config_group' => 'input', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'compression_level', 'config_value' => '', 'config_group' => 'input', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'compression_buffer', 'config_value' => '', 'config_group' => 'input', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'type', 'config_value' => 'ipv4', 'config_group' => 'input', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'blockId', 'config_value' => '2_3', 'config_group' => 'input', 'config_group_id' => '0', 'grp_level' => '0', ], ]; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonRemote/Domain/Resources/RemoteConfig/BrokerInfo/LoggerSql.php
centreon/src/CentreonRemote/Domain/Resources/RemoteConfig/BrokerInfo/LoggerSql.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 CentreonRemote\Domain\Resources\RemoteConfig\BrokerInfo; /** * Get broker configuration template. */ class LoggerSql { /** * Get template configuration. * * @todo move it as yml * * @return array<int, string[]> the configuration template */ public static function getConfiguration(): array { return [ [ 'config_key' => 'name', 'config_value' => '/var/log/centreon-broker/broker-sql.log', 'config_group' => 'logger', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'config', 'config_value' => 'yes', 'config_group' => 'logger', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'debug', 'config_value' => 'no', 'config_group' => 'logger', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'error', 'config_value' => 'yes', 'config_group' => 'logger', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'info', 'config_value' => 'no', 'config_group' => 'logger', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'level', 'config_value' => 'low', 'config_group' => 'logger', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'max_size', 'config_value' => '', 'config_group' => 'logger', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'type', 'config_value' => 'file', 'config_group' => 'logger', 'config_group_id' => '0', 'grp_level' => '0', ], [ 'config_key' => 'blockId', 'config_value' => '3_17', 'config_group' => 'logger', 'config_group_id' => '0', 'grp_level' => '0', ], ]; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonRemote/Domain/Resources/DefaultConfig/CfgNagiosBrokerModule.php
centreon/src/CentreonRemote/Domain/Resources/DefaultConfig/CfgNagiosBrokerModule.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 CentreonRemote\Domain\Resources\DefaultConfig; /** * Get broker configuration template. */ class CfgNagiosBrokerModule { /** * Get template configuration. * * @todo move it as yml * * @return array<int, array<string,int|string>> the configuration template */ public static function getConfiguration(): array { return [ [ 'cfg_nagios_id' => 1, 'broker_module' => '@centreon_engine_lib@/externalcmd.so', ], ]; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonRemote/Domain/Resources/DefaultConfig/CfgCentreonBrokerLog.php
centreon/src/CentreonRemote/Domain/Resources/DefaultConfig/CfgCentreonBrokerLog.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 CentreonRemote\Domain\Resources\DefaultConfig; use CentreonDB; /** * Get broker configuration template. */ class CfgCentreonBrokerLog { /** * Get template configuration. * * @param CentreonDB $db * @param int $brokerId * * @return \Generator<array<string,string|int>> the configuration template */ public static function getConfiguration(CentreonDB $db, int $brokerId): \Generator { $loggerIds = self::getLoggerIds($db); $loggerLevelIds = self::getLoggerLevelIds($db); $loggerConfigurations = [ $loggerIds['core'] => $loggerLevelIds['info'], $loggerIds['config'] => $loggerLevelIds['error'], $loggerIds['sql'] => $loggerLevelIds['error'], $loggerIds['processing'] => $loggerLevelIds['error'], $loggerIds['perfdata'] => $loggerLevelIds['error'], $loggerIds['bbdo'] => $loggerLevelIds['error'], $loggerIds['tcp'] => $loggerLevelIds['error'], $loggerIds['tls'] => $loggerLevelIds['error'], $loggerIds['lua'] => $loggerLevelIds['error'], $loggerIds['bam'] => $loggerLevelIds['error'], $loggerIds['neb'] => $loggerLevelIds['error'], $loggerIds['rrd'] => $loggerLevelIds['error'], $loggerIds['grpc'] => $loggerLevelIds['error'], $loggerIds['influxdb'] => $loggerLevelIds['error'], $loggerIds['graphite'] => $loggerLevelIds['error'], $loggerIds['victoria_metrics'] => $loggerLevelIds['error'], $loggerIds['stats'] => $loggerLevelIds['error'], ]; foreach ($loggerConfigurations as $loggerId => $loggerLevel) { yield [ 'id_centreonbroker' => $brokerId, 'id_log' => $loggerId, 'id_level' => $loggerLevel, ]; } } /** * Get logger ids. * * @param CentreonDB $db * * @return array<string,int> */ private static function getLoggerIds(CentreonDB $db): array { $result = $db->query( 'SELECT name, id FROM cb_log' ); return $result->fetchAll(\PDO::FETCH_KEY_PAIR); } /** * Get logger level ids. * * @param CentreonDB $db * * @return array<string,int> */ private static function getLoggerLevelIds(CentreonDB $db): array { $result = $db->query( 'SELECT name, id FROM cb_log_level' ); return $result->fetchAll(\PDO::FETCH_KEY_PAIR); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonRemote/Domain/Resources/DefaultConfig/CfgNagiosLogger.php
centreon/src/CentreonRemote/Domain/Resources/DefaultConfig/CfgNagiosLogger.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 CentreonRemote\Domain\Resources\DefaultConfig; /** * Get broker configuration template. */ class CfgNagiosLogger { /** * Get template configuration. * * @return array<string,string|int> */ public static function getConfiguration(): array { return [ 'cfg_nagios_id' => 1, 'log_v2_logger' => 'file', 'log_level_functions' => 'warning', 'log_level_config' => 'info', 'log_level_events' => 'info', 'log_level_checks' => 'info', 'log_level_notifications' => 'info', 'log_level_eventbroker' => 'warning', 'log_level_external_command' => 'info', 'log_level_commands' => 'warning', 'log_level_downtimes' => 'info', 'log_level_comments' => 'info', 'log_level_macros' => 'warning', 'log_level_process' => 'info', 'log_level_runtime' => 'warning', ]; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonRemote/Domain/Resources/DefaultConfig/CfgCentreonBrokerInfo.php
centreon/src/CentreonRemote/Domain/Resources/DefaultConfig/CfgCentreonBrokerInfo.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 CentreonRemote\Domain\Resources\DefaultConfig; /** * Get broker configuration template. */ class CfgCentreonBrokerInfo { /** * Get template configuration. * * @todo move it as yml * * @return array<int, array<string,int|string>> the configuration template */ public static function getConfiguration(): array { return [ [ 'config_id' => 1, 'config_key' => 'name', 'config_value' => 'central-broker-master-input', 'config_group' => 'input', 'config_group_id' => 1, ], [ 'config_id' => 1, 'config_key' => 'port', 'config_value' => '5669', 'config_group' => 'input', 'config_group_id' => 1, ], [ 'config_id' => 1, 'config_key' => 'buffering_timeout', 'config_value' => '0', 'config_group' => 'input', 'config_group_id' => 1, ], [ 'config_id' => 1, 'config_key' => 'host', 'config_value' => '', 'config_group' => 'input', 'config_group_id' => 1, ], [ 'config_id' => 1, 'config_key' => 'retry_interval', 'config_value' => '15', 'config_group' => 'input', 'config_group_id' => 1, ], [ 'config_id' => 1, 'config_key' => 'protocol', 'config_value' => 'bbdo', 'config_group' => 'input', 'config_group_id' => 1, ], [ 'config_id' => 1, 'config_key' => 'tls', 'config_value' => 'auto', 'config_group' => 'input', 'config_group_id' => 1, ], [ 'config_id' => 1, 'config_key' => 'private_key', 'config_value' => '', 'config_group' => 'input', 'config_group_id' => 1, ], [ 'config_id' => 1, 'config_key' => 'public_cert', 'config_value' => '', 'config_group' => 'input', 'config_group_id' => 1, ], [ 'config_id' => 1, 'config_key' => 'ca_certificate', 'config_value' => '', 'config_group' => 'input', 'config_group_id' => 1, ], [ 'config_id' => 1, 'config_key' => 'negotiation', 'config_value' => 'yes', 'config_group' => 'input', 'config_group_id' => 1, ], [ 'config_id' => 1, 'config_key' => 'one_peer_retention_mode', 'config_value' => 'no', 'config_group' => 'input', 'config_group_id' => 1, ], [ 'config_id' => 1, 'config_key' => 'compression', 'config_value' => 'auto', 'config_group' => 'input', 'config_group_id' => 1, ], [ 'config_id' => 1, 'config_key' => 'compression_level', 'config_value' => '', 'config_group' => 'input', 'config_group_id' => 1, ], [ 'config_id' => 1, 'config_key' => 'compression_buffer', 'config_value' => '', 'config_group' => 'input', 'config_group_id' => 1, ], [ 'config_id' => 1, 'config_key' => 'type', 'config_value' => 'ipv4', 'config_group' => 'input', 'config_group_id' => 1, ], [ 'config_id' => 1, 'config_key' => 'blockId', 'config_value' => '2_3', 'config_group' => 'input', 'config_group_id' => 1, ], [ 'config_id' => 1, 'config_key' => 'name', 'config_value' => '@centreonbroker_log@/central-broker-master.log', 'config_group' => 'logger', 'config_group_id' => 1, ], [ 'config_id' => 1, 'config_key' => 'config', 'config_value' => 'yes', 'config_group' => 'logger', 'config_group_id' => 1, ], [ 'config_id' => 1, 'config_key' => 'debug', 'config_value' => 'no', 'config_group' => 'logger', 'config_group_id' => 1, ], [ 'config_id' => 1, 'config_key' => 'error', 'config_value' => 'yes', 'config_group' => 'logger', 'config_group_id' => 1, ], [ 'config_id' => 1, 'config_key' => 'info', 'config_value' => 'no', 'config_group' => 'logger', 'config_group_id' => 1, ], [ 'config_id' => 1, 'config_key' => 'level', 'config_value' => 'low', 'config_group' => 'logger', 'config_group_id' => 1, ], [ 'config_id' => 1, 'config_key' => 'max_size', 'config_value' => '', 'config_group' => 'logger', 'config_group_id' => 1, ], [ 'config_id' => 1, 'config_key' => 'type', 'config_value' => 'file', 'config_group' => 'logger', 'config_group_id' => 1, ], [ 'config_id' => 1, 'config_key' => 'blockId', 'config_value' => '3_17', 'config_group' => 'logger', 'config_group_id' => 1, ], [ 'config_id' => 1, 'config_key' => 'name', 'config_value' => 'central-broker-master-unified-sql', 'config_group' => 'output', 'config_group_id' => 1, ], [ 'config_id' => 1, 'config_key' => 'db_type', 'config_value' => 'mysql', 'config_group' => 'output', 'config_group_id' => 1, ], [ 'config_id' => 1, 'config_key' => 'retry_interval', 'config_value' => '15', 'config_group' => 'output', 'config_group_id' => 1, ], [ 'config_id' => 1, 'config_key' => 'buffering_timeout', 'config_value' => '0', 'config_group' => 'output', 'config_group_id' => 1, ], [ 'config_id' => 1, 'config_key' => 'db_host', 'config_value' => '@address@', 'config_group' => 'output', 'config_group_id' => 1, ], [ 'config_id' => 1, 'config_key' => 'db_port', 'config_value' => '@port@', 'config_group' => 'output', 'config_group_id' => 1, ], [ 'config_id' => 1, 'config_key' => 'db_user', 'config_value' => '@db_user@', 'config_group' => 'output', 'config_group_id' => 1, ], [ 'config_id' => 1, 'config_key' => 'db_password', 'config_value' => '@db_password@', 'config_group' => 'output', 'config_group_id' => 1, ], [ 'config_id' => 1, 'config_key' => 'db_name', 'config_value' => '@db_storage@', 'config_group' => 'output', 'config_group_id' => 1, ], [ 'config_id' => 1, 'config_key' => 'queries_per_transaction', 'config_value' => '', 'config_group' => 'output', 'config_group_id' => 1, ], [ 'config_id' => 1, 'config_key' => 'read_timeout', 'config_value' => '', 'config_group' => 'output', 'config_group_id' => 1, ], [ 'config_id' => 1, 'config_key' => 'interval', 'config_value' => '60', 'config_group' => 'output', 'config_group_id' => 1, ], [ 'config_id' => 1, 'config_key' => 'length', 'config_value' => '15552000', 'config_group' => 'output', 'config_group_id' => 1, ], [ 'config_id' => 1, 'config_key' => 'rebuild_check_interval', 'config_value' => '', 'config_group' => 'output', 'config_group_id' => 1, ], [ 'config_id' => 1, 'config_key' => 'store_in_data_bin', 'config_value' => 'yes', 'config_group' => 'output', 'config_group_id' => 1, ], [ 'config_id' => 1, 'config_key' => 'insert_in_index_data', 'config_value' => '1', 'config_group' => 'output', 'config_group_id' => 1, ], [ 'config_id' => 1, 'config_key' => 'type', 'config_value' => 'unified_sql', 'config_group' => 'output', 'config_group_id' => 1, ], [ 'config_id' => 1, 'config_key' => 'blockId', 'config_value' => '1_34', 'config_group' => 'output', 'config_group_id' => 1, ], [ 'config_id' => 1, 'config_key' => 'name', 'config_value' => 'centreon-broker-master-rrd', 'config_group' => 'output', 'config_group_id' => 2, ], [ 'config_id' => 1, 'config_key' => 'port', 'config_value' => '5670', 'config_group' => 'output', 'config_group_id' => 2, ], [ 'config_id' => 1, 'config_key' => 'buffering_timeout', 'config_value' => '0', 'config_group' => 'output', 'config_group_id' => 2, ], [ 'config_id' => 1, 'config_key' => 'host', 'config_value' => 'localhost', 'config_group' => 'output', 'config_group_id' => 2, ], [ 'config_id' => 1, 'config_key' => 'retry_interval', 'config_value' => '15', 'config_group' => 'output', 'config_group_id' => 2, ], [ 'config_id' => 1, 'config_key' => 'protocol', 'config_value' => 'bbdo', 'config_group' => 'output', 'config_group_id' => 2, ], [ 'config_id' => 1, 'config_key' => 'tls', 'config_value' => 'no', 'config_group' => 'output', 'config_group_id' => 2, ], [ 'config_id' => 1, 'config_key' => 'private_key', 'config_value' => '', 'config_group' => 'output', 'config_group_id' => 2, ], [ 'config_id' => 1, 'config_key' => 'public_cert', 'config_value' => '', 'config_group' => 'output', 'config_group_id' => 2, ], [ 'config_id' => 1, 'config_key' => 'ca_certificate', 'config_value' => '', 'config_group' => 'output', 'config_group_id' => 2, ], [ 'config_id' => 1, 'config_key' => 'negotiation', 'config_value' => 'yes', 'config_group' => 'output', 'config_group_id' => 2, ], [ 'config_id' => 1, 'config_key' => 'one_peer_retention_mode', 'config_value' => 'no', 'config_group' => 'output', 'config_group_id' => 2, ], [ 'config_id' => 1, 'config_key' => 'compression', 'config_value' => 'no', 'config_group' => 'output', 'config_group_id' => 2, ], [ 'config_id' => 1, 'config_key' => 'compression_level', 'config_value' => '', 'config_group' => 'output', 'config_group_id' => 2, ], [ 'config_id' => 1, 'config_key' => 'compression_buffer', 'config_value' => '', 'config_group' => 'output', 'config_group_id' => 2, ], [ 'config_id' => 1, 'config_key' => 'type', 'config_value' => 'ipv4', 'config_group' => 'output', 'config_group_id' => 2, ], [ 'config_id' => 1, 'config_key' => 'blockId', 'config_value' => '1_3', 'config_group' => 'output', 'config_group_id' => 2, ], // /////////////////////////////////////////////////////////////////////////////////// // /////////////////////////////////////////////////////////////////////////////////// // /////////////////////////////////////////////////////////////////////////////////// // /////////////////////////////////////////////////////////////////////////////////// // /////////////////////////////////////////////////////////////////////////////////// [ 'config_id' => 2, 'config_key' => 'name', 'config_value' => 'central-rrd-master-input', 'config_group' => 'input', 'config_group_id' => 1, ], [ 'config_id' => 2, 'config_key' => 'port', 'config_value' => '5670', 'config_group' => 'input', 'config_group_id' => 1, ], [ 'config_id' => 2, 'config_key' => 'buffering_timeout', 'config_value' => '0', 'config_group' => 'input', 'config_group_id' => 1, ], [ 'config_id' => 2, 'config_key' => 'host', 'config_value' => '', 'config_group' => 'input', 'config_group_id' => 1, ], [ 'config_id' => 2, 'config_key' => 'retry_interval', 'config_value' => '15', 'config_group' => 'input', 'config_group_id' => 1, ], [ 'config_id' => 2, 'config_key' => 'protocol', 'config_value' => 'bbdo', 'config_group' => 'input', 'config_group_id' => 1, ], [ 'config_id' => 2, 'config_key' => 'tls', 'config_value' => 'auto', 'config_group' => 'input', 'config_group_id' => 1, ], [ 'config_id' => 2, 'config_key' => 'private_key', 'config_value' => '', 'config_group' => 'input', 'config_group_id' => 1, ], [ 'config_id' => 2, 'config_key' => 'public_cert', 'config_value' => '', 'config_group' => 'input', 'config_group_id' => 1, ], [ 'config_id' => 2, 'config_key' => 'ca_certificate', 'config_value' => '', 'config_group' => 'input', 'config_group_id' => 1, ], [ 'config_id' => 2, 'config_key' => 'negotiation', 'config_value' => 'yes', 'config_group' => 'input', 'config_group_id' => 1, ], [ 'config_id' => 2, 'config_key' => 'one_peer_retention_mode', 'config_value' => 'no', 'config_group' => 'input', 'config_group_id' => 1, ], [ 'config_id' => 2, 'config_key' => 'compression', 'config_value' => 'auto', 'config_group' => 'input', 'config_group_id' => 1, ], [ 'config_id' => 2, 'config_key' => 'compression_level', 'config_value' => '', 'config_group' => 'input', 'config_group_id' => 1, ], [ 'config_id' => 2, 'config_key' => 'compression_buffer', 'config_value' => '', 'config_group' => 'input', 'config_group_id' => 1, ], [ 'config_id' => 2, 'config_key' => 'type', 'config_value' => 'ipv4', 'config_group' => 'input', 'config_group_id' => 1, ], [ 'config_id' => 2, 'config_key' => 'blockId', 'config_value' => '2_3', 'config_group' => 'input', 'config_group_id' => 1, ], [ 'config_id' => 2, 'config_key' => 'name', 'config_value' => '@centreonbroker_log@/central-rrd-master.log', 'config_group' => 'logger', 'config_group_id' => 1, ], [ 'config_id' => 2, 'config_key' => 'config', 'config_value' => 'yes', 'config_group' => 'logger', 'config_group_id' => 1, ], [ 'config_id' => 2, 'config_key' => 'debug', 'config_value' => 'no', 'config_group' => 'logger', 'config_group_id' => 1, ], [ 'config_id' => 2, 'config_key' => 'error', 'config_value' => 'yes', 'config_group' => 'logger', 'config_group_id' => 1, ], [ 'config_id' => 2, 'config_key' => 'info', 'config_value' => 'no', 'config_group' => 'logger', 'config_group_id' => 1, ], [ 'config_id' => 2, 'config_key' => 'level', 'config_value' => 'low', 'config_group' => 'logger', 'config_group_id' => 1, ], [ 'config_id' => 2, 'config_key' => 'max_size', 'config_value' => '', 'config_group' => 'logger', 'config_group_id' => 1, ], [ 'config_id' => 2, 'config_key' => 'type', 'config_value' => 'file', 'config_group' => 'logger', 'config_group_id' => 1, ], [ 'config_id' => 2, 'config_key' => 'blockId', 'config_value' => '3_17', 'config_group' => 'logger', 'config_group_id' => 1, ], [ 'config_id' => 2, 'config_key' => 'name', 'config_value' => 'central-rrd-master-output', 'config_group' => 'output', 'config_group_id' => 1, ], [ 'config_id' => 2, 'config_key' => 'metrics_path', 'config_value' => '@centreon_varlib@/metrics', 'config_group' => 'output', 'config_group_id' => 1, ], [ 'config_id' => 2, 'config_key' => 'status_path', 'config_value' => '@centreon_varlib@/status', 'config_group' => 'output', 'config_group_id' => 1, ], [ 'config_id' => 2, 'config_key' => 'retry_interval', 'config_value' => '15', 'config_group' => 'output', 'config_group_id' => 1, ], [ 'config_id' => 2, 'config_key' => 'buffering_timeout', 'config_value' => '0', 'config_group' => 'output', 'config_group_id' => 1, ], [ 'config_id' => 2, 'config_key' => 'path', 'config_value' => '', 'config_group' => 'output', 'config_group_id' => 1, ], [ 'config_id' => 2, 'config_key' => 'port', 'config_value' => '', 'config_group' => 'output', 'config_group_id' => 1, ], [ 'config_id' => 2, 'config_key' => 'write_metrics', 'config_value' => 'yes', 'config_group' => 'output', 'config_group_id' => 1, ], [ 'config_id' => 2, 'config_key' => 'write_status', 'config_value' => 'yes', 'config_group' => 'output', 'config_group_id' => 1, ], [ 'config_id' => 2, 'config_key' => 'type', 'config_value' => 'rrd', 'config_group' => 'output', 'config_group_id' => 1, ], [ 'config_id' => 2, 'config_key' => 'blockId', 'config_value' => '1_13', 'config_group' => 'output', 'config_group_id' => 1, ], // /////////////////////////////////////////////////////////////////////////////////// // /////////////////////////////////////////////////////////////////////////////////// // /////////////////////////////////////////////////////////////////////////////////// // /////////////////////////////////////////////////////////////////////////////////// // /////////////////////////////////////////////////////////////////////////////////// [ 'config_id' => 3, 'config_key' => 'name', 'config_value' => '@centreonbroker_log@/central-module-master.log', 'config_group' => 'logger', 'config_group_id' => 1, ], [ 'config_id' => 3, 'config_key' => 'config', 'config_value' => 'yes', 'config_group' => 'logger', 'config_group_id' => 1, ], [ 'config_id' => 3, 'config_key' => 'debug', 'config_value' => 'no', 'config_group' => 'logger', 'config_group_id' => 1, ], [ 'config_id' => 3, 'config_key' => 'error', 'config_value' => 'yes', 'config_group' => 'logger', 'config_group_id' => 1, ], [ 'config_id' => 3, 'config_key' => 'info', 'config_value' => 'no', 'config_group' => 'logger', 'config_group_id' => 1, ], [ 'config_id' => 3, 'config_key' => 'level', 'config_value' => 'low', 'config_group' => 'logger', 'config_group_id' => 1, ], [ 'config_id' => 3, 'config_key' => 'max_size', 'config_value' => '', 'config_group' => 'logger', 'config_group_id' => 1, ], [ 'config_id' => 3, 'config_key' => 'type', 'config_value' => 'file', 'config_group' => 'logger', 'config_group_id' => 1, ], [ 'config_id' => 3, 'config_key' => 'blockId', 'config_value' => '3_17', 'config_group' => 'logger', 'config_group_id' => 1, ], [ 'config_id' => 3, 'config_key' => 'name', 'config_value' => 'central-module-master-output', 'config_group' => 'output', 'config_group_id' => 1, ], [ 'config_id' => 3, 'config_key' => 'port', 'config_value' => '5669', 'config_group' => 'output', 'config_group_id' => 1, ], [ 'config_id' => 3, 'config_key' => 'host', 'config_value' => 'localhost', 'config_group' => 'output', 'config_group_id' => 1, ], [ 'config_id' => 3, 'config_key' => 'retry_interval', 'config_value' => '15', 'config_group' => 'output', 'config_group_id' => 1, ], [ 'config_id' => 3, 'config_key' => 'buffering_timeout', 'config_value' => '0', 'config_group' => 'output', 'config_group_id' => 1, ], [ 'config_id' => 3, 'config_key' => 'protocol', 'config_value' => 'bbdo', 'config_group' => 'output', 'config_group_id' => 1, ], [ 'config_id' => 3, 'config_key' => 'tls', 'config_value' => 'no', 'config_group' => 'output', 'config_group_id' => 1, ], [ 'config_id' => 3, 'config_key' => 'private_key', 'config_value' => '', 'config_group' => 'output', 'config_group_id' => 1, ], [ 'config_id' => 3, 'config_key' => 'public_cert', 'config_value' => '', 'config_group' => 'output', 'config_group_id' => 1, ], [ 'config_id' => 3, 'config_key' => 'ca_certificate', 'config_value' => '', 'config_group' => 'output', 'config_group_id' => 1, ], [ 'config_id' => 3, 'config_key' => 'negotiation', 'config_value' => 'yes', 'config_group' => 'output', 'config_group_id' => 1, ], [ 'config_id' => 3, 'config_key' => 'one_peer_retention_mode', 'config_value' => 'no', 'config_group' => 'output', 'config_group_id' => 1, ], [ 'config_id' => 3, 'config_key' => 'compression', 'config_value' => 'no', 'config_group' => 'output', 'config_group_id' => 1, ], [ 'config_id' => 3, 'config_key' => 'compression_level', 'config_value' => '', 'config_group' => 'output', 'config_group_id' => 1, ], [ 'config_id' => 3, 'config_key' => 'compression_buffer', 'config_value' => '', 'config_group' => 'output', 'config_group_id' => 1, ], [ 'config_id' => 3, 'config_key' => 'type', 'config_value' => 'ipv4', 'config_group' => 'output', 'config_group_id' => 1, ], [ 'config_id' => 3, 'config_key' => 'blockId', 'config_value' => '1_3', 'config_group' => 'output', 'config_group_id' => 1, ], ]; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonRemote/Domain/Resources/DefaultConfig/CfgNagios.php
centreon/src/CentreonRemote/Domain/Resources/DefaultConfig/CfgNagios.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 CentreonRemote\Domain\Resources\DefaultConfig; /** * Get broker configuration template. */ class CfgNagios { /** * Get template configuration. * * @todo move it as yml * * @return array<string, int|string|null> the configuration template */ public static function getConfiguration(): array { return [ 'nagios_id' => 1, 'nagios_name' => 'Centreon Engine Central', 'log_file' => '@monitoring_varlog@/centengine.log', 'cfg_dir' => '@monitoring_etc@', 'status_file' => '@monitoring_varlog@/status.dat', 'status_update_interval' => '60', 'enable_notifications' => '1', 'execute_service_checks' => '1', 'accept_passive_service_checks' => '1', 'execute_host_checks' => '1', 'accept_passive_host_checks' => '1', 'enable_event_handlers' => '1', 'check_external_commands' => '1', 'external_command_buffer_slots' => '4096', 'command_check_interval' => '1s', 'command_file' => '@monitoring_var_lib@/rw/centengine.cmd', 'retain_state_information' => '1', 'state_retention_file' => '@monitoring_varlog@/retention.dat', 'retention_update_interval' => 60, 'use_retained_program_state' => '1', 'use_retained_scheduling_info' => '1', 'use_syslog' => '0', 'log_notifications' => '1', 'log_service_retries' => '1', 'log_host_retries' => '1', 'log_event_handlers' => '1', 'log_external_commands' => '1', 'log_passive_checks' => '1', 'global_host_event_handler' => null, 'global_service_event_handler' => null, 'sleep_time' => '0.5', 'service_inter_check_delay_method' => 's', 'host_inter_check_delay_method' => 's', 'service_interleave_factor' => 's', 'max_concurrent_checks' => 0, 'max_service_check_spread' => 15, 'max_host_check_spread' => 15, 'check_result_reaper_frequency' => 5, 'auto_reschedule_checks' => '0', 'auto_rescheduling_interval' => '30', 'auto_rescheduling_window' => '180', 'enable_flap_detection' => '1', 'low_service_flap_threshold' => '25.0', 'high_service_flap_threshold' => '50.0', 'low_host_flap_threshold' => '25.0', 'high_host_flap_threshold' => '50.0', 'soft_state_dependencies' => '0', 'service_check_timeout' => 60, 'host_check_timeout' => 12, 'event_handler_timeout' => 30, 'notification_timeout' => 30, 'check_for_orphaned_services' => '1', 'check_for_orphaned_hosts' => '1', 'check_service_freshness' => '0', 'service_freshness_check_interval' => '0', 'freshness_check_interval' => null, 'check_host_freshness' => '0', 'host_freshness_check_interval' => null, 'date_format' => 'euro', 'illegal_object_name_chars' => '~!$%^&*"|\'<>?,()=', 'illegal_macro_output_chars' => '`~$^&"|\'<>', 'use_regexp_matching' => '0', 'use_true_regexp_matching' => '0', 'admin_email' => 'admin@localhost', 'admin_pager' => 'admin@localhost', 'nagios_comment' => 'Centreon Engine config file for a central instance', 'nagios_activate' => '1', 'event_broker_options' => '-1', 'nagios_server_id' => 1, 'enable_predictive_host_dependency_checks' => '1', 'enable_predictive_service_dependency_checks' => '1', 'host_down_disable_service_checks' => '1', 'cached_host_check_horizon' => 60, 'cached_service_check_horizon' => null, 'enable_environment_macros' => '0', 'additional_freshness_latency' => '15', 'debug_file' => '@monitoring_varlog@/centengine.debug', 'debug_level' => 0, 'debug_level_opt' => '0', 'debug_verbosity' => '1', 'max_debug_file_size' => '1000000000', 'daemon_dumps_core' => '0', 'cfg_file' => 'centengine.cfg', 'logger_version' => 'log_v2_enabled', 'log_pid' => '1', 'broker_module_cfg_file' => '@centreonbroker_etc@/central-module.json', ]; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonRemote/Domain/Resources/DefaultConfig/CfgCentreonBroker.php
centreon/src/CentreonRemote/Domain/Resources/DefaultConfig/CfgCentreonBroker.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 CentreonRemote\Domain\Resources\DefaultConfig; /** * Get broker configuration template. */ class CfgCentreonBroker { /** * Get template configuration. * * @todo move it as yml * * @return array<int, array<string,int|string>> the configuration template */ public static function getConfiguration(): array { return [ [ 'config_id' => 1, 'config_name' => 'central-broker-master', 'config_filename' => 'central-broker.json', 'config_write_timestamp' => '1', 'config_write_thread_id' => '0', 'config_activate' => '1', 'event_queue_max_size' => 100000, 'cache_directory' => '@centreonbroker_varlib@', 'command_file' => '@centreonbroker_varlib@/command.sock', 'daemon' => 1, ], [ 'config_id' => 2, 'config_name' => 'central-rrd-master', 'config_filename' => 'central-rrd.json', 'config_write_timestamp' => '1', 'config_write_thread_id' => '0', 'config_activate' => '1', 'ns_nagios_server' => 1, 'event_queue_max_size' => 100000, 'cache_directory' => '@centreonbroker_varlib@', 'daemon' => 1, ], [ 'config_id' => 3, 'config_name' => 'central-module-master', 'config_filename' => 'central-module.json', 'config_write_timestamp' => '0', 'config_write_thread_id' => '0', 'config_activate' => '1', 'ns_nagios_server' => 1, 'event_queue_max_size' => 100000, 'cache_directory' => '@monitoring_var_lib@', 'daemon' => 0, ], ]; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonRemote/Domain/Resources/DefaultConfig/CfgResource.php
centreon/src/CentreonRemote/Domain/Resources/DefaultConfig/CfgResource.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 CentreonRemote\Domain\Resources\DefaultConfig; /** * Get broker configuration template. */ class CfgResource { /** * Get template configuration. * * @todo move it as yml * * @return array<int, string[]> the configuration template */ public static function getConfiguration(): array { return [ [ 'resource_name' => '$USER1$', 'resource_line' => '@plugin_dir@', 'resource_comment' => 'Nagios Plugins Path', 'resource_activate' => '1', ], [ 'resource_name' => '$CENTREONPLUGINS$', 'resource_line' => '@centreonplugins@', 'resource_comment' => 'Centreon Plugins Path', 'resource_activate' => '1', ], ]; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonRemote/Domain/Resources/DefaultConfig/NagiosServer.php
centreon/src/CentreonRemote/Domain/Resources/DefaultConfig/NagiosServer.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 CentreonRemote\Domain\Resources\DefaultConfig; /** * Get broker configuration template. */ class NagiosServer { /** * Get template configuration. * * @todo move it as yml * * @return array<string, int|string> */ public static function getConfiguration(): array { return [ 'name' => 'Central', 'localhost' => '1', 'is_default' => 1, 'last_restart' => 0, 'ns_ip_address' => '127.0.0.1', 'ns_activate' => '1', 'ns_status' => '0', 'engine_start_command' => 'service centengine start', 'engine_stop_command' => 'service centengine stop', 'engine_restart_command' => 'service centengine restart', 'engine_reload_command' => 'service centengine reload', 'nagios_bin' => '@monitoring_binary@', 'nagiostats_bin' => '@centreon_engine_stats_binary@', 'nagios_perfdata' => '@monitoring_varlog@/service-perfdata', 'centreonbroker_cfg_path' => '@broker_etc@', 'centreonbroker_module_path' => '@centreonbroker_lib@', 'centreonconnector_path' => '@centreon_engine_connectors@', 'ssh_port' => 22, 'gorgone_communication_type' => '1', 'gorgone_port' => 5556, 'init_script_centreontrapd' => 'centreontrapd', 'snmp_trapd_path_conf' => '/etc/snmp/centreon_traps/', ]; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonRemote/Domain/Service/TaskService.php
centreon/src/CentreonRemote/Domain/Service/TaskService.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 CentreonRemote\Domain\Service; use Centreon\Domain\Entity\Command; use Centreon\Domain\Entity\Task; use Centreon\Domain\Repository\TaskRepository; use Centreon\Infrastructure\Service\CentcoreCommandService; use Centreon\Infrastructure\Service\CentreonDBManagerService; use Centreon\Infrastructure\Service\Exception\NotFoundException; class TaskService { /** @var CentreonDBManagerService */ private $dbManager; /** @var CentcoreCommandService */ private $cmdService; /** @var \CentreonRestHttp */ private $centreonRestHttp; /** * TaskService constructor. * * @param CentreonDBManagerService $dbManager * @param CentcoreCommandService $cmdService */ public function __construct( CentreonDBManagerService $dbManager, CentcoreCommandService $cmdService, ) { $this->dbManager = $dbManager; $this->cmdService = $cmdService; } /** * @return CentcoreCommandService */ public function getCmdService(): CentcoreCommandService { return $this->cmdService; } /** * @param CentcoreCommandService $cmdService */ public function setCmdService(CentcoreCommandService $cmdService): void { $this->cmdService = $cmdService; } /** * @return CentreonDBManagerService */ public function getDbManager(): CentreonDBManagerService { return $this->dbManager; } /** * @param \CentreonRestHttp $centreonRestHttp */ public function setCentreonRestHttp(\CentreonRestHttp $centreonRestHttp): void { $this->centreonRestHttp = $centreonRestHttp; } /** * @return \CentreonRestHttp */ public function getCentreonRestHttp(): \CentreonRestHttp { return $this->centreonRestHttp; } /** * Adds a new task. * * @param string $type * @param array<string, array<string,mixed>> $params * @param int $parentId * * @return int|bool */ public function addTask(string $type, array $params, ?int $parentId = null): int|bool { $newTask = new Task(); $newTask->setStatus(Task::STATE_PENDING); $newTask->setParams(serialize($params)); $newTask->setParentId($parentId); switch ($type) { case Task::TYPE_EXPORT: case Task::TYPE_IMPORT: $newTask->setType($type); $result = $this->getDbManager()->getAdapter('configuration_db')->insert('task', $newTask->toArray()); $cmd = new Command(); $cmd->setCommandLine(Command::COMMAND_START_IMPEX_WORKER); $cmdWritten = $this->getCmdService()->sendCommand($cmd); break; default: return false; } return ($result && $cmdWritten) ? $result : false; } /** * Get Existing Task status. * * @param string $taskId */ public function getStatus(string $taskId) { $task = $this->getRepository()->findOneById($taskId); return $task ? $task->getStatus() : null; } /** * Get existing task status by parent id. * * @param int $parentId the parent task id on remote server */ public function getStatusByParent(int $parentId) { $task = $this->getRepository() ->findOneByParentId($parentId); return $task ? $task->getStatus() : null; } /** * Update task status. * * @param string $taskId * @param string $status * * @throws NotFoundException * @throws \Exception * * @return mixed */ public function updateStatus(string $taskId, string $status) { $task = $this->getRepository() ->findOneById($taskId); if (! in_array($status, $task->getStatuses())) { return false; } return $this->getRepository() ->updateStatus($status, $taskId); } /** * @return TaskRepository */ private function getRepository() { /** @var TaskRepository */ return $this ->getDbManager() ->getAdapter('configuration_db') ->getRepository(TaskRepository::class); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonRemote/Domain/Service/NotifyMasterService.php
centreon/src/CentreonRemote/Domain/Service/NotifyMasterService.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 CentreonRemote\Domain\Service; use Centreon\Domain\Repository\InformationsRepository; use Centreon\Infrastructure\Service\CentreonDBManagerService; use Curl\Curl; class NotifyMasterService { /** * fail constants. */ public const CANT_RESOLVE_HOST = 'Could not resolve the host'; public const CANT_CONNECT = 'Could not connect'; public const TIMEOUT = 'Timeout'; public const UNKNOWN_ERROR = 'Unknown Error'; public const NO_APP_KEY = 'No Application Key found'; /** * statuses. */ public const SUCCESS = 'success'; public const FAIL = 'fail'; /** @var CentreonDBManagerService */ private $dbManager; /** @var Curl */ private $curl; /** * NotifyMasterService constructor. * * @param CentreonDBManagerService $dbManager */ public function __construct(CentreonDBManagerService $dbManager) { $this->dbManager = $dbManager; } /** * @param Curl $curl */ public function setCurl(Curl $curl): void { $this->curl = $curl; } /** * @return Curl */ public function getCurl(): Curl { return $this->curl; } /** * Ping the master IP requesting to be slave for it. * * @param string $ip The IP address of the master * @param bool $noCheckCertificate To do not check SLL CA on master * @param bool $noProxy * @param (string|null|false)[] $data The information for the master how to contact the remote * * @throws \ErrorException * * @return string[] */ public function pingMaster($ip, $data, $noCheckCertificate = false, $noProxy = false) { $url = "{$ip}/centreon/api/external.php?object=centreon_remote_server&action=addToWaitList"; $repository = $this->dbManager->getRepository(InformationsRepository::class); $version = $repository->getOneByKey('version'); try { $curlData = [ 'version' => $version->getValue(), 'http_method' => $data['remoteHttpMethod'] ?? 'http', 'http_port' => $data['remoteHttpPort'] ?? '', 'no_check_certificate' => $data['remoteNoCheckCertificate'] ?? 0, ]; if ($noCheckCertificate) { $this->getCurl()->setOpt(CURLOPT_SSL_VERIFYPEER, false); } if ($noProxy) { $this->getCurl()->setOpt(CURLOPT_PROXY, false); } $this->getCurl()->post($url, $curlData); if ($this->getCurl()->error) { switch ($this->getCurl()->error_code) { case 6: $details = self::CANT_RESOLVE_HOST; break; case 7: $details = self::CANT_CONNECT; break; case 28: $details = self::TIMEOUT; break; default: $details = self::UNKNOWN_ERROR; break; } return [ 'status' => 'fail', 'details' => $details, ]; } } catch (\ErrorException $e) { return [ 'status' => self::FAIL, 'details' => self::UNKNOWN_ERROR, ]; } return ['status' => self::SUCCESS]; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonRemote/Domain/Service/InformationsService.php
centreon/src/CentreonRemote/Domain/Service/InformationsService.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 CentreonRemote\Domain\Service; use Centreon\Domain\Repository\InformationsRepository; use Pimple\Container; class InformationsService { /** @var Container */ private $di; /** * NotifyMasterService constructor. * * @param Container $di */ public function __construct(Container $di) { $this->di = $di; } /** * Get status for centreon instance (is remote or is not remote). * * @return bool */ public function serverIsRemote(): bool { $repository = $this->getDi()[\Centreon\ServiceProvider::CENTREON_DB_MANAGER] ->getRepository(InformationsRepository::class); $isRemote = $repository->getOneByKey('isRemote'); if (! $isRemote) { return false; } return $isRemote->getValue() == 'yes'; } /** * Get status for centreon instance (is master or is not master). * * @return bool */ public function serverIsMaster(): bool { return ! $this->serverIsRemote(); } /** * Get status for centreon instance if it is a central and has connected remotes to it. * * @return bool */ public function serverIsCentral(): bool { $repository = $this->getDi()[\Centreon\ServiceProvider::CENTREON_DB_MANAGER] ->getRepository(InformationsRepository::class); $isCentral = $repository->getOneByKey('isCentral'); if (! $isCentral) { return false; } return $isCentral->getValue() == 'yes'; } private function getDi(): Container { return $this->di; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonRemote/Domain/Service/PollerDefaultsOverwriteService.php
centreon/src/CentreonRemote/Domain/Service/PollerDefaultsOverwriteService.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 CentreonRemote\Domain\Service; use CentreonRemote\Domain\Resources\DefaultConfig\CfgCentreonBrokerInfo; use CentreonRemote\Domain\Resources\DefaultConfig\CfgNagiosBrokerModule; class PollerDefaultsOverwriteService { /** @var int|null */ private $pollerID = null; /** @var int[] */ private $brokerConfigIDs = []; /** @var int[] */ private $nagiosConfigIDs = []; /** * @param int|null $pollerID */ public function setPollerID($pollerID): void { $this->pollerID = $pollerID; } /** * Get poller information. * * @param array<string|int, array<string,int>> $data the poller data * * @return array<string|int, array<string,int>> the complete poller data */ public function getNagiosServer(array $data): array { return $this->findPollerAndSetResourceData( $data, 'id', \CentreonRemote\Domain\Resources\DefaultConfig\NagiosServer::class ); } /** * Get engine information. * * @param array<string|int, array<string,int>> $data the engine data * * @return array<string|int, array<string,int>> the complete engine data */ public function getCfgNagios(array $data): array { $configsOfRemote = array_filter($data, function ($pollerData) { return $pollerData['nagios_server_id'] == $this->pollerID; }); $this->nagiosConfigIDs = array_column($configsOfRemote, 'nagios_id'); return $this->findPollerAndSetResourceData( $data, 'nagios_server_id', \CentreonRemote\Domain\Resources\DefaultConfig\CfgNagios::class ); } /** * Get engine broker module information. * * @param array<string|int, array<string,int>> $data the engine broker module data * * @return array<string|int, array<string,int>> the complete engine broker module data */ public function getCfgNagiosBroker(array $data): array { // Remove nagios config info which is related to the broker module of the remote poller $data = array_filter($data, function ($pollerData) { return ! in_array($pollerData['cfg_nagios_id'], $this->nagiosConfigIDs); }); $defaultData = CfgNagiosBrokerModule::getConfiguration(); return array_merge($defaultData, $data); } /** * Get broker information. * * @param array<string|int, array<string,int>> $data the broker data * * @return array<string|int, array<string,int>> the complete broker data */ public function getCfgCentreonBroker(array $data): array { $configsOfRemote = array_filter($data, function ($pollerData) { return $pollerData['ns_nagios_server'] == $this->pollerID; }); $this->brokerConfigIDs = array_column($configsOfRemote, 'config_id'); return $this->findPollerAndSetResourceData( $data, 'ns_nagios_server', \CentreonRemote\Domain\Resources\DefaultConfig\CfgCentreonBroker::class ); } /** * Get broker detailed information. * * @param array<string|int, array<string,int>> $data the broker detailed data * * @return array<string|int, array<string,int>> the complete broker detailed data */ public function getCfgCentreonBrokerInfo(array $data): array { // Remove broker config info which is related to the broker module of the remote poller $data = array_filter($data, function ($pollerData) { return ! in_array($pollerData['config_id'], $this->brokerConfigIDs); }); $defaultData = CfgCentreonBrokerInfo::getConfiguration(); return array_merge($defaultData, $data); } /** * Get global macro information. * * @param array<string|int, array<string,int>> $data the global macro data * * @return array<string|int, array<string, int>> the complete global macro data */ public function getCfgResource(array $data): array { // prepare _instance_id for method findPollerAndSetResourceData foreach ($data as $key => $val) { $instanceIds = explode(',', $val['_instance_id']); $data[$key]['_instance_id'] = in_array($this->pollerID, $instanceIds) ? $this->pollerID : ''; } return $this->findPollerAndSetResourceData( $data, '_instance_id', \CentreonRemote\Domain\Resources\DefaultConfig\CfgResource::class ); } /** * @param array<string|int, array<string,int>> $data - the table data for all pollers * @param string $columnName - the name of the column which is FK to the poller * @param string $resourceName - the name of the table for which the data is * * @return array<string|int, array<string,int>> */ private function findPollerAndSetResourceData(array $data, $columnName, $resourceName): array { // Remove remote poller resources in the array by the column name and pollerID $data = array_filter($data, function ($pollerData) use ($columnName) { return $pollerData[$columnName] != $this->pollerID; }); // Get default data for the specified resource $defaultData = $resourceName::getConfiguration(); // Make the data multidimensional array if its not, so it can be merged $dataToMerge = is_array($defaultData[key($defaultData)]) ? $defaultData : [$defaultData]; // Set the correct pollerID in the column name which is FK to the poller foreach ($dataToMerge as $key => $arrayData) { $dataToMerge[$key][$columnName] = $this->pollerID; } return array_merge($data, $dataToMerge); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonRemote/Domain/Service/ConfigurationWizard/RemoteConnectionConfigurationService.php
centreon/src/CentreonRemote/Domain/Service/ConfigurationWizard/RemoteConnectionConfigurationService.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 CentreonRemote\Domain\Service\ConfigurationWizard; use CentreonRemote\Domain\Resources\DefaultConfig\CfgCentreonBrokerLog; use CentreonRemote\Domain\Resources\RemoteConfig\CfgCentreonBroker; use CentreonRemote\Domain\Resources\RemoteConfig\CfgCentreonBrokerInfo; class RemoteConnectionConfigurationService extends ServerConnectionConfigurationService { /** * @inheritDoc */ protected function isRemote(): bool { return true; } /** * @inheritDoc */ protected function insertConfigCentreonBroker(int $serverID): void { $brokerConfiguration = CfgCentreonBroker::getConfiguration($serverID, $this->name); $brokerInfoConfiguration = CfgCentreonBrokerInfo::getConfiguration( $this->name, $this->dbUser, $this->dbPassword ); $this->brokerID = (int) $this->insertWithAdapter('cfg_centreonbroker', $brokerConfiguration['broker']); $moduleID = (int) $this->insertWithAdapter('cfg_centreonbroker', $brokerConfiguration['module']); $rrdID = (int) $this->insertWithAdapter('cfg_centreonbroker', $brokerConfiguration['rrd']); $this->insertBrokerLog( CfgCentreonBrokerLog::getConfiguration( $this->getDbAdapter()->getCentreonDBInstance(), $this->brokerID ) ); $this->insertBrokerLog( CfgCentreonBrokerLog::getConfiguration( $this->getDbAdapter()->getCentreonDBInstance(), $moduleID ) ); $this->insertBrokerLog( CfgCentreonBrokerLog::getConfiguration( $this->getDbAdapter()->getCentreonDBInstance(), $rrdID ) ); $brokerInfoConfiguration['central-broker'] = $this->saveCredentialInVault($brokerInfoConfiguration['central-broker']); $this->insertBrokerInfo($this->brokerID, $brokerInfoConfiguration['central-broker']); $brokerInfoConfiguration['central-module'] = $this->saveCredentialInVault($brokerInfoConfiguration['central-module']); $this->insertBrokerInfo($moduleID, $brokerInfoConfiguration['central-module']); $brokerInfoConfiguration['central-rrd'] = $this->saveCredentialInVault($brokerInfoConfiguration['central-rrd']); $this->insertBrokerInfo($rrdID, $brokerInfoConfiguration['central-rrd']); } /** * insert broker information. * * @param int $configurationId * @param array<string,array<string,mixed>> $brokerInfo */ private function insertBrokerInfo(int $configurationId, array $brokerInfo): void { foreach ($brokerInfo as $brokerConfig => $brokerData) { foreach ($brokerData as $row) { $row['config_id'] = $configurationId; if ($brokerConfig === 'output_forward' && $row['config_key'] === 'host') { $row['config_value'] = $this->centralIp; } $this->insertWithAdapter('cfg_centreonbroker_info', $row); } } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonRemote/Domain/Service/ConfigurationWizard/PollerConnectionConfigurationService.php
centreon/src/CentreonRemote/Domain/Service/ConfigurationWizard/PollerConnectionConfigurationService.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 CentreonRemote\Domain\Service\ConfigurationWizard; use Centreon\Domain\Repository\Interfaces\CfgCentreonBrokerInterface; use Centreon\Domain\Service\BrokerConfigurationService; use CentreonRemote\Domain\Resources\DefaultConfig\CfgCentreonBrokerLog; use CentreonRemote\Domain\Resources\RemoteConfig\CfgCentreonBroker; use CentreonRemote\Domain\Resources\RemoteConfig\CfgCentreonBrokerInfo; use CentreonRemote\Domain\Resources\RemoteConfig\InputFlowOnePeerRetention; class PollerConnectionConfigurationService extends ServerConnectionConfigurationService { /** @var CfgCentreonBrokerInterface */ private $brokerRepository; /** @var BrokerConfigurationService */ private $brokerConfigurationService; /** * Set broker repository to manage general broker configuration. * * @param CfgCentreonBrokerInterface $cfgCentreonBroker the centreon broker configuration repository */ public function setBrokerRepository(CfgCentreonBrokerInterface $cfgCentreonBroker): void { $this->brokerRepository = $cfgCentreonBroker; } /** * Set broker configuration service to broker info configuration. * * @param BrokerConfigurationService $brokerConfigurationService the service to manage broker confiration */ public function setBrokerConfigurationService(BrokerConfigurationService $brokerConfigurationService): void { $this->brokerConfigurationService = $brokerConfigurationService; } /** * Insert centreon broker configuration to a given poller * this configuration i only for broker module (not cbd). * * @param int $serverID the poller id */ protected function insertConfigCentreonBroker(int $serverID): void { $configCentreonBrokerData = CfgCentreonBroker::getConfiguration($serverID, $this->name); $configCentreonBrokerInfoData = CfgCentreonBrokerInfo::getConfiguration($this->name, null, null); $outputHost = $this->centralIp; $onePeerRetentionMode = 'no'; $moduleID = $this->insertWithAdapter('cfg_centreonbroker', $configCentreonBrokerData['module']); $this->insertBrokerLog( CfgCentreonBrokerLog::getConfiguration( $this->getDbAdapter()->getCentreonDBInstance(), $moduleID ) ); // if one peer retention mode is enabled, // we need to add an input in central broker configuration if ($this->onePeerRetention) { // update poller broker module parameters for one peer retention $outputHost = ''; $onePeerRetentionMode = 'yes'; if ($this->isLinkedToCentralServer) { // get central broker config id // we need it to add an input to pull broker data from distant poller $centralBrokerConfigId = $this->brokerRepository->findCentralBrokerConfigId(); // add broker input configuration on central to get data from poller $brokerInfosEntities = InputFlowOnePeerRetention::getConfiguration($this->name, $this->serverIp); $this->brokerConfigurationService->addFlow($centralBrokerConfigId, 'input', $brokerInfosEntities); } } /** * Add poller module output flow to send data to the central server. * Do not handle vault credential storage, has there is no crednetials inserted for now. */ foreach ($configCentreonBrokerInfoData['central-module']['output'] as $row) { if ($row['config_key'] == 'host') { $row['config_value'] = $outputHost; } elseif ($row['config_key'] == 'one_peer_retention_mode') { $row['config_value'] = $onePeerRetentionMode; } $row['config_id'] = $moduleID; $this->insertWithAdapter('cfg_centreonbroker_info', $row); } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonRemote/Domain/Service/ConfigurationWizard/PollerConfigurationRequestBridge.php
centreon/src/CentreonRemote/Domain/Service/ConfigurationWizard/PollerConfigurationRequestBridge.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 CentreonRemote\Domain\Service\ConfigurationWizard; use Centreon\Infrastructure\CentreonLegacyDB\CentreonDBAdapter; use CentreonRemote\Domain\Value\PollerServer; use CentreonRemote\Domain\Value\ServerWizardIdentity; use Pimple\Container; class PollerConfigurationRequestBridge { /** @var CentreonDBAdapter */ private $dbAdapter; /** @var PollerServer[] */ private $pollers = []; /** @var PollerServer[] */ private $additionalRemotes = []; public function __construct(Container $di) { $this->dbAdapter = $di[\Centreon\ServiceProvider::CENTREON_DB_MANAGER]->getAdapter('configuration_db'); } public function hasPollersForUpdating(): bool { return ! empty($this->pollers); } /** * @return PollerServer[] */ public function getLinkedPollersSelectedForUpdate(): array { return $this->pollers; } /** * @return PollerServer[] */ public function getAdditionalRemoteServers(): array { return $this->additionalRemotes; } /** * Set linked pollers regarding wizard type (poller/remote server). */ public function collectDataFromRequest(): void { $isRemoteServerWizard = (new ServerWizardIdentity())->requestConfigurationIsRemote(); if ($isRemoteServerWizard) { // configure remote server // pollers linked to the remote server $linkedPollers = isset($_POST['linked_pollers']) ? (array) $_POST['linked_pollers'] : []; } else { // configure poller // if the poller is linked to a remote server $linkedPollers = isset($_POST['linked_remote_master']) ? [$_POST['linked_remote_master']] : []; } $this->pollers = $this->getPollersToLink($linkedPollers); // set and instantiate linked pollers } /** * Set linked Additonal Remote Servers regarding wizard type poller (poller/remote server). */ public function collectDataFromAdditionalRemoteServers(): void { $isRemoteServerWizard = (new ServerWizardIdentity())->requestConfigurationIsRemote(); $linkedRemotes = []; if (! $isRemoteServerWizard && isset($_POST['linked_remote_slaves'])) { $linkedRemotes = $_POST['linked_remote_slaves']; } $this->additionalRemotes = $this->getPollersToLink($linkedRemotes); // set and instantiate linked pollers } /** * Get poller information from poller id. * * @param int $pollerId the poller id to get * * @return null|PollerServer */ public function getPollerFromId(int $pollerId): ?PollerServer { $query = 'SELECT id, name, ns_ip_address as ip FROM nagios_server WHERE id = ?'; $this->dbAdapter->query($query, [$pollerId]); $results = $this->dbAdapter->results(); if (count($results)) { $remoteData = reset($results); $remoteServer = new PollerServer(); $remoteServer->setId($remoteData->id); $remoteServer->setName($remoteData->name); $remoteServer->setIp($remoteData->ip); return $remoteServer; } return null; } /** * Get pollers to link a set of poller information. * * @param array<mixed> $pollers the pollers to get list of poller objects * * @return PollerServer[] the pollers to link */ private function getPollersToLink(array $pollers) { if ($pollers === []) { return []; } $pollerIDs = []; if (is_array(reset($pollers))) { foreach ($pollers as $poller) { if (isset($poller['value'])) { $pollerIDs[] = $poller['value']; } } } else { $pollerIDs = $pollers; } $idBindString = str_repeat('?,', count($pollerIDs)); $idBindString = rtrim($idBindString, ','); $queryPollers = "SELECT id, name, ns_ip_address as ip FROM nagios_server WHERE id IN ({$idBindString})"; $this->dbAdapter->query($queryPollers, $pollerIDs); $results = $this->dbAdapter->results(); $data = []; foreach ($results as $result) { $poller = new PollerServer(); $poller->setId($result->id); $poller->setName($result->name); $poller->setIp($result->ip); $data[] = $poller; } return $data; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonRemote/Domain/Service/ConfigurationWizard/LinkedPollerConfigurationService.php
centreon/src/CentreonRemote/Domain/Service/ConfigurationWizard/LinkedPollerConfigurationService.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 CentreonRemote\Domain\Service\ConfigurationWizard; require_once __DIR__ . '/../../../../../www/class/centreonContactgroup.class.php'; require_once __DIR__ . '/../../../../../www/class/config-generate/generate.class.php'; require_once __DIR__ . '/../../../../../www/class/centreonBroker.class.php'; require_once __DIR__ . '/../../../../../www/class/centreonConfigCentreonBroker.php'; require_once __DIR__ . '/../../../../../www/include/configuration/configGenerate/DB-Func.php'; use Centreon\Domain\Entity\Task; use Centreon\Domain\Repository\Interfaces\CfgCentreonBrokerInterface; use Centreon\Domain\Service\BrokerConfigurationService; use Centreon\Infrastructure\CentreonLegacyDB\CentreonDBAdapter; use CentreonRemote\Domain\Resources\RemoteConfig\BrokerInfo\OutputForwardMaster; use CentreonRemote\Domain\Resources\RemoteConfig\InputFlowOnePeerRetention; use CentreonRemote\Domain\Service\TaskService; use CentreonRemote\Domain\Value\PollerServer; use CentreonRemote\Infrastructure\Service\PollerInteractionService; class LinkedPollerConfigurationService { /** @var bool */ protected $onePeerRetention = false; /** @var \CentreonDB */ private $db; /** @var CfgCentreonBrokerInterface */ private $brokerRepository; /** @var BrokerConfigurationService */ private $brokerConfigurationService; /** @var TaskService */ private $taskService; /** @var PollerInteractionService */ private $pollerInteractionService; public function __construct(CentreonDBAdapter $dbAdapter) { $this->db = $dbAdapter->getCentreonDBInstance(); } /** * Set broker repository to manage general broker configuration. * * @param CfgCentreonBrokerInterface $cfgCentreonBroker the centreon broker configuration repository */ public function setBrokerRepository(CfgCentreonBrokerInterface $cfgCentreonBroker): void { $this->brokerRepository = $cfgCentreonBroker; } /** * Set broker configuration service to broker info configuration. * * @param BrokerConfigurationService $brokerConfigurationService the service to manage broker confiration */ public function setBrokerConfigurationService(BrokerConfigurationService $brokerConfigurationService): void { $this->brokerConfigurationService = $brokerConfigurationService; } /** * Set poller interaction service. * * @param PollerInteractionService $pollerInteractionService the poller interaction service */ public function setPollerInteractionService(PollerInteractionService $pollerInteractionService): void { $this->pollerInteractionService = $pollerInteractionService; } /** * Set task service to add export task. * * @param TaskService $taskService the task service */ public function setTaskService(TaskService $taskService): void { $this->taskService = $taskService; } /** * Set one peer retention mode. * * @param bool $onePeerRetention if one peer retention mode is enabled */ public function setOnePeerRetention(bool $onePeerRetention): void { $this->onePeerRetention = $onePeerRetention; } /** * Link a set of pollers to a parent poller by creating broker input/output. * * @param PollerServer[] $pollers * @param PollerServer $remote */ public function linkPollersToParentPoller(array $pollers, PollerServer $remote): void { $pollerIds = array_map(function ($poller) { return $poller->getId(); }, $pollers); // Before linking the pollers to the new remote, we have to tell the old remote they are no longer linked to it $this->triggerExportForOldRemotes($pollerIds); foreach ($pollers as $poller) { // If one peer retention is enabled, add input on remote server to get data from poller if ($this->onePeerRetention) { $this->setBrokerInputOfRemoteServer($remote->getId(), $poller); } else { // If one peer retention is disabled, we need to set the host output of the poller $this->setBrokerOutputOfPoller($poller->getId(), $remote); } $this->setPollerRelationToRemote($poller->getId(), $remote); } // Generate configuration for pollers and restart them $this->pollerInteractionService->generateAndExport($pollerIds); } /** * Link a poller to additional Remote Servers. * * @param PollerServer $poller * @param PollerServer[] $remotes */ public function linkPollerToAdditionalRemoteServers(PollerServer $poller, array $remotes): void { $pollerIds = array_map(function ($poller) { return $poller->getId(); }, $remotes); foreach ($remotes as $remote) { // If one peer retention is enabled, add input on remote server to get data from poller if ($this->onePeerRetention) { $this->setBrokerInputOfRemoteServer($remote->getId(), $poller); } else { // If one peer retention is disabled, we need to set the host output of the poller $this->setBrokerOutputOfPoller($poller->getId(), $remote, true); } } $this->insertAddtitionnalRemoteServersRelations($poller, $remotes); // Generate configuration for poller and restart it $this->pollerInteractionService->generateAndExport($pollerIds); } /** * Add broker input configuration on remote server to get data from poller. * * @param int $remoteId * @param PollerServer $poller */ private function setBrokerInputOfRemoteServer($remoteId, PollerServer $poller): void { // get broker config id of linked remote server (cbd broker) $remoteBrokerConfigId = $this->brokerRepository->findBrokerConfigIdByPollerId($remoteId); // get template function to generate input flow in remote server broker configuration $brokerInfosEntities = InputFlowOnePeerRetention::getConfiguration($poller->getName(), $poller->getIp()); $this->brokerConfigurationService->addFlow($remoteBrokerConfigId, 'input', $brokerInfosEntities); } /** * Add relation between poller and Remote Servers. * * @param PollerServer $poller * @param PollerServer[] $remotes */ private function insertAddtitionnalRemoteServersRelations(PollerServer $poller, array $remotes): void { $query = 'INSERT INTO `rs_poller_relation` VALUES (:remoteId, :pollerId)'; $this->db->beginTransaction(); $statement = $this->db->prepare($query); try { $pollerId = $poller->getId(); foreach ($remotes as $remote) { $remoteId = $remote->getId(); $statement->bindParam(':remoteId', $remoteId, \PDO::PARAM_INT); $statement->bindParam(':pollerId', $pollerId, \PDO::PARAM_INT); $statement->execute(); } $this->db->commit(); } catch (\PDOException $Exception) { $this->db->rollBack(); } } /** * Update host field of broker output on poller to link it the the remote server. * * @param int $pollerId * @param PollerServer $remote * @param bool $additional */ private function setBrokerOutputOfPoller($pollerId, PollerServer $remote, $additional = false): void { if ($additional) { // insert new broker output relation $statement = $this->db->prepare('SELECT `config_id` FROM `cfg_centreonbroker` WHERE `ns_nagios_server` = :id AND `daemon` = 0'); $statement->bindParam(':id', $pollerId, \PDO::PARAM_INT); $statement->execute(); $configId = $statement->fetchColumn(); $statement = $this->db->prepare('SELECT MAX(`config_group_id`) AS config_group_id FROM `cfg_centreonbroker_info` WHERE `config_id` = :id'); $statement->bindParam(':id', $configId, \PDO::PARAM_INT); $statement->execute(); $configGRoupId = $statement->fetchColumn() + 1; $defaultBrokerOutput = (new OutputForwardMaster())->getConfiguration(); $defaultBrokerOutput[0]['config_value'] = 'forward-to-' . str_replace(' ', '-', $remote->getName()); $this->db->beginTransaction(); $statement = $this->db->prepare('INSERT INTO `cfg_centreonbroker_info` ( config_id, config_key, config_value, config_group, config_group_id, grp_level ) VALUES ( :config_id, :config_key, :config_value, :config_group, :config_group_id, :grp_level )'); try { foreach ($defaultBrokerOutput as $item) { $statement->bindParam(':config_id', $configId, \PDO::PARAM_INT); $statement->bindParam(':config_key', $item['config_key'], \PDO::PARAM_STR); if ($item['config_key'] == 'host') { $item['config_value'] = $remote->getIp(); } $statement->bindParam(':config_value', $item['config_value'], \PDO::PARAM_STR); $statement->bindParam(':config_group', $item['config_group'], \PDO::PARAM_STR); $statement->bindParam(':config_group_id', $configGRoupId, \PDO::PARAM_INT); $statement->bindParam(':grp_level', $item['grp_level'], \PDO::PARAM_INT); $statement->execute(); } $this->db->commit(); } catch (\PDOException $Exception) { $this->db->rollBack(); } } else { // update host field of poller module output to link it the remote server // find broker config id of poller module $statement = $this->db->prepare('SELECT `config_id` FROM `cfg_centreonbroker` WHERE `ns_nagios_server` = :id AND `daemon` = 0'); $statement->bindParam(':id', $pollerId, \PDO::PARAM_INT); $statement->execute(); $configId = $statement->fetchColumn(); // update output ip address to master remote server $statement = $this->db->prepare("UPDATE `cfg_centreonbroker_info` SET `config_value` = :config_value WHERE `config_id` = :config_id AND `config_key` = 'host' AND `config_group` = 'output'"); $statement->bindValue(':config_value', $remote->getIp(), \PDO::PARAM_STR); $statement->bindValue(':config_id', $configId, \PDO::PARAM_INT); $statement->execute(); // update output name to master remote server $statement = $this->db->prepare("UPDATE `cfg_centreonbroker_info` SET `config_value` = :config_value WHERE `config_id` = :config_id AND `config_key` = 'name' AND `config_group` = 'output'"); $statement->bindValue( ':config_value', 'forward-to-' . str_replace(' ', '-', $remote->getName()), \PDO::PARAM_STR ); $statement->bindValue(':config_id', $configId, \PDO::PARAM_INT); $statement->execute(); } } /** * Link poller with remote server in database. * * @param int $pollerId * @param PollerServer $remote */ private function setPollerRelationToRemote($pollerId, PollerServer $remote): void { $query = 'UPDATE `nagios_server` ' . 'SET `remote_id` = :remote_id ' . 'WHERE `id` = :id'; $statement = $this->db->prepare($query); $statement->bindValue(':remote_id', $remote->getId(), \PDO::PARAM_INT); $statement->bindValue(':id', $pollerId, \PDO::PARAM_INT); $statement->execute(); } /** * Export to existing remote servers. * * @param int[] $pollerIDs the poller ids to export */ private function triggerExportForOldRemotes(array $pollerIDs): void { // Get from the database only the pollers that are linked to a remote $idBindString = str_repeat('?,', count($pollerIDs)); $idBindString = rtrim($idBindString, ','); $queryPollers = 'SELECT id, remote_id FROM nagios_server ' . "WHERE id IN({$idBindString}) AND remote_id IS NOT NULL"; $remotesStatement = $this->db->prepare($queryPollers); $remotesStatement->execute($pollerIDs); $pollersWithRemote = $remotesStatement->fetchAll(\PDO::FETCH_ASSOC); $alreadyExportedRemotes = []; // For each remote get the currently linked pollers, exclude the ones selected and trigger export foreach ($pollersWithRemote as $poller) { $remoteID = $poller['remote_id']; if (in_array($remoteID, $alreadyExportedRemotes)) { continue; } $alreadyExportedRemotes[] = $remoteID; // Get all linked pollers of the remote $linkedStatement = $this->db->prepare( 'SELECT id FROM nagios_server WHERE remote_id = :remote_id' ); $linkedStatement->bindValue(':remote_id', $remoteID, \PDO::PARAM_INT); $linkedStatement->execute(); $linkedResults = $linkedStatement->fetchAll(\PDO::FETCH_ASSOC); $linkedPollersOfRemote = array_column($linkedResults, 'id'); // Get information of remote $remoteDataStatement = $this->db->prepare( 'SELECT ns.ns_ip_address as ip, rs.centreon_path, rs.http_method, rs.http_port, rs.no_check_certificate, rs.no_proxy FROM nagios_server as ns JOIN remote_servers as rs ON rs.server_id = ns.id WHERE ns.id = :server_id' ); $remoteDataStatement->bindValue(':server_id', $remoteID, \PDO::PARAM_INT); $remoteDataStatement->execute(); $remoteDataResults = $remoteDataStatement->fetchAll(\PDO::FETCH_ASSOC); // Exclude the selected pollers which are going to another remote $pollerIDsToExport = array_diff($linkedPollersOfRemote, $pollerIDs); $exportParams = [ 'server' => $remoteID, 'pollers' => $pollerIDsToExport, 'remote_ip' => $remoteDataResults[0]['ip'], 'centreon_path' => $remoteDataResults[0]['centreon_path'], 'http_method' => $remoteDataResults[0]['http_method'], 'http_port' => $remoteDataResults[0]['http_port'], 'no_check_certificate' => $remoteDataResults[0]['no_check_certificate'], 'no_proxy' => $remoteDataResults[0]['no_proxy'], ]; $this->taskService->addTask(Task::TYPE_EXPORT, ['params' => $exportParams]); } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonRemote/Domain/Service/ConfigurationWizard/ServerConnectionConfigurationService.php
centreon/src/CentreonRemote/Domain/Service/ConfigurationWizard/ServerConnectionConfigurationService.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 CentreonRemote\Domain\Service\ConfigurationWizard; use App\Kernel; use Centreon\Infrastructure\CentreonLegacyDB\CentreonDBAdapter; use CentreonRemote\Domain\Resources\RemoteConfig\BamBrokerCfgInfo; use CentreonRemote\Domain\Resources\RemoteConfig\CfgNagios; use CentreonRemote\Domain\Resources\RemoteConfig\CfgNagiosBrokerModule; use CentreonRemote\Domain\Resources\RemoteConfig\CfgNagiosLogger; use CentreonRemote\Domain\Resources\RemoteConfig\NagiosServer; use Core\Common\Application\Repository\WriteVaultRepositoryInterface; use Core\Common\Application\UseCase\VaultTrait; use Core\Common\Infrastructure\FeatureFlags; use Core\Common\Infrastructure\Repository\AbstractVaultRepository; use Core\Security\Vault\Application\Repository\ReadVaultConfigurationRepositoryInterface; abstract class ServerConnectionConfigurationService { use VaultTrait; protected string|null $serverIp = null; protected string|null $centralIp = null; protected string|null $dbUser = null; protected string|null $dbPassword = null; protected string|null $name = null; protected bool $onePeerRetention = false; protected bool $shouldInsertBamBrokers = false; protected bool $isLinkedToCentralServer = false; protected int|null $brokerID = null; public function __construct( protected CentreonDBAdapter $dbAdapter, ) { } /** * @param string|null $ip */ public function setServerIp($ip): void { $this->serverIp = $ip; } /** * @param string|null $name */ public function setName($name): void { $this->name = $name; } /** * @param string|null $ip */ public function setCentralIp($ip): void { $this->centralIp = $ip; } /** * @param string|null $user */ public function setDbUser($user): void { $this->dbUser = $user; } /** * @param string|null $password */ public function setDbPassword($password): void { $this->dbPassword = $password; } /** * Set one peer retention mode. * * @param bool $onePeerRetention if one peer retention mode is enabled */ public function setOnePeerRetention(bool $onePeerRetention): void { $this->onePeerRetention = $onePeerRetention; } /** * @throws \Exception * * @return int */ public function insert(): int { $this->getDbAdapter()->beginTransaction(); $serverID = $this->insertNagiosServer(); if (! $serverID) { throw new \Exception('Error inserting nagios server.'); } $this->insertConfigNagios($serverID); $this->insertConfigResources($serverID); $this->insertConfigCentreonBroker($serverID); if ($this->shouldInsertBamBrokers && $this->isRemote()) { $this->insertBamBrokers(); } $this->getDbAdapter()->commit(); return $serverID; } public function shouldInsertBamBrokers(): void { $this->shouldInsertBamBrokers = true; } public function isLinkedToCentralServer(): void { $this->isLinkedToCentralServer = true; } abstract protected function insertConfigCentreonBroker(int $serverID): void; protected function getDbAdapter(): CentreonDBAdapter { return $this->dbAdapter; } protected function insertNagiosServer(): int { return $this->insertWithAdapter('nagios_server', NagiosServer::getConfiguration($this->name, $this->serverIp)); } /** * @param int $serverID * * @return int */ protected function insertConfigNagios($serverID): int { $configID = $this->insertWithAdapter('cfg_nagios', CfgNagios::getConfiguration($this->name, $serverID)); $this->insertWithAdapter('cfg_nagios_logger', CfgNagiosLogger::getConfiguration($configID)); $configBroker = CfgNagiosBrokerModule::getConfiguration($configID, $this->name); $this->insertWithAdapter('cfg_nagios_broker_module', $configBroker[0]); return $configID; } /** * @param int $serverID * * @throws \Exception */ protected function insertConfigResources($serverID): void { $sql = 'SELECT `resource_id`, `resource_name` FROM `cfg_resource`'; $sql .= "WHERE `resource_name` IN('\$USER1$', '\$CENTREONPLUGINS$') ORDER BY `resource_name` DESC"; $this->getDbAdapter()->query($sql); $results = $this->getDbAdapter()->results(); if (count($results) < 2) { throw new \Exception('Resources records from `cfg_resource` could not be fetched.'); } if ( $results[0]->resource_name !== '$USER1$' || $results[1]->resource_name !== '$CENTREONPLUGINS$' ) { throw new \Exception('Resources records from `cfg_resource` are not as expected.'); } $userResourceData = ['resource_id' => $results[0]->resource_id, 'instance_id' => $serverID]; $pluginResourceData = ['resource_id' => $results[1]->resource_id, 'instance_id' => $serverID]; $this->insertWithAdapter('cfg_resource_instance_relations', $userResourceData); $this->insertWithAdapter('cfg_resource_instance_relations', $pluginResourceData); } /** * insert broker log information. * * @param \Generator<array<string,string|int>> $brokerLogs */ protected function insertBrokerLog(\Generator $brokerLogs): void { foreach ($brokerLogs as $brokerLog) { $this->insertWithAdapter('cfg_centreonbroker_log', $brokerLog); } } /** * @throws \Exception */ protected function insertBamBrokers(): void { global $conf_centreon; if (! $this->brokerID) { throw new \Exception('Broker ID was not inserted in order to add BAM broker configs to it.'); } $bamBrokerInfoData = BamBrokerCfgInfo::getConfiguration($conf_centreon['password']); $bamBrokerInfoData = $this->saveCredentialInVault($bamBrokerInfoData); foreach ($bamBrokerInfoData['monitoring'] as $row) { $row['config_id'] = $this->brokerID; $this->insertWithAdapter('cfg_centreonbroker_info', $row); } foreach ($bamBrokerInfoData['reporting'] as $row) { $row['config_id'] = $this->brokerID; $this->insertWithAdapter('cfg_centreonbroker_info', $row); } } /** * @param string $table * @param array<string,mixed> $data * * @throws \Exception * * @return int */ protected function insertWithAdapter($table, array $data): int { try { $result = $this->getDbAdapter()->insert($table, $data); } catch (\Exception $e) { $this->getDbAdapter()->rollBack(); throw new \Exception("Error inserting remote configuration. Rolling back. Table name: {$table}."); } return $result; } protected function isRemote(): bool { return false; } /** * @param array<string, array<int, string[]>> $brokerInfos * * @throws \Throwable * * @return array<string, array<int, string[]>> */ protected function saveCredentialInVault(array $brokerInfos): array { $kernel = Kernel::createForWeb(); /** @var ReadVaultConfigurationRepositoryInterface $readVaultConfigurationRepository */ $readVaultConfigurationRepository = $kernel->getContainer()->get( ReadVaultConfigurationRepositoryInterface::class ); /** @var FeatureFlags $featureFlags */ $featureFlags = $kernel->getContainer()->get(FeatureFlags::class); /** @var WriteVaultRepositoryInterface $writeVaultRepository */ $writeVaultRepository = $kernel->getContainer()->get(WriteVaultRepositoryInterface::class); $writeVaultRepository->setCustomPath(AbstractVaultRepository::BROKER_VAULT_PATH); $vaultConfiguration = $readVaultConfigurationRepository->find(); if ( ! $featureFlags->isEnabled('vault') || ! $featureFlags->isEnabled('vault_broker') || $vaultConfiguration === null ) { return $brokerInfos; } foreach ($brokerInfos as $key => $inputOutput) { $inputOutputName = null; $credentialKey = null; $credentialValue = null; foreach ($inputOutput as $index => $row) { if (isset($row['config_key']) && $row['config_key'] === 'name') { $inputOutputName = $row['config_value']; } if (isset($row['config_key']) && $row['config_key'] === 'db_password') { $credentialKey = $index; $credentialValue = $row['config_value']; } } if ( $inputOutputName === null || $credentialKey === null || $credentialValue === null ) { continue; } $paths = $writeVaultRepository->upsert( $this->uuid, ["{$inputOutputName}_db_password" => $credentialValue] ); $path = end($paths); if ($path !== false) { $this->uuid = $this->getUuidFromPath($path); } $brokerInfos[$key][$credentialKey]['config_value'] = $paths["{$inputOutputName}_db_password"]; } return $brokerInfos; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonRemote/Infrastructure/Export/ExportParserYaml.php
centreon/src/CentreonRemote/Infrastructure/Export/ExportParserYaml.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 CentreonRemote\Infrastructure\Export; use Symfony\Component\Yaml\Yaml; class ExportParserYaml implements ExportParserInterface { /** * @param string $filename * @param callable|null $macros * * @return array<mixed> */ public function parse(string $filename, ?callable $macros = null): array { if (! file_exists($filename)) { return []; } $content = file_get_contents($filename); if ($macros !== null) { $macros($content); } return Yaml::parse($content); } /** * @param string[] $input * @param string $filename */ public function dump(array $input, string $filename): void { if (! $input) { return; } $yaml = Yaml::dump($input); file_put_contents($filename, $yaml); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonRemote/Infrastructure/Export/ExportCommitment.php
centreon/src/CentreonRemote/Infrastructure/Export/ExportCommitment.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 CentreonRemote\Infrastructure\Export; final class ExportCommitment { /** @var int[] */ private $pollers; /** @var string */ private $path; /** @var ExportParserInterface */ private $parser; /** @var array<mixed> */ private $exporters; /** @var array<mixed> */ private $meta; /** @var int */ private $filePermission = 0775; /** @var int */ private $remote; /** * Construct. * * @param int $remote * @param int[] $pollers * @param array<mixed> $meta * @param ExportParserInterface $parser * @param string $path * @param array<int,string> $exporters */ public function __construct( ?int $remote = null, ?array $pollers = null, ?array $meta = null, ?ExportParserInterface $parser = null, ?string $path = null, ?array $exporters = null, ) { if ($remote && $pollers && ! in_array($remote, $pollers)) { $pollers[] = $remote; } $this->remote = $remote; $this->pollers = $pollers; $this->meta = $meta; $this->path = $path; $this->exporters = $exporters ?? []; if ($this->path === null) { $this->path = _CENTREON_CACHEDIR_ . '/config/export/' . $this->remote; } $this->parser = $parser ?? new ExportParserJson(); } public function getRemote(): int { return $this->remote; } /** * @return int[] */ public function getPollers(): array { return $this->pollers; } /** * @return array<mixed>|null */ public function getMeta() { return $this->meta; } public function getPath(): string { return $this->path; } /** * @return array<mixed> */ public function getExporters(): array { return $this->exporters; } public function getFilePermission(): int { return $this->filePermission; } public function getParser(): ExportParserInterface { return $this->parser; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonRemote/Infrastructure/Export/ExportManifest.php
centreon/src/CentreonRemote/Infrastructure/Export/ExportManifest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 CentreonRemote\Infrastructure\Export; use Exception; /** * Writes manifest of exported files and reads them for import process. */ class ExportManifest { public const EXPORT_FILE = 'manifest.json'; public const ERR_CODE_MANIFEST_NOT_FOUND = 1001; public const ERR_CODE_MANIFEST_WRONG_FORMAT = 1002; public const ERR_CODE_INCOMPATIBLE_VERSIONS = 1005; /** @var ExportCommitment */ private $commitment; /** @var string */ private $version; /** @var array<mixed> */ private $data; /** * @param ExportCommitment $commitment * @param string|null $version */ public function __construct(ExportCommitment $commitment, ?string $version = null) { $this->commitment = $commitment; $this->version = $version; } /** * Retrieves data array field based on key. * * @param string $key Key of data array to retrieve * * @return array<mixed> */ public function get(string $key) { return $this->data && array_key_exists($key, $this->data) ? $this->data[$key] : null; } /** * Validate manifest format and return content. * * @throws Exception * * @return array<mixed> */ public function validate() { $file = $this->getFile(); if (! file_exists($file)) { throw new Exception(sprintf('Manifest file %s not found', $file), static::ERR_CODE_MANIFEST_NOT_FOUND); } $this->data = $this->commitment->getParser()->parse($file); $checkManifestKeys = function (array $data): array { $keys = ['date', 'remote_server', 'pollers', 'import']; $missingKeys = []; foreach ($keys as $key) { if (! array_key_exists($key, $data)) { $missingKeys[] = $key; } } return $missingKeys; }; if ($missingKeys = $checkManifestKeys($this->data)) { throw new Exception( sprintf("Missing data in a manifest file:\n - %s", join("\n - ", $missingKeys)), static::ERR_CODE_MANIFEST_WRONG_FORMAT ); } // Compare only the major and minor version, not bugfix because no SQL schema changes $centralVersion = preg_replace('/^(\d+\.\d+).*/', '$1', $this->data['version']); $remoteVersion = preg_replace('/^(\d+\.\d+).*/', '$1', $this->version); if (! version_compare($centralVersion, $remoteVersion, '==')) { throw new Exception( sprintf( 'The version of the Central "%s" and of the Remote "%s" are incompatible', $this->data['version'], $this->version ), static::ERR_CODE_INCOMPATIBLE_VERSIONS ); } return $this->data; } /** * Dump data in file. * * @param array<string,mixed> $exportManifest */ public function dump(array $exportManifest): void { $data = array_merge($exportManifest, ['version' => $this->version]); $this->commitment->getParser()->dump($data, $this->getFile()); } /** * Get file path. * * @return string */ public function getFile(): string { $file = $this->commitment->getPath() . '/' . static::EXPORT_FILE; return $file; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonRemote/Infrastructure/Export/ExportParserInterface.php
centreon/src/CentreonRemote/Infrastructure/Export/ExportParserInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 CentreonRemote\Infrastructure\Export; interface ExportParserInterface { /** * @param string $filename * @param callable|null $macros * * @return array<mixed> */ public function parse(string $filename, ?callable $macros = null): array; /** * @param array<mixed> $input * @param string $filename */ public function dump(array $input, string $filename): void; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonRemote/Infrastructure/Export/ExportParserJson.php
centreon/src/CentreonRemote/Infrastructure/Export/ExportParserJson.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 CentreonRemote\Infrastructure\Export; class ExportParserJson implements ExportParserInterface { /** * @param string $filename * @param callable|null $macros * * @return array<mixed> */ public function parse(string $filename, ?callable $macros = null): array { if (! file_exists($filename)) { return []; } $content = file_get_contents($filename); if ($macros !== null) { $macros($content); } // true to return array return json_decode($content, true); } /** * @param string[] $input * @param string $filename */ public function dump(array $input, string $filename): void { if (! $input) { return; } $json = json_encode($input); file_put_contents($filename, $json); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonRemote/Infrastructure/Service/ExporterServiceInterface.php
centreon/src/CentreonRemote/Infrastructure/Service/ExporterServiceInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 CentreonRemote\Infrastructure\Service; use CentreonRemote\Infrastructure\Export\ExportCommitment; use CentreonRemote\Infrastructure\Export\ExportManifest; use Pimple\Container; interface ExporterServiceInterface { public function __construct(Container $services); public function setCommitment(ExportCommitment $commitment): void; public function setManifest(ExportManifest $manifest): void; /** * @param int $remoteId * * @return array<mixed> */ public function export(int $remoteId): array; public function import(ExportManifest $manifest): void; public static function getName(): string; public static function order(): int; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonRemote/Infrastructure/Service/ExporterServicePartialInterface.php
centreon/src/CentreonRemote/Infrastructure/Service/ExporterServicePartialInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 CentreonRemote\Infrastructure\Service; interface ExporterServicePartialInterface { public function exportPartial(): void; }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonRemote/Infrastructure/Service/ExporterService.php
centreon/src/CentreonRemote/Infrastructure/Service/ExporterService.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 CentreonRemote\Infrastructure\Service; use Centreon\Infrastructure\Service\Exception\NotFoundException; use Centreon\Infrastructure\Service\Traits\ServiceContainerTrait; use Psr\Container\ContainerInterface; use ReflectionClass; class ExporterService implements ContainerInterface { use ServiceContainerTrait; /** * @param string $object * @param callable $factory */ public function add(string $object, callable $factory): void { $interface = ExporterServiceInterface::class; $hasInterface = (new ReflectionClass($object)) ->implementsInterface($interface); if ($hasInterface === false) { throw new NotFoundException(sprintf('Object %s must implement %s', $object, $interface)); } $name = strtolower($object::getName()); $this->objects[$name] = [ 'name' => $name, 'classname' => $object, 'factory' => $factory, ]; $this->sort(); } /** * @param string $id * * @return bool */ public function has($id): bool { $result = $this->getKey($id); return $result !== null; } /** * @param string $id * * @return int[] */ public function get($id): array { $key = $this->getKey($id); if ($key === null) { throw new NotFoundException('Not found exporter with name: ' . $id); } return $this->objects[$key]; } /** * @param string $id * * @return int|null */ private function getKey($id): ?int { foreach ($this->objects as $key => $object) { if ($object['name'] === $id) { return $key; } } return null; } private function sort(): void { usort($this->objects, function ($a, $b) { return $a['classname']::order() - $b['classname']::order(); }); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonRemote/Infrastructure/Service/PollerInteractionService.php
centreon/src/CentreonRemote/Infrastructure/Service/PollerInteractionService.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 CentreonRemote\Infrastructure\Service; use Centreon; use Centreon\ServiceProvider; use CentreonBroker; use CentreonContactgroup; use CentreonDB; use Exception; use Generate; use Pimple\Container; /** * Class * * @class PollerInteractionService * @package CentreonRemote\Infrastructure\Service */ class PollerInteractionService { /** @var Container */ private $di; /** @var CentreonDB */ private $db; /** @var Centreon */ private $centreon; /** * PollerInteractionService constructor * * @param Container $di */ public function __construct(Container $di) { global $centreon; $this->di = $di; $this->db = $di[ServiceProvider::CENTREON_DB_MANAGER] ->getAdapter('configuration_db') ->getCentreonDBInstance(); $this->centreon = $centreon; } /** * @param int[] $pollers * * @throws Exception */ public function generateAndExport($pollers): void { $pollers = (array) $pollers; $this->generateConfiguration($pollers); $this->moveConfigurationFiles($pollers); $this->restartPoller($pollers); } /** * @param int[] $pollerIDs * * @throws Exception */ private function generateConfiguration(array $pollerIDs): void { $username = 'unknown'; if (isset($this->centreon->user->name)) { $username = $this->centreon->user->name; } try { // Sync contact groups with ldap $contactGroupObject = new CentreonContactgroup($this->db); $contactGroupObject->syncWithLdap(); // Generate configuration $configGenerateObject = new Generate($this->di); foreach ($pollerIDs as $pollerID) { $configGenerateObject->reset(); $configGenerateObject->configPollerFromId($pollerID, $username); } } catch (Exception $e) { throw new Exception('There was an error generating the configuration for a poller.'); } } /** * @param int[] $pollerIDs * * @throws Exception */ private function moveConfigurationFiles(array $pollerIDs): void { $centreonBrokerPath = _CENTREON_CACHEDIR_ . '/config/broker/'; $centCorePipe = defined('_CENTREON_VARLIB_') ? _CENTREON_VARLIB_ . '/centcore.cmd' : '/var/lib/centreon/centcore.cmd'; $tabServer = []; $tabs = $this->centreon->user->access->getPollerAclConf([ 'fields' => ['name', 'id', 'localhost'], 'order' => ['name'], 'conditions' => ['ns_activate' => '1'], 'keys' => ['id'], ]); foreach ($tabs as $tab) { if (in_array($tab['id'], $pollerIDs)) { $tabServer[$tab['id']] = [ 'id' => $tab['id'], 'name' => $tab['name'], 'localhost' => $tab['localhost'], ]; } } foreach ($tabServer as $host) { if (in_array($host['id'], $pollerIDs)) { passthru("echo 'SENDCFGFILE:{$host['id']}' >> {$centCorePipe}", $return); if ($return) { throw new Exception(_('Could not write into centcore.cmd. Please check file permissions.')); } } } } /** * @param int[] $pollerIDs * * @throws Exception */ private function restartPoller(array $pollerIDs): void { $tabServers = []; $centCorePipe = defined('_CENTREON_VARLIB_') ? _CENTREON_VARLIB_ . '/centcore.cmd' : '/var/lib/centreon/centcore.cmd'; $tabs = $this->centreon->user->access->getPollerAclConf([ 'fields' => ['name', 'id', 'localhost', 'engine_restart_command'], 'order' => ['name'], 'conditions' => ['ns_activate' => '1'], 'keys' => ['id'], ]); $broker = new CentreonBroker($this->db); $broker->reload(); foreach ($tabs as $tab) { if (in_array($tab['id'], $pollerIDs)) { $tabServers[$tab['id']] = [ 'id' => $tab['id'], 'name' => $tab['name'], 'localhost' => $tab['localhost'], 'engine_restart_command' => $tab['engine_restart_command'], ]; } } foreach ($tabServers as $poller) { if (isset($poller['localhost']) && $poller['localhost'] == 1) { if ($poller['engine_restart_command'] != '') { shell_exec(escapeshellcmd("sudo -n -- {$poller['engine_restart_command']}")); } } elseif ($fh = @fopen($centCorePipe, 'a+')) { fwrite($fh, 'RESTART:' . $poller['id'] . "\n"); fclose($fh); } else { throw new Exception(_('Could not write into centcore.cmd. Please check file permissions.')); } $restartTimeQuery = "UPDATE `nagios_server` SET `last_restart` = '" . time() . "' WHERE `id` = '{$poller['id']}'"; $this->db->query($restartTimeQuery); } // Find restart actions in modules foreach ($this->centreon->modules as $key => $value) { $moduleFiles = glob(_CENTREON_PATH_ . 'www/modules/' . $key . '/restart_pollers/*.php'); if ($value['restart'] && $moduleFiles) { foreach ($moduleFiles as $fileName) { include $fileName; } } } } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonRemote/Infrastructure/Service/ExporterCacheService.php
centreon/src/CentreonRemote/Infrastructure/Service/ExporterCacheService.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 CentreonRemote\Infrastructure\Service; class ExporterCacheService { /** @var mixed */ private $data; /** * Get info if exists and if not add it using callback function. * * @param string $key * @param callable $data * * @return mixed */ public function getIf(string $key, callable $data) { if (! $this->has($key)) { $this->data[$key] = $data(); } return $this->data[$key]; } /** * Setter. * * @param string $key * @param mixed $data */ public function set(string $key, $data): void { $this->data[$key] = $data; } /** * Merge. * * @param string $key * @param mixed $data */ public function merge(string $key, $data): void { if (! $this->has($key)) { $this->set($key, $data); } else { $this->data[$key] = array_merge($data, $this->data[$key]); } } /** * @param string $key * * @return bool */ public function has(string $key): bool { return $this->data === null ? false : array_key_exists($key, $this->data); } /** * Getter. * * @param string $key * * @return mixed */ public function get(string $key) { if (! $this->has($key)) { return; } return $this->data[$key]; } /** * Destroy data. */ public function destroy(): void { $this->data = null; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonRemote/Infrastructure/Service/ExportService.php
centreon/src/CentreonRemote/Infrastructure/Service/ExportService.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 CentreonRemote\Infrastructure\Service; use Centreon\Domain\Repository; use Centreon\Domain\Repository\Interfaces\AclResourceRefreshInterface; use CentreonRemote\Infrastructure\Export\ExportCommitment; use CentreonRemote\Infrastructure\Export\ExportManifest; use Psr\Container\ContainerInterface; class ExportService { /** * Path to store exported remote server files. * * @var string */ private $pathExportedData; /** @var ExporterService */ private $exporter; /** @var \CentreonClapi\CentreonACL */ private $acl; /** @var \Centreon\Infrastructure\Service\CentreonDBManagerService */ private $db; /** @var string */ private $version; /** * Construct. * * @param ContainerInterface $services */ public function __construct(ContainerInterface $services) { $this->exporter = $services->get('centreon_remote.exporter'); $this->acl = $services->get('centreon.acl'); $this->db = $services->get(\Centreon\ServiceProvider::CENTREON_DB_MANAGER); $this->pathExportedData = _CENTREON_CACHEDIR_ . '/config/remote-data'; $version = $this->db ->getRepository(Repository\InformationsRepository::class) ->getOneByKey('version'); if ($version) { $this->version = $version->getValue(); } } /** * Export all that is registered in exporter. * * @param ExportCommitment $commitment * * @throws \Exception * * @todo separate work of exporters */ public function export(ExportCommitment $commitment): void { $remoteId = $commitment->getRemote(); // remove export directory if exists $exportPath = $commitment->getPath(); if (is_dir($exportPath)) { system('rm -rf ' . escapeshellarg($exportPath)); } $manifest = new ExportManifest($commitment, $this->version); // export configuration and media $configurationExporter = $this->exporter->get('configuration')['factory'](); $configurationExporter->setCommitment($commitment); $exportManifest = $configurationExporter->export($remoteId); $manifest->dump($exportManifest); } /** * Import. * * @param ExportCommitment $commitment * * @throws \Exception */ public function import(?ExportCommitment $commitment = null): void { $commitment ??= new ExportCommitment(null, null, null, null, $this->pathExportedData); // check is export directory $exportPath = $commitment->getPath(); if (! is_dir($exportPath)) { return; } // parse manifest $manifest = new ExportManifest($commitment, $this->version); $manifest->validate(); // import configuration and media $configurationExporter = $this->exporter->get('configuration')['factory'](); $configurationExporter->setCommitment($commitment); $configurationExporter->import($manifest); // cleanup ACL removed data $this->refreshAcl(); // remove export directory system('rm -rf ' . escapeshellarg($exportPath)); } private function refreshAcl(): void { // cleanup resource table from deleted entities $resourceList = [ Repository\AclResourcesHcRelationsRepository::class, Repository\AclResourcesHgRelationsRepository::class, Repository\AclResourcesHostexRelationsRepository::class, Repository\AclResourcesHostRelationsRepository::class, Repository\AclResourcesMetaRelationsRepository::class, Repository\AclResourcesPollerRelationsRepository::class, Repository\AclResourcesScRelationsRepository::class, Repository\AclResourcesServiceRelationsRepository::class, Repository\AclResourcesSgRelationsRepository::class, ]; foreach ($resourceList as $resource) { $repository = $this->db->getRepository($resource); if ($repository instanceof AclResourceRefreshInterface) { $repository->refresh(); } } // refresh ACL $this->acl->reload(true); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/CentreonRemote/Infrastructure/Service/ExporterServiceAbstract.php
centreon/src/CentreonRemote/Infrastructure/Service/ExporterServiceAbstract.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 CentreonRemote\Infrastructure\Service; use CentreonRemote\Infrastructure\Export\ExportCommitment; use CentreonRemote\Infrastructure\Export\ExportManifest; use Pimple\Container; abstract class ExporterServiceAbstract implements ExporterServiceInterface { /** @var Container */ protected $dependencyInjector; /** @var \Centreon\Infrastructure\Service\CentreonDBManagerService */ protected $db; /** @var ExporterCacheService */ protected $cache; /** @var ExportCommitment */ protected $commitment; /** @var \Centreon\Infrastructure\Service\CentcoreConfigService */ protected $config; /** @var mixed */ protected $manifest; /** * Construct. * * @param Container $services */ public function __construct(Container $services) { $this->dependencyInjector = $services; $this->db = $services['centreon.db-manager']; $this->config = $services['centreon.config']; } /** * @param ExporterCacheService $cache */ public function setCache(ExporterCacheService $cache): void { $this->cache = $cache; } /** * @param ExportCommitment $commitment */ public function setCommitment(ExportCommitment $commitment): void { $this->commitment = $commitment; } /** * @param ExportManifest $manifest */ public function setManifest(ExportManifest $manifest): void { $this->manifest = $manifest; } /** * Create path for export. * * @param string $exportPath * * @return string */ public function createPath(?string $exportPath = null): string { // Create export path $exportPath = $this->getPath($exportPath); // make directory if missing if (! is_dir($exportPath)) { mkdir($exportPath, $this->commitment->getFilePermission(), true); } return $exportPath; } /** * Get path of export. * * @param string $exportPath * * @return string */ public function getPath(?string $exportPath = null): string { $exportPath ??= $this->commitment->getPath() . '/' . $this->getName(); return $exportPath; } /** * Get exported file. * * @param string $filename * * @return string */ public function getFile(string $filename): string { return $this->getPath() . '/' . $filename; } public static function order(): int { return 10; } }
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/ExpressionBuilder/ExpressionBuilderInterface.php
centreon/src/Adaptation/Database/ExpressionBuilder/ExpressionBuilderInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\ExpressionBuilder; use Adaptation\Database\ExpressionBuilder\Enum\ComparisonOperatorEnum; /** * Interface. * * @class ExpressionBuilderInterface */ interface ExpressionBuilderInterface { /** * Creates a conjunction of the given expressions. * * @example * method : and("field1 = :value1", ["field2 = :value2","field3 = :value3"]) * return : "(field1 = :value1) AND (field2 = :value2) AND (field3 = :value3)" */ public function and(string $expression, string ...$expressions): string; /** * Creates a disjunction of the given expressions. * * @example * method : or("field1 = :value1", ["field2 = :value2","field3 = :value3"]) * return : "(field1 = :value1) OR (field2 = :value2) OR (field3 = :value3)" */ public function or(string $expression, string ...$expressions): string; /** * Creates a comparison expression. * * @param string $leftExpression the left expression * @param ComparisonOperatorEnum $operator the comparison operator * @param string $rightExpression the right expression * * @example * method : comparison('field1', '=', ':value1') * return : "field1 = :value1" */ public function comparison( string $leftExpression, ComparisonOperatorEnum $operator, string $rightExpression, ): string; /** * Creates an equality comparison expression with the given arguments. * * First argument is considered the left expression and the second is the right expression. * When converted to string, it will generated a <left expr> = <right expr>. * * @param string $leftExpression the left expression * @param string $rightExpression the right expression * * @example * method : equal('field1', ':value1') * return : "field1 = :value1" */ public function equal(string $leftExpression, string $rightExpression): string; /** * Creates a non equality comparison expression with the given arguments. * * First argument is considered the left expression and the second is the right expression. * When converted to string, it will generated a <left expr> <> <right expr>. * * @param string $leftExpression the left expression * @param string $rightExpression the right expression * * @example * method : notEqual('field1', ':value1') * return : "field1 <> :value1" */ public function notEqual(string $leftExpression, string $rightExpression): string; /** * Creates a lower-than comparison expression with the given arguments. * * First argument is considered the left expression and the second is the right expression. * When converted to string, it will generated a <left expr> < <right expr>. * * @param string $leftExpression the left expression * @param string $rightExpression the right expression * * @example * method : lowerThan('field1', ':value1') * return : "field1 < :value1" */ public function lowerThan(string $leftExpression, string $rightExpression): string; /** * Creates a lower-than-equal comparison expression with the given arguments. * * First argument is considered the left expression and the second is the right expression. * When converted to string, it will generated a <left expr> <= <right expr>. * * @param string $leftExpression the left expression * @param string $rightExpression the right expression * * @example * method : lowerThanEqual('field1', ':value1') * return : "field1 <= :value1" */ public function lowerThanEqual(string $leftExpression, string $rightExpression): string; /** * Creates a greater-than comparison expression with the given arguments. * First argument is considered the left expression and the second is the right expression. * When converted to string, it will generated a <left expr> > <right expr>. * * @param string $leftExpression the left expression * @param string $rightExpression the right expression * * @example * method : greaterThan('field1', ':value1') * return : "field1 > :value1" */ public function greaterThan(string $leftExpression, string $rightExpression): string; /** * Creates a greater-than-equal comparison expression with the given arguments. * * First argument is considered the left expression and the second is the right expression. * When converted to string, it will generated a <left expr> >= <right expr>. * * @param string $leftExpression the left expression * @param string $rightExpression the right expression * * @example * method : greaterThanEqual('field1', ':value1') * return : "field1 >= :value1" */ public function greaterThanEqual(string $leftExpression, string $rightExpression): string; /** * Creates an IS NULL expression with the given arguments. * * @param string $expression the expression to be restricted by IS NULL * * @example * method : isNull('field1') * return : "field1 IS NULL" */ public function isNull(string $expression): string; /** * Creates an IS NOT NULL expression with the given arguments. * * @param string $expression the expression to be restricted by IS NOT NULL * * @example * method : isNotNull('field1') * return : "field1 IS NOT NULL" */ public function isNotNull(string $expression): string; /** * Creates a LIKE comparison expression. * * @param string $expression The expression to be inspected by the LIKE comparison * @param string $pattern The pattern to compare against * @param string|null $escapeChar To indicate the escape character, by default it's '\' (optional) * * @example * method : like('field1', ':value1') * return : "field1 LIKE :value1" * method : like('field1', ':value1','$') * return : "field1 LIKE :value1" ESCAPE '$' */ public function like(string $expression, string $pattern, ?string $escapeChar = null): string; /** * Creates a NOT LIKE comparison expression. * * @param string $expression The expression to be inspected by the NOT LIKE comparison * @param string $pattern The pattern to compare against * @param string|null $escapeChar To indicate the escape character, by default it's '\' (optional) * * @example * method : notLike('field1', ':value1') * return : "field1 NOT LIKE :value1" * method : notLike('field1', ':value1','$') * return : "field1 NOT LIKE :value1" ESCAPE '$' */ public function notLike(string $expression, string $pattern, ?string $escapeChar = null): string; /** * Creates an IN () comparison expression with the given arguments. * * @param string $expressionToBeMatched the SQL expression to be matched against the set * @param string|string[] $set the SQL expression or an array of SQL expressions representing the set * * @example * method : in('field1', [:value1, :value2, :value3]) * return : "field1 IN (:value1, :value2, :value3)" */ public function in(string $expressionToBeMatched, string|array $set): string; /** * Creates a NOT IN () comparison expression with the given arguments. * * @param string $expressionToBeMatched the SQL expression to be matched against the set * @param string|string[] $set the SQL expression or an array of SQL expressions representing the set * * @example * method : notIn('field1', [:value1, :value2, :value3]) * return : "field1 NOT IN (:value1, :value2, :value3)" */ public function notIn(string $expressionToBeMatched, string|array $set): string; }
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/ExpressionBuilder/Enum/ComparisonOperatorEnum.php
centreon/src/Adaptation/Database/ExpressionBuilder/Enum/ComparisonOperatorEnum.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\ExpressionBuilder\Enum; /** * Enum. * * @class ComparisonOperatorEnum */ enum ComparisonOperatorEnum: string { case EQUAL = '='; case NOT_EQUAL = '<>'; case GREATER_THAN = '>'; case GREATER_THAN_OR_EQUAL = '>='; case LESS_THAN = '<'; case LESS_THAN_OR_EQUAL = '<='; }
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/ExpressionBuilder/Exception/ExpressionBuilderException.php
centreon/src/Adaptation/Database/ExpressionBuilder/Exception/ExpressionBuilderException.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\ExpressionBuilder\Exception; use Adaptation\Database\Exception\DatabaseException; /** * Class. * * @class ExpressionBuilderException */ class ExpressionBuilderException extends DatabaseException { public static function createFromConnectionConfigFailed(?\Throwable $previous = null): self { $message = 'Error while instantiate the expression builder'; if ($previous instanceof \Throwable && ! empty($previous->getMessage())) { $message .= " : {$previous->getMessage()}"; } return new self($message, self::ERROR_CODE_EXPRESSION_BUILDER, 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/ExpressionBuilder/Adapter/Dbal/DbalExpressionBuilderAdapter.php
centreon/src/Adaptation/Database/ExpressionBuilder/Adapter/Dbal/DbalExpressionBuilderAdapter.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\ExpressionBuilder\Adapter\Dbal; use Adaptation\Database\Connection\Adapter\Dbal\DbalConnectionAdapter; use Adaptation\Database\Connection\Exception\ConnectionException; use Adaptation\Database\Connection\Model\ConnectionConfig; use Adaptation\Database\ExpressionBuilder\Enum\ComparisonOperatorEnum; use Adaptation\Database\ExpressionBuilder\Exception\ExpressionBuilderException; use Adaptation\Database\ExpressionBuilder\ExpressionBuilderInterface; use Centreon\Domain\Log\Logger; use Doctrine\DBAL\Query\Expression\ExpressionBuilder as DoctrineDbalExpressionBuilder; /** * Class. * * @class ExpressionBuilder * * @see DoctrineDbalExpressionBuilder * * To dynamically create SQL query parts. */ final readonly class DbalExpressionBuilderAdapter implements ExpressionBuilderInterface { /** * DbalExpressionBuilderAdapter constructor. */ public function __construct(private DoctrineDbalExpressionBuilder $dbalExpressionBuilder) { } /** * Factory. * * Creates an expression builder for the connection. * * We have to use a connection configuration to instantiate the query builder because the query builder needs a * connection to work. * * @throws ExpressionBuilderException * * @return DbalExpressionBuilderAdapter */ public static function createFromConnectionConfig(ConnectionConfig $connectionConfig): ExpressionBuilderInterface { try { $connection = DbalConnectionAdapter::createFromConfig($connectionConfig); return new self(new DoctrineDbalExpressionBuilder($connection->getDbalConnection())); } catch (ConnectionException $exception) { Logger::create()->error( 'An error occurred while trying to create an instance of expression builder', ['exception' => $exception->getContext()] ); throw ExpressionBuilderException::createFromConnectionConfigFailed($exception); } } /** * Creates a conjunction of the given expressions. * * @example * method : and("field1 = :value1", ["field2 = :value2","field3 = :value3"]) * return : "(field1 = :value1) AND (field2 = :value2) AND (field3 = :value3)" */ public function and(string $expression, string ...$expressions): string { return $this->dbalExpressionBuilder->and($expression, ...$expressions)->__toString(); } /** * Creates a disjunction of the given expressions. * * @example * method : or("field1 = :value1", ["field2 = :value2","field3 = :value3"]) * return : "(field1 = :value1) OR (field2 = :value2) OR (field3 = :value3)" */ public function or(string $expression, string ...$expressions): string { return $this->dbalExpressionBuilder->or($expression, ...$expressions)->__toString(); } /** * Creates a comparison expression. * * @param string $leftExpression the left expression * @param ComparisonOperatorEnum $operator the comparison operator * @param string $rightExpression the right expression * * @example * method : comparison('field1', '=', ':value1') * return : "field1 = :value1" */ public function comparison( string $leftExpression, ComparisonOperatorEnum $operator, string $rightExpression, ): string { return $this->dbalExpressionBuilder->comparison($leftExpression, $operator->value, $rightExpression); } /** * Creates an equality comparison expression with the given arguments. * * First argument is considered the left expression and the second is the right expression. * When converted to string, it will generated a <left expr> = <right expr>. * * @param string $leftExpression the left expression * @param string $rightExpression the right expression * * @example * method : equal('field1', ':value1') * return : "field1 = :value1" */ public function equal(string $leftExpression, string $rightExpression): string { return $this->dbalExpressionBuilder->eq($leftExpression, $rightExpression); } /** * Creates a non equality comparison expression with the given arguments. * * First argument is considered the left expression and the second is the right expression. * When converted to string, it will generated a <left expr> <> <right expr>. * * @param string $leftExpression the left expression * @param string $rightExpression the right expression * * @example * method : notEqual('field1', ':value1') * return : "field1 <> :value1" */ public function notEqual(string $leftExpression, string $rightExpression): string { return $this->dbalExpressionBuilder->neq($leftExpression, $rightExpression); } /** * Creates a lower-than comparison expression with the given arguments. * * First argument is considered the left expression and the second is the right expression. * When converted to string, it will generated a <left expr> < <right expr>. * * @param string $leftExpression the left expression * @param string $rightExpression the right expression * * @example * method : lowerThan('field1', ':value1') * return : "field1 < :value1" */ public function lowerThan(string $leftExpression, string $rightExpression): string { return $this->dbalExpressionBuilder->lt($leftExpression, $rightExpression); } /** * Creates a lower-than-equal comparison expression with the given arguments. * * First argument is considered the left expression and the second is the right expression. * When converted to string, it will generated a <left expr> <= <right expr>. * * @param string $leftExpression the left expression * @param string $rightExpression the right expression * * @example * method : lowerThanEqual('field1', ':value1') * return : "field1 <= :value1" */ public function lowerThanEqual(string $leftExpression, string $rightExpression): string { return $this->dbalExpressionBuilder->lte($leftExpression, $rightExpression); } /** * Creates a greater-than comparison expression with the given arguments. * First argument is considered the left expression and the second is the right expression. * When converted to string, it will generated a <left expr> > <right expr>. * * @param string $leftExpression the left expression * @param string $rightExpression the right expression * * @example * method : greaterThan('field1', ':value1') * return : "field1 > :value1" */ public function greaterThan(string $leftExpression, string $rightExpression): string { return $this->dbalExpressionBuilder->gt($leftExpression, $rightExpression); } /** * Creates a greater-than-equal comparison expression with the given arguments. * * First argument is considered the left expression and the second is the right expression. * When converted to string, it will generated a <left expr> >= <right expr>. * * @param string $leftExpression the left expression * @param string $rightExpression the right expression * * @example * method : greaterThanEqual('field1', ':value1') * return : "field1 >= :value1" */ public function greaterThanEqual(string $leftExpression, string $rightExpression): string { return $this->dbalExpressionBuilder->gte($leftExpression, $rightExpression); } /** * Creates an IS NULL expression with the given arguments. * * @param string $expression the expression to be restricted by IS NULL * * @example * method : isNull('field1') * return : "field1 IS NULL" */ public function isNull(string $expression): string { return $this->dbalExpressionBuilder->isNull($expression); } /** * Creates an IS NOT NULL expression with the given arguments. * * @param string $expression the expression to be restricted by IS NOT NULL * * @example * method : isNotNull('field1') * return : "field1 IS NOT NULL" */ public function isNotNull(string $expression): string { return $this->dbalExpressionBuilder->isNotNull($expression); } /** * Creates a LIKE comparison expression. * * @param string $expression The expression to be inspected by the LIKE comparison * @param string $pattern The pattern to compare against * @param string|null $escapeChar To indicate the escape character, by default it's '\' (optional) * * @example * method : like('field1', ':value1') * return : "field1 LIKE :value1" * method : like('field1', ':value1','$') * return : "field1 LIKE :value1" ESCAPE '$' */ public function like(string $expression, string $pattern, ?string $escapeChar = null): string { return $this->dbalExpressionBuilder->like($expression, $pattern, $escapeChar); } /** * Creates a NOT LIKE comparison expression. * * @param string $expression The expression to be inspected by the NOT LIKE comparison * @param string $pattern The pattern to compare against * @param string|null $escapeChar To indicate the escape character, by default it's '\' (optional) * * @example * method : notLike('field1', ':value1') * return : "field1 NOT LIKE :value1" * method : notLike('field1', ':value1','$') * return : "field1 NOT LIKE :value1" ESCAPE '$' */ public function notLike(string $expression, string $pattern, ?string $escapeChar = null): string { return $this->dbalExpressionBuilder->notLike($expression, $pattern, $escapeChar); } /** * Creates an IN () comparison expression with the given arguments. * * @param string $expressionToBeMatched the SQL expression to be matched against the set * @param string|string[] $set the SQL expression or an array of SQL expressions representing the set * * @example * method : in('field1', [:value1, :value2, :value3]) * return : "field1 IN (:value1, :value2, :value3)" */ public function in(string $expressionToBeMatched, string|array $set): string { return $this->dbalExpressionBuilder->in($expressionToBeMatched, $set); } /** * Creates a NOT IN () comparison expression with the given arguments. * * @param string $expressionToBeMatched the SQL expression to be matched against the set * @param string|string[] $set the SQL expression or an array of SQL expressions representing the set * * @example * method : notIn('field1', [:value1, :value2, :value3]) * return : "field1 NOT IN (:value1, :value2, :value3)" */ public function notIn(string $expressionToBeMatched, string|array $set): string { return $this->dbalExpressionBuilder->notIn($expressionToBeMatched, $set); } }
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/Exception/DatabaseException.php
centreon/src/Adaptation/Database/Exception/DatabaseException.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\Exception; use Core\Common\Domain\Exception\BusinessLogicException; /** * Class. * * @class DatabaseException */ abstract class DatabaseException extends BusinessLogicException { public const ERROR_CODE_DATABASE = 10; public const ERROR_CODE_DATABASE_TRANSACTION = 11; public const ERROR_CODE_UNBUFFERED_QUERY = 12; public const ERROR_CODE_QUERY_BUILDER = 20; public const ERROR_CODE_EXPRESSION_BUILDER = 30; }
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/QueryBuilder/QueryBuilderInterface.php
centreon/src/Adaptation/Database/QueryBuilder/QueryBuilderInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\QueryBuilder; use Adaptation\Database\ExpressionBuilder\ExpressionBuilderInterface; /** * Interface QueryBuilderInterface. * * @class QueryBuilderInterface */ interface QueryBuilderInterface { /** * To build where clauses easier. */ public function expr(): ExpressionBuilderInterface; /** * Gets the complete SQL string formed by the current specifications of this QueryBuilder. * * <code> * $qb = $db->createQueryBuilder() * ->select('u') * ->from('User', 'u') * echo $qb->getQuery(); // SELECT u FROM User u * </code> * * @return string the SQL query string */ public function getQuery(): string; /** * Specifies an item that is to be returned in the query result. * Replaces any previously specified selections, if any. * * <code> * $qb = $db->createQueryBuilder() * ->select('u.id', 'p.id') * ->from('users', 'u') * ->leftJoin('u', 'phonenumbers', 'p', 'u.id = p.user_id') * ->getQuery(); * </code> * * @param string ...$expressions The selection expressions. * * @return QueryBuilderInterface this QueryBuilder instance */ public function select(string ...$expressions): self; /** * Adds or removes DISTINCT to/from the query. * * <code> * $qb = $db->createQueryBuilder() * ->select('u.id') * ->distinct() * ->from('users', 'u') * ->getQuery(); * </code> * * @return QueryBuilderInterface this QueryBuilder instance */ public function distinct(): self; /** * Adds an item that is to be returned in the query result. * * <code> * $qb = $db->createQueryBuilder() * ->select('u.id') * ->addSelect('p.id') * ->from('users', 'u') * ->leftJoin('u', 'phonenumbers', 'u.id = p.user_id') * ->getQuery(); * </code> * * @param string $expression the selection expression * @param string ...$expressions Additional selection expressions. * * @return QueryBuilderInterface this QueryBuilder instance */ public function addSelect(string $expression, string ...$expressions): self; /** * Turns the query being built into a bulk delete query that ranges over * a certain table. * * <code> * $qb = $db->createQueryBuilder() * ->delete('users u') * ->where('u.id = :user_id') * ->setParameter(':user_id', 1) * ->getQuery(); * </code> * * @param string $table the table whose rows are subject to the deletion * * @return QueryBuilderInterface this QueryBuilder instance */ public function delete(string $table): self; /** * Turns the query being built into a bulk update query that ranges over * a certain table. * * <code> * $qb = $db->createQueryBuilder() * ->update('counters c') * ->set('c.value', 'c.value + 1') * ->where('c.id = ?') * ->getQuery(); * </code> * * @param string $table the table whose rows are subject to the update * * @return QueryBuilderInterface this QueryBuilder instance */ public function update(string $table): self; /** * Turns the query being built into an insert query that inserts into * a certain table. * * <code> * $qb = $db->createQueryBuilder() * ->insert('users') * ->values( * array( * 'name' => '?', * 'password' => '?' * ) * ) * ->getQuery(); * </code> * * @param string $table the table into which the rows should be inserted * * @return QueryBuilderInterface this QueryBuilder instance */ public function insert(string $table): self; /** * Creates and adds a query root corresponding to the table identified by the * given alias, forming a cartesian product with any existing query roots. * * <code> * $qb = $db->createQueryBuilder() * ->select('u.id') * ->from('users', 'u') * ->getQuery(); * </code> * * @param string $table the table * @param string|null $alias the alias of the table * * @return QueryBuilderInterface this QueryBuilder instance */ public function from(string $table, ?string $alias = null): self; /** * Creates and adds a join to the query. * * <code> * $qb = $db->createQueryBuilder() * ->select('u.name') * ->from('users', 'u') * ->join('u', 'phonenumbers', 'p', 'p.is_primary = 1') * ->getQuery(); * </code> * * @param string $fromAlias the alias that points to a from clause * @param string $join the table name to join * @param string $joinAlias the alias of the join table * @param string $condition the condition for the join * * @return QueryBuilderInterface this QueryBuilder instance */ public function join( string $fromAlias, string $join, string $joinAlias, string $condition, ): self; /** * Creates and adds a join to the query. * * <code> * $qb = $db->createQueryBuilder() * ->select('u.name') * ->from('users', 'u') * ->innerJoin('u', 'phonenumbers', 'p', 'p.is_primary = 1') * ->getQuery(); * </code> * * @param string $fromAlias the alias that points to a from clause * @param string $join the table name to join * @param string $joinAlias the alias of the join table * @param string $condition the condition for the join * * @return QueryBuilderInterface this QueryBuilder instance */ public function innerJoin( string $fromAlias, string $join, string $joinAlias, string $condition, ): self; /** * Creates and adds a left join to the query. * * <code> * $qb = $db->createQueryBuilder() * ->select('u.name') * ->from('users', 'u') * ->leftJoin('u', 'phonenumbers', 'p', 'p.is_primary = 1') * ->getQuery(); * </code> * * @param string $fromAlias the alias that points to a from clause * @param string $join the table name to join * @param string $joinAlias the alias of the join table * @param string $condition the condition for the join * * @return QueryBuilderInterface this QueryBuilder instance */ public function leftJoin( string $fromAlias, string $join, string $joinAlias, string $condition, ): self; /** * Creates and adds a right join to the query. * * <code> * $qb = $db->createQueryBuilder() * ->select('u.name') * ->from('users', 'u') * ->rightJoin('u', 'phonenumbers', 'p', 'p.is_primary = 1') * ->getQuery(); * </code> * * @param string $fromAlias the alias that points to a from clause * @param string $join the table name to join * @param string $joinAlias the alias of the join table * @param string $condition the condition for the join * * @return QueryBuilderInterface this QueryBuilder instance */ public function rightJoin( string $fromAlias, string $join, string $joinAlias, string $condition, ): self; /** * Sets a new value for a column in a bulk update query. * * <code> * $qb = $db->createQueryBuilder() * ->update('counters c') * ->set('c.value', 'c.value + 1') * ->where('c.id = ?') * ->getQuery(); * </code> * * @param string $column the column to set * @param string $value the value, expression, placeholder, etc * * @return QueryBuilderInterface this QueryBuilder instance */ public function set(string $column, string $value): self; /** * Specifies one or more restrictions to the query result. * Replaces any previously specified restrictions, if any. * * Use {@see ExpressionBuilderInterface} to build the where clause expression * * <code> * $qb = $db->createQueryBuilder() * ->select('c.value') * ->from('counters', 'c') * ->where('c.id = ?') * ->getQuery(); * * // You can optionally programmatically build and/or expressions * $qb = $db->createQueryBuilder(); * * $expr = $db->createExpressionBuilder(); * $eq1 = $expr->equal('c.id', 1); * $eq2 = $expr->equal('c.id', 2); * $or = $expr->or($eq1, $eq2); * * $qb->update('counters c') * ->set('c.value', 'c.value + 1') * ->where($or) * ->getQuery(); * </code> * * @param string $whereClauseExpression the WHERE clause predicate * @param string ...$whereClauseExpressions Additional WHERE clause predicates. * * @return QueryBuilderInterface this QueryBuilder instance */ public function where(string $whereClauseExpression, string ...$whereClauseExpressions): self; /** * Adds one or more restrictions to the query results, forming a logical * conjunction with any previously specified restrictions. * * Use {@see ExpressionBuilderInterface} to build the where clause expression * * <code> * $qb = $db->createQueryBuilder() * ->select('u') * ->from('users', 'u') * ->where('u.username LIKE ?') * ->andWhere('u.is_active = 1') * ->getQuery(); * </code> * * @param string $whereClauseExpression the predicate to append * @param string ...$whereClauseExpressions Additional predicates to append. * * @return QueryBuilderInterface this QueryBuilder instance * * @see where() */ public function andWhere(string $whereClauseExpression, string ...$whereClauseExpressions): self; /** * Adds one or more restrictions to the query results, forming a logical * disjunction with any previously specified restrictions. * * Use {@see ExpressionBuilderInterface} to build the where clause expression * * @param string $whereClauseExpression the predicate to append * @param string ...$whereClauseExpressions Additional predicates to append. * * @return QueryBuilderInterface this QueryBuilder instance * * @see where() * * <code> * $qb = $db->createQueryBuilder() * ->select('u.name') * ->from('users', 'u') * ->where('u.id = 1') * ->orWhere('u.id = 2') * ->getQuery(); * </code> */ public function orWhere(string $whereClauseExpression, string ...$whereClauseExpressions): self; /** * Specifies one or more grouping expressions over the results of the query. * Replaces any previously specified groupings, if any. * * <code> * $qb = $db->createQueryBuilder() * ->select('u.name') * ->from('users', 'u') * ->groupBy('u.id'); * </code> * * @param string $expression The grouping expression * @param string ...$expressions Additional grouping expressions * * @return QueryBuilderInterface this QueryBuilder instance */ public function groupBy(string $expression, string ...$expressions): self; /** * Adds one or more grouping expressions to the query. * * <code> * $qb = $db->createQueryBuilder() * ->select('u.name') * ->from('users', 'u') * ->groupBy('u.lastLogin') * ->addGroupBy('u.createdAt') * ->getQuery(); * </code> * * @param string $expression The grouping expression * @param string ...$expressions Additional grouping expressions * * @return QueryBuilderInterface this QueryBuilder instance */ public function addGroupBy(string $expression, string ...$expressions): self; /** * Specifies values for an insert query indexed by column names. * Replaces any previous values, if any. * * <code> * $qb = $db->createQueryBuilder() * ->insert('users') * ->values( * array( * 'name' => '?', * 'password' => '?' * ) * ) * ->getQuery(); * </code> * * @param array<string, mixed> $values the values to specify for the insert query indexed by column names * * @return QueryBuilderInterface this QueryBuilder instance */ public function values(array $values): self; /** * Sets a value for a column in an insert query. * * <code> * $qb = $db->createQueryBuilder() * ->insert('users') * ->values( * array( * 'name' => '?' * ) * ) * ->setValue('password', '?') * ->getQuery(); * </code> * * @param string $column the column into which the value should be inserted * @param string $value the value that should be inserted into the column * * @return QueryBuilderInterface this QueryBuilder instance */ public function setValue(string $column, string $value): self; /** * Specifies a restriction over the groups of the query. * Replaces any previous having restrictions, if any. * * Use {@see ExpressionBuilderInterface} to build the having clause expression * * @param string $havingClause the HAVING clause predicate * @param string ...$havingClauses Additional HAVING clause predicates. * * @return QueryBuilderInterface this QueryBuilder instance */ public function having(string $havingClause, string ...$havingClauses): self; /** * Adds a restriction over the groups of the query, forming a logical * conjunction with any existing having restrictions. * * Use {@see ExpressionBuilderInterface} to build the having clause expression * * @param string $havingClause the predicate to append * @param string ...$havingClauses Additional predicates to append. * * @return QueryBuilderInterface this QueryBuilder instance */ public function andHaving(string $havingClause, string ...$havingClauses): self; /** * Adds a restriction over the groups of the query, forming a logical * disjunction with any existing having restrictions. * * Use {@see ExpressionBuilderInterface} to build the having clause expression * * @param string $havingClause the predicate to append * @param string ...$havingClauses Additional predicates to append. * * @return QueryBuilderInterface this QueryBuilder instance */ public function orHaving(string $havingClause, string ...$havingClauses): self; /** * Specifies an ordering for the query results. * Replaces any previously specified orderings, if any. * * @param string $sort the ordering expression * @param string|null $order the ordering direction * * @return QueryBuilderInterface this QueryBuilder instance */ public function orderBy(string $sort, ?string $order = null): self; /** * Adds an ordering to the query results. * * @param string $sort the ordering expression * @param string|null $order the ordering direction * * @return QueryBuilderInterface this QueryBuilder instance */ public function addOrderBy(string $sort, ?string $order = null): self; public function limit(int $limit): self; public function offset(int $offset): self; /** * Resets the WHERE conditions for the query. * * @return QueryBuilderInterface this QueryBuilder instance */ public function resetWhere(): self; /** * Resets the grouping for the query. * * @return QueryBuilderInterface this QueryBuilder instance */ public function resetGroupBy(): self; /** * Resets the HAVING conditions for the query. * * @return QueryBuilderInterface this QueryBuilder instance */ public function resetHaving(): self; /** * Resets the ordering for the query. * * @return QueryBuilderInterface this QueryBuilder instance */ public function resetOrderBy(): self; /** * Resets the limit for the query. * * @return QueryBuilderInterface this QueryBuilder instance */ public function resetLimit(): self; }
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/QueryBuilder/Exception/QueryBuilderException.php
centreon/src/Adaptation/Database/QueryBuilder/Exception/QueryBuilderException.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\QueryBuilder\Exception; use Adaptation\Database\Exception\DatabaseException; /** * Class. * * @class QueryBuilderException */ class QueryBuilderException extends DatabaseException { public static function createFromConnectionConfigFailed(?\Throwable $previous = null): self { $message = 'Error while instantiate the query builder'; if ($previous instanceof \Throwable && ! empty($previous->getMessage())) { $message .= " : {$previous->getMessage()}"; } return new self($message, self::ERROR_CODE_QUERY_BUILDER, previous: $previous); } public static function getExpressionBuilderFailed(?\Throwable $previous = null): self { $message = 'Error while getting the expression builder'; if ($previous instanceof \Throwable && ! empty($previous->getMessage())) { $message .= " : {$previous->getMessage()}"; } return new self($message, self::ERROR_CODE_QUERY_BUILDER, 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/QueryBuilder/Adapter/Dbal/DbalQueryBuilderAdapter.php
centreon/src/Adaptation/Database/QueryBuilder/Adapter/Dbal/DbalQueryBuilderAdapter.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\QueryBuilder\Adapter\Dbal; use Adaptation\Database\Connection\Adapter\Dbal\DbalConnectionAdapter; use Adaptation\Database\Connection\Exception\ConnectionException; use Adaptation\Database\Connection\Model\ConnectionConfig; use Adaptation\Database\ExpressionBuilder\Adapter\Dbal\DbalExpressionBuilderAdapter; use Adaptation\Database\ExpressionBuilder\Exception\ExpressionBuilderException; use Adaptation\Database\ExpressionBuilder\ExpressionBuilderInterface; use Adaptation\Database\QueryBuilder\Exception\QueryBuilderException; use Adaptation\Database\QueryBuilder\QueryBuilderInterface; use Centreon\Domain\Log\Logger; use Doctrine\DBAL\Query\QueryBuilder as DoctrineDbalQueryBuilder; /** * Class. * * @class DbalQueryBuilderAdapter * * @see DoctrineDbalQueryBuilder * * To dynamically create SQL queries. */ final readonly class DbalQueryBuilderAdapter implements QueryBuilderInterface { /** * DbalQueryBuilderAdapter constructor. */ public function __construct( private DoctrineDbalQueryBuilder $dbalQueryBuilder, private ConnectionConfig $connectionConfig, ) { } /** * Factory. * * Creates a new instance of a SQL query builder. * * We have to use a connection configuration to instantiate the query builder because the query builder needs a * connection to work. * * @throws QueryBuilderException * * @return DbalQueryBuilderAdapter */ public static function createFromConnectionConfig(ConnectionConfig $connectionConfig): QueryBuilderInterface { try { $connection = DbalConnectionAdapter::createFromConfig($connectionConfig); return new self(new DoctrineDbalQueryBuilder($connection->getDbalConnection()), $connectionConfig); } catch (ConnectionException $exception) { Logger::create()->error( 'An error occurred while trying to create a new instance of query builder', ['exception' => $exception->getContext()] ); throw QueryBuilderException::createFromConnectionConfigFailed($exception); } } /** * To build where clauses easier. * * @throws QueryBuilderException * * @return DbalExpressionBuilderAdapter */ public function expr(): ExpressionBuilderInterface { try { return DbalExpressionBuilderAdapter::createFromConnectionConfig($this->connectionConfig); } catch (ExpressionBuilderException $exception) { Logger::create()->error( 'An error occurred while trying to create a new instance of expression builder', ['exception' => $exception->getContext()] ); throw QueryBuilderException::getExpressionBuilderFailed($exception); } } /** * Gets the complete SQL string formed by the current specifications of this QueryBuilder. * * <code> * $qb = $db->createQueryBuilder() * ->select('u') * ->from('User', 'u') * echo $qb->getQuery(); // SELECT u FROM User u * </code> * * @return string the SQL query string */ public function getQuery(): string { return $this->dbalQueryBuilder->getSQL(); } /** * Specifies an item that is to be returned in the query result. * Replaces any previously specified selections, if any. * * <code> * $qb = $db->createQueryBuilder() * ->select('u.id', 'p.id') * ->from('users', 'u') * ->leftJoin('u', 'phonenumbers', 'p', 'u.id = p.user_id') * ->getQuery(); * </code> * * @param string ...$expressions The selection expressions. * * @return DbalQueryBuilderAdapter this QueryBuilder instance */ public function select(string ...$expressions): QueryBuilderInterface { $this->dbalQueryBuilder->select(...$expressions); return $this; } /** * Adds or removes DISTINCT to/from the query. * * <code> * $qb = $db->createQueryBuilder() * ->select('u.id') * ->distinct() * ->from('users', 'u') * ->getQuery(); * </code> * * @return DbalQueryBuilderAdapter this QueryBuilder instance */ public function distinct(): QueryBuilderInterface { $this->dbalQueryBuilder->distinct(); return $this; } /** * Adds an item that is to be returned in the query result. * * <code> * $qb = $db->createQueryBuilder() * ->select('u.id') * ->addSelect('p.id') * ->from('users', 'u') * ->leftJoin('u', 'phonenumbers', 'u.id = p.user_id') * ->getQuery(); * </code> * * @param string $expression the selection expression * @param string ...$expressions Additional selection expressions. * * @return DbalQueryBuilderAdapter this QueryBuilder instance */ public function addSelect(string $expression, string ...$expressions): QueryBuilderInterface { $this->dbalQueryBuilder->addSelect($expression, ...$expressions); return $this; } /** * Turns the query being built into a bulk delete query that ranges over * a certain table. * * <code> * $qb = $db->createQueryBuilder() * ->delete('users u') * ->where('u.id = :user_id') * ->setParameter(':user_id', 1) * ->getQuery(); * </code> * * @param string $table the table whose rows are subject to the deletion * * @return DbalQueryBuilderAdapter this QueryBuilder instance */ public function delete(string $table): QueryBuilderInterface { $this->dbalQueryBuilder->delete($table); return $this; } /** * Turns the query being built into a bulk update query that ranges over * a certain table. * * <code> * $qb = $db->createQueryBuilder() * ->update('counters c') * ->set('c.value', 'c.value + 1') * ->where('c.id = ?') * ->getQuery(); * </code> * * @param string $table the table whose rows are subject to the update * * @return DbalQueryBuilderAdapter this QueryBuilder instance */ public function update(string $table): QueryBuilderInterface { $this->dbalQueryBuilder->update($table); return $this; } /** * Turns the query being built into an insert query that inserts into * a certain table. * * <code> * $qb = $db->createQueryBuilder() * ->insert('users') * ->values( * array( * 'name' => '?', * 'password' => '?' * ) * ) * ->getQuery(); * </code> * * @param string $table the table into which the rows should be inserted * * @return DbalQueryBuilderAdapter this QueryBuilder instance */ public function insert(string $table): QueryBuilderInterface { $this->dbalQueryBuilder->insert($table); return $this; } /** * Creates and adds a query root corresponding to the table identified by the * given alias, forming a cartesian product with any existing query roots. * * <code> * $qb = $db->createQueryBuilder() * ->select('u.id') * ->from('users', 'u') * ->getQuery(); * </code> * * @param string $table the table * @param string|null $alias the alias of the table * * @return DbalQueryBuilderAdapter this QueryBuilder instance */ public function from(string $table, ?string $alias = null): QueryBuilderInterface { $this->dbalQueryBuilder->from($table, $alias); return $this; } /** * Creates and adds a join to the query. * * <code> * $qb = $db->createQueryBuilder() * ->select('u.name') * ->from('users', 'u') * ->join('u', 'phonenumbers', 'p', 'p.is_primary = 1') * ->getQuery(); * </code> * * @param string $fromAlias the alias that points to a from clause * @param string $join the table name to join * @param string $joinAlias the alias of the join table * @param string $condition the condition for the join * * @return DbalQueryBuilderAdapter this QueryBuilder instance */ public function join( string $fromAlias, string $join, string $joinAlias, string $condition, ): QueryBuilderInterface { $this->dbalQueryBuilder->join($fromAlias, $join, $joinAlias, $condition); return $this; } /** * Creates and adds a join to the query. * * <code> * $qb = $db->createQueryBuilder() * ->select('u.name') * ->from('users', 'u') * ->innerJoin('u', 'phonenumbers', 'p', 'p.is_primary = 1') * ->getQuery(); * </code> * * @param string $fromAlias the alias that points to a from clause * @param string $join the table name to join * @param string $joinAlias the alias of the join table * @param string $condition the condition for the join * * @return DbalQueryBuilderAdapter this QueryBuilder instance */ public function innerJoin( string $fromAlias, string $join, string $joinAlias, string $condition, ): QueryBuilderInterface { $this->dbalQueryBuilder->innerJoin($fromAlias, $join, $joinAlias, $condition); return $this; } /** * Creates and adds a left join to the query. * * <code> * $qb = $db->createQueryBuilder() * ->select('u.name') * ->from('users', 'u') * ->leftJoin('u', 'phonenumbers', 'p', 'p.is_primary = 1') * ->getQuery(); * </code> * * @param string $fromAlias the alias that points to a from clause * @param string $join the table name to join * @param string $joinAlias the alias of the join table * @param string $condition the condition for the join * * @return DbalQueryBuilderAdapter this QueryBuilder instance */ public function leftJoin( string $fromAlias, string $join, string $joinAlias, string $condition, ): QueryBuilderInterface { $this->dbalQueryBuilder->leftJoin($fromAlias, $join, $joinAlias, $condition); return $this; } /** * Creates and adds a right join to the query. * * <code> * $qb = $db->createQueryBuilder() * ->select('u.name') * ->from('users', 'u') * ->rightJoin('u', 'phonenumbers', 'p', 'p.is_primary = 1') * ->getQuery(); * </code> * * @param string $fromAlias the alias that points to a from clause * @param string $join the table name to join * @param string $joinAlias the alias of the join table * @param string $condition the condition for the join * * @return DbalQueryBuilderAdapter this QueryBuilder instance */ public function rightJoin( string $fromAlias, string $join, string $joinAlias, string $condition, ): QueryBuilderInterface { $this->dbalQueryBuilder->rightJoin($fromAlias, $join, $joinAlias, $condition); return $this; } /** * Sets a new value for a column in a bulk update query. * * <code> * $qb = $db->createQueryBuilder() * ->update('counters c') * ->set('c.value', 'c.value + 1') * ->where('c.id = ?') * ->getQuery(); * </code> * * @param string $column the column to set * @param string $value the value, expression, placeholder, etc * * @return DbalQueryBuilderAdapter this QueryBuilder instance */ public function set(string $column, string $value): QueryBuilderInterface { $this->dbalQueryBuilder->set($column, $value); return $this; } /** * Specifies one or more restrictions to the query result. * Replaces any previously specified restrictions, if any. * * Use {@see DbalExpressionBuilderAdapter} to build the where clause expression * * <code> * $qb = $db->createQueryBuilder() * ->select('c.value') * ->from('counters', 'c') * ->where('c.id = ?') * ->getQuery(); * * // You can optionally programmatically build and/or expressions * $qb = $db->createQueryBuilder(); * * $expr = $db->createExpressionBuilder(); * $eq1 = $expr->equal('c.id', 1); * $eq2 = $expr->equal('c.id', 2); * $or = $expr->or($eq1, $eq2); * * $qb->update('counters c') * ->set('c.value', 'c.value + 1') * ->where($or) * ->getQuery(); * </code> * * @param string $whereClauseExpression the WHERE clause predicate * @param string ...$whereClauseExpressions Additional WHERE clause predicates. * * @return DbalQueryBuilderAdapter this QueryBuilder instance */ public function where(string $whereClauseExpression, string ...$whereClauseExpressions): QueryBuilderInterface { $this->dbalQueryBuilder->where($whereClauseExpression, ...$whereClauseExpressions); return $this; } /** * Adds one or more restrictions to the query results, forming a logical * conjunction with any previously specified restrictions. * * Use {@see DbalExpressionBuilderAdapter} to build the where clause expression * * <code> * $qb = $db->createQueryBuilder() * ->select('u') * ->from('users', 'u') * ->where('u.username LIKE ?') * ->andWhere('u.is_active = 1') * ->getQuery(); * </code> * * @param string $whereClauseExpression the predicate to append * @param string ...$whereClauseExpressions Additional predicates to append. * * @return DbalQueryBuilderAdapter this QueryBuilder instance * * @see where() */ public function andWhere(string $whereClauseExpression, string ...$whereClauseExpressions): QueryBuilderInterface { $this->dbalQueryBuilder->andWhere($whereClauseExpression, ...$whereClauseExpressions); return $this; } /** * Adds one or more restrictions to the query results, forming a logical * disjunction with any previously specified restrictions. * * Use {@see DbalExpressionBuilderAdapter} to build the where clause expression * * @param string $whereClauseExpression the predicate to append * @param string ...$whereClauseExpressions Additional predicates to append. * * @return DbalQueryBuilderAdapter this QueryBuilder instance * * @see where() * * <code> * $qb = $em->createQueryBuilder() * ->select('u.name') * ->from('users', 'u') * ->where('u.id = 1') * ->orWhere('u.id = 2') * ->getQuery(); * </code> */ public function orWhere(string $whereClauseExpression, string ...$whereClauseExpressions): QueryBuilderInterface { $this->dbalQueryBuilder->orWhere($whereClauseExpression, ...$whereClauseExpressions); return $this; } /** * Specifies one or more grouping expressions over the results of the query. * Replaces any previously specified groupings, if any. * * <code> * $qb = $db->createQueryBuilder() * ->select('u.name') * ->from('users', 'u') * ->groupBy('u.id') * ->getQuery(); * </code> * * @param string $expression The grouping expression * @param string ...$expressions Additional grouping expressions * * @return DbalQueryBuilderAdapter this QueryBuilder instance */ public function groupBy(string $expression, string ...$expressions): QueryBuilderInterface { $this->dbalQueryBuilder->groupBy($expression, ...$expressions); return $this; } /** * Adds one or more grouping expressions to the query. * * <code> * $qb = $db->createQueryBuilder() * ->select('u.name') * ->from('users', 'u') * ->groupBy('u.lastLogin') * ->addGroupBy('u.createdAt') * ->getQuery(); * </code> * * @param string $expression The grouping expression * @param string ...$expressions Additional grouping expressions * * @return DbalQueryBuilderAdapter this QueryBuilder instance */ public function addGroupBy(string $expression, string ...$expressions): QueryBuilderInterface { $this->dbalQueryBuilder->addGroupBy($expression, ...$expressions); return $this; } /** * Specifies values for an insert query indexed by column names. * Replaces any previous values, if any. * * <code> * $qb = $db->createQueryBuilder() * ->insert('users') * ->values( * array( * 'name' => '?', * 'password' => '?' * ) * ) * ->getQuery(); * </code> * * @param array<string, mixed> $values the values to specify for the insert query indexed by column names * * @return DbalQueryBuilderAdapter this QueryBuilder instance */ public function values(array $values): QueryBuilderInterface { $this->dbalQueryBuilder->values($values); return $this; } /** * Sets a value for a column in an insert query. * * <code> * $qb = $db->createQueryBuilder() * ->insert('users') * ->values( * array( * 'name' => '?' * ) * ) * ->setValue('password', '?') * ->getQuery(); * </code> * * @param string $column the column into which the value should be inserted * @param string $value the value that should be inserted into the column * * @return DbalQueryBuilderAdapter this QueryBuilder instance */ public function setValue(string $column, string $value): QueryBuilderInterface { $this->dbalQueryBuilder->setValue($column, $value); return $this; } /** * Specifies a restriction over the groups of the query. * Replaces any previous having restrictions, if any. * * Use {@see DbalExpressionBuilderAdapter} to build the having clause expression * * @param string $havingClause the HAVING clause predicate * @param string ...$havingClauses Additional HAVING clause predicates. * * @return DbalQueryBuilderAdapter this QueryBuilder instance */ public function having(string $havingClause, string ...$havingClauses): QueryBuilderInterface { $this->dbalQueryBuilder->having($havingClause, ...$havingClauses); return $this; } /** * Adds a restriction over the groups of the query, forming a logical * conjunction with any existing having restrictions. * * Use {@see DbalExpressionBuilderAdapter} to build the having clause expression * * @param string $havingClause the predicate to append * @param string ...$havingClauses Additional predicates to append. * * @return DbalQueryBuilderAdapter this QueryBuilder instance */ public function andHaving(string $havingClause, string ...$havingClauses): QueryBuilderInterface { $this->dbalQueryBuilder->andHaving($havingClause, ...$havingClauses); return $this; } /** * Adds a restriction over the groups of the query, forming a logical * disjunction with any existing having restrictions. * * Use {@see DbalExpressionBuilderAdapter} to build the having clause expression * * @param string $havingClause the predicate to append * @param string ...$havingClauses Additional predicates to append. * * @return DbalQueryBuilderAdapter this QueryBuilder instance */ public function orHaving(string $havingClause, string ...$havingClauses): QueryBuilderInterface { $this->dbalQueryBuilder->orHaving($havingClause, ...$havingClauses); return $this; } /** * Specifies an ordering for the query results. * Replaces any previously specified orderings, if any. * * @param string $sort the ordering expression * @param string|null $order the ordering direction * * @return DbalQueryBuilderAdapter this QueryBuilder instance */ public function orderBy(string $sort, ?string $order = null): QueryBuilderInterface { $this->dbalQueryBuilder->orderBy($sort, $order); return $this; } /** * Adds an ordering to the query results. * * @param string $sort the ordering expression * @param string|null $order the ordering direction * * @return DbalQueryBuilderAdapter this QueryBuilder instance */ public function addOrderBy(string $sort, ?string $order = null): QueryBuilderInterface { $this->dbalQueryBuilder->addOrderBy($sort, $order); return $this; } /** * @return DbalQueryBuilderAdapter */ public function limit(int $limit): QueryBuilderInterface { $this->dbalQueryBuilder->setMaxResults($limit); return $this; } /** * @return DbalQueryBuilderAdapter */ public function offset(int $offset): QueryBuilderInterface { $this->dbalQueryBuilder->setFirstResult($offset); return $this; } /** * Resets the WHERE conditions for the query. * * @return DbalQueryBuilderAdapter this QueryBuilder instance */ public function resetWhere(): QueryBuilderInterface { $this->dbalQueryBuilder->resetWhere(); return $this; } /** * Resets the grouping for the query. * * @return DbalQueryBuilderAdapter this QueryBuilder instance */ public function resetGroupBy(): QueryBuilderInterface { $this->dbalQueryBuilder->resetGroupBy(); return $this; } /** * Resets the HAVING conditions for the query. * * @return DbalQueryBuilderAdapter this QueryBuilder instance */ public function resetHaving(): QueryBuilderInterface { $this->dbalQueryBuilder->resetHaving(); return $this; } /** * Resets the ordering for the query. * * @return DbalQueryBuilderAdapter this QueryBuilder instance */ public function resetOrderBy(): QueryBuilderInterface { $this->dbalQueryBuilder->resetOrderBy(); return $this; } /** * Resets the limit for the query. * * @return DbalQueryBuilderAdapter this QueryBuilder instance */ public function resetLimit(): QueryBuilderInterface { $this->dbalQueryBuilder->setMaxResults(null); return $this; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Adaptation/Database/Connection/ConnectionInterface.php
centreon/src/Adaptation/Database/Connection/ConnectionInterface.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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; use Adaptation\Database\Connection\Collection\BatchInsertParameters; use Adaptation\Database\Connection\Collection\QueryParameters; use Adaptation\Database\Connection\Enum\ConnectionDriverEnum; use Adaptation\Database\Connection\Exception\ConnectionException; use Adaptation\Database\Connection\Model\ConnectionConfig; use Adaptation\Database\ExpressionBuilder\Exception\ExpressionBuilderException; use Adaptation\Database\ExpressionBuilder\ExpressionBuilderInterface; use Adaptation\Database\QueryBuilder\Exception\QueryBuilderException; use Adaptation\Database\QueryBuilder\QueryBuilderInterface; /** * Interface. * * @class ConnectionInterface */ interface ConnectionInterface { /** * The list of drivers that allow the use of unbuffered queries. */ public const DRIVER_ALLOWED_UNBUFFERED_QUERY = [ ConnectionDriverEnum::DRIVER_PDO_MYSQL->value, ]; /** * Factory. * * @throws ConnectionException */ public static function createFromConfig(ConnectionConfig $connectionConfig): self; /** * To create an instance of the query builder. * * @throws QueryBuilderException */ public function createQueryBuilder(): QueryBuilderInterface; /** * To create an instance of the expression builder. * * @throws ExpressionBuilderException */ public function createExpressionBuilder(): ExpressionBuilderInterface; public function getConnectionConfig(): ConnectionConfig; /** * Return the database name if it exists. * * @throws ConnectionException */ public function getDatabaseName(): ?string; /** * To get the used native connection by DBAL (PDO, mysqli, ...). * * @throws ConnectionException * * @return object|resource */ public function getNativeConnection(): mixed; /** * 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; /** * Check if a connection with the database exist. */ public function isConnected(): bool; /** * The usage of this method is discouraged. Use prepared statements. */ public function quoteString(string $value): string; // ----------------------------------------- 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 */ 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; /** * 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; /** * 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; /** * 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; // --------------------------------------- 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; /** * 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; /** * 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; /** * 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; /** * 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; /** * 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; /** * 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; /** * 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; // --------------------------------------- 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; /** * 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; /** * 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,list<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; /** * 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; /** * 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; // ----------------------------------------- TRANSACTIONS ----------------------------------------- /** * Checks whether a transaction is currently active. * * @return bool TRUE if a transaction is currently active, FALSE otherwise */ public function isTransactionActive(): bool; /** * Opens a new transaction. This must be closed by calling one of the following methods: * {@see commitTransaction} or {@see rollBackTransaction} * * @throws ConnectionException */ public function startTransaction(): void; /** * To validate a transaction. * * @throws ConnectionException */ public function commitTransaction(): bool; /** * To cancel a transaction. * * @throws ConnectionException */ public function rollBackTransaction(): bool; // ------------------------------------- UNBUFFERED QUERIES ----------------------------------------- /** * Checks that the connection instance allows the use of unbuffered queries. * * @throws ConnectionException */ public function allowUnbufferedQuery(): bool; /** * Prepares a statement to execute a query without buffering. Only works for SELECT queries. * * @throws ConnectionException */ public function startUnbufferedQuery(): void; /** * Checks whether an unbuffered query is currently active. */ public function isUnbufferedQueryActive(): bool; /** * To close an unbuffered query. * * @throws ConnectionException */ public function stopUnbufferedQuery(): void; // --------------------------------------- DDL TOOLS ----------------------------------------------- /** * Check if a column exists in a table. * * @throws ConnectionException */ public function columnExists(string $dbName, string $tableName, string $columnName): bool; }
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/Model/ConnectionConfig.php
centreon/src/Adaptation/Database/Connection/Model/ConnectionConfig.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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\Model; use Adaptation\Database\Connection\Enum\ConnectionDriverEnum; /** * Class. * * @class ConnectionConfig */ final readonly class ConnectionConfig { /** * ConnectionConfig constructor. * * @param string $databaseNameConfiguration Configuration database name of Centreon * @param string $databaseNameRealTime Real time database name of Centreon */ public function __construct( private string $host, private string $user, private string $password, private string $databaseNameConfiguration, private string $databaseNameRealTime, private int $port = 3306, private string $charset = 'utf8mb4', private ConnectionDriverEnum $driver = ConnectionDriverEnum::DRIVER_PDO_MYSQL, ) { } public function getHost(): string { return $this->host; } public function getUser(): string { return $this->user; } public function getPassword(): string { return $this->password; } public function getDatabaseNameConfiguration(): string { return $this->databaseNameConfiguration; } public function getDatabaseNameRealTime(): string { return $this->databaseNameRealTime; } public function getPort(): int { return $this->port; } public function getCharset(): string { return $this->charset; } public function getDriver(): ConnectionDriverEnum { return $this->driver; } public function getMysqlDsn(): string { return sprintf( 'mysql:dbname=%s;host=%s;port=%s;charset=%s', $this->getDatabaseNameConfiguration(), $this->getHost(), $this->getPort(), $this->getCharset() ); } public function getOracleDsn(): string { return sprintf( 'oci:dbname=//%s:%s/%s', $this->getHost(), $this->getPort(), $this->getDatabaseNameConfiguration() ); } public function getPgsqlDsn(): string { return sprintf( 'pgsql:host=%s;port=%s;dbname=%s;user=%s;password=%s', $this->getHost(), $this->getPort(), $this->getDatabaseNameConfiguration(), $this->getUser(), $this->getPassword(), ); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false