From 4de8b7d8142c28dfb22cabb412e9bbdcec61500b Mon Sep 17 00:00:00 2001 From: Charles Gautier <33026375+chgautier@users.noreply.github.com> Date: Thu, 25 Aug 2022 17:35:04 +0200 Subject: [PATCH 1/7] Merge release-22.04.3 into 22.04.x (#11623) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(git): resync 22.04.x to dev-22.04.x (#11503) * [SNYK] Sanitize and bind ACL host dependency queries (#11389) (#11394) * Sanitize and bind ACL host dependency queries * fix issues * removed old variable userCrypted and the use of it (#11334) (#11352) Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> * enh(Header/userMenu):reduce spacing user menu (#11393) * update user menu * fix(hostgroup): fix display of hostgroups in select2 (#11431) (#11443) * fix(ci): fix debian packaging with freshly instanciated jenkins slave (#11398) (#11399) Refs: MON-14377 * Sanitized and bound queries (#11413) (#11445) lines : 130 -142 * Snyk: Sanitize and bind media sync queries 22.04.x (#11418) * sanitizing and binding sync dir file queries * Applying some fixes * Snyk: Sanitize and bind ACL service dependency queries dev-22.04.x (#11395) * Snyk: Sanitize and bind Auth class queries 22.04.x (#11448) * [Backport/need review] fix(UI): Fix layout for Safari and form validation (#11440) * fix(UI): Fix layout for Safari and form validation (#11373) * Fix form validation * Fix padlock layout for safari * Update centreon-frontend * Remove debug variable * Fix test * Fix page respsoniveness * Rename variable * update deps * Fix package-lock * Fix package-lock * Add debug statement for debian * Install nodejs rather npm * Attempt fix * Attempt to fix nodejs installation * add sudo * Fix redoc-cli usage * Try to fix permission on npm * Fix * Fix permission * Fix permission (please work) * Fix source * Stop using npx because..... * Allow legacy-peer-deps * Remove nodejs installation * Fix image to pull for debian 11 * [SNYK] Sanitize and bind centreonGraph class queries (#11409) (#11421) 1122 1153 1134 * [Snyk] Sanitize and bind ACL action access queries (#11385) (#11402) * Sanitize and bind ACL action access queries _ sanitize if possible each variables inserted in a query _ use PDO prepared statement and bind() method _ Do not use $pearDB->escape on which is for examples useless on integers and on non closed HTML tags (svg, img, etc) * fix line length * fix failed checks * feat(api): implement endpoint to update centreon web (#11391) (#11401) Refs: MON-12296 * Clean(platform): Clean appKey method and usage 22.04.x (#11452) * Clean(platform): Clean appKey method and usage (#11336) * removing appKey from information table in baseConf and 22.10 update script * removing appKey from NotifyMasterService.php * removing appKey from CentreonRemoteServer.php * applying suggested changes * Applying suggested changes Co-authored-by: Kevin Duret * adding 22.04.2 update script file with changes * revert 22.04 beta 1 script to its original Co-authored-by: Kevin Duret * enh(platform): Use API to select metrics in virtual metrics configuration form 22.04.x (#11461) * changing select with select2 of metrics * fix alignement * remove unecessary files and replace selec by select2 in formComponentTemplate * fix select id name for acceptance tests * update composer for acceptance tests * fix acceptance test 2 * add allow clear to metrics select2 * applying suggested changes * final changes for merging * remove unecessary select tag * [SNYK] Sanitize and bind ACL class queries (#11392) (#11472) * Sanitize and bind ACL class queries Queries sanitized and bound using PDO statement * fix spaces spaces between (int) cast and variables * update file delete spaces after comma * change variables names due to a review * Line exceeds 120 characters; contains 123 characters * fix(conf) fix broker conf name display in listing (#11372) (#11376) Co-authored-by: Elmahdi ABBASSI <108519266+emabassi-ext@users.noreply.github.com> Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> Co-authored-by: Nouha-ElAbrouki <97687698+Noha-ElAbrouki@users.noreply.github.com> Co-authored-by: Kevin Duret Co-authored-by: hyahiaoui-ext <97593234+hyahiaoui-ext@users.noreply.github.com> Co-authored-by: Tom Darneix Co-authored-by: alaunois * fix(cron): Escape database name in CentACL 22.04.x (#11510) * fix(test): wait 8s before checking downtime is active in rest api v1 test (#11498) (#11504) Refs: MON-14585 * fix(UI): Include host_id when selecting ServiceGroups on dashreports (#11428) (#11519) Co-authored-by: VHS Co-authored-by: VHS * fix(Resources/Graph): export graph image after selecting png (#11491) * [SNYK] Sanitize and bind ACL host dependency queries (#11389) (#11394) * Sanitize and bind ACL host dependency queries * fix issues * removed old variable userCrypted and the use of it (#11334) (#11352) Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> * enh(Header/userMenu):reduce spacing user menu (#11393) * update user menu * fix(hostgroup): fix display of hostgroups in select2 (#11431) (#11443) * fix(ci): fix debian packaging with freshly instanciated jenkins slave (#11398) (#11399) Refs: MON-14377 * Sanitized and bound queries (#11413) (#11445) lines : 130 -142 * Snyk: Sanitize and bind media sync queries 22.04.x (#11418) * sanitizing and binding sync dir file queries * Applying some fixes * Snyk: Sanitize and bind ACL service dependency queries dev-22.04.x (#11395) * Snyk: Sanitize and bind Auth class queries 22.04.x (#11448) * [Backport/need review] fix(UI): Fix layout for Safari and form validation (#11440) * fix(UI): Fix layout for Safari and form validation (#11373) * Fix form validation * Fix padlock layout for safari * Update centreon-frontend * Remove debug variable * Fix test * Fix page respsoniveness * Rename variable * update deps * Fix package-lock * Fix package-lock * Add debug statement for debian * Install nodejs rather npm * Attempt fix * Attempt to fix nodejs installation * add sudo * Fix redoc-cli usage * Try to fix permission on npm * Fix * Fix permission * Fix permission (please work) * Fix source * Stop using npx because..... * Allow legacy-peer-deps * Remove nodejs installation * Fix image to pull for debian 11 * [SNYK] Sanitize and bind centreonGraph class queries (#11409) (#11421) 1122 1153 1134 * [Snyk] Sanitize and bind ACL action access queries (#11385) (#11402) * Sanitize and bind ACL action access queries _ sanitize if possible each variables inserted in a query _ use PDO prepared statement and bind() method _ Do not use $pearDB->escape on which is for examples useless on integers and on non closed HTML tags (svg, img, etc) * fix line length * fix failed checks * feat(api): implement endpoint to update centreon web (#11391) (#11401) Refs: MON-12296 * Clean(platform): Clean appKey method and usage 22.04.x (#11452) * Clean(platform): Clean appKey method and usage (#11336) * removing appKey from information table in baseConf and 22.10 update script * removing appKey from NotifyMasterService.php * removing appKey from CentreonRemoteServer.php * applying suggested changes * Applying suggested changes Co-authored-by: Kevin Duret * adding 22.04.2 update script file with changes * revert 22.04 beta 1 script to its original Co-authored-by: Kevin Duret * enh(platform): Use API to select metrics in virtual metrics configuration form 22.04.x (#11461) * changing select with select2 of metrics * fix alignement * remove unecessary files and replace selec by select2 in formComponentTemplate * fix select id name for acceptance tests * update composer for acceptance tests * fix acceptance test 2 * add allow clear to metrics select2 * applying suggested changes * final changes for merging * remove unecessary select tag * [SNYK] Sanitize and bind ACL class queries (#11392) (#11472) * Sanitize and bind ACL class queries Queries sanitized and bound using PDO statement * fix spaces spaces between (int) cast and variables * update file delete spaces after comma * change variables names due to a review * Line exceeds 120 characters; contains 123 characters * fix(conf) fix broker conf name display in listing (#11372) (#11376) * fix export graph image after selecting png Co-authored-by: Elmahdi ABBASSI <108519266+emabassi-ext@users.noreply.github.com> Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> Co-authored-by: Kevin Duret Co-authored-by: hyahiaoui-ext <97593234+hyahiaoui-ext@users.noreply.github.com> Co-authored-by: Tom Darneix Co-authored-by: alaunois * Fix(platform): Removing appkey key (#11511) * fix(trap): Removal of the restriction on the uniqueness of the OID of a trap (#11327) Currently, an error appears when we try to save an existing trap because a test is performed on the uniqueness of the OID. This PR aims to remove the restriction on the uniqueness of the OID of a trap. * fix(pendo): correctly set locale when language is detection by browser (#11484) (#11528) * fix(test): fix random fails on virtual metric test (#11523) Refs: MON-14359 * fix(autoload): Add classmap to fix autoload with legacy classes (#11492) (#11532) Refs: MON-14496 * fix(ldap): small refacto of ldap authentication and log failures (#11422) (#11534) Refs: MON-7417 * fix(api): allow api platform updates from installed 22.04.0 (#11495) (#11533) Refs: MON-12296 * fix(api): fix call to api on fresh install (#11536) (#11537) Refs: MON-12296 * doc(ack): acknowledge Hakaï security (#11540) * fix(api): do not init db connection in event subscriber (#11543) (#11545) Refs: MON-12296 * fix(web): fix the comment deletion for host monitored by poller (#11138) (#11556) Refs: MON-12828 Co-authored-by: Stéphane Duret * SNYK: Sanitize and bind ACL actions queries (#11547) * sanitizing and binding acl actions queries * fix missing bind * SNYK: Sanitize and bind Broker listing queries (#11550) * Sanitizing and binding broker listing queries * applying suggested changes * fix(conf) fix encoding in template service listing (#11558) (#11564) * fix encoding * remove useless function * SNYK: Sanitize and bind generateImage queries (#11561) * sanitize and bind generate image queries * adding throw exception * applying suggested changes * Update www/include/views/graphs/generateGraphs/generateImage.php Co-authored-by: Kevin Duret Co-authored-by: Kevin Duret * MON-14501 - sanitize query in centreonXmlbgRequest class (#11570) * sanitize query in centreonXmlbgRequest class * add closeCursor func to resolve conv * SNYK: Sanitize and bind Meta-Services dependency queries (#11567) * sanityze 2 insert queries * spaces removed in a query * chore(install):Update version to 22.04.3 * fix(sql): fix query to select contact during ldap import (#11578) Refs: MON-14263 * fix(UI): Fix layout for Safari and form validation (#11373) (#11604) * Fix form validation * Fix padlock layout for safari * Update centreon-frontend * Remove debug variable * Fix test * Fix page respsoniveness * Rename variable * update deps * Fix package-lock Co-authored-by: Elmahdi ABBASSI <108519266+emabassi-ext@users.noreply.github.com> Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> Co-authored-by: Nouha-ElAbrouki <97687698+Noha-ElAbrouki@users.noreply.github.com> Co-authored-by: Kevin Duret Co-authored-by: hyahiaoui-ext <97593234+hyahiaoui-ext@users.noreply.github.com> Co-authored-by: Tom Darneix Co-authored-by: alaunois Co-authored-by: VHS Co-authored-by: Laurent Calvet Co-authored-by: Stéphane Chapron <34628915+sc979@users.noreply.github.com> Co-authored-by: Stéphane Duret --- Jenkinsfile | 2 +- SECURITY_ACK.md | 1 + ci/debian/rules | 2 +- ci/scripts/centreon-deb-package.sh | 5 +- composer.json | 3 +- composer.lock | 91 ++++- config/packages/Centreon.yaml | 40 ++ config/routes/Centreon/platform.yaml | 6 + config/services.yaml | 5 + cron/centAcl.php | 10 +- doc/API/centreon-api-v22.04.yaml | 4 +- doc/API/v22.04/Administration/updates.yaml | 30 ++ features/VirtualMetricHandle.feature | 6 +- .../bootstrap/VirtualMetricHandleContext.php | 3 +- lang/es_ES.UTF-8/LC_MESSAGES/messages.po | 4 - lang/fr_FR.UTF-8/LC_MESSAGES/messages.po | 70 +++- lang/pt_BR.UTF-8/LC_MESSAGES/messages.po | 4 - lang/pt_PT.UTF-8/LC_MESSAGES/messages.po | 4 - .../Infrastructure/DatabaseConnection.php | 10 + .../Repository/AbstractRepositoryDRB.php | 4 +- .../CentreonConfigurationRemote.php | 1 - .../Webservice/CentreonRemoteServer.php | 13 +- .../Domain/Service/NotifyMasterService.php | 9 - .../ReadUpdateRepositoryInterface.php | 34 ++ .../ReadVersionRepositoryInterface.php | 33 ++ .../Repository/UpdateLockerException.php | 44 +++ .../UpdateLockerRepositoryInterface.php | 42 ++ .../Repository/UpdateNotFoundException.php | 36 ++ .../WriteUpdateRepositoryInterface.php | 40 ++ .../UseCase/UpdateVersions/UpdateVersions.php | 219 +++++++++++ .../UpdateVersionsException.php | 87 +++++ .../UpdateVersionsPresenterInterface.php | 29 ++ .../Validator/RequirementException.php | 27 ++ .../RequirementValidatorInterface.php | 33 ++ .../RequirementValidatorsInterface.php | 33 ++ .../UpdateVersionsController.php | 70 ++++ .../UpdateVersionsPresenter.php | 31 ++ .../UpdateVersions/UpdateVersionsSchema.json | 25 ++ .../Repository/DbReadVersionRepository.php | 60 +++ .../Repository/DbWriteUpdateRepository.php | 319 +++++++++++++++ .../Repository/FsReadUpdateRepository.php | 105 +++++ .../SymfonyUpdateLockerRepository.php | 79 ++++ .../Validator/RequirementValidators.php | 63 +++ .../DatabaseRequirementException.php | 49 +++ .../DatabaseRequirementValidator.php | 128 ++++++ .../DatabaseRequirementValidatorInterface.php | 43 +++ .../MariaDbRequirementException.php | 44 +++ .../MariaDbRequirementValidator.php | 82 ++++ .../PhpRequirementException.php | 56 +++ .../PhpRequirementValidator.php | 108 ++++++ src/EventSubscriber/UpdateEventSubscriber.php | 109 ++++++ .../PlatformInstallationStatusContext.php | 52 +++ tests/api/Context/PlatformUpdateContext.php | 48 +++ tests/api/behat.yml | 8 + .../PlatformInstallationStatus.feature | 18 + tests/api/features/PlatformUpdate.feature | 41 ++ .../UpdateVersions/UpdateVersionsTest.php | 157 ++++++++ .../Repository/FsReadUpdateRepositoryTest.php | 89 +++++ tests/php/bootstrap.php | 3 +- .../realtime_rest_api.postman_collection.json | 2 +- www/api/class/centreon_ceip.class.php | 4 +- .../centreon-clapi/centreonAPI.class.php | 2 +- www/class/centreonACL.class.php | 50 ++- www/class/centreonAuth.LDAP.class.php | 145 +++---- www/class/centreonAuth.class.php | 364 ++++++++++-------- www/class/centreonContactgroup.class.php | 67 ++-- www/class/centreonGraph.class.php | 32 +- www/class/centreonHostgroups.class.php | 22 +- www/class/centreonLDAP.class.php | 51 ++- www/class/centreonTraps.class.php | 31 -- www/class/centreonUser.class.php | 2 - www/class/centreonXMLBGRequest.class.php | 11 +- .../FormInputs/FieldsTable/Row.tsx | 1 + .../src/Authentication/Openid/Form/inputs.ts | 18 +- .../src/Authentication/Openid/index.test.tsx | 41 +- .../Openid/useValidationSchema.ts | 11 +- www/front_src/src/Authentication/index.tsx | 74 ++-- www/front_src/src/Header/Clock/index.tsx | 6 +- .../Header/SwitchThemeMode/images/moon.svg | 3 - .../src/Header/SwitchThemeMode/images/sun.svg | 3 - .../src/Header/SwitchThemeMode/index.tsx | 135 +++---- .../SwitchThemeMode/useSwitchThemeMode.tsx | 30 ++ www/front_src/src/Header/helpers/index.ts | 5 + www/front_src/src/Header/index.tsx | 17 +- .../src/Header/userMenu/index.test.tsx | 6 +- www/front_src/src/Header/userMenu/index.tsx | 127 ++++-- .../exportToPng.ts | 10 +- .../Graph/Performance/GraphActions.tsx | 4 + .../Administration/parameters/DB-Func.php | 1 - .../Administration/parameters/ldap/form.php | 4 +- .../listCentreonBroker.php | 29 +- .../configObject/host_dependency/DB-Func.php | 27 +- .../hostgroup_dependency/DB-Func.php | 16 +- .../metaservice_dependency/DB-Func.php | 16 +- .../service_dependency/DB-Func.php | 37 +- .../listServiceTemplateModel.php | 13 +- .../configObject/traps/formTraps.php | 2 - www/include/monitoring/comments/comments.php | 2 +- .../monitoring/comments/common-Func.php | 1 - .../accessLists/actionsACL/DB-Func.php | 28 +- .../accessLists/menusACL/formMenusAccess.php | 31 +- www/include/options/media/images/syncDir.php | 30 +- www/include/reporting/dashboard/DB-Func.php | 2 +- .../formComponentTemplate.ihtml | 3 + .../formComponentTemplate.php | 22 +- .../graphs/common/makeJS_formMetricsList.php | 177 --------- .../graphs/common/makeXML_ListMetrics.php | 173 --------- .../graphs/generateGraphs/generateImage.php | 38 +- .../virtualMetrics/formVirtualMetrics.ihtml | 5 +- .../virtualMetrics/formVirtualMetrics.php | 24 +- www/install/createTables.sql | 1 - www/install/insertBaseConf.sql | 2 +- www/install/php/Update-22.04.2.php | 31 ++ www/install/php/Update-22.04.3.php | 20 + .../step_upgrade/process/process_step4.php | 134 ++----- .../step_upgrade/process/process_step5.php | 58 +-- www/install/steps/process/insertBaseConf.php | 2 - 117 files changed, 3690 insertions(+), 1284 deletions(-) create mode 100644 doc/API/v22.04/Administration/updates.yaml create mode 100644 src/Core/Platform/Application/Repository/ReadUpdateRepositoryInterface.php create mode 100644 src/Core/Platform/Application/Repository/ReadVersionRepositoryInterface.php create mode 100644 src/Core/Platform/Application/Repository/UpdateLockerException.php create mode 100644 src/Core/Platform/Application/Repository/UpdateLockerRepositoryInterface.php create mode 100644 src/Core/Platform/Application/Repository/UpdateNotFoundException.php create mode 100644 src/Core/Platform/Application/Repository/WriteUpdateRepositoryInterface.php create mode 100644 src/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersions.php create mode 100644 src/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersionsException.php create mode 100644 src/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersionsPresenterInterface.php create mode 100644 src/Core/Platform/Application/Validator/RequirementException.php create mode 100644 src/Core/Platform/Application/Validator/RequirementValidatorInterface.php create mode 100644 src/Core/Platform/Application/Validator/RequirementValidatorsInterface.php create mode 100644 src/Core/Platform/Infrastructure/Api/UpdateVersions/UpdateVersionsController.php create mode 100644 src/Core/Platform/Infrastructure/Api/UpdateVersions/UpdateVersionsPresenter.php create mode 100644 src/Core/Platform/Infrastructure/Api/UpdateVersions/UpdateVersionsSchema.json create mode 100644 src/Core/Platform/Infrastructure/Repository/DbReadVersionRepository.php create mode 100644 src/Core/Platform/Infrastructure/Repository/DbWriteUpdateRepository.php create mode 100644 src/Core/Platform/Infrastructure/Repository/FsReadUpdateRepository.php create mode 100644 src/Core/Platform/Infrastructure/Repository/SymfonyUpdateLockerRepository.php create mode 100644 src/Core/Platform/Infrastructure/Validator/RequirementValidators.php create mode 100644 src/Core/Platform/Infrastructure/Validator/RequirementValidators/DatabaseRequirementException.php create mode 100644 src/Core/Platform/Infrastructure/Validator/RequirementValidators/DatabaseRequirementValidator.php create mode 100644 src/Core/Platform/Infrastructure/Validator/RequirementValidators/DatabaseRequirementValidatorInterface.php create mode 100644 src/Core/Platform/Infrastructure/Validator/RequirementValidators/DatabaseRequirementValidators/MariaDbRequirementException.php create mode 100644 src/Core/Platform/Infrastructure/Validator/RequirementValidators/DatabaseRequirementValidators/MariaDbRequirementValidator.php create mode 100644 src/Core/Platform/Infrastructure/Validator/RequirementValidators/PhpRequirementException.php create mode 100644 src/Core/Platform/Infrastructure/Validator/RequirementValidators/PhpRequirementValidator.php create mode 100644 src/EventSubscriber/UpdateEventSubscriber.php create mode 100644 tests/api/Context/PlatformInstallationStatusContext.php create mode 100644 tests/api/Context/PlatformUpdateContext.php create mode 100644 tests/api/features/PlatformInstallationStatus.feature create mode 100644 tests/api/features/PlatformUpdate.feature create mode 100644 tests/php/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersionsTest.php create mode 100644 tests/php/Core/Platform/Infrastructure/Repository/FsReadUpdateRepositoryTest.php delete mode 100644 www/front_src/src/Header/SwitchThemeMode/images/moon.svg delete mode 100644 www/front_src/src/Header/SwitchThemeMode/images/sun.svg create mode 100644 www/front_src/src/Header/SwitchThemeMode/useSwitchThemeMode.tsx create mode 100644 www/front_src/src/Header/helpers/index.ts delete mode 100644 www/include/views/graphs/common/makeJS_formMetricsList.php delete mode 100644 www/include/views/graphs/common/makeXML_ListMetrics.php create mode 100644 www/install/php/Update-22.04.3.php diff --git a/Jenkinsfile b/Jenkinsfile index dbc405468e8..4a12d0562f6 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -308,7 +308,7 @@ try { checkout scm } sh 'rm -rf *.deb' - sh 'docker run -i --entrypoint /src/centreon/ci/scripts/centreon-deb-package.sh -w "/src" -v "$PWD:/src" -e DISTRIB="bullseye" -e VERSION=$VERSION -e RELEASE=$RELEASE registry.centreon.com/centreon-debian11-dependencies:22.04' + sh 'docker run -i --entrypoint /src/centreon/ci/scripts/centreon-deb-package.sh -w "/src" -v "$PWD:/src" -e DISTRIB="bullseye" -e VERSION=$VERSION -e RELEASE=$RELEASE registry.centreon.com/mon-build-dependencies-22.04:debian11' stash name: 'Debian11', includes: '*.deb' archiveArtifacts artifacts: "*" sh 'rm -rf *.deb' diff --git a/SECURITY_ACK.md b/SECURITY_ACK.md index e0ab076587b..ebe04dfb8f7 100644 --- a/SECURITY_ACK.md +++ b/SECURITY_ACK.md @@ -14,6 +14,7 @@ Centreon reserves the right to make final decisions regarding publishing acknowl

2022

+* 2022/05/23 - Lucas Carmo and Daniel França Lima from [Hakaï Security](https://www.hakaioffensivesecurity.com/) * 2022/02/16 - Anonymous working with Trend Micro Zero Day Initiative

2021

diff --git a/ci/debian/rules b/ci/debian/rules index 0e8ee8a1a3c..287f52a3658 100644 --- a/ci/debian/rules +++ b/ci/debian/rules @@ -13,7 +13,7 @@ override_dh_clean: override_dh_auto_build: composer install --no-dev --optimize-autoloader -n - npm ci + npm ci --legacy-peer-deps npm run build find . -type f | \ grep -v debian/extra/centreon-web/centreon-macroreplacement.txt | \ diff --git a/ci/scripts/centreon-deb-package.sh b/ci/scripts/centreon-deb-package.sh index d7a1cdcca36..be700cfccb0 100755 --- a/ci/scripts/centreon-deb-package.sh +++ b/ci/scripts/centreon-deb-package.sh @@ -39,9 +39,8 @@ done rm -rf lang # Generate API documentation. -apt install -y npm && sleep 30 -npm install -g redoc-cli -/usr/local/bin/redoc-cli bundle --options.hideDownloadButton=true doc/API/centreon-api-v${MAJOR_VERSION}.yaml -o ../centreon-api-v${MAJOR_VERSION}.html +npm i -g redoc-cli +redoc-cli build --options.hideDownloadButton=true doc/API/centreon-api-v${MAJOR_VERSION}.yaml -o ../centreon-api-v${MAJOR_VERSION}.html # Make tar with original content cd .. diff --git a/composer.json b/composer.json index c7c1a574bcd..aade76f0c59 100644 --- a/composer.json +++ b/composer.json @@ -65,6 +65,7 @@ "symfony/framework-bundle": "5.4.*", "symfony/http-client": "5.4.*", "symfony/http-kernel": "5.4.*", + "symfony/lock": "5.4.*", "symfony/maker-bundle": "^1.11", "symfony/monolog-bundle": "^3.7", "symfony/options-resolver": "5.4.*", @@ -85,7 +86,7 @@ "Tests\\": "tests/php/", "Centreon\\Test\\Api\\": "tests/api/" }, - "classmap": ["www/class/"], + "classmap": ["www/class/", "lib/Centreon"], "files" : [ "GPL_LIB/smarty-plugins/function.eval.php", "www/api/exceptions.php", diff --git a/composer.lock b/composer.lock index 23c9b05bd79..366ec06e77c 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "94134d5a5dc2cb311e57863a9f0dafd8", + "content-hash": "668e34fd2ddb66b073d8e525d65c166a", "packages": [ { "name": "beberlei/assert", @@ -3623,6 +3623,85 @@ ], "time": "2022-05-27T07:09:08+00:00" }, + { + "name": "symfony/lock", + "version": "v5.4.10", + "source": { + "type": "git", + "url": "https://github.com/symfony/lock.git", + "reference": "41a308008d92d30cae5615d903c4d46d95932eea" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/lock/zipball/41a308008d92d30cae5615d903c4d46d95932eea", + "reference": "41a308008d92d30cae5615d903c4d46d95932eea", + "shasum": "" + }, + "require": { + "php": ">=7.2.5", + "psr/log": "^1|^2|^3", + "symfony/deprecation-contracts": "^2.1|^3", + "symfony/polyfill-php80": "^1.16" + }, + "conflict": { + "doctrine/dbal": "<2.13" + }, + "require-dev": { + "doctrine/dbal": "^2.13|^3.0", + "predis/predis": "~1.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "Symfony\\Component\\Lock\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Jérémy Derussé", + "email": "jeremy@derusse.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Creates and manages locks, a mechanism to provide exclusive access to a shared resource", + "homepage": "https://symfony.com", + "keywords": [ + "cas", + "flock", + "locking", + "mutex", + "redlock", + "semaphore" + ], + "support": { + "source": "https://github.com/symfony/lock/tree/v5.4.10" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2022-06-09T13:29:56+00:00" + }, { "name": "symfony/maker-bundle", "version": "v1.43.0", @@ -6549,12 +6628,12 @@ "source": { "type": "git", "url": "https://github.com/centreon/centreon-test-lib.git", - "reference": "2aed30ebf46d7b76478166fdf122112a1c3722c6" + "reference": "6333b03d4d26974d1595e2b00960b86e9a338f74" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/centreon/centreon-test-lib/zipball/2aed30ebf46d7b76478166fdf122112a1c3722c6", - "reference": "2aed30ebf46d7b76478166fdf122112a1c3722c6", + "url": "https://api.github.com/repos/centreon/centreon-test-lib/zipball/6333b03d4d26974d1595e2b00960b86e9a338f74", + "reference": "6333b03d4d26974d1595e2b00960b86e9a338f74", "shasum": "" }, "require": { @@ -6599,7 +6678,7 @@ "issues": "https://github.com/centreon/centreon-test-lib/issues", "source": "https://github.com/centreon/centreon-test-lib/tree/master" }, - "time": "2022-04-27T09:10:57+00:00" + "time": "2022-08-05T09:52:42+00:00" }, { "name": "facade/ignition-contracts", @@ -10885,5 +10964,5 @@ "platform-overrides": { "php": "8.0" }, - "plugin-api-version": "2.1.0" + "plugin-api-version": "2.3.0" } diff --git a/config/packages/Centreon.yaml b/config/packages/Centreon.yaml index f0d99f90221..f8efbb150f4 100644 --- a/config/packages/Centreon.yaml +++ b/config/packages/Centreon.yaml @@ -223,6 +223,42 @@ services: class: Core\Infrastructure\Platform\Repository\FileReadPlatformRepository arguments: ['%centreon_etc_path%', '%centreon_install_path%'] + Core\Platform\Application\Validator\RequirementValidatorsInterface: + class: Core\Platform\Infrastructure\Validator\RequirementValidators + arguments: + $requirementValidators: !tagged_iterator 'platform.requirement.validators' + + Core\Platform\Infrastructure\Validator\RequirementValidators\DatabaseRequirementValidator: + arguments: + $dbRequirementValidators: !tagged_iterator 'platform.requirement.database.validators' + + Core\Platform\Infrastructure\Validator\RequirementValidators\PhpRequirementValidator: + arguments: + $requiredPhpVersion: '%required_php_version%' + + Core\Platform\Infrastructure\Validator\RequirementValidators\DatabaseRequirementValidators\MariaDbRequirementValidator: + arguments: + $requiredMariaDbMinVersion: '%required_mariadb_min_version%' + + Core\Platform\Application\Repository\ReadVersionRepositoryInterface: + class: Core\Platform\Infrastructure\Repository\DbReadVersionRepository + public: true + + Core\Platform\Application\Repository\ReadUpdateRepositoryInterface: + class: Core\Platform\Infrastructure\Repository\FsReadUpdateRepository + arguments: + $installDir: '%centreon_install_path%' + public: true + + Core\Platform\Application\Repository\UpdateLockerRepositoryInterface: + class: Core\Platform\Infrastructure\Repository\SymfonyUpdateLockerRepository + public: true + + Core\Platform\Application\Repository\WriteUpdateRepositoryInterface: + class: Core\Platform\Infrastructure\Repository\DbWriteUpdateRepository + arguments: ['%centreon_var_lib%', '%centreon_install_path%'] + public: true + # Monitoring resources _instanceof: Centreon\Infrastructure\Monitoring\Resource\Provider\ProviderInterface: @@ -238,6 +274,10 @@ services: tags: ['authentication.provider.responses'] Core\Security\Infrastructure\Api\FindProviderConfigurations\ProviderPresenter\ProviderPresenterInterface: tags: ['authentication.provider.presenters'] + Core\Platform\Application\Validator\RequirementValidatorInterface: + tags: ['platform.requirement.validators'] + Core\Platform\Infrastructure\Validator\RequirementValidators\DatabaseRequirementValidatorInterface: + tags: ['platform.requirement.database.validators'] Centreon\Domain\Monitoring\Interfaces\ResourceRepositoryInterface: factory: ['@Centreon\Infrastructure\Monitoring\Resource\ResourceRepositoryFactory', 'createResourceRepository'] diff --git a/config/routes/Centreon/platform.yaml b/config/routes/Centreon/platform.yaml index a521348ecbf..d77666e43f6 100644 --- a/config/routes/Centreon/platform.yaml +++ b/config/routes/Centreon/platform.yaml @@ -4,6 +4,12 @@ centreon_application_platform_getversion: controller: 'Centreon\Application\Controller\PlatformController::getVersions' condition: "request.attributes.get('version') >= 21.10" +centreon_application_platform_updateversions: + methods: PATCH + path: /platform/updates + controller: 'Core\Platform\Infrastructure\Api\UpdateVersions\UpdateVersionsController' + condition: "request.attributes.get('version') >= 22.04" + centreon_application_platformtopology_addplatformtotopology: methods: POST path: /platform/topology diff --git a/config/services.yaml b/config/services.yaml index 41975cd9de1..566596ebc51 100644 --- a/config/services.yaml +++ b/config/services.yaml @@ -22,6 +22,8 @@ parameters: media_path: "img/media" redirect_default_page: "/monitoring/resources" session_expiration_delay: 120 + required_php_version: "%env(_CENTREON_PHP_VERSION_)%" + required_mariadb_min_version: "%env(_CENTREON_MARIA_DB_MIN_VERSION_)%" services: # Default configuration for services in *this* file @@ -66,6 +68,9 @@ services: decorates: router arguments: ['@.inner'] + Symfony\Component\Finder\Finder: + shared: false + # Security Security\Domain\Authentication\Interfaces\AuthenticationRepositoryInterface: diff --git a/cron/centAcl.php b/cron/centAcl.php index be8e3dc0c61..320231a2d43 100644 --- a/cron/centAcl.php +++ b/cron/centAcl.php @@ -172,15 +172,15 @@ * Remove data from old groups (deleted groups) */ $aclGroupToDelete = "SELECT DISTINCT acl_group_id - FROM " . $centreonDbName . ".acl_groups WHERE acl_group_activate = '1'"; - $aclGroupToDelete2 = "SELECT DISTINCT acl_group_id FROM " . $centreonDbName . ".acl_res_group_relations"; - $pearDB->beginTransaction(); + FROM `" . $centreonDbName . "`.acl_groups WHERE acl_group_activate = '1'"; + $aclGroupToDelete2 = "SELECT DISTINCT acl_group_id FROM `" . $centreonDbName . "`.acl_res_group_relations"; + $pearDBO->beginTransaction(); try { $pearDBO->query("DELETE FROM centreon_acl WHERE group_id NOT IN (" . $aclGroupToDelete . ")"); $pearDBO->query("DELETE FROM centreon_acl WHERE group_id NOT IN (" . $aclGroupToDelete2 . ")"); - $pearDB->commit(); + $pearDBO->commit(); } catch (\PDOException $e) { - $pearDB->rollBack(); + $pearDBO->rollBack(); $centreonLog->insertLog( 2, "CentACL CRON: failed to delete old groups relations" diff --git a/doc/API/centreon-api-v22.04.yaml b/doc/API/centreon-api-v22.04.yaml index a75b7a57821..34f82120597 100644 --- a/doc/API/centreon-api-v22.04.yaml +++ b/doc/API/centreon-api-v22.04.yaml @@ -3528,6 +3528,8 @@ paths: moduleName: type: object $ref: '#/components/schemas/Platform.Versions' + /platform/updates: + $ref: "./v22.04/Administration/updates.yaml" /platform/installation/status: get: tags: @@ -3541,7 +3543,7 @@ paths: application/json: schema: type: object - required: ["installed_version", "has_upgrade_available"] + required: ["is_installed", "has_upgrade_available"] properties: is_installed: type: boolean diff --git a/doc/API/v22.04/Administration/updates.yaml b/doc/API/v22.04/Administration/updates.yaml new file mode 100644 index 00000000000..58e895903c1 --- /dev/null +++ b/doc/API/v22.04/Administration/updates.yaml @@ -0,0 +1,30 @@ +--- +patch: + tags: + - Platform + summary: "Update Centreon web" + description: | + Update Centreon web component + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + components: + type: array + items: + type: object + properties: + name: + type: string + enum: [ centreon-web ] + responses: + 204: + description: "Platform updated" + 404: + description: "Updates not found" + 500: + $ref: "../../centreon-api-v22.04.yaml#/components/responses/InternalServerError" +... \ No newline at end of file diff --git a/features/VirtualMetricHandle.feature b/features/VirtualMetricHandle.feature index d6fc325ee21..9e128d34b64 100644 --- a/features/VirtualMetricHandle.feature +++ b/features/VirtualMetricHandle.feature @@ -5,16 +5,16 @@ Feature: Virtual Metric Handle Background: Given I am logged in a Centreon server with configured metrics - + Scenario: Create a virtual metric When I add a virtual metric Then all properties are saved - + Scenario: Duplicate a virtual metric Given an existing virtual metric When I duplicate a virtual metric Then all properties are copied except the name - + Scenario: Delete a virtual metric Given an existing virtual metric When I delete a virtual metric diff --git a/features/bootstrap/VirtualMetricHandleContext.php b/features/bootstrap/VirtualMetricHandleContext.php index 47c44733822..16130030d81 100644 --- a/features/bootstrap/VirtualMetricHandleContext.php +++ b/features/bootstrap/VirtualMetricHandleContext.php @@ -24,7 +24,8 @@ public function iAddAVirtualMetric() $this->page = new MetricsConfigurationPage($this); $this->page->setProperties(array( 'name' => $this->vmName, - 'linked-host_services' => $this->host . ' - ' . $this->hostService + 'linked-host_services' => $this->host . ' - ' . $this->hostService, + 'known_metrics' => $this->functionRPN, )); $this->page->setProperties(array('function' => $this->functionRPN)); $this->page->save(); diff --git a/lang/es_ES.UTF-8/LC_MESSAGES/messages.po b/lang/es_ES.UTF-8/LC_MESSAGES/messages.po index 3ef62236f25..c2938b35436 100644 --- a/lang/es_ES.UTF-8/LC_MESSAGES/messages.po +++ b/lang/es_ES.UTF-8/LC_MESSAGES/messages.po @@ -9079,10 +9079,6 @@ msgstr "Compruebe si el servicio está parado" msgid "Preexec definition" msgstr "Definiendo el comando PREEXEC" -#: centreon-web/www/include/configuration/configObject/traps/formTraps.php:360 -msgid "The same OID element already exists" -msgstr "El mismo OID ya existe." - #: centreon-web/www/include/configuration/configObject/traps/formTraps.php:368 msgid "Advanced matching rules" msgstr "Reglas de correspondencia avanzadas" diff --git a/lang/fr_FR.UTF-8/LC_MESSAGES/messages.po b/lang/fr_FR.UTF-8/LC_MESSAGES/messages.po index 1c1b0bbed83..ae774523348 100644 --- a/lang/fr_FR.UTF-8/LC_MESSAGES/messages.po +++ b/lang/fr_FR.UTF-8/LC_MESSAGES/messages.po @@ -9554,10 +9554,6 @@ msgstr "Contrôle si le service est en plage de maintenance" msgid "Preexec definition" msgstr "Définition de la commande PREEXEC" -#: centreon-web/www/include/configuration/configObject/traps/formTraps.php:360 -msgid "The same OID element already exists" -msgstr "Le même OID existe déjà" - #: centreon-web/www/include/configuration/configObject/traps/formTraps.php:368 msgid "Advanced matching rules" msgstr "Règles de correspondance avancées" @@ -16914,3 +16910,69 @@ msgstr "Les attributs liés suivants sont manquants : %s" msgid "Warning, maximum size exceeded for input '%s' (max: %d), it will be truncated upon saving" msgstr "Attention, taille maximale dépassée pour le champ '%s' (max: %d), il sera tronqué à l'enregistrement" + +msgid "Update already in progress" +msgstr "Une mise à jour est déjà en cours" + +msgid "An error occurred when retrieving the current version" +msgstr "Une erreur s'est produite lors de la récupération de la version actuelle" + +msgid "Cannot retrieve the current version" +msgstr "La version actuelle n'a pas pu être récupérée" + +msgid "An error occurred when retrieving available updates" +msgstr "Une erreur s'est produite lors de la récupération des mises à jour disponibles" + +msgid "An error occurred when applying the update %s (%s)" +msgstr "Une erreur s'est produite lors de l'application de la mise à jour %s (%s)" + +msgid "Error while locking the update process" +msgstr "Erreur lors du verrouillage du processus de mise à jour" + +msgid "Error while unlocking the update process" +msgstr "Erreur lors du déverrouillage du processus de mise à jour" + +msgid "An error occurred when applying post update actions" +msgstr "Une erreur s'est produite lors de l'application des actions postérieures à la mise à jour" + +msgid "Updates not found" +msgstr "Les mises à jour n'ont pas été trouvées" + +msgid "PHP version %s required (%s installed)" +msgstr "La version %s de PHP est requise (%s installée)" + +msgid "PHP extension %s not loaded" +msgstr "L'extension %s de PHP n'est pas chargée" + +msgid "Error when retrieving the database version" +msgstr "Erreur lors de la récupération de la version de la base de données" + +msgid "Cannot retrieve the database version information" +msgstr "Les informations de version de la base de données n'ont pas pu être récupérées" + +msgid "MariaDB version %s required (%s installed)" +msgstr "La version %s de MariaDB est requise (%s installée)" + +msgid "Service severity" +msgstr "Criticité du service" + +msgid "Service severity level" +msgstr "Niveau de criticité du service" + +msgid "Host severity" +msgstr "Criticité d'hôte" + +msgid "Host severity level" +msgstr "Niveau de criticité d'hôte" + +msgid "Centreon database schema does not seem to be installed." +msgstr "Le schema de base de données de Centreon ne semble pas installé." + +msgid "Centreon database schema version is \"%s\" (\"%s\" required)." +msgstr "La version du schema de base de données de Centreon est \"%s\" (\"%s\" requise)." + +msgid "Please use Web UI to install Centreon." +msgstr "Veuillez utiliser l'interface Web pour installer Centreon." + +msgid "Please use Web UI to update Centreon." +msgstr "Veuillez utiliser l'interface Web pour mettre à jour Centreon." diff --git a/lang/pt_BR.UTF-8/LC_MESSAGES/messages.po b/lang/pt_BR.UTF-8/LC_MESSAGES/messages.po index fe81994ea1f..9e76be908f9 100644 --- a/lang/pt_BR.UTF-8/LC_MESSAGES/messages.po +++ b/lang/pt_BR.UTF-8/LC_MESSAGES/messages.po @@ -10237,10 +10237,6 @@ msgstr "Checagem de Manutenção" msgid "Preexec definition" msgstr "Definição de pré-execução" -#: centreon-web/www/include/configuration/configObject/traps/formTraps.php:376 -msgid "The same OID element already exists" -msgstr "O mesmo OID já existe" - #: centreon-web/www/include/configuration/configObject/traps/formTraps.php:384 msgid "Advanced matching rules" msgstr "Regras de correspondencia avançada" diff --git a/lang/pt_PT.UTF-8/LC_MESSAGES/messages.po b/lang/pt_PT.UTF-8/LC_MESSAGES/messages.po index f72a46f3aee..664500c9dc4 100644 --- a/lang/pt_PT.UTF-8/LC_MESSAGES/messages.po +++ b/lang/pt_PT.UTF-8/LC_MESSAGES/messages.po @@ -10238,10 +10238,6 @@ msgstr "Checagem de Manutenção" msgid "Preexec definition" msgstr "Definição de pré-execução" -#: centreon-web/www/include/configuration/configObject/traps/formTraps.php:376 -msgid "The same OID element already exists" -msgstr "O mesmo OID já existe" - #: centreon-web/www/include/configuration/configObject/traps/formTraps.php:384 msgid "Advanced matching rules" msgstr "Regras de correspondencia avançada" diff --git a/src/Centreon/Infrastructure/DatabaseConnection.php b/src/Centreon/Infrastructure/DatabaseConnection.php index 404ada96717..39263cc0cff 100644 --- a/src/Centreon/Infrastructure/DatabaseConnection.php +++ b/src/Centreon/Infrastructure/DatabaseConnection.php @@ -91,4 +91,14 @@ public function setStorageDbName(string $storageDbName) { $this->storageDbName = $storageDbName; } + + /** + * switch connection to another database + * + * @param string $dbName + */ + public function switchToDb(string $dbName): void + { + $this->query('use ' . $dbName); + } } diff --git a/src/Centreon/Infrastructure/Repository/AbstractRepositoryDRB.php b/src/Centreon/Infrastructure/Repository/AbstractRepositoryDRB.php index c8ccf79ea23..27e68c256fd 100644 --- a/src/Centreon/Infrastructure/Repository/AbstractRepositoryDRB.php +++ b/src/Centreon/Infrastructure/Repository/AbstractRepositoryDRB.php @@ -48,8 +48,8 @@ class AbstractRepositoryDRB protected function translateDbName(string $request): string { return str_replace( - array(':dbstg', ':db'), - array($this->db->getStorageDbName(), $this->db->getCentreonDbName()), + [':dbstg', ':db'], + [$this->db->getStorageDbName(), $this->db->getCentreonDbName()], $request ); } diff --git a/src/CentreonRemote/Application/Webservice/CentreonConfigurationRemote.php b/src/CentreonRemote/Application/Webservice/CentreonConfigurationRemote.php index f9bb7e1eabc..1ff417403b2 100755 --- a/src/CentreonRemote/Application/Webservice/CentreonConfigurationRemote.php +++ b/src/CentreonRemote/Application/Webservice/CentreonConfigurationRemote.php @@ -564,7 +564,6 @@ private function addServerToListOfRemotes( } else { $data = [ 'ip' => $serverIP, - 'app_key' => '', 'version' => '', 'is_connected' => '1', 'created_at' => $date, diff --git a/src/CentreonRemote/Application/Webservice/CentreonRemoteServer.php b/src/CentreonRemote/Application/Webservice/CentreonRemoteServer.php index 40768c67cfe..8bfd90de78f 100644 --- a/src/CentreonRemote/Application/Webservice/CentreonRemoteServer.php +++ b/src/CentreonRemote/Application/Webservice/CentreonRemoteServer.php @@ -109,14 +109,6 @@ public function postAddToWaitList(): string throw new \RestBadRequestException('Can not access your address.'); } - if ( - !isset($_POST['app_key']) - || !$_POST['app_key'] - || empty($appKey = filter_var($_POST['app_key'], FILTER_SANITIZE_STRING)) - ) { - throw new \RestBadRequestException('Please send \'app_key\' in the request.'); - } - if ( !isset($_POST['version']) || !$_POST['version'] @@ -147,15 +139,14 @@ public function postAddToWaitList(): string } $createdAt = date('Y-m-d H:i:s'); - $insertQuery = "INSERT INTO `remote_servers` (`ip`, `app_key`, `version`, `is_connected`, + $insertQuery = "INSERT INTO `remote_servers` (`ip`, `version`, `is_connected`, `created_at`, `http_method`, `http_port`, `no_check_certificate`) - VALUES (:ip, :app_key, :version, 0, '{$createdAt}', + VALUES (:ip, :version, 0, '{$createdAt}', :http_method, :http_port, :no_check_certificate )"; $insert = $this->pearDB->prepare($insertQuery); $insert->bindValue(':ip', $ip, \PDO::PARAM_STR); - $insert->bindValue(':app_key', $appKey, \PDO::PARAM_STR); $insert->bindValue(':version', $version, \PDO::PARAM_STR); $insert->bindValue(':http_method', $httpScheme, \PDO::PARAM_STR); $insert->bindValue(':http_port', $httpPort, \PDO::PARAM_INT); diff --git a/src/CentreonRemote/Domain/Service/NotifyMasterService.php b/src/CentreonRemote/Domain/Service/NotifyMasterService.php index d5b0295f933..9af5d665ddb 100644 --- a/src/CentreonRemote/Domain/Service/NotifyMasterService.php +++ b/src/CentreonRemote/Domain/Service/NotifyMasterService.php @@ -93,19 +93,10 @@ public function pingMaster($ip, $data, $noCheckCertificate = false, $noProxy = f $url = "{$ip}/centreon/api/external.php?object=centreon_remote_server&action=addToWaitList"; $repository = $this->dbManager->getRepository(InformationsRepository::class); - $applicationKey = $repository->getOneByKey('appKey'); $version = $repository->getOneByKey('version'); - if (empty($applicationKey)) { - return [ - 'status' => self::FAIL, - 'details' => self::NO_APP_KEY - ]; - } - try { $curlData = [ - 'app_key' => $applicationKey->getValue(), 'version' => $version->getValue(), 'http_method' => $data['remoteHttpMethod'] ?? 'http', 'http_port' => $data['remoteHttpPort'] ?? '', diff --git a/src/Core/Platform/Application/Repository/ReadUpdateRepositoryInterface.php b/src/Core/Platform/Application/Repository/ReadUpdateRepositoryInterface.php new file mode 100644 index 00000000000..db999e5fa71 --- /dev/null +++ b/src/Core/Platform/Application/Repository/ReadUpdateRepositoryInterface.php @@ -0,0 +1,34 @@ +info('Updating versions'); + + try { + $this->validateRequirementsOrFail(); + + $this->lockUpdate(); + + $currentVersion = $this->getCurrentVersionOrFail(); + + $availableUpdates = $this->getAvailableUpdatesOrFail($currentVersion); + + $this->runUpdates($availableUpdates); + + $this->unlockUpdate(); + + $this->runPostUpdate($this->getCurrentVersionOrFail()); + } catch (UpdateNotFoundException $e) { + $this->error( + $e->getMessage(), + ['trace' => $e->getTraceAsString()], + ); + + $presenter->setResponseStatus(new NotFoundResponse('Updates')); + + return; + } catch (\Throwable $e) { + $this->error( + $e->getMessage(), + ['trace' => $e->getTraceAsString()], + ); + + $presenter->setResponseStatus(new ErrorResponse($e->getMessage())); + + return; + } + + $presenter->setResponseStatus(new NoContentResponse()); + } + + /** + * Validate platform requirements or fail + * + * @throws \Exception + */ + private function validateRequirementsOrFail(): void + { + $this->info('Validating platform requirements'); + + $this->requirementValidators->validateRequirementsOrFail(); + } + + /** + * Lock update process + */ + private function lockUpdate(): void + { + $this->info('Locking centreon update process...'); + + if (!$this->updateLocker->lock()) { + throw UpdateVersionsException::updateAlreadyInProgress(); + } + } + + /** + * Unlock update process + */ + private function unlockUpdate(): void + { + $this->info('Unlocking centreon update process...'); + + $this->updateLocker->unlock(); + } + + /** + * Get current version or fail + * + * @return string + * + * @throws \Exception + */ + private function getCurrentVersionOrFail(): string + { + $this->info('Getting current version'); + + try { + $currentVersion = $this->readVersionRepository->findCurrentVersion(); + } catch (\Exception $e) { + throw UpdateVersionsException::errorWhenRetrievingCurrentVersion($e); + } + + if ($currentVersion === null) { + throw UpdateVersionsException::cannotRetrieveCurrentVersion(); + } + + return $currentVersion; + } + + /** + * Get available updates + * + * @param string $currentVersion + * @return string[] + */ + private function getAvailableUpdatesOrFail(string $currentVersion): array + { + try { + $this->info( + 'Getting available updates', + [ + 'current_version' => $currentVersion, + ], + ); + + return $this->readUpdateRepository->findOrderedAvailableUpdates($currentVersion); + } catch (UpdateNotFoundException $e) { + throw $e; + } catch (\Throwable $e) { + throw UpdateVersionsException::errorWhenRetrievingAvailableUpdates($e); + } + } + + /** + * Run given version updates + * + * @param string[] $versions + * + * @throws \Throwable + */ + private function runUpdates(array $versions): void + { + foreach ($versions as $version) { + try { + $this->info("Running update $version"); + $this->writeUpdateRepository->runUpdate($version); + } catch (\Throwable $e) { + throw UpdateVersionsException::errorWhenApplyingUpdate($version, $e->getMessage(), $e); + } + } + } + + /** + * Run post update actions + * + * @param string $currentVersion + * + * @throws UpdateVersionsException + */ + private function runPostUpdate(string $currentVersion): void + { + $this->info("Running post update actions"); + + try { + $this->writeUpdateRepository->runPostUpdate($currentVersion); + } catch (\Throwable $e) { + throw UpdateVersionsException::errorWhenApplyingPostUpdate($e); + } + } +} diff --git a/src/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersionsException.php b/src/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersionsException.php new file mode 100644 index 00000000000..dbfaec97ba3 --- /dev/null +++ b/src/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersionsException.php @@ -0,0 +1,87 @@ +denyAccessUnlessGrantedForApiConfiguration(); + + /** + * @var Contact $contact + */ + $contact = $this->getUser(); + if (! $contact->isAdmin()) { + $presenter->setResponseStatus(new UnauthorizedResponse('Only admin user can perform upgrade')); + + return $presenter->show(); + } + + $this->info('Validating request body...'); + $this->validateDataSent($request, __DIR__ . '/UpdateVersionsSchema.json'); + + $useCase($presenter); + + return $presenter->show(); + } +} diff --git a/src/Core/Platform/Infrastructure/Api/UpdateVersions/UpdateVersionsPresenter.php b/src/Core/Platform/Infrastructure/Api/UpdateVersions/UpdateVersionsPresenter.php new file mode 100644 index 00000000000..a27dcfad745 --- /dev/null +++ b/src/Core/Platform/Infrastructure/Api/UpdateVersions/UpdateVersionsPresenter.php @@ -0,0 +1,31 @@ +db = $db; + } + + /** + * @inheritDoc + */ + public function findCurrentVersion(): ?string + { + $currentVersion = null; + + $statement = $this->db->query( + "SELECT `value` FROM `informations` WHERE `key` = 'version'" + ); + if ($statement !== false && is_array($result = $statement->fetch(\PDO::FETCH_ASSOC))) { + $currentVersion = $result['value']; + } + + return $currentVersion; + } +} diff --git a/src/Core/Platform/Infrastructure/Repository/DbWriteUpdateRepository.php b/src/Core/Platform/Infrastructure/Repository/DbWriteUpdateRepository.php new file mode 100644 index 00000000000..1255ee9ecc8 --- /dev/null +++ b/src/Core/Platform/Infrastructure/Repository/DbWriteUpdateRepository.php @@ -0,0 +1,319 @@ +db = $db; + } + + /** + * @inheritDoc + */ + public function runUpdate(string $version): void + { + $this->runMonitoringSql($version); + $this->runScript($version); + $this->runConfigurationSql($version); + $this->runPostScript($version); + $this->updateVersionInformation($version); + } + + /** + * @inheritDoc + */ + public function runPostUpdate(string $currentVersion): void + { + if (! $this->filesystem->exists($this->installDir)) { + return; + } + + $this->backupInstallDirectory($currentVersion); + $this->removeInstallDirectory(); + } + + /** + * Backup installation directory + * + * @param string $currentVersion + */ + private function backupInstallDirectory(string $currentVersion): void + { + $backupDirectory = $this->libDir . '/installs/install-' . $currentVersion . '-' . date('Ymd_His'); + + $this->info( + "Backing up installation directory", + [ + 'source' => $this->installDir, + 'destination' => $backupDirectory, + ], + ); + + $this->filesystem->mirror( + $this->installDir, + $backupDirectory, + ); + } + + /** + * Remove installation directory + */ + private function removeInstallDirectory(): void + { + $this->info( + "Removing installation directory", + [ + 'installation_directory' => $this->installDir, + ], + ); + + $this->filesystem->remove($this->installDir); + } + + /** + * Run sql queries on monitoring database + * + * @param string $version + */ + private function runMonitoringSql(string $version): void + { + $upgradeFilePath = $this->installDir . '/sql/centstorage/Update-CSTG-' . $version . '.sql'; + if (is_readable($upgradeFilePath)) { + $this->db->switchToDb($this->db->getStorageDbName()); + $this->runSqlFile($upgradeFilePath); + } + } + + /** + * Run php upgrade script + * + * @param string $version + */ + private function runScript(string $version): void + { + $pearDB = $this->dependencyInjector['configuration_db']; + $pearDBO = $this->dependencyInjector['realtime_db']; + + $upgradeFilePath = $this->installDir . '/php/Update-' . $version . '.php'; + if (is_readable($upgradeFilePath)) { + include_once $upgradeFilePath; + } + } + + /** + * Run sql queries on configuration database + * + * @param string $version + */ + private function runConfigurationSql(string $version): void + { + $upgradeFilePath = $this->installDir . '/sql/centreon/Update-DB-' . $version . '.sql'; + if (is_readable($upgradeFilePath)) { + $this->db->switchToDb($this->db->getCentreonDbName()); + $this->runSqlFile($upgradeFilePath); + } + } + + /** + * Run php post upgrade script + * + * @param string $version + */ + private function runPostScript(string $version): void + { + $pearDB = $this->dependencyInjector['configuration_db']; + $pearDBO = $this->dependencyInjector['realtime_db']; + + $upgradeFilePath = $this->installDir . '/php/Update-' . $version . '.post.php'; + if (is_readable($upgradeFilePath)) { + include_once $upgradeFilePath; + } + } + + /** + * Update version information + * + * @param string $version + */ + private function updateVersionInformation(string $version): void + { + $statement = $this->db->prepare( + $this->translateDbName( + "UPDATE `:db`.`informations` SET `value` = :version WHERE `key` = 'version'" + ) + ); + $statement->bindValue(':version', $version, \PDO::PARAM_STR); + $statement->execute(); + } + + /** + * Run sql file and use temporary file to store last executed line + * + * @param string $filePath + * @return void + */ + private function runSqlFile(string $filePath): void + { + set_time_limit(0); + + $fileName = basename($filePath); + $tmpFile = $this->installDir . '/tmp/' . $fileName; + + $alreadyExecutedQueriesCount = $this->getAlreadyExecutedQueriesCount($tmpFile); + + if (is_readable($filePath)) { + $fileStream = fopen($filePath, 'r'); + if (is_resource($fileStream)) { + $query = ''; + $currentLineNumber = 0; + $executedQueriesCount = 0; + try { + while (! feof($fileStream)) { + $currentLineNumber++; + $currentLine = fgets($fileStream); + if ($currentLine && ! $this->isSqlComment($currentLine)) { + $query .= ' ' . trim($currentLine); + } + + if ($this->isSqlCompleteQuery($query)) { + $executedQueriesCount++; + if ($executedQueriesCount > $alreadyExecutedQueriesCount) { + try { + $this->executeQuery($query); + } catch (RepositoryException $e) { + throw $e; + } + + $this->writeExecutedQueriesCountInTemporaryFile($tmpFile, $executedQueriesCount); + } + $query = ''; + } + } + } catch (\Throwable $e) { + $this->error($e->getMessage(), ['trace' => $e->getTraceAsString()]); + throw $e; + } finally { + fclose($fileStream); + } + } + } + } + + /** + * Get stored executed queries count in temporary file to retrieve next query to run in case of an error occurred + * + * @param string $tmpFile + * @return int + */ + private function getAlreadyExecutedQueriesCount(string $tmpFile): int + { + $startLineNumber = 0; + if (is_readable($tmpFile)) { + $lineNumber = file_get_contents($tmpFile); + if (is_numeric($lineNumber)) { + $startLineNumber = (int) $lineNumber; + } + } + + return $startLineNumber; + } + + /** + * Write executed queries count in temporary file to retrieve upgrade when an error occurred + * + * @param string $tmpFile + * @param int $count + */ + private function writeExecutedQueriesCountInTemporaryFile(string $tmpFile, int $count): void + { + if (! file_exists($tmpFile) || is_writable($tmpFile)) { + $this->info('Writing in temporary file : ' . $tmpFile); + file_put_contents($tmpFile, $count); + } else { + $this->warning('Cannot write in temporary file : ' . $tmpFile); + } + } + + /** + * Check if a line a sql comment + * + * @param string $line + * @return bool + */ + private function isSqlComment(string $line): bool + { + return str_starts_with('--', trim($line)); + } + + /** + * Check if a query is complete (trailing semicolon) + * + * @param string $query + * @return bool + */ + private function isSqlCompleteQuery(string $query): bool + { + return ! empty(trim($query)) && preg_match('/;\s*$/', $query); + } + + /** + * Execute sql query + * + * @param string $query + * + * @throws \Exception + */ + private function executeQuery(string $query): void + { + try { + $this->db->query($query); + } catch (\Exception $e) { + throw new RepositoryException('Cannot execute query: ' . $query, 0, $e); + } + } +} diff --git a/src/Core/Platform/Infrastructure/Repository/FsReadUpdateRepository.php b/src/Core/Platform/Infrastructure/Repository/FsReadUpdateRepository.php new file mode 100644 index 00000000000..8c0a7916698 --- /dev/null +++ b/src/Core/Platform/Infrastructure/Repository/FsReadUpdateRepository.php @@ -0,0 +1,105 @@ +findAvailableUpdates($currentVersion); + + return $this->orderUpdates($availableUpdates); + } + + /** + * Get available updates + * + * @param string $currentVersion + * @return string[] + */ + private function findAvailableUpdates(string $currentVersion): array + { + if (! $this->filesystem->exists($this->installDir)) { + $this->error('Install directory not found on filesystem: ' . $this->installDir); + throw UpdateNotFoundException::updatesNotFound(); + } + + $fileNameVersionRegex = '/Update-(?[a-zA-Z0-9\-\.]+)\.php/'; + $availableUpdates = []; + + $updateFiles = $this->finder->files() + ->in($this->installDir) + ->name($fileNameVersionRegex); + + foreach ($updateFiles as $updateFile) { + if (preg_match($fileNameVersionRegex, $updateFile->getFilename(), $matches)) { + if (version_compare($matches['version'], $currentVersion, '>')) { + $this->info('Update version found: ' . $matches['version']); + $availableUpdates[] = $matches['version']; + } + } + } + + return $availableUpdates; + } + + /** + * Order updates + * + * @param string[] $updates + * @return string[] + */ + private function orderUpdates(array $updates): array + { + usort( + $updates, + fn (string $versionA, string $versionB) => version_compare($versionA, $versionB), + ); + + return $updates; + } +} diff --git a/src/Core/Platform/Infrastructure/Repository/SymfonyUpdateLockerRepository.php b/src/Core/Platform/Infrastructure/Repository/SymfonyUpdateLockerRepository.php new file mode 100644 index 00000000000..2442b6c0e0b --- /dev/null +++ b/src/Core/Platform/Infrastructure/Repository/SymfonyUpdateLockerRepository.php @@ -0,0 +1,79 @@ +lock = $lockFactory->createLock(self::LOCK_NAME); + } + + /** + * @inheritDoc + */ + public function lock(): bool + { + $this->info('Locking centreon update process on filesystem...'); + + try { + return $this->lock->acquire(); + } catch (\Throwable $e) { + throw UpdateLockerException::errorWhileLockingUpdate($e); + } + } + + /** + * @inheritDoc + */ + public function unlock(): void + { + $this->info('Unlocking centreon update process from filesystem...'); + + try { + $this->lock->release(); + } catch (\Throwable $e) { + throw UpdateLockerException::errorWhileUnlockingUpdate($e); + } + } +} diff --git a/src/Core/Platform/Infrastructure/Validator/RequirementValidators.php b/src/Core/Platform/Infrastructure/Validator/RequirementValidators.php new file mode 100644 index 00000000000..b573a47a62d --- /dev/null +++ b/src/Core/Platform/Infrastructure/Validator/RequirementValidators.php @@ -0,0 +1,63 @@ + $requirementValidators + * + * @throws \Exception + */ + public function __construct( + \Traversable $requirementValidators, + ) { + if (iterator_count($requirementValidators) === 0) { + throw new \Exception('Requirement validators not found'); + } + $this->requirementValidators = iterator_to_array($requirementValidators); + } + + /** + * @inheritDoc + */ + public function validateRequirementsOrFail(): void + { + foreach ($this->requirementValidators as $requirementValidator) { + $this->info('Validating platform requirement with ' . $requirementValidator::class); + $requirementValidator->validateRequirementOrFail(); + } + } +} diff --git a/src/Core/Platform/Infrastructure/Validator/RequirementValidators/DatabaseRequirementException.php b/src/Core/Platform/Infrastructure/Validator/RequirementValidators/DatabaseRequirementException.php new file mode 100644 index 00000000000..f9517d8216a --- /dev/null +++ b/src/Core/Platform/Infrastructure/Validator/RequirementValidators/DatabaseRequirementException.php @@ -0,0 +1,49 @@ + $dbRequirementValidators + * + * @throws \Exception + */ + public function __construct( + DatabaseConnection $db, + \Traversable $dbRequirementValidators, + ) { + $this->db = $db; + + if (iterator_count($dbRequirementValidators) === 0) { + throw new \Exception('Database requirement validators not found'); + } + $this->dbRequirementValidators = iterator_to_array($dbRequirementValidators); + } + + /** + * {@inheritDoc} + * + * @throws DatabaseRequirementException + */ + public function validateRequirementOrFail(): void + { + $this->initDatabaseVersionInformation(); + + foreach ($this->dbRequirementValidators as $dbRequirementValidator) { + if ($dbRequirementValidator->isValidFor($this->versionComment)) { + $this->info( + 'Validating requirement by ' . $dbRequirementValidator::class, + [ + 'current_version' => $this->version, + ], + ); + $dbRequirementValidator->validateRequirementOrFail($this->version); + $this->info('Requirement validated by ' . $dbRequirementValidator::class); + } + } + } + + /** + * Get database version information + * + * @throws DatabaseRequirementException + */ + private function initDatabaseVersionInformation(): void + { + $this->info('Getting database version information'); + + try { + $statement = $this->db->query("SHOW VARIABLES WHERE Variable_name IN ('version', 'version_comment')"); + while ($statement !== false && is_array($row = $statement->fetch(\PDO::FETCH_ASSOC))) { + if ($row['Variable_name'] === "version") { + $this->info('Retrieved DBMS version: ' . $row['Value']); + $this->version = $row['Value']; + } elseif ($row['Variable_name'] === "version_comment") { + $this->info('Retrieved DBMS version comment: ' . $row['Value']); + $this->versionComment = $row['Value']; + } + } + } catch (\Throwable $e) { + $this->error( + 'Error when getting DBMS version from database', + [ + 'message' => $e->getMessage(), + 'trace' => $e->getTraceAsString(), + ], + ); + throw DatabaseRequirementException::errorWhenGettingDatabaseVersion($e); + } + + if (empty($this->version) || empty($this->versionComment)) { + $this->info('Cannot retrieve the database version information'); + throw DatabaseRequirementException::cannotRetrieveVersionInformation(); + } + } +} diff --git a/src/Core/Platform/Infrastructure/Validator/RequirementValidators/DatabaseRequirementValidatorInterface.php b/src/Core/Platform/Infrastructure/Validator/RequirementValidators/DatabaseRequirementValidatorInterface.php new file mode 100644 index 00000000000..ba44860931b --- /dev/null +++ b/src/Core/Platform/Infrastructure/Validator/RequirementValidators/DatabaseRequirementValidatorInterface.php @@ -0,0 +1,43 @@ +info( + 'Checking if version comment contains MariaDB string', + [ + 'version_comment' => $versionComment, + ], + ); + + return strpos($versionComment, "MariaDB") !== false; + } + + /** + * {@inheritDoc} + * + * @throws MariaDbRequirementException + */ + public function validateRequirementOrFail(string $version): void + { + $currentMariaDBMajorVersion = VersionHelper::regularizeDepthVersion($version, 1); + + $this->info( + 'Comparing current MariaDB version ' . $currentMariaDBMajorVersion + . ' to minimal required version ' . $this->requiredMariaDbMinVersion + ); + + if ( + VersionHelper::compare($currentMariaDBMajorVersion, $this->requiredMariaDbMinVersion, VersionHelper::LT) + ) { + $this->error('MariaDB requirement is not validated'); + + throw MariaDbRequirementException::badMariaDbVersion( + $this->requiredMariaDbMinVersion, + $currentMariaDBMajorVersion, + ); + } + } +} diff --git a/src/Core/Platform/Infrastructure/Validator/RequirementValidators/PhpRequirementException.php b/src/Core/Platform/Infrastructure/Validator/RequirementValidators/PhpRequirementException.php new file mode 100644 index 00000000000..8086d3d86bc --- /dev/null +++ b/src/Core/Platform/Infrastructure/Validator/RequirementValidators/PhpRequirementException.php @@ -0,0 +1,56 @@ +validatePhpVersionOrFail(); + $this->validatePhpExtensionsOrFail(); + } + + /** + * Check installed php version + * + * @throws PhpRequirementException + */ + private function validatePhpVersionOrFail(): void + { + $currentPhpMajorVersion = VersionHelper::regularizeDepthVersion(PHP_VERSION, 1); + + $this->info( + 'Comparing current PHP version ' . $currentPhpMajorVersion + . ' to required version ' . $this->requiredPhpVersion + ); + if (! VersionHelper::compare($currentPhpMajorVersion, $this->requiredPhpVersion, VersionHelper::EQUAL)) { + throw PhpRequirementException::badPhpVersion($this->requiredPhpVersion, $currentPhpMajorVersion); + } + } + + /** + * Check if required php extensions are loaded + * + * @throws PhpRequirementException + */ + private function validatePhpExtensionsOrFail(): void + { + $this->info('Checking PHP extensions'); + foreach (self::EXTENSION_REQUIREMENTS as $extensionName) { + $this->validatePhpExtensionOrFail($extensionName); + } + } + + /** + * check if given php extension is loaded + * + * @param string $extensionName + * + * @throws PhpRequirementException + */ + private function validatePhpExtensionOrFail(string $extensionName): void + { + $this->info('Checking PHP extension ' . $extensionName); + if (! extension_loaded($extensionName)) { + $this->error('PHP extension ' . $extensionName . ' is not loaded'); + throw PhpRequirementException::phpExtensionNotLoaded($extensionName); + } + } +} diff --git a/src/EventSubscriber/UpdateEventSubscriber.php b/src/EventSubscriber/UpdateEventSubscriber.php new file mode 100644 index 00000000000..9c629695103 --- /dev/null +++ b/src/EventSubscriber/UpdateEventSubscriber.php @@ -0,0 +1,109 @@ + [ + ['validateCentreonWebVersionOrFail', 35], + ], + ]; + } + + /** + * validate centreon web installed version when update endpoint is called + * + * @param RequestEvent $event + * @throws \Exception + */ + public function validateCentreonWebVersionOrFail(RequestEvent $event): void + { + $this->debug('Checking if route matches updates endpoint'); + if ( + $event->getRequest()->getMethod() === Request::METHOD_PATCH + && preg_match( + '#^.*/api/(?:latest|beta|v[0-9]+|v[0-9]+\.[0-9]+)/platform/updates$#', + $event->getRequest()->getPathInfo(), + ) + ) { + $this->debug('Getting Centreon web current version'); + $currentVersion = $this->readVersionRepository->findCurrentVersion(); + + if ($currentVersion === null) { + $errorMessage = + _('Centreon database schema does not seem to be installed.') + . ' ' + . _('Please use Web UI to install Centreon.'); + $this->error($errorMessage); + throw new \Exception(_($errorMessage)); + } + + $this->debug( + sprintf( + 'Comparing installed version %s to required version %s', + $currentVersion, + self::MINIMAL_INSTALLED_VERSION, + ), + ); + if (version_compare($currentVersion, self::MINIMAL_INSTALLED_VERSION, '<')) { + $errorMessage = sprintf( + _('Centreon database schema version is "%s" ("%s" required).') + . ' ' + . _('Please use Web UI to update Centreon.'), + $currentVersion, + self::MINIMAL_INSTALLED_VERSION, + ); + $this->debug($errorMessage); + throw new \Exception(_($errorMessage)); + } + } + } +} diff --git a/tests/api/Context/PlatformInstallationStatusContext.php b/tests/api/Context/PlatformInstallationStatusContext.php new file mode 100644 index 00000000000..e1bf8b4e561 --- /dev/null +++ b/tests/api/Context/PlatformInstallationStatusContext.php @@ -0,0 +1,52 @@ +getContainer()->execute( + 'mysql -e "DROP DATABASE centreon_storage"', + 'web' + ); + $this->getContainer()->execute( + 'mysql -e "DROP DATABASE centreon"', + 'web' + ); + $this->getContainer()->execute( + 'rm -f /etc/centreon/centreon.conf.php', + 'web' + ); + $this->getContainer()->execute( + 'rm -rf /var/cache/centreon/symfony', + 'web' + ); + } +} diff --git a/tests/api/Context/PlatformUpdateContext.php b/tests/api/Context/PlatformUpdateContext.php new file mode 100644 index 00000000000..842bd5c0379 --- /dev/null +++ b/tests/api/Context/PlatformUpdateContext.php @@ -0,0 +1,48 @@ +getContainer()->execute( + 'mkdir -p /usr/share/centreon/www/install/php', + 'web' + ); + $this->getContainer()->execute( + "sh -c 'echo \" /usr/share/centreon/www/install/php/Update-99.99.99.php'", + 'web' + ); + $this->getContainer()->execute( + 'chown -R apache. /usr/share/centreon/www/install', + 'web' + ); + } +} diff --git a/tests/api/behat.yml b/tests/api/behat.yml index be4954bf1ae..8e8ece2e02a 100644 --- a/tests/api/behat.yml +++ b/tests/api/behat.yml @@ -72,6 +72,14 @@ default: paths: [ "%paths.base%/features/PlatformInformation.feature" ] contexts: - Centreon\Test\Api\Context\PlatformInformationContext + platform_fresh_install: + paths: [ "%paths.base%/features/PlatformInstallationStatus.feature" ] + contexts: + - Centreon\Test\Api\Context\PlatformInstallationStatusContext + platform_update: + paths: [ "%paths.base%/features/PlatformUpdate.feature" ] + contexts: + - Centreon\Test\Api\Context\PlatformUpdateContext host_groups: paths: [ "%paths.base%/features/HostGroup.feature" ] contexts: diff --git a/tests/api/features/PlatformInstallationStatus.feature b/tests/api/features/PlatformInstallationStatus.feature new file mode 100644 index 00000000000..5df7be8f915 --- /dev/null +++ b/tests/api/features/PlatformInstallationStatus.feature @@ -0,0 +1,18 @@ +Feature: + In order to maintain centreon platform + As an administrator + I want to known the platform installation status + + Background: + Given a running instance of Centreon Web API + And the endpoints are described in Centreon Web API documentation + + Scenario: Update platform information + When I send a GET request to '/api/latest/platform/installation/status' + Then the response code should be "200" + And the JSON node "is_installed" should be equal to true + + Given Centreon Web is not installed + When I send a GET request to '/api/latest/platform/installation/status' + Then the response code should be "200" + And the JSON node "is_installed" should be equal to false diff --git a/tests/api/features/PlatformUpdate.feature b/tests/api/features/PlatformUpdate.feature new file mode 100644 index 00000000000..624d875699d --- /dev/null +++ b/tests/api/features/PlatformUpdate.feature @@ -0,0 +1,41 @@ +Feature: + In order to maintain easily centreon platform + As a user + I want to update centreon web using api + + Background: + Given a running instance of Centreon Web API + And the endpoints are described in Centreon Web API documentation + + Scenario: Update platform information + Given I am logged in + + When an update is available + And I send a PATCH request to '/api/latest/platform/updates' with body: + """ + { + "components": [ + { + "name": "centreon-web" + } + ] + } + """ + Then the response code should be "204" + + When I send a GET request to '/api/latest/platform/versions' + Then the response code should be "200" + And the JSON node "web.version" should be equal to the string "99.99.99" + + When I send a PATCH request to '/api/latest/platform/updates' with body: + """ + { + "components": [ + { + "name": "centreon-web" + } + ] + } + """ + Then the response code should be "404" + And the JSON node "message" should be equal to the string "Updates not found" \ No newline at end of file diff --git a/tests/php/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersionsTest.php b/tests/php/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersionsTest.php new file mode 100644 index 00000000000..6f96a95531a --- /dev/null +++ b/tests/php/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersionsTest.php @@ -0,0 +1,157 @@ +requirementValidators = $this->createMock(RequirementValidatorsInterface::class); + $this->updateLockerRepository = $this->createMock(UpdateLockerRepositoryInterface::class); + $this->readVersionRepository = $this->createMock(ReadVersionRepositoryInterface::class); + $this->readUpdateRepository = $this->createMock(ReadUpdateRepositoryInterface::class); + $this->writeUpdateRepository = $this->createMock(WriteUpdateRepositoryInterface::class); + $this->presenter = $this->createMock(UpdateVersionsPresenterInterface::class); +}); + +it('should stop update process when an other update is already started', function () { + $updateVersions = new UpdateVersions( + $this->requirementValidators, + $this->updateLockerRepository, + $this->readVersionRepository, + $this->readUpdateRepository, + $this->writeUpdateRepository, + ); + + $this->updateLockerRepository + ->expects($this->once()) + ->method('lock') + ->willReturn(false); + + $this->presenter + ->expects($this->once()) + ->method('setResponseStatus') + ->with(new ErrorResponse('Update already in progress')); + + $updateVersions($this->presenter); +}); + +it('should present an error response if a requirement is not validated', function () { + $updateVersions = new UpdateVersions( + $this->requirementValidators, + $this->updateLockerRepository, + $this->readVersionRepository, + $this->readUpdateRepository, + $this->writeUpdateRepository, + ); + + $this->requirementValidators + ->expects($this->once()) + ->method('validateRequirementsOrFail') + ->willThrowException(new RequirementException('Requirement is not validated')); + + $this->presenter + ->expects($this->once()) + ->method('setResponseStatus') + ->with(new ErrorResponse('Requirement is not validated')); + + $updateVersions($this->presenter); +}); + +it('should present an error response if current centreon version is not found', function () { + $updateVersions = new UpdateVersions( + $this->requirementValidators, + $this->updateLockerRepository, + $this->readVersionRepository, + $this->readUpdateRepository, + $this->writeUpdateRepository, + ); + + $this->updateLockerRepository + ->expects($this->once()) + ->method('lock') + ->willReturn(true); + + $this->readVersionRepository + ->expects($this->once()) + ->method('findCurrentVersion') + ->willReturn(null); + + $this->presenter + ->expects($this->once()) + ->method('setResponseStatus') + ->with(new ErrorResponse('Cannot retrieve the current version')); + + $updateVersions($this->presenter); +}); + +it('should run found updates', function () { + $updateVersions = new UpdateVersions( + $this->requirementValidators, + $this->updateLockerRepository, + $this->readVersionRepository, + $this->readUpdateRepository, + $this->writeUpdateRepository, + ); + + $this->updateLockerRepository + ->expects($this->once()) + ->method('lock') + ->willReturn(true); + + $this->readVersionRepository + ->expects($this->exactly(2)) + ->method('findCurrentVersion') + ->will($this->onConsecutiveCalls('22.04.0', '22.10.1')); + + $this->readUpdateRepository + ->expects($this->once()) + ->method('findOrderedAvailableUpdates') + ->with('22.04.0') + ->willReturn(['22.10.0-beta.1', '22.10.0', '22.10.1']); + + $this->writeUpdateRepository + ->expects($this->exactly(3)) + ->method('runUpdate') + ->withConsecutive( + [$this->equalTo('22.10.0-beta.1')], + [$this->equalTo('22.10.0')], + [$this->equalTo('22.10.1')], + ); + + $this->presenter + ->expects($this->once()) + ->method('setResponseStatus') + ->with(new NoContentResponse()); + + $updateVersions($this->presenter); +}); diff --git a/tests/php/Core/Platform/Infrastructure/Repository/FsReadUpdateRepositoryTest.php b/tests/php/Core/Platform/Infrastructure/Repository/FsReadUpdateRepositoryTest.php new file mode 100644 index 00000000000..16682e3ea3c --- /dev/null +++ b/tests/php/Core/Platform/Infrastructure/Repository/FsReadUpdateRepositoryTest.php @@ -0,0 +1,89 @@ +filesystem = $this->createMock(Filesystem::class); + $this->finder = $this->createMock(Finder::class); +}); + +it('should return an error when install directory does not exist', function () { + $repository = new FsReadUpdateRepository(sys_get_temp_dir(), $this->filesystem, $this->finder); + + $this->filesystem + ->expects($this->once()) + ->method('exists') + ->willReturn(false); + + $availableUpdates = $repository->findOrderedAvailableUpdates('22.04.0'); +})->throws( + UpdateNotFoundException::class, + UpdateNotFoundException::updatesNotFound()->getMessage(), +); + +it('should order found updates', function () { + $repository = new FsReadUpdateRepository(sys_get_temp_dir(), $this->filesystem, $this->finder); + + $this->filesystem + ->expects($this->once()) + ->method('exists') + ->willReturn(true); + + $this->finder + ->expects($this->once()) + ->method('files') + ->willReturn($this->finder); + + $this->finder + ->expects($this->once()) + ->method('in') + ->willReturn($this->finder); + + $this->finder + ->expects($this->once()) + ->method('name') + ->willReturn( + [ + new \SplFileInfo('Update-21.10.0.php'), + new \SplFileInfo('Update-22.04.0.php'), + new \SplFileInfo('Update-22.10.11.php'), + new \SplFileInfo('Update-22.10.1.php'), + new \SplFileInfo('Update-22.10.0-beta.3.php'), + new \SplFileInfo('Update-22.10.0-alpha.1.php'), + ] + ); + + $availableUpdates = $repository->findOrderedAvailableUpdates('22.04.0'); + expect($availableUpdates)->toEqual([ + '22.10.0-alpha.1', + '22.10.0-beta.3', + '22.10.1', + '22.10.11' + ]); +}); diff --git a/tests/php/bootstrap.php b/tests/php/bootstrap.php index 2ca3e800b03..d1d41179b9f 100644 --- a/tests/php/bootstrap.php +++ b/tests/php/bootstrap.php @@ -24,8 +24,7 @@ } $mockedPreRequisiteConstants = [ - '_CENTREON_PHP_MIN_VERSION_' => '8.0', - '_CENTREON_PHP_MAX_VERSION_' => '8.0', + '_CENTREON_PHP_VERSION_' => '8.0', '_CENTREON_MARIA_DB_MIN_VERSION_' => '10.5', ]; foreach ($mockedPreRequisiteConstants as $mockedPreRequisiteConstant => $value) { diff --git a/tests/rest_api/realtime_rest_api.postman_collection.json b/tests/rest_api/realtime_rest_api.postman_collection.json index bcaea1bfb75..3f7f0535134 100644 --- a/tests/rest_api/realtime_rest_api.postman_collection.json +++ b/tests/rest_api/realtime_rest_api.postman_collection.json @@ -6730,7 +6730,7 @@ " while(curDate-date < millis);", "}", "", - "wait(5000);" + "wait(8000);" ] } }, diff --git a/www/api/class/centreon_ceip.class.php b/www/api/class/centreon_ceip.class.php index 396cdc213cc..2fc08f64262 100644 --- a/www/api/class/centreon_ceip.class.php +++ b/www/api/class/centreon_ceip.class.php @@ -120,9 +120,7 @@ private function getServerType(): array */ private function getVisitorInformation(): array { - $locale = $this->user->lang === 'browser' - ? null - : $this->user->lang; + $locale = $this->user->get_lang(); $role = $this->user->admin ? "admin" diff --git a/www/class/centreon-clapi/centreonAPI.class.php b/www/class/centreon-clapi/centreonAPI.class.php index 89844631e99..dd4cbadda48 100644 --- a/www/class/centreon-clapi/centreonAPI.class.php +++ b/www/class/centreon-clapi/centreonAPI.class.php @@ -594,7 +594,7 @@ public function checkUser($useSha1 = false, $isWorker = false) $row, $row['ar_id'] ); - if ($centreonAuth->checkPassword() == 1) { + if ($centreonAuth->checkPassword() == \CentreonAuth::PASSWORD_VALID) { \CentreonClapi\CentreonUtils::setUserId($row['contact_id']); return 1; } diff --git a/www/class/centreonACL.class.php b/www/class/centreonACL.class.php index e1e244c7ca3..699419dd29a 100644 --- a/www/class/centreonACL.class.php +++ b/www/class/centreonACL.class.php @@ -400,15 +400,17 @@ private function setTopology() if ($DBRESULT->rowCount()) { $topology = array(); $tmp_topo_page = array(); - while ($topo_group = $DBRESULT->fetchRow()) { - $query2 = "SELECT topology_topology_id, acl_topology_relations.access_right " + $statement = $centreonDb + ->prepare("SELECT topology_topology_id, acl_topology_relations.access_right " . "FROM acl_topology_relations, acl_topology " . "WHERE acl_topology.acl_topo_activate = '1' " . "AND acl_topology.acl_topo_id = acl_topology_relations.acl_topo_id " - . "AND acl_topology_relations.acl_topo_id = '" . $topo_group["acl_topology_id"] . "' " - . "AND acl_topology_relations.access_right != 0"; // do not get "access none" - $DBRESULT2 = $centreonDb->query($query2); - while ($topo_page = $DBRESULT2->fetchRow()) { + . "AND acl_topology_relations.acl_topo_id = :acl_topology_id " + . "AND acl_topology_relations.access_right != 0"); + while ($topo_group = $DBRESULT->fetchRow()) { + $statement->bindValue(':acl_topology_id', (int) $topo_group["acl_topology_id"], \PDO::PARAM_INT); + $statement->execute(); + while ($topo_page = $statement->fetchRow()) { $topology[] = (int) $topo_page["topology_topology_id"]; if (!isset($tmp_topo_page[$topo_page['topology_topology_id']])) { $tmp_topo_page[$topo_page["topology_topology_id"]] = $topo_page["access_right"]; @@ -423,7 +425,7 @@ private function setTopology() } } } - $DBRESULT2->closeCursor(); + $statement->closeCursor(); } $DBRESULT->closeCursor(); @@ -1691,22 +1693,28 @@ public function updateACL($data = null) $request = "SELECT group_id FROM centreon_acl " . "WHERE host_id = " . $data['duplicate_host'] . " AND service_id IS NULL"; $DBRESULT = \CentreonDBInstance::getMonInstance()->query($request); + $hostAclStatement = \CentreonDBInstance::getMonInstance() + ->prepare("INSERT INTO centreon_acl (host_id, service_id, group_id) " + . "VALUES (:data_id, NULL, :group_id)"); + $serviceAclStatement = \CentreonDBInstance::getMonInstance() + ->prepare("INSERT INTO centreon_acl (host_id, service_id, group_id) " + . "VALUES (:data_id, :service_id, :group_id) " + . "ON DUPLICATE KEY UPDATE group_id = :group_id"); while ($row = $DBRESULT->fetchRow()) { // Insert New Host - $request1 = "INSERT INTO centreon_acl (host_id, service_id, group_id) " - . "VALUES ('" . $data["id"] . "', NULL, " . $row['group_id'] . ")"; - \CentreonDBInstance::getMonInstance()->query($request1); - + $hostAclStatement->bindValue(':data_id', (int) $data["id"], \PDO::PARAM_INT); + $hostAclStatement->bindValue(':group_id', (int) $row['group_id'], \PDO::PARAM_INT); + $hostAclStatement->execute(); // Insert services $request = "SELECT service_id, group_id FROM centreon_acl " . "WHERE host_id = " . $data['duplicate_host'] . " AND service_id IS NOT NULL"; $DBRESULT2 = \CentreonDBInstance::getMonInstance()->query($request); while ($row2 = $DBRESULT2->fetch()) { - $request2 = "INSERT INTO centreon_acl (host_id, service_id, group_id) " - . "VALUES ('" . $data["id"] . "', " - . "'" . $row2["service_id"] . "', " . $row2['group_id'] . ") " - . "ON DUPLICATE KEY UPDATE group_id = " . $row2['group_id']; - \CentreonDBInstance::getMonInstance()->query($request2); + $serviceAclStatement->bindValue(':data_id', (int) $data["id"], \PDO::PARAM_INT); + $serviceAclStatement + ->bindValue(':service_id', (int) $row2["service_id"], \PDO::PARAM_INT); + $serviceAclStatement->bindValue(':group_id', (int) $row2['group_id'], \PDO::PARAM_INT); + $serviceAclStatement->execute(); } } } @@ -1730,10 +1738,14 @@ public function updateACL($data = null) $request = "SELECT group_id FROM centreon_acl " . "WHERE host_id = $host_id AND service_id = " . $data['duplicate_service']; $DBRESULT = \CentreonDBInstance::getMonInstance()->query($request); + $statement = \CentreonDBInstance::getMonInstance() + ->prepare("INSERT INTO centreon_acl (host_id, service_id, group_id) " + . "VALUES (:host_id, :data_id, :group_id)"); while ($row = $DBRESULT->fetchRow()) { - $request2 = "INSERT INTO centreon_acl (host_id, service_id, group_id) " - . "VALUES ('" . $host_id . "', '" . $data["id"] . "', " . $row['group_id'] . ")"; - \CentreonDBInstance::getMonInstance()->query($request2); + $statement->bindValue(':host_id', (int) $host_id, \PDO::PARAM_INT); + $statement->bindValue(':data_id', (int) $data["id"], \PDO::PARAM_INT); + $statement->bindValue(':group_id', (int) $row['group_id'], \PDO::PARAM_INT); + $statement->execute(); } } } diff --git a/www/class/centreonAuth.LDAP.class.php b/www/class/centreonAuth.LDAP.class.php index a51cbe8c260..3006d15eff9 100644 --- a/www/class/centreonAuth.LDAP.class.php +++ b/www/class/centreonAuth.LDAP.class.php @@ -33,7 +33,8 @@ * */ -require_once _CENTREON_PATH_ . 'www/class/centreonLDAP.class.php'; +require_once __DIR__ . '/centreonAuth.class.php'; +require_once __DIR__ . '/centreonLDAP.class.php'; /** * Class for Ldap authentication @@ -91,8 +92,6 @@ public function __construct($pearDB, $CentreonLog, $login, $password, $contactIn */ private function getLogFlag() { - global $pearDB; - $res = $this->pearDB->query("SELECT value FROM options WHERE `key` = 'debug_ldap_import'"); $data = $res->fetch(); if (isset($data["value"])) { @@ -107,34 +106,39 @@ private function getLogFlag() */ public function checkPassword() { - if (!isset($this->contactInfos['contact_ldap_dn']) || $this->contactInfos['contact_ldap_dn'] == '') { + if (empty(trim($this->contactInfos['contact_ldap_dn']))) { $this->contactInfos['contact_ldap_dn'] = $this->ldap->findUserDn($this->contactInfos['contact_alias']); - - /* Validate if user exists in this resource */ } elseif ( - isset($this->contactInfos['contact_ldap_dn']) - && $this->contactInfos['contact_ldap_dn'] != '' - && $this->ldap->findUserDn($this->contactInfos['contact_alias']) !== $this->contactInfos['contact_ldap_dn'] - ) { - if ($this->ldap->connect()) { + ($userDn = $this->ldap->findUserDn($this->contactInfos['contact_alias'])) + && $userDn !== $this->contactInfos['contact_ldap_dn'] + ) { // validate if user exists in this resource + if (! $userDn) { //User resource error - return 0; + return CentreonAuth::PASSWORD_INVALID; } else { //LDAP fallback - return 2; + return CentreonAuth::PASSWORD_CANNOT_BE_VERIFIED; } } - /* - * LDAP BIND - */ - if (!isset($this->contactInfos['contact_ldap_dn']) || trim($this->contactInfos['contact_ldap_dn']) == '') { - return 2; + if (empty(trim($this->contactInfos['contact_ldap_dn']))) { + return CentreonAuth::PASSWORD_CANNOT_BE_VERIFIED; } - @ldap_bind($this->ds, $this->contactInfos['contact_ldap_dn'], $this->typePassword); + if ($this->debug) { - $this->CentreonLog->insertLog(3, "Connexion = " . $this->contactInfos['contact_ldap_dn'] . " :: " . - ldap_error($this->ds)); + $this->CentreonLog->insertLog( + 3, + 'LDAP AUTH : ' . $this->contactInfos['contact_ldap_dn'] . ' :: Authentication in progress' + ); + } + + @ldap_bind($this->ds, $this->contactInfos['contact_ldap_dn'], $this->typePassword); + + if (empty($this->ds)) { + if ($this->debug) { + $this->CentreonLog->insertLog(3, "DS empty"); + } + return CentreonAuth::PASSWORD_CANNOT_BE_VERIFIED; } /* @@ -146,54 +150,29 @@ public function checkPassword() * 52 : Server is unavailable => Fallback * 81 : Can't contact LDAP server (php5) => Fallback */ - if (isset($this->ds) && $this->ds) { - switch (ldap_errno($this->ds)) { - case 0: - if ($this->debug) { - $this->CentreonLog->insertLog(3, "LDAP AUTH : OK, let's go ! "); - } - if (false == $this->updateUserDn()) { - return 0; - } - return 1; - break; - case 2: - if ($this->debug) { - $this->CentreonLog->insertLog(3, "LDAP AUTH : Protocol Error "); - } - return 2; - break; - case -1: - case 51: - if ($this->debug) { - $this->CentreonLog->insertLog(3, "LDAP AUTH : Error, Server Busy. Try later"); - } - return -1; - break; - case 52: - if ($this->debug) { - $this->CentreonLog->insertLog(3, "LDAP AUTH : Error, Server unavailable. Try later"); - } - return -1; - break; - case 81: - if ($this->debug) { - $this->CentreonLog->insertLog(3, "LDAP AUTH : Error, Fallback to Local AUTH"); - } - return 2; - break; - default: - if ($this->debug) { - $this->CentreonLog->insertLog(3, "LDAP AUTH : LDAP don't like you, sorry"); - } - return 0; - break; - } - } else { - if ($this->debug) { - $this->CentreonLog->insertLog(3, "DS empty"); - } - return 0; /* 2 ?? */ + switch (ldap_errno($this->ds)) { + case 0: + if ($this->debug) { + $this->CentreonLog->insertLog(3, "LDAP AUTH : Success"); + } + if (false == $this->updateUserDn()) { + return CentreonAuth::PASSWORD_INVALID; + } + return CentreonAuth::PASSWORD_VALID; + case -1: + case 2: // protocol error + case 51: // busy + case 52: // unavailable + case 81: // server down + if ($this->debug) { + $this->CentreonLog->insertLog(3, "LDAP AUTH : " . ldap_error($this->ds)); + } + return CentreonAuth::PASSWORD_CANNOT_BE_VERIFIED; + default: + if ($this->debug) { + $this->CentreonLog->insertLog(3, "LDAP AUTH : " . ldap_error($this->ds)); + } + return CentreonAuth::PASSWORD_INVALID; } } @@ -260,24 +239,26 @@ public function updateUserDn() * Searching if the user already exist in the DB and updating OR adding him */ if (isset($this->contactInfos['contact_id'])) { - $stmt = $this->pearDB->prepare( - 'UPDATE contact SET - contact_ldap_dn = :userDn, - contact_name = :userDisplay, - contact_email = :userEmail, - contact_pager = :userPager, - ar_id = :arId - WHERE contact_id = :contactId' - ); try { // checking if the LDAP synchronization on login is enabled or needed - if ( - !$this->ldap->isSyncNeededAtLogin($this->arId, $this->contactInfos['contact_id']) - ) { + if (!$this->ldap->isSyncNeededAtLogin($this->arId, $this->contactInfos['contact_id'])) { // skipping the update return true; } - // Updating the user DN and extended information + + $this->CentreonLog->insertLog( + 3, + 'LDAP AUTH : Updating user DN of ' . $userDisplay + ); + $stmt = $this->pearDB->prepare( + 'UPDATE contact SET + contact_ldap_dn = :userDn, + contact_name = :userDisplay, + contact_email = :userEmail, + contact_pager = :userPager, + ar_id = :arId + WHERE contact_id = :contactId' + ); $stmt->bindValue(':userDn', $userDn, \PDO::PARAM_STR); $stmt->bindValue(':userDisplay', $userDisplay, \PDO::PARAM_STR); $stmt->bindValue(':userEmail', $userEmail, \PDO::PARAM_STR); diff --git a/www/class/centreonAuth.class.php b/www/class/centreonAuth.class.php index a2ea42427bb..f4927c283af 100644 --- a/www/class/centreonAuth.class.php +++ b/www/class/centreonAuth.class.php @@ -35,6 +35,7 @@ */ require_once __DIR__ . '/centreonContact.class.php'; +require_once __DIR__ . '/centreonAuth.LDAP.class.php'; class CentreonAuth { @@ -49,10 +50,15 @@ class CentreonAuth public const PASSWORD_HASH_ALGORITHM = PASSWORD_BCRYPT; + public const PASSWORD_VALID = 1; + public const PASSWORD_INVALID = 0; + public const PASSWORD_CANNOT_BE_VERIFIED = -1; + public const ENCRYPT_MD5 = 1; public const ENCRYPT_SHA1 = 2; public const AUTH_TYPE_LOCAL = 'local'; + public const AUTH_TYPE_LDAP = 'ldap'; // Declare Values public $userInfos; @@ -63,7 +69,12 @@ class CentreonAuth protected $cryptEngine; protected $autologin; protected $cryptPossibilities; + + /** + * @var CentreonDB + */ protected $pearDB; + protected $debug; protected $dependencyInjector; @@ -157,158 +168,170 @@ protected function getLogFlag() */ protected function checkPassword($password, $token = "", $autoImport = false) { - if ((strlen($password) == 0 || $password === "") && $token === "") { - $this->passwdOk = 0; + if (empty($password) && empty($token)) { + $this->passwdOk = self::PASSWORD_INVALID; return; } - if ($this->userInfos["contact_auth_type"] == "ldap" && $this->autologin == 0) { - /* - * Insert LDAP Class - */ - include_once(_CENTREON_PATH_ . "/www/class/centreonAuth.LDAP.class.php"); - - $query = "SELECT ar_id FROM auth_ressource WHERE ar_enable = '1'"; - $res = $this->pearDB->query($query); - $authResources = array(); - while ($row = $res->fetch()) { - $index = $row['ar_id']; - if (isset($this->userInfos['ar_id']) && $this->userInfos['ar_id'] == $row['ar_id']) { - $index = 0; - } - $authResources[$index] = $row['ar_id']; + + if ($this->autologin) { + $this->checkAutologinKey($password, $token); + return; + } + + if ($this->userInfos["contact_auth_type"] === self::AUTH_TYPE_LDAP) { + $this->checkLdapPassword($password, $autoImport); + return; + } + + if ( + empty($this->userInfos["contact_auth_type"]) + || $this->userInfos["contact_auth_type"] === self::AUTH_TYPE_LOCAL + ) { + $this->checkLocalPassword($password); + return; + } + + $this->passwdOk = self::PASSWORD_INVALID; + } + + /** + * Check autologin key + * + * @param string $password + * @param string $token + */ + private function checkAutologinKey($password, $token): void + { + if ( + !empty($this->userInfos["contact_autologin_key"]) + && $this->userInfos["contact_autologin_key"] === $token + ) { + $this->passwdOk = self::PASSWORD_VALID; + } elseif ( + !empty($password) + && $this->userInfos["contact_passwd"] === $password + ) { + $this->passwdOk = self::PASSWORD_VALID; + } else { + $this->passwdOk = self::PASSWORD_INVALID; + } + } + + /** + * Check ldap user password + * + * @param string $password + * @param bool $autoImport + */ + private function checkLdapPassword($password, $autoImport): void + { + $res = $this->pearDB->query("SELECT ar_id FROM auth_ressource WHERE ar_enable = '1'"); + $authResources = []; + while ($row = $res->fetch()) { + $index = $row['ar_id']; + if (isset($this->userInfos['ar_id']) && $this->userInfos['ar_id'] == $row['ar_id']) { + $index = 0; } + $authResources[$index] = $row['ar_id']; + } - foreach ($authResources as $arId) { - if ($autoImport && !isset($this->ldap_auto_import[$arId])) { - break; - } - if ($this->passwdOk == 1) { - break; - } - $authLDAP = new CentreonAuthLDAP( - $this->pearDB, - $this->CentreonLog, - $this->login, - $this->password, - $this->userInfos, - $arId - ); - $this->passwdOk = $authLDAP->checkPassword(); - if ($this->passwdOk == -1) { - $this->passwdOk = 0; - if ( - isset($this->userInfos["contact_passwd"]) - && password_verify($this->password, $this->userInfos["contact_passwd"]) - ) { - $this->passwdOk = 1; - if (isset($this->ldap_store_password[$arId]) && $this->ldap_store_password[$arId]) { - $hashedPassword = password_hash($this->password, self::PASSWORD_HASH_ALGORITHM); - $contact = new \CentreonContact($this->pearDB); - $contact->addPasswordByContactId( - (int) $this->userInfos['contact_id'], + foreach ($authResources as $arId) { + if ($autoImport && !isset($this->ldap_auto_import[$arId])) { + break; + } + if ($this->passwdOk == self::PASSWORD_VALID) { + break; + } + $authLDAP = new CentreonAuthLDAP( + $this->pearDB, + $this->CentreonLog, + $this->login, + $this->password, + $this->userInfos, + $arId + ); + $this->passwdOk = $authLDAP->checkPassword(); + + if ($this->passwdOk == self::PASSWORD_VALID) { + if (isset($this->ldap_store_password[$arId]) && $this->ldap_store_password[$arId]) { + if (!isset($this->userInfos["contact_passwd"])) { + $hashedPassword = password_hash($this->password, self::PASSWORD_HASH_ALGORITHM); + $contact = new \CentreonContact($this->pearDB); + $contactId = $contact->findContactIdByAlias($this->login); + if ($contactId !== null) { + $contact->addPasswordByContactId($contactId, $hashedPassword); + } + // Update password if LDAP authentication is valid but password not up to date in Centreon. + } elseif (!password_verify($this->password, $this->userInfos["contact_passwd"])) { + $hashedPassword = password_hash($this->password, self::PASSWORD_HASH_ALGORITHM); + $contact = new \CentreonContact($this->pearDB); + $contactId = $contact->findContactIdByAlias($this->login); + if ($contactId !== null) { + $contact->replacePasswordByContactId( + $contactId, + $this->userInfos["contact_passwd"], $hashedPassword ); } } - } elseif ($this->passwdOk == 1) { - if (isset($this->ldap_store_password[$arId]) && $this->ldap_store_password[$arId]) { - if (!isset($this->userInfos["contact_passwd"])) { - $hashedPassword = password_hash($this->password, self::PASSWORD_HASH_ALGORITHM); - $contact = new \CentreonContact($this->pearDB); - $contactId = $contact->findContactIdByAlias($this->login); - if ($contactId !== null) { - $contact->addPasswordByContactId($contactId, $hashedPassword); - } - // Update password if LDAP authentication is valid but password not up to date in Centreon. - } elseif (!password_verify($this->password, $this->userInfos["contact_passwd"])) { - $hashedPassword = password_hash($this->password, self::PASSWORD_HASH_ALGORITHM); - $contact = new \CentreonContact($this->pearDB); - $contactId = $contact->findContactIdByAlias($this->login); - if ($contactId !== null) { - $contact->replacePasswordByContactId( - $contactId, - $this->userInfos["contact_passwd"], - $hashedPassword - ); - } - } - } } - } - } elseif ( - $this->userInfos["contact_auth_type"] == "" - || $this->userInfos["contact_auth_type"] === self::AUTH_TYPE_LOCAL - || $this->autologin - ) { - if ( - $this->autologin - && $this->userInfos["contact_autologin_key"] - && $this->userInfos["contact_autologin_key"] === $token - ) { - $this->passwdOk = 1; - } elseif ( - !empty($password) - && $this->userInfos["contact_passwd"] === $password - && $this->autologin - ) { - $this->passwdOk = 1; - - // Update password from md5 to bcrypt if old md5 password is valid. - } elseif ( - !empty($password) - && (str_starts_with($this->userInfos["contact_passwd"], 'md5__') - && $this->userInfos["contact_passwd"] === $this->myCrypt($password) - || 'md5__' . $this->userInfos["contact_passwd"] === $this->myCrypt($password)) - ) { - $newPassword = password_hash($password, self::PASSWORD_HASH_ALGORITHM); - $statement = $this->pearDB->prepare( - "UPDATE `contact_password` SET password = :newPassword - WHERE password = :oldPassword AND contact_id = :contactId" - ); - $statement->bindValue(':newPassword', $newPassword, \PDO::PARAM_STR); - $statement->bindValue(':oldPassword', $this->userInfos["contact_passwd"], \PDO::PARAM_STR); - $statement->bindValue(':contactId', $this->userInfos["contact_id"], \PDO::PARAM_INT); - $statement->execute(); - $this->passwdOk = 1; - } elseif ( - !empty($password) - && password_verify($password, $this->userInfos["contact_passwd"]) - && $this->autologin == 0 - ) { - $this->passwdOk = 1; - } else { - $this->passwdOk = 0; + break; } } - /** - * LDAP - fallback - */ - if ($this->passwdOk == 2) { + if ($this->passwdOk == self::PASSWORD_CANNOT_BE_VERIFIED) { if ( - $this->autologin && $this->userInfos["contact_autologin_key"] - && $this->userInfos["contact_autologin_key"] === $token - ) { - $this->passwdOk = 1; - } elseif ( - !empty($password) - && isset($this->userInfos["contact_passwd"]) - && $this->userInfos["contact_passwd"] === $password && $this->autologin - ) { - $this->passwdOk = 1; - } elseif ( !empty($password) - && isset($this->userInfos["contact_passwd"]) + && !empty($this->userInfos["contact_passwd"]) && password_verify($password, $this->userInfos["contact_passwd"]) - && $this->autologin == 0 ) { - $this->passwdOk = 1; + $this->passwdOk = self::PASSWORD_VALID; } else { - $this->passwdOk = 0; + $this->passwdOk = self::PASSWORD_INVALID; } } } + /** + * Check local user password + * + * @param string $password + */ + private function checkLocalPassword($password) + { + if (empty($password)) { + $this->passwdOk = self::PASSWORD_INVALID; + return; + } + + if (password_verify($password, $this->userInfos["contact_passwd"])) { + $this->passwdOk = self::PASSWORD_VALID; + return; + } + + if ( + ( + str_starts_with($this->userInfos["contact_passwd"], 'md5__') + && $this->userInfos["contact_passwd"] === $this->myCrypt($password) + ) + || 'md5__' . $this->userInfos["contact_passwd"] === $this->myCrypt($password) + ) { + $newPassword = password_hash($password, self::PASSWORD_HASH_ALGORITHM); + $statement = $this->pearDB->prepare( + "UPDATE `contact_password` SET password = :newPassword + WHERE password = :oldPassword AND contact_id = :contactId" + ); + $statement->bindValue(':newPassword', $newPassword, \PDO::PARAM_STR); + $statement->bindValue(':oldPassword', $this->userInfos["contact_passwd"], \PDO::PARAM_STR); + $statement->bindValue(':contactId', $this->userInfos["contact_id"], \PDO::PARAM_INT); + $statement->execute(); + $this->passwdOk = self::PASSWORD_VALID; + return; + } + + $this->passwdOk = self::PASSWORD_INVALID; + } + /** * Check user password * @@ -339,12 +362,13 @@ protected function checkUser($username, $password, $token) if ($dbResult->rowCount()) { $this->userInfos = $dbResult->fetch(); if ($this->userInfos["default_page"]) { - $dbResult2 = $this->pearDB->query( - "SELECT topology_url_opt FROM topology WHERE topology_page = " - . $this->userInfos["default_page"] + $statement = $this->pearDB->prepare( + "SELECT topology_url_opt FROM topology WHERE topology_page = :topology_page" ); - if ($dbResult2->numRows()) { - $data = $dbResult2->fetch(); + $statement->bindValue(':topology_page', (int) $this->userInfos["default_page"], \PDO::PARAM_INT); + $statement->execute(); + if ($statement->rowCount()) { + $data = $statement->fetch(\PDO::FETCH_ASSOC); $this->userInfos["default_page"] .= $data["topology_url_opt"]; } } @@ -354,7 +378,7 @@ protected function checkUser($username, $password, $token) */ $this->getCryptFunction(); $this->checkPassword($password, $token); - if ($this->passwdOk == 1) { + if ($this->passwdOk == self::PASSWORD_VALID) { $this->CentreonLog->setUID($this->userInfos["contact_id"]); $this->CentreonLog->insertLog( CentreonUserLog::TYPE_LOGIN, @@ -362,54 +386,49 @@ protected function checkUser($username, $password, $token) . "Authentication succeeded for '" . $username . "'" ); } else { - // Take care before modifying this message pattern as it may break tools such as fail2ban - $this->CentreonLog->insertLog( - CentreonUserLog::TYPE_LOGIN, - "[" . self::AUTH_TYPE_LOCAL . "] [" . $_SERVER["REMOTE_ADDR"] . "] " - . "Authentication failed for '" . $username . "'" + $this->setAuthenticationError( + $this->userInfos['contact_auth_type'], + $username, + 'invalid credentials' ); - $this->error = _('Your credentials are incorrect.'); } } elseif (count($this->ldap_auto_import)) { /* * Add temporary userinfo auth_type */ $this->userInfos['contact_alias'] = $username; - $this->userInfos['contact_auth_type'] = "ldap"; + $this->userInfos['contact_auth_type'] = self::AUTH_TYPE_LDAP; $this->userInfos['contact_email'] = ''; $this->userInfos['contact_pager'] = ''; $this->checkPassword($password, "", true); /* * Reset userInfos with imported information */ - $dbResult = $this->pearDB->query( + $statement = $this->pearDB->prepare( "SELECT * FROM `contact` " . - "WHERE `contact_alias` = '" . $this->pearDB->escape($username, true) . "'" . + "WHERE `contact_alias` = :contact_alias " . "AND `contact_activate` = '1' AND `contact_register` = '1' LIMIT 1" ); - if ($dbResult->rowCount()) { - $this->userInfos = $dbResult->fetch(); + $statement->bindValue(':contact_alias', $this->pearDB->escape($username, true), \PDO::PARAM_STR); + $statement->execute(); + if ($statement->rowCount()) { + $this->userInfos = $statement->fetch(\PDO::FETCH_ASSOC); if ($this->userInfos["default_page"]) { - $dbResult2 = $this->pearDB->query( - "SELECT topology_url_opt FROM topology WHERE topology_page = " - . $this->userInfos["default_page"] + $statement = $this->pearDB->prepare( + "SELECT topology_url_opt FROM topology WHERE topology_page = :topology_page" ); - if ($dbResult2->numRows()) { - $data = $dbResult2->fetch(); + $statement->bindValue(':topology_page', (int) $this->userInfos["default_page"], \PDO::PARAM_INT); + $statement->execute(); + if ($statement->rowCount()) { + $data = $statement->fetch(\PDO::FETCH_ASSOC); $this->userInfos["default_page"] .= $data["topology_url_opt"]; } } + } else { + $this->setAuthenticationError(self::AUTH_TYPE_LDAP, $username, 'not found'); } } else { - if (strlen($username) > 0) { - // Take care before modifying this message pattern as it may break tools such as fail2ban - $this->CentreonLog->insertLog( - CentreonUserLog::TYPE_LOGIN, - "[" . self::AUTH_TYPE_LOCAL . "] [" . $_SERVER["REMOTE_ADDR"] . "] " - . "Authentication failed for '" . $username . "' : not found" - ); - } - $this->error = _('Your credentials are incorrect.'); + $this->setAuthenticationError(self::AUTH_TYPE_LOCAL, $username, 'not found'); } } @@ -482,4 +501,25 @@ protected function getAuthType() { return $this->authType; } + + /** + * Set authentication error and log it + * + * @param string $authenticationType + * @param string|bool $username + * @param string $reason + */ + private function setAuthenticationError(string $authenticationType, $username, string $reason): void + { + if (is_string($username) && strlen($username) > 0) { + // Take care before modifying this message pattern as it may break tools such as fail2ban + $this->CentreonLog->insertLog( + CentreonUserLog::TYPE_LOGIN, + "[" . $authenticationType . "] [" . $_SERVER["REMOTE_ADDR"] . "] " + . "Authentication failed for '" . $username . "' : " . $reason + ); + } + + $this->error = _('Your credentials are incorrect.'); + } } diff --git a/www/class/centreonContactgroup.class.php b/www/class/centreonContactgroup.class.php index 4eab2bd3d4e..9c297811ed3 100644 --- a/www/class/centreonContactgroup.class.php +++ b/www/class/centreonContactgroup.class.php @@ -279,20 +279,27 @@ public function syncWithLdapConfigGen() $msg = array(); $ldapServerConnError = array(); - $cgRes = $this->db->query("SELECT cg.cg_id, cg.cg_name, cg.cg_ldap_dn, cg.ar_id " . - "FROM contactgroup as cg, auth_ressource as ar " . - "WHERE cg.cg_type = 'ldap' AND cg.ar_id = ar.ar_id AND ar.ar_enable = '1' AND (" . - "EXISTS(SELECT 1 FROM contactgroup_host_relation chr WHERE chr.contactgroup_cg_id = cg.cg_id LIMIT 1) " - . " OR " . - "EXISTS(SELECT 1 FROM contactgroup_service_relation csr WHERE csr.contactgroup_cg_id = cg.cg_id LIMIT 1)" - . " OR " . - "EXISTS(SELECT 1 FROM contactgroup_hostgroup_relation chr WHERE chr.contactgroup_cg_id = cg.cg_id LIMIT 1)" - . " OR " . - "EXISTS(SELECT 1 FROM contactgroup_servicegroup_relation csr " . - "WHERE csr.contactgroup_cg_id = cg.cg_id LIMIT 1)" - . " OR " . - "EXISTS(SELECT 1 FROM escalation_contactgroup_relation ecr WHERE ecr.contactgroup_cg_id = cg.cg_id LIMIT 1)" - . ") ORDER BY cg.ar_id"); + $cgRes = $this->db->query( + "SELECT cg.cg_id, cg.cg_name, cg.cg_ldap_dn, cg.ar_id, ar.ar_name + FROM contactgroup as cg, auth_ressource as ar + WHERE cg.cg_type = 'ldap' + AND cg.ar_id = ar.ar_id + AND ar.ar_enable = '1' + AND ( + EXISTS ( + SELECT 1 FROM contactgroup_host_relation chr WHERE chr.contactgroup_cg_id = cg.cg_id LIMIT 1 + ) OR EXISTS ( + SELECT 1 FROM contactgroup_service_relation csr WHERE csr.contactgroup_cg_id = cg.cg_id LIMIT 1 + ) OR EXISTS ( + SELECT 1 FROM contactgroup_hostgroup_relation chr WHERE chr.contactgroup_cg_id = cg.cg_id LIMIT 1 + ) OR EXISTS ( + SELECT 1 FROM contactgroup_servicegroup_relation csr WHERE csr.contactgroup_cg_id = cg.cg_id LIMIT 1 + ) OR EXISTS ( + SELECT 1 FROM escalation_contactgroup_relation ecr WHERE ecr.contactgroup_cg_id = cg.cg_id LIMIT 1 + ) + ) + ORDER BY cg.ar_id" + ); $currentLdapId = 0; // the chosen LDAP configuration which should never stay to 0 if the LDAP is found $ldapConn = null; @@ -310,10 +317,7 @@ public function syncWithLdapConfigGen() $connectionResult = $ldapConn->connect(); if ($connectionResult == false) { $ldapServerConnError[$cgRow['ar_id']] = 1; - $stmt = $this->db->query("SELECT ar_name FROM auth_ressource " . - "WHERE ar_id = " . (int)$cgRow['ar_id']); - $res = $stmt->fetch(); - $msg[] = "Unable to connect to LDAP server : " . $res['ar_name'] . "."; + $msg[] = "Unable to connect to LDAP server : " . $cgRow['ar_name'] . "."; continue; } } @@ -331,9 +335,7 @@ public function syncWithLdapConfigGen() if (!$contact) { // no need to continue. If there's no contact, there's no relation to insert. - $stmt = $this->db->query("SELECT ar_name FROM auth_ressource WHERE ar_id = " . (int)$cgRow['ar_id']); - $res = $stmt->fetch(); - $msg[] = "Error : there's no contact to update for LDAP : " . $res['ar_name'] . "."; + $msg[] = "Error : there's no contact to update for LDAP : " . $cgRow['ar_name'] . "."; return $msg; } try { @@ -436,18 +438,19 @@ public function syncWithLdap() throw $e; } continue; - } else { - // Update the ldap group in contactgroup - $queryUpdateDn = "UPDATE contactgroup SET cg_ldap_dn = '" . $dn . - "' WHERE cg_id = " . $row['cg_id']; + } else { // Update the ldap group dn in contactgroup try { - $this->db->query($queryUpdateDn); + $updateDnStatement = $this->db->prepare( + "UPDATE contactgroup SET cg_ldap_dn = :cg_dn WHERE cg_id = :cg_id" + ); + $updateDnStatement->bindValue(':cg_dn', $dn, \PDO::PARAM_STR); + $updateDnStatement->bindValue(':cg_id', $row['cg_id'], \PDO::PARAM_INT); + $updateDnStatement->execute(); $row['cg_ldap_dn'] = $dn; } catch (\PDOException $e) { $msg[] = "Error processing update contactgroup request of ldap group : " . $row['cg_name']; throw $e; - continue; } } } @@ -460,16 +463,16 @@ public function syncWithLdap() ); $deleteStmt->bindValue(':cgId', $row['cg_id'], \PDO::PARAM_INT); $deleteStmt->execute(); - $contact = ''; + $contactDns = ''; foreach ($members as $member) { - $contact .= $this->db->quote($member) . ','; + $contactDns .= $this->db->quote($member) . ','; } - $contact = rtrim($contact, ","); + $contactDns = rtrim($contactDns, ","); - if ($contact !== '') { + if ($contactDns !== '') { try { $resContact = $this->db->query( - "SELECT contact_id FROM contact WHERE contact_ldap_dn IN (" . $contact . ")" + "SELECT contact_id FROM contact WHERE contact_ldap_dn IN (" . $contactDns . ")" ); } catch (\PDOException $e) { $msg[] = "Error in getting contact id from members."; diff --git a/www/class/centreonGraph.class.php b/www/class/centreonGraph.class.php index fd55822883a..4ae3ef297d8 100644 --- a/www/class/centreonGraph.class.php +++ b/www/class/centreonGraph.class.php @@ -1076,16 +1076,18 @@ private function getDefaultGraphTemplate() return; } else { $command_id = getMyServiceField($this->indexData["service_id"], "command_command_id"); - $DBRESULT = $this->DB->query("SELECT graph_id FROM command WHERE `command_id` = '" . $command_id . "'"); - if ($DBRESULT->rowCount()) { - $data = $DBRESULT->fetch(); + $statement = $this->DB->prepare("SELECT graph_id FROM command WHERE `command_id` = :command_id"); + $statement->bindValue(':command_id', (int) $command_id, \PDO::PARAM_INT); + $statement->execute(); + if ($statement->rowCount()) { + $data = $statement->fetch(); if ($data["graph_id"] != 0) { $this->templateId = $data["graph_id"]; unset($data); return; } } - $DBRESULT->closeCursor(); + $statement->closeCursor(); unset($command_id); } $DBRESULT = $this->DB->query("SELECT graph_id FROM giv_graphs_template WHERE default_tpl1 = '1' LIMIT 1"); @@ -1119,12 +1121,12 @@ public function setTemplate($template_id = null) /* * Graph is based on a module check point */ - $DBRESULT_meta = $this->DB->query( - "SELECT graph_id + $statement = $this->DB->prepare("SELECT graph_id FROM meta_service - WHERE `meta_name` = '" . $this->indexData["service_description"] . "'" - ); - $meta = $DBRESULT_meta->fetch(); + WHERE `meta_name` = :service_desc"); + $statement->bindValue(':service_desc', $this->indexData["service_description"], PDO::PARAM_STR); + $statement->execute(); + $meta = $statement->fetch(); $this->templateId = $meta["graph_id"]; unset($meta); } @@ -1149,14 +1151,14 @@ private function getServiceGraphID() $service_id = $this->indexData["service_id"]; $tab = array(); - while (1) { - $DBRESULT = $this->DB->query( - "SELECT esi.graph_id, service_template_model_stm_id + $statement = $this->DB->prepare("SELECT esi.graph_id, service_template_model_stm_id FROM service LEFT JOIN extended_service_information esi ON esi.service_service_id = service_id - WHERE service_id = '" . $service_id . "' LIMIT 1" - ); - $row = $DBRESULT->fetch(); + WHERE service_id = :service_id LIMIT 1"); + while (1) { + $statement->bindValue(':service_id', (int) $service_id, \PDO::PARAM_INT); + $statement->execute(); + $row = $statement->fetch(); if ($row["graph_id"]) { $this->graphID = $row["graph_id"]; return $this->graphID; diff --git a/www/class/centreonHostgroups.class.php b/www/class/centreonHostgroups.class.php index c8c5b1225a2..34dd68d6947 100644 --- a/www/class/centreonHostgroups.class.php +++ b/www/class/centreonHostgroups.class.php @@ -334,6 +334,12 @@ public function getObjectForSelect2($values = array(), $options = array()) return $items; } + $hostgroups = []; + // $values structure: ['1,2,3,4'], keeping the foreach in case it could have more than one index + foreach ($values as $value) { + $hostgroups = array_merge($hostgroups, explode(',', $value)); + } + // get list of authorized hostgroups if (!$centreon->user->access->admin) { $hgAcl = $centreon->user->access->getHostGroupAclConf( @@ -347,7 +353,7 @@ public function getObjectForSelect2($values = array(), $options = array()) 'conditions' => array( 'hostgroup.hg_id' => array( 'IN', - $values + $hostgroups ) ) ), @@ -359,15 +365,13 @@ public function getObjectForSelect2($values = array(), $options = array()) $listValues = ''; $queryValues = array(); - foreach ($values as $k => $v) { - //As it happens that $v could be like "X,Y" when two hostgroups are selected, we added a second foreach - $multiValues = explode(',', $v); - foreach ($multiValues as $item) { - $ids = explode('-', $item); - $listValues .= ':hgId_' . $ids[0] . ', '; - $queryValues['hgId_' . $ids[0]] = (int)$ids[0]; - } + foreach ($hostgroups as $item) { + // the below explode may not be useful + $ids = explode('-', $item); + $listValues .= ':hgId_' . $ids[0] . ', '; + $queryValues['hgId_' . $ids[0]] = (int)$ids[0]; } + $listValues = rtrim($listValues, ', '); $query = 'SELECT hg_id, hg_name FROM hostgroup WHERE hg_id IN (' . $listValues . ') ORDER BY hg_name '; $stmt = $this->DB->prepare($query); diff --git a/www/class/centreonLDAP.class.php b/www/class/centreonLDAP.class.php index ec88cec5d00..d8dd7d18c93 100644 --- a/www/class/centreonLDAP.class.php +++ b/www/class/centreonLDAP.class.php @@ -65,8 +65,8 @@ public function __construct($pearDB, $centreonLog = null, $arId = null) /* Check if use service form DNS */ $use_dns_srv = 0; $dbResult = $this->db->query( - "SELECT `ari_value` - FROM `auth_ressource_info` + "SELECT `ari_value` + FROM `auth_ressource_info` WHERE `ari_name` = 'ldap_srv_dns' AND ar_id = " . (int) $arId ); $row = $dbResult->fetch(); @@ -76,9 +76,9 @@ public function __construct($pearDB, $centreonLog = null, $arId = null) } $dbResult = $this->db->query( - "SELECT `key`, `value` - FROM `options` - WHERE `key` + "SELECT `key`, `value` + FROM `options` + WHERE `key` IN ('debug_ldap_import', 'debug_path')" ); while ($row = $dbResult->fetch()) { @@ -97,22 +97,17 @@ public function __construct($pearDB, $centreonLog = null, $arId = null) $searchTimeout = 5; $tempSearchTimeout = $this->getLdapHostParameters($arId, 'ldap_search_timeout'); - if (count($tempSearchTimeout) > 0) { - if ( - isset($tempSearchTimeout['ari_value']) - && !empty($tempSearchTimeout['ari_value']) - ) { - $searchTimeout = $tempSearchTimeout['ari_value']; - } + if (!empty($tempSearchTimeout['ari_value'])) { + $searchTimeout = $tempSearchTimeout['ari_value']; } /* Get the list of server ldap */ if ($use_dns_srv != "0") { $dns_query = '_ldap._tcp'; $dbResult = $this->db->query( - "SELECT `ari_value` - FROM auth_ressource_info - WHERE `ari_name` = 'ldap_dns_use_domain' + "SELECT `ari_value` + FROM auth_ressource_info + WHERE `ari_name` = 'ldap_dns_use_domain' AND ar_id = " . (int) $arId ); $row = $dbResult->fetch(); @@ -122,11 +117,12 @@ public function __construct($pearDB, $centreonLog = null, $arId = null) } $list = dns_get_record($dns_query, DNS_SRV); foreach ($list as $entry) { - $ldap = array(); - $ldap['host'] = $entry['target']; - $ldap['id'] = $arId; - $ldap['search_timeout'] = $searchTimeout; - $ldap['info'] = $this->getInfoUseDnsConnect(); + $ldap = [ + 'host' => $entry['target'], + 'id' => $arId, + 'search_timeout' => $searchTimeout, + 'info' => $this->getInfoUseDnsConnect(), + ]; $ldap['info']['port'] = $entry['port']; $ldap['info'] = array_merge($ldap['info'], $this->getBindInfo((int) $arId)); $this->ldapHosts[] = $ldap; @@ -138,10 +134,12 @@ public function __construct($pearDB, $centreonLog = null, $arId = null) WHERE auth_ressource_id = ' . (int) $arId . ' ORDER BY host_order' ); while ($row = $dbResult->fetch()) { - $ldap = array(); - $ldap['host'] = $row['host_address']; - $ldap['id'] = $arId; - $ldap['search_timeout'] = $searchTimeout; + $ldap = [ + 'host' => $row['host_address'], + 'id' => $arId, + 'search_timeout' => $searchTimeout, + 'info' => $this->getInfoUseDnsConnect(), + ]; $ldap['info'] = $this->getInfoConnect($row['ldap_host_id']); $ldap['info'] = array_merge($ldap['info'], $this->getBindInfo((int) $arId)); $this->ldapHosts[] = $ldap; @@ -1003,11 +1001,6 @@ public function isSyncNeededAtLogin(int $arId, int $contactId): bool 'Error while getting automatic synchronization value for LDAP Id : ' . $arId ); // assuming it needs to be synchronized - $this->centreonLog->insertLog( - 3, - 'LDAP AUTH : Updating user DN of ' . - (!empty($contactData['contact_name']) ? $contactData['contact_name'] : "contact id $contactId") - ); return true; } $this->centreonLog->insertLog( diff --git a/www/class/centreonTraps.class.php b/www/class/centreonTraps.class.php index e10b7bbbd15..0e05dd4ad6a 100644 --- a/www/class/centreonTraps.class.php +++ b/www/class/centreonTraps.class.php @@ -170,37 +170,6 @@ public function testOidFormat($oid = null) } } - /** - * - * tests if trap already exists - * @param $oid - */ - public function testTrapExistence($oid = null) - { - if ($oid !== null && $this->testOidFormat($oid) === true) { - $id = null; - if (isset($this->form)) { - $id = $this->form->getSubmitValue('traps_id'); - } - $query = "SELECT traps_oid, traps_id FROM traps WHERE traps_oid = :oid "; - - $statement = $this->db->prepare($query); - $statement->bindValue(':oid', $oid, \PDO::PARAM_STR); - $statement->execute(); - - $trap = $statement->fetch(\PDO::FETCH_ASSOC); - - /** - * If the trap already existing return false to trigger an error with the form validation rule - */ - if ($statement->rowCount() >= 1 && $trap["traps_id"] != $id) { - return false; - } else { - return true; - } - } - } - /** * * Delete Traps diff --git a/www/class/centreonUser.class.php b/www/class/centreonUser.class.php index 2c61e80a732..398ed4733f2 100644 --- a/www/class/centreonUser.class.php +++ b/www/class/centreonUser.class.php @@ -56,7 +56,6 @@ class CentreonUser public $groupListStr; public $access; public $log; - public $userCrypted; protected $token; public $default_page; private $showDeprecatedPages; @@ -109,7 +108,6 @@ public function __construct($user = array()) * Initiate Log Class */ $this->log = new CentreonUserLog($this->user_id, $pearDB); - $this->userCrypted = md5($this->alias); /** * Init rest api auth diff --git a/www/class/centreonXMLBGRequest.class.php b/www/class/centreonXMLBGRequest.class.php index 695afe56a02..49e25bbf15a 100644 --- a/www/class/centreonXMLBGRequest.class.php +++ b/www/class/centreonXMLBGRequest.class.php @@ -221,11 +221,12 @@ public function __construct( private function isUserAdmin() { - $query = "SELECT contact_admin, contact_id FROM contact " . - "WHERE contact.contact_id = '" . CentreonDB::escape($this->user_id) . "' LIMIT 1"; - $dbResult = $this->DB->query($query); - $admin = $dbResult->fetchRow(); - $dbResult->closeCursor(); + $statement = $this->DB->prepare("SELECT contact_admin, contact_id FROM contact " . + "WHERE contact.contact_id = :userId LIMIT 1"); + $statement->bindValue(":userId", (int) $this->user_id, \PDO::PARAM_INT); + $statement->execute(); + $admin = $statement->fetchRow(); + $statement->closeCursor(); if ($admin !== false && $admin["contact_admin"]) { $this->is_admin = 1; } else { diff --git a/www/front_src/src/Authentication/FormInputs/FieldsTable/Row.tsx b/www/front_src/src/Authentication/FormInputs/FieldsTable/Row.tsx index b43d27bcc96..d44ab8453fc 100644 --- a/www/front_src/src/Authentication/FormInputs/FieldsTable/Row.tsx +++ b/www/front_src/src/Authentication/FormInputs/FieldsTable/Row.tsx @@ -19,6 +19,7 @@ const useStyles = makeStyles((theme) => ({ columnGap: theme.spacing(2), display: 'grid', gridTemplateColumns: `repeat(${columns}, 1fr) ${theme.spacing(6)}`, + gridTemplateRows: 'min-content', }), })); diff --git a/www/front_src/src/Authentication/Openid/Form/inputs.ts b/www/front_src/src/Authentication/Openid/Form/inputs.ts index 01c07962a97..55b3b1fa125 100644 --- a/www/front_src/src/Authentication/Openid/Form/inputs.ts +++ b/www/front_src/src/Authentication/Openid/Form/inputs.ts @@ -1,4 +1,4 @@ -import { equals, isEmpty, isNil, not, path, prop } from 'ramda'; +import { equals, isEmpty, not, prop } from 'ramda'; import { FormikValues } from 'formik'; import { @@ -32,7 +32,7 @@ import { labelDeleteRelation, labelAuthorizationKey, } from '../translatedLabels'; -import { AuthenticationType, AuthorizationRule } from '../models'; +import { AuthenticationType } from '../models'; import { InputProps, InputType } from '../../FormInputs/models'; import { labelActivation, @@ -249,20 +249,6 @@ export const inputs: Array = [ claimValue: '', }, deleteLabel: labelDeleteRelation, - getRequired: ({ values, index }): boolean => { - const tableValues = prop('authorizationRules', values); - - const rowValues = path( - ['authorizationRules', index], - values, - ); - - return isNil(prop('contactGroup', values)) - ? not(isNil(rowValues)) - : isNil(tableValues) || - isEmpty(rowValues?.claimValue) || - isNil(rowValues?.accessGroup); - }, }, label: labelDefineRelationAuthorizationValueAndAccessGroup, type: InputType.FieldsTable, diff --git a/www/front_src/src/Authentication/Openid/index.test.tsx b/www/front_src/src/Authentication/Openid/index.test.tsx index d7fffde1689..ab9b4efb751 100644 --- a/www/front_src/src/Authentication/Openid/index.test.tsx +++ b/www/front_src/src/Authentication/Openid/index.test.tsx @@ -445,11 +445,10 @@ describe('Openid configuration form', () => { accessGroupsEndpoint, labelAccessGroup, 'Access Group 2', - 1, ], ])( 'updates the %p field when an option is selected from the retrieved options', - async (_, retrievedOptions, endpoint, label, value, index = 0) => { + async (_, retrievedOptions, endpoint, label, value) => { mockGetRequestsWithNoAuthorizationConfiguration(); renderOpenidConfigurationForm(); @@ -484,7 +483,7 @@ describe('Openid configuration form', () => { userEvent.click(screen.getByText(value)); await waitFor(() => { - expect(screen.getAllByLabelText(label)[index]).toHaveValue(value); + expect(screen.getAllByLabelText(label)[0]).toHaveValue(value); }); }, ); @@ -508,40 +507,4 @@ describe('Openid configuration form', () => { ); }); }); - - it('displays the "Authorization value" and "Access group" fields as required when the "Contact group" field is filled', async () => { - mockGetRequestsWithNoAuthorizationConfiguration(); - mockedAxios.get.mockResolvedValueOnce({ - data: retrievedContactGroups, - }); - - renderOpenidConfigurationForm(); - - await waitFor(() => { - expect(screen.getByLabelText(labelContactGroup)).toBeInTheDocument(); - }); - - userEvent.click(screen.getByLabelText(labelContactGroup)); - - await waitFor(() => { - expect(mockedAxios.get).toHaveBeenCalledWith( - `${contactGroupsEndpoint}?page=1&sort_by=${encodeURIComponent( - '{"name":"ASC"}', - )}`, - cancelTokenRequestParam, - ); - }); - - await waitFor(() => { - expect(screen.getByText('Contact Group 1')).toBeInTheDocument(); - }); - - userEvent.click(screen.getByText('Contact Group 1')); - - await waitFor(() => { - expect(screen.getByLabelText(labelAuthorizationValue)).toHaveAttribute( - 'required', - ); - }); - }); }); diff --git a/www/front_src/src/Authentication/Openid/useValidationSchema.ts b/www/front_src/src/Authentication/Openid/useValidationSchema.ts index 4f703165f68..038812dadee 100644 --- a/www/front_src/src/Authentication/Openid/useValidationSchema.ts +++ b/www/front_src/src/Authentication/Openid/useValidationSchema.ts @@ -6,7 +6,6 @@ import { labelRequired, labelInvalidURL, labelInvalidIPAddress, - labelAtLeastOneAuthorizationIsRequired, } from './translatedLabels'; const IPAddressRegexp = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(\/\d{1,3})?$/; @@ -29,15 +28,7 @@ const useValidationSchema = (): Yup.SchemaOf => { return Yup.object({ authenticationType: Yup.string().required(t(labelRequired)), authorizationEndpoint: Yup.string().nullable().required(t(labelRequired)), - authorizationRules: Yup.array() - .of(authorizationSchema) - .when('contactGroup', (contactGroup, schema) => { - return contactGroup - ? schema - .min(1, t(labelAtLeastOneAuthorizationIsRequired)) - .required(t(labelRequired)) - : schema.nullable(); - }), + authorizationRules: Yup.array().of(authorizationSchema), autoImport: Yup.boolean().required(t(labelRequired)), baseUrl: Yup.string() .matches(urlRegexp, t(labelInvalidURL)) diff --git a/www/front_src/src/Authentication/index.tsx b/www/front_src/src/Authentication/index.tsx index bf12422f160..71668d687f8 100644 --- a/www/front_src/src/Authentication/index.tsx +++ b/www/front_src/src/Authentication/index.tsx @@ -1,9 +1,8 @@ -import { useMemo } from 'react'; +import { useEffect, useMemo, useRef, useState } from 'react'; import { useTranslation } from 'react-i18next'; import { useAtomValue } from 'jotai'; import { useUpdateAtom } from 'jotai/utils'; -import { Responsive } from '@visx/visx'; import { Box, Container, Paper, Tab } from '@mui/material'; import { TabContext, TabList, TabPanel } from '@mui/lab'; @@ -90,35 +89,39 @@ const useStyles = makeStyles((theme) => ({ formContainer: { display: 'grid', gridTemplateColumns: '1.2fr 0.6fr', - height: '100%', - overflowY: 'auto', + justifyItems: 'center', padding: theme.spacing(3), }, image: { + height: '200px', opacity: 0.5, padding: theme.spacing(0, 5), position: 'sticky', top: 0, + width: '200px', }, panel: { - height: '80%', padding: 0, }, paper: { boxShadow: theme.shadows[3], - height: '100%', }, tabList: { boxShadow: theme.shadows[2], }, })); -const marginBottomHeight = 88; +const scrollMargin = 8; const Authentication = (): JSX.Element => { const classes = useStyles(); const { t } = useTranslation(); + const formContainerRef = useRef(null); + + const [windowHeight, setWindowHeight] = useState(window.innerHeight); + const [clientRect, setClientRect] = useState(null); + const appliedTab = useAtomValue(appliedTabAtom); const { themeMode } = useAtomValue(userAtom); const setTab = useUpdateAtom(tabAtom); @@ -127,6 +130,23 @@ const Authentication = (): JSX.Element => { setTab(newTab); }; + const resize = (): void => { + setWindowHeight(window.innerHeight); + }; + + useEffect(() => { + window.addEventListener('resize', resize); + + setClientRect(formContainerRef.current?.getBoundingClientRect() ?? null); + + return () => { + window.removeEventListener('resize', resize); + }; + }, []); + + const formContainerHeight = + windowHeight - (clientRect?.top || 0) - scrollMargin; + const tabs = useMemo( () => panels.map(({ title, value }) => ( @@ -136,33 +156,31 @@ const Authentication = (): JSX.Element => { ); const tabPanels = useMemo( - () => ( - - {({ height }): Array => - panels.map(({ Component, value, image }) => ( - -
- - padlock -
-
- )) - } -
- ), - [themeMode], + () => + panels.map(({ Component, value, image }) => ( + + +
+ + padlock +
+
+
+ )), + [themeMode, formContainerHeight], ); return ( - + ({ dateTime: { @@ -20,7 +20,7 @@ const Clock = (): JSX.Element => { time: '', }); - const { format, toTime } = useLocaleDateTimeFormat(); + const { format, toTime } = centreonUi.useLocaleDateTimeFormat(); const updateDateTime = (): void => { const now = new Date(); @@ -48,7 +48,7 @@ const Clock = (): JSX.Element => { const { date, time } = dateTime; return ( -
+
{date} {time}
diff --git a/www/front_src/src/Header/SwitchThemeMode/images/moon.svg b/www/front_src/src/Header/SwitchThemeMode/images/moon.svg deleted file mode 100644 index 4c16f826815..00000000000 --- a/www/front_src/src/Header/SwitchThemeMode/images/moon.svg +++ /dev/null @@ -1,3 +0,0 @@ - \ No newline at end of file diff --git a/www/front_src/src/Header/SwitchThemeMode/images/sun.svg b/www/front_src/src/Header/SwitchThemeMode/images/sun.svg deleted file mode 100644 index c819f5b586d..00000000000 --- a/www/front_src/src/Header/SwitchThemeMode/images/sun.svg +++ /dev/null @@ -1,3 +0,0 @@ - \ No newline at end of file diff --git a/www/front_src/src/Header/SwitchThemeMode/index.tsx b/www/front_src/src/Header/SwitchThemeMode/index.tsx index 8a3eca92bda..ef83ec81ebf 100644 --- a/www/front_src/src/Header/SwitchThemeMode/index.tsx +++ b/www/front_src/src/Header/SwitchThemeMode/index.tsx @@ -1,105 +1,70 @@ -import { equals } from 'ramda'; -import { useAtom } from 'jotai'; +import { useState } from 'react'; + +import clsx from 'clsx'; import { useLocation } from 'react-router-dom'; -import { styled } from '@mui/material/styles'; -import Switch from '@mui/material/Switch'; +import { ListItemText, Switch } from '@mui/material'; import makeStyles from '@mui/styles/makeStyles'; -import { userAtom, ThemeMode } from '@centreon/ui-context'; import { patchData, useRequest } from '@centreon/ui'; -import svgSun from './images/sun.svg'; -import svgMoon from './images/moon.svg'; - -interface StyleProps { - darkModeSvg?: string; - lightModeSvg?: string; -} +import useSwitchThemeMode from './useSwitchThemeMode'; -const ThemeModeSwitch = styled(Switch, { - shouldForwardProp: (prop) => - !equals(prop, 'color') && - !equals(prop, 'lightModeSvg') && - !equals(prop, 'darkModeSvg'), -})(({ theme, darkModeSvg, lightModeSvg }) => ({ - '& .MuiSwitch-switchBase': { +const useStyles = makeStyles((theme) => ({ + container: { + '& .MuiSwitch-thumb': { + backgroundColor: 'white', + }, + '& .MuiSwitch-track': { + backgroundColor: '#aab4be', + opacity: 1, + }, + alignItems: 'center', + display: 'flex', + }, + containerMode: { + display: 'flex', + justifyContent: 'space-around', + }, + containerSwitch: { + '& .MuiSwitch-switchBase': { + padding: theme.spacing(0.5, 0.5, 0.5, 0.75), + }, '&.Mui-checked': { - '& + .MuiSwitch-track': { - backgroundColor: '#aab4be', - opacity: 1, - }, - '& .MuiSwitch-thumb:before': { - backgroundImage: `url(${darkModeSvg})`, + '&:hover': { + backgroundColor: 'unset', }, - color: 'transparent', - transform: 'translate(15px,-50%)', }, '&:hover': { - backgroundColor: 'transparent', + backgroundColor: 'unset', }, - color: 'black', - margin: 0, - position: 'absolute', - top: '50%', - transform: 'translate(-0.5px,-50%)', }, - '& .MuiSwitch-thumb': { - '&:before': { - backgroundImage: `url(${lightModeSvg})`, - backgroundPosition: 'center', - backgroundRepeat: 'no-repeat', - content: "''", - height: '100%', - left: theme.spacing(0), - position: 'absolute', - top: theme.spacing(0), - width: '100%', - }, - backgroundColor: 'white', - height: theme.spacing(3), - width: theme.spacing(3), + disabledMode: { + color: theme.palette.common.white, + opacity: 0.5, }, - '& .MuiSwitch-track': { - backgroundColor: '#aab4be', - borderRadius: theme.spacing(10 / 8), - opacity: 1, - }, - height: theme.spacing(32 / 8), - padding: theme.spacing(11 / 8, 4 / 8, 11 / 8, 9 / 8), - width: theme.spacing(50 / 8), -})); - -const useStyles = makeStyles(() => ({ - container: { - alignItems: 'center', - display: 'flex', + mode: { + paddingLeft: theme.spacing(1), }, })); const SwitchThemeMode = (): JSX.Element => { - const props = { - darkModeSvg: svgMoon, - lightModeSvg: svgSun, - }; const classes = useStyles(); const { pathname } = useLocation(); + const [isPending, isDarkMode, themeMode, updateUser] = useSwitchThemeMode(); + + const [isDark, setIsDark] = useState(isDarkMode); const { sendRequest } = useRequest({ request: patchData, }); - const [user, setUser] = useAtom(userAtom); - const isDarkMode = equals(user.themeMode, ThemeMode.dark); const switchEndPoint = './api/latest/configuration/users/current/parameters'; const switchThemeMode = (): void => { - const themeMode = isDarkMode ? ThemeMode.light : ThemeMode.dark; const isCurrentPageLegacy = pathname.includes('php'); - setUser({ - ...user, - themeMode, - }); + setIsDark(!isDark); + updateUser(); sendRequest({ data: { theme: themeMode }, endpoint: switchEndPoint, @@ -112,11 +77,29 @@ const SwitchThemeMode = (): JSX.Element => { return (
- +
+ + Light + + + + Dark + +
); }; diff --git a/www/front_src/src/Header/SwitchThemeMode/useSwitchThemeMode.tsx b/www/front_src/src/Header/SwitchThemeMode/useSwitchThemeMode.tsx new file mode 100644 index 00000000000..f25adff71f7 --- /dev/null +++ b/www/front_src/src/Header/SwitchThemeMode/useSwitchThemeMode.tsx @@ -0,0 +1,30 @@ +import { useTransition } from 'react'; + +import { useAtom } from 'jotai'; +import { equals } from 'ramda'; + +import { userAtom, ThemeMode } from '@centreon/ui-context'; + +const useSwitchThemeMode = (): [ + isDarkMode: boolean, + isPending: boolean, + themeMode: ThemeMode, + updateUser: () => void, +] => { + const [user, setUser] = useAtom(userAtom); + const isDarkMode = equals(user.themeMode, ThemeMode.dark); + const [isPending, startTransition] = useTransition(); + + const themeMode = isDarkMode ? ThemeMode.light : ThemeMode.dark; + const updateUser = (): void => + startTransition(() => { + setUser({ + ...user, + themeMode, + }); + }); + + return [isPending, isDarkMode, themeMode, updateUser]; +}; + +export default useSwitchThemeMode; diff --git a/www/front_src/src/Header/helpers/index.ts b/www/front_src/src/Header/helpers/index.ts new file mode 100644 index 00000000000..62d01d70451 --- /dev/null +++ b/www/front_src/src/Header/helpers/index.ts @@ -0,0 +1,5 @@ +import { useLocaleDateTimeFormat } from '@centreon/ui'; + +export const centreonUi = { + useLocaleDateTimeFormat, +}; diff --git a/www/front_src/src/Header/index.tsx b/www/front_src/src/Header/index.tsx index 3d1262da36d..dbf1e2c3cfd 100755 --- a/www/front_src/src/Header/index.tsx +++ b/www/front_src/src/Header/index.tsx @@ -1,3 +1,5 @@ +import { useRef } from 'react'; + import { makeStyles } from '@mui/styles'; import Hook from '../components/Hook'; @@ -6,7 +8,6 @@ import PollerMenu from './PollerMenu'; import HostStatusCounter from './RessourceStatusCounter/Host'; import ServiceStatusCounter from './RessourceStatusCounter/Service'; import UserMenu from './userMenu'; -import SwitchMode from './SwitchThemeMode'; const HookComponent = Hook as unknown as (props) => JSX.Element; @@ -30,12 +31,12 @@ const useStyles = makeStyles((theme) => ({ justifyContent: 'center', }, pollerContainer: { - flex: 0.5, + flex: 0.4, }, rightContainer: { alignItems: 'center', display: 'flex', - flex: 1.1, + flex: 0.9, }, serviceStatusContainer: { display: 'flex', @@ -49,16 +50,17 @@ const useStyles = makeStyles((theme) => ({ userMenuContainer: { alignItems: 'center', display: 'flex', - flex: 0.4, + flex: 0.3, justifyContent: 'flex-end', }, })); const Header = (): JSX.Element => { const classes = useStyles(); + const headerRef = useRef(null); return ( -
+
@@ -74,10 +76,7 @@ const Header = (): JSX.Element => {
- -
- -
+
diff --git a/www/front_src/src/Header/userMenu/index.test.tsx b/www/front_src/src/Header/userMenu/index.test.tsx index 471ef21a908..2878468f19a 100644 --- a/www/front_src/src/Header/userMenu/index.test.tsx +++ b/www/front_src/src/Header/userMenu/index.test.tsx @@ -109,11 +109,9 @@ describe('User Menu', () => { userEvent.click(screen.getByLabelText(labelProfile)); await waitFor(() => { - expect(screen.getByText('Admin admin')).toBeInTheDocument(); + expect(screen.getByText('admin')).toBeInTheDocument(); }); - expect(screen.getByText('as admin')).toBeInTheDocument(); - await waitFor(() => { expect(screen.getByText('1:20 PM')).toBeInTheDocument(); }); @@ -139,7 +137,7 @@ describe('User Menu', () => { }); await waitFor(() => { - expect(screen.getByText('Admin admin')).toBeInTheDocument(); + expect(screen.getByText('admin')).toBeInTheDocument(); }); userEvent.click(screen.getByText(labelCopyAutologinLink)); diff --git a/www/front_src/src/Header/userMenu/index.tsx b/www/front_src/src/Header/userMenu/index.tsx index 45adb4fc4e7..9b66220f892 100755 --- a/www/front_src/src/Header/userMenu/index.tsx +++ b/www/front_src/src/Header/userMenu/index.tsx @@ -6,6 +6,8 @@ import { useNavigate } from 'react-router-dom'; import { useUpdateAtom } from 'jotai/utils'; import { gt, isNil, not, __ } from 'ramda'; +import { grey } from '@mui/material/colors'; +import Divider from '@mui/material/Divider'; import { Typography, Paper, @@ -35,6 +37,7 @@ import { useLocaleDateTimeFormat, } from '@centreon/ui'; +import SwitchMode from '../SwitchThemeMode/index'; import Clock from '../Clock'; import useNavigation from '../../Navigation/useNavigation'; import { areUserParametersLoadedAtom } from '../../Main/useUser'; @@ -79,6 +82,27 @@ const ListItemIcon = styled(MUIListItemIcon)(({ theme }) => ({ })); const useStyles = makeStyles((theme) => ({ + button: { + '&:hover': { + '&:after': { + backgroundColor: theme.palette.common.white, + content: '""', + height: '100%', + left: 0, + opacity: 0.08, + position: 'absolute', + right: 0, + top: 0, + }, + }, + }, + containerList: { + padding: theme.spacing(0.5, 0, 0.5, 0), + }, + divider: { + borderColor: grey[600], + margin: theme.spacing(0, 1.25, 0, 1.25), + }, fullname: { overflow: 'hidden', textOverflow: 'ellipsis', @@ -91,14 +115,23 @@ const useStyles = makeStyles((theme) => ({ top: theme.spacing(-13), width: theme.spacing(0), }, + icon: { + minWidth: theme.spacing(3.75), + }, loaderUserMenu: { - marginRight: 22, + marginRight: theme.spacing(22 / 8), }, menu: { backgroundColor: theme.palette.common.black, + borderRadius: 0, color: theme.palette.common.white, - maxWidth: 230, - width: '100%', + minWidth: 190, + }, + menuItem: { + padding: theme.spacing(0, 2, 0.25, 2), + }, + nameContainer: { + padding: theme.spacing(0, 2, 0.25, 2.25), }, passwordExpiration: { color: theme.palette.warning.main, @@ -107,6 +140,9 @@ const useStyles = makeStyles((theme) => ({ overflow: 'hidden', zIndex: theme.zIndex.tooltip, }, + switchItem: { + padding: theme.spacing(0, 2, 0.25, 11 / 8), + }, text: { overflow: 'hidden', textOverflow: 'ellipsis', @@ -119,6 +155,7 @@ const useStyles = makeStyles((theme) => ({ }, wrapRightUser: { alignItems: 'center', + background: theme.palette.common.black, display: 'flex', flexWrap: 'wrap', marginLeft: theme.spacing(0.5), @@ -131,8 +168,11 @@ const useStyles = makeStyles((theme) => ({ justifyContent: 'flex-end', }, })); +interface Props { + headerRef?: RefObject; +} -const UserMenu = (): JSX.Element => { +const UserMenu = ({ headerRef }: Props): JSX.Element => { const classes = useStyles(); const { t } = useTranslation(); const { allowedPages } = useNavigation(); @@ -140,10 +180,12 @@ const UserMenu = (): JSX.Element => { const [copied, setCopied] = useState(false); const [data, setData] = useState(null); const [anchorEl, setAnchorEl] = useState(null); + const [anchorHeight, setAnchorHeight] = useState(12); const profile = useRef(); const userMenu = useRef(); const autologinNode = useRef(); const refreshTimeout = useRef(); + const userIconRef = useRef(null); const { sendRequest: logoutRequest } = useRequest({ request: postData, }); @@ -198,6 +240,21 @@ const UserMenu = (): JSX.Element => { }, 60000); }; + const getPositionOfPopper = (): void => { + if (isNil(headerRef?.current) || isNil(userIconRef?.current)) { + return; + } + const headerHeight = headerRef?.current?.getBoundingClientRect()?.height; + + const userMenuBottom = + userIconRef?.current?.getBoundingClientRect()?.bottom; + + if (isNil(headerHeight)) { + return; + } + setAnchorHeight(headerHeight - userMenuBottom); + }; + const toggle = (event: MouseEvent): void => { if (anchorEl) { setAnchorEl(null); @@ -205,6 +262,7 @@ const UserMenu = (): JSX.Element => { return; } setAnchorEl(event.currentTarget); + getPositionOfPopper(); }; const closeUserMenu = (): void => { @@ -246,10 +304,14 @@ const UserMenu = (): JSX.Element => { useEffect(() => { window.addEventListener('mousedown', handleClick, false); + window.addEventListener('resize', getPositionOfPopper); + loadUserData(); return (): void => { window.removeEventListener('mousedown', handleClick, false); + window.removeEventListener('resize', getPositionOfPopper); + if (refreshTimeout.current) { clearTimeout(refreshTimeout.current); } @@ -279,9 +341,9 @@ const UserMenu = (): JSX.Element => { }; return ( -
+
} > @@ -302,8 +364,10 @@ const UserMenu = (): JSX.Element => { > @@ -312,8 +376,16 @@ const UserMenu = (): JSX.Element => { transition anchorEl={anchorEl} className={classes.popper} + data-cy="popper" + modifiers={[ + { + name: 'offset', + options: { + offset: [22, anchorHeight], + }, + }, + ]} open={not(isNil(anchorEl))} - placement="bottom-end" > {({ TransitionProps }): JSX.Element => ( @@ -324,21 +396,18 @@ const UserMenu = (): JSX.Element => { display: isNil(anchorEl) ? 'none' : 'block', }} > - - + + - {data.fullname} + {data.username} - - {`${t('as')} ${data.username}`} - + + {not(passwordIsNotYetAboutToExpire) && ( - +
{t(labelPasswordWillExpireIn)}: @@ -350,11 +419,12 @@ const UserMenu = (): JSX.Element => { )} {allowEditProfile && ( - + - + {t(labelEditProfile)} @@ -362,9 +432,9 @@ const UserMenu = (): JSX.Element => { )} {data.autologinkey && ( - + - + {copied ? ( ) : ( @@ -384,9 +454,18 @@ const UserMenu = (): JSX.Element => { /> )} - - - +
+ +
+ + + + + + {t(labelLogout)} diff --git a/www/front_src/src/Resources/Graph/Performance/ExportableGraphWithTimeline/exportToPng.ts b/www/front_src/src/Resources/Graph/Performance/ExportableGraphWithTimeline/exportToPng.ts index 35f49e5507e..0f308c7c332 100644 --- a/www/front_src/src/Resources/Graph/Performance/ExportableGraphWithTimeline/exportToPng.ts +++ b/www/front_src/src/Resources/Graph/Performance/ExportableGraphWithTimeline/exportToPng.ts @@ -2,12 +2,18 @@ import { saveAs } from 'file-saver'; import dom2image from 'dom-to-image'; interface Props { + backgroundColor: string; element: HTMLElement; ratio: number; title: string; } -const exportToPng = async ({ element, title, ratio }: Props): Promise => { +const exportToPng = async ({ + element, + title, + ratio, + backgroundColor, +}: Props): Promise => { const dateTime = new Date().toISOString().substring(0, 19); const getTranslation = (size: number): number => { @@ -19,7 +25,7 @@ const exportToPng = async ({ element, title, ratio }: Props): Promise => { return dom2image .toBlob(element, { - bgcolor: '#FFFFFF', + bgcolor: backgroundColor, height: element.offsetHeight * ratio, style: { transform: `translate(-${translateX}px, -${translateY}px) scale(${ratio})`, diff --git a/www/front_src/src/Resources/Graph/Performance/GraphActions.tsx b/www/front_src/src/Resources/Graph/Performance/GraphActions.tsx index b731ff5bb11..c19c93ed464 100644 --- a/www/front_src/src/Resources/Graph/Performance/GraphActions.tsx +++ b/www/front_src/src/Resources/Graph/Performance/GraphActions.tsx @@ -8,6 +8,7 @@ import { Menu, MenuItem } from '@mui/material'; import makeStyles from '@mui/styles/makeStyles'; import SaveAsImageIcon from '@mui/icons-material/SaveAlt'; import LaunchIcon from '@mui/icons-material/Launch'; +import { useTheme } from '@mui/material/styles'; import { ContentWithCircularLoading, @@ -56,6 +57,8 @@ const GraphActions = ({ performanceGraphRef, }: Props): JSX.Element => { const classes = useStyles(); + const theme = useTheme(); + const { t } = useTranslation(); const [menuAnchor, setMenuAnchor] = useState(null); const [exporting, setExporting] = useState(false); @@ -96,6 +99,7 @@ const GraphActions = ({ setMenuAnchor(null); setExporting(true); exportToPng({ + backgroundColor: theme.palette.background.default, element: performanceGraphRef.current as HTMLElement, ratio, title: `${resourceName}-performance`, diff --git a/www/include/Administration/parameters/DB-Func.php b/www/include/Administration/parameters/DB-Func.php index 69cec29760c..46077c5e8b7 100644 --- a/www/include/Administration/parameters/DB-Func.php +++ b/www/include/Administration/parameters/DB-Func.php @@ -472,7 +472,6 @@ function updateLdapConfigData($gopt_id = null) { global $form, $pearDB, $centreon; - $ret = array(); $ret = $form->getSubmitValues(); updateOption( diff --git a/www/include/Administration/parameters/ldap/form.php b/www/include/Administration/parameters/ldap/form.php index da20aa5da01..bd9517846d5 100644 --- a/www/include/Administration/parameters/ldap/form.php +++ b/www/include/Administration/parameters/ldap/form.php @@ -153,8 +153,8 @@ /** * Default contactgroup for imported contact */ -$cgAvRoute = './include/common/webServices/rest/internal.php?object=centreon_configuration_contactgroup&action=list'; -$cgDeRoute = './include/common/webServices/rest/internal.php?object=centreon_configuration_contactgroup' +$cgAvRoute = './api/internal.php?object=centreon_configuration_contactgroup&action=list'; +$cgDeRoute = './api/internal.php?object=centreon_configuration_contactgroup' . '&action=defaultValues&target=contact&field=ldap_default_cg&id=' . $arId; $attrContactGroup = array( 'datasourceOrigin' => 'ajax', diff --git a/www/include/configuration/configCentreonBroker/listCentreonBroker.php b/www/include/configuration/configCentreonBroker/listCentreonBroker.php index 7e2e86df5ad..8ed2fbac2a1 100644 --- a/www/include/configuration/configCentreonBroker/listCentreonBroker.php +++ b/www/include/configuration/configCentreonBroker/listCentreonBroker.php @@ -124,6 +124,12 @@ $elemArr = array(); $centreonToken = createCSRFToken(); +$statementBrokerInfo = $pearDB->prepare( + "SELECT COUNT(DISTINCT(config_group_id)) as num " . + "FROM cfg_centreonbroker_info " . + "WHERE config_group = :config_group " . + "AND config_id = :config_id" +); for ($i = 0; $config = $dbResult->fetch(); $i++) { $moptions = ""; @@ -147,29 +153,22 @@ . "style=\"margin-bottom:0px;\" name='dupNbr[" . $config['config_id'] . "]'>"; // Number of output - $res = $pearDB->query( - "SELECT COUNT(DISTINCT(config_group_id)) as num " . - "FROM cfg_centreonbroker_info " . - "WHERE config_group = 'output' " . - "AND config_id = " . $config['config_id'] - ); - $row = $res->fetch(); + $statementBrokerInfo->bindValue(':config_id', (int) $config['config_id'], \PDO::PARAM_INT); + $statementBrokerInfo->bindValue(':config_group', 'output', \PDO::PARAM_STR); + $statementBrokerInfo->execute(); + $row = $statementBrokerInfo->fetch(\PDO::FETCH_ASSOC); $outputNumber = $row["num"]; // Number of input - $res = $pearDB->query( - "SELECT COUNT(DISTINCT(config_group_id)) as num " . - "FROM cfg_centreonbroker_info " . - "WHERE config_group = 'input' " . - "AND config_id = " . $config['config_id'] - ); - $row = $res->fetch(); + $statementBrokerInfo->bindValue(':config_group', 'input', \PDO::PARAM_STR); + $statementBrokerInfo->execute(); + $row = $statementBrokerInfo->fetch(\PDO::FETCH_ASSOC); $inputNumber = $row["num"]; $elemArr[$i] = array( "MenuClass" => "list_" . $style, "RowMenu_select" => $selectedElements->toHtml(), - "RowMenu_name" => CentreonUtils::escapeSecure($config["config_name"]), + "RowMenu_name" => htmlentities($config["config_name"], ENT_QUOTES, 'UTF-8'), "RowMenu_link" => "main.php?p=" . $p . "&o=c&id=" . $config['config_id'], "RowMenu_desc" => CentreonUtils::escapeSecure( substr( diff --git a/www/include/configuration/configObject/host_dependency/DB-Func.php b/www/include/configuration/configObject/host_dependency/DB-Func.php index a7b09cbeeaf..57209f88c74 100644 --- a/www/include/configuration/configObject/host_dependency/DB-Func.php +++ b/www/include/configuration/configObject/host_dependency/DB-Func.php @@ -123,11 +123,14 @@ function multipleHostDependencyInDB($dependencies = array(), $nbrDup = array()) "WHERE dependency_dep_id = " . $key; $dbResult = $pearDB->query($query); $fields["dep_serviceChilds"] = ""; + $statement = $pearDB->prepare("INSERT INTO dependency_serviceChild_relation " . + " VALUES (:max_dep_id, :service_id, :host_host_id)"); while ($service = $dbResult->fetch()) { - $query = "INSERT INTO dependency_serviceChild_relation VALUES ('" . - $maxId["MAX(dep_id)"] . "', '" . $service["service_service_id"] . "', '" . - $service["host_host_id"] . "')"; - $pearDB->query($query); + $statement->bindValue(':max_dep_id', (int)$maxId["MAX(dep_id)"], \PDO::PARAM_INT); + $statement->bindValue(':service_id', (int)$service["service_service_id"], \PDO::PARAM_INT); + $statement->bindValue(':host_host_id', (int)$service["host_host_id"], \PDO::PARAM_INT); + $statement->execute(); + $fields["dep_serviceChilds"] .= $service["host_host_id"] . '-' . $service["service_service_id"] . ","; } @@ -136,10 +139,12 @@ function multipleHostDependencyInDB($dependencies = array(), $nbrDup = array()) "WHERE dependency_dep_id = '" . $key . "'"; $dbResult = $pearDB->query($query); $fields["dep_hostParents"] = ""; + $statement = $pearDB->prepare("INSERT INTO dependency_hostParent_relation " . + "VALUES (:max_dep_id, :host_host_id)"); while ($host = $dbResult->fetch()) { - $query = "INSERT INTO dependency_hostParent_relation " . - "VALUES ('" . $maxId["MAX(dep_id)"] . "', '" . $host["host_host_id"] . "')"; - $pearDB->query($query); + $statement->bindValue(':max_dep_id', (int)$maxId["MAX(dep_id)"], \PDO::PARAM_INT); + $statement->bindValue(':host_host_id', (int)$host["host_host_id"], \PDO::PARAM_INT); + $statement->execute(); $fields["dep_hostParents"] .= $host["host_host_id"] . ","; } $fields["dep_hostParents"] = trim($fields["dep_hostParents"], ","); @@ -148,10 +153,12 @@ function multipleHostDependencyInDB($dependencies = array(), $nbrDup = array()) "WHERE dependency_dep_id = '" . $key . "'"; $dbResult = $pearDB->query($query); $fields["dep_hostChilds"] = ""; + $statement = $pearDB->prepare("INSERT INTO dependency_hostChild_relation " . + "VALUES (:max_dep_id, :host_host_id)"); while ($host = $dbResult->fetch()) { - $query = "INSERT INTO dependency_hostChild_relation " . - "VALUES ('" . $maxId["MAX(dep_id)"] . "', '" . $host["host_host_id"] . "')"; - $pearDB->query($query); + $statement->bindValue(':max_dep_id', (int)$maxId["MAX(dep_id)"], \PDO::PARAM_INT); + $statement->bindValue(':host_host_id', (int)$host["host_host_id"], \PDO::PARAM_INT); + $statement->execute(); $fields["dep_hostChilds"] .= $host["host_host_id"] . ","; } $fields["dep_hostChilds"] = trim($fields["dep_hostChilds"], ","); diff --git a/www/include/configuration/configObject/hostgroup_dependency/DB-Func.php b/www/include/configuration/configObject/hostgroup_dependency/DB-Func.php index ded4d3c58ff..1ddeac48d46 100644 --- a/www/include/configuration/configObject/hostgroup_dependency/DB-Func.php +++ b/www/include/configuration/configObject/hostgroup_dependency/DB-Func.php @@ -124,10 +124,12 @@ function multipleHostGroupDependencyInDB($dependencies = array(), $nbrDup = arra "WHERE dependency_dep_id = '" . $key . "'"; $dbResult = $pearDB->query($query); $fields["dep_hgParents"] = ""; + $query = "INSERT INTO dependency_hostgroupParent_relation VALUES (:max_id, :hg_id)"; + $statement = $pearDB->prepare($query); while ($hg = $dbResult->fetch()) { - $query = "INSERT INTO dependency_hostgroupParent_relation VALUES ('" . - $maxId["MAX(dep_id)"] . "', '" . $hg["hostgroup_hg_id"] . "')"; - $pearDB->query($query); + $statement->bindValue(':max_id', (int) $maxId["MAX(dep_id)"], \PDO::PARAM_INT); + $statement->bindValue(':hg_id', (int) $hg["hostgroup_hg_id"], \PDO::PARAM_INT); + $statement->execute(); $fields["dep_hgParents"] .= $hg["hostgroup_hg_id"] . ","; } $fields["dep_hgParents"] = trim($fields["dep_hgParents"], ","); @@ -136,10 +138,12 @@ function multipleHostGroupDependencyInDB($dependencies = array(), $nbrDup = arra "WHERE dependency_dep_id = '" . $key . "'"; $dbResult = $pearDB->query($query); $fields["dep_hgChilds"] = ""; + $query = "INSERT INTO dependency_hostgroupChild_relation VALUES (:max_id, :hg_id)"; + $statement = $pearDB->prepare($query); while ($hg = $dbResult->fetch()) { - $query = "INSERT INTO dependency_hostgroupChild_relation VALUES ('" . - $maxId["MAX(dep_id)"] . "', '" . $hg["hostgroup_hg_id"] . "')"; - $pearDB->query($query); + $statement->bindValue(':max_id', (int) $maxId["MAX(dep_id)"], \PDO::PARAM_INT); + $statement->bindValue(':hg_id', (int) $hg["hostgroup_hg_id"], \PDO::PARAM_INT); + $statement->execute(); $fields["dep_hgChilds"] .= $hg["hostgroup_hg_id"] . ","; } $fields["dep_hgChilds"] = trim($fields["dep_hgChilds"], ","); diff --git a/www/include/configuration/configObject/metaservice_dependency/DB-Func.php b/www/include/configuration/configObject/metaservice_dependency/DB-Func.php index 94fc2cde99b..65c42c120cc 100644 --- a/www/include/configuration/configObject/metaservice_dependency/DB-Func.php +++ b/www/include/configuration/configObject/metaservice_dependency/DB-Func.php @@ -114,19 +114,23 @@ function multipleMetaServiceDependencyInDB($dependencies = array(), $nbrDup = ar $query = "SELECT DISTINCT meta_service_meta_id FROM dependency_metaserviceParent_relation " . "WHERE dependency_dep_id = '" . $key . "'"; $dbResult = $pearDB->query($query); + $statement = $pearDB->prepare("INSERT INTO dependency_metaserviceParent_relation " . + "VALUES (:maxId, :metaId)"); while ($ms = $dbResult->fetch()) { - $query = "INSERT INTO dependency_metaserviceParent_relation " . - "VALUES ('" . $maxId["MAX(dep_id)"] . "', '" . $ms["meta_service_meta_id"] . "')"; - $pearDB->query($query); + $statement->bindValue(':maxId', (int) $maxId["MAX(dep_id)"], \PDO::PARAM_INT); + $statement->bindValue(':metaId', (int) $ms["meta_service_meta_id"], \PDO::PARAM_INT); + $statement->execute(); } $dbResult->closeCursor(); $query = "SELECT DISTINCT meta_service_meta_id FROM dependency_metaserviceChild_relation " . "WHERE dependency_dep_id = '" . $key . "'"; $dbResult = $pearDB->query($query); + $childStatement = $pearDB->prepare("INSERT INTO dependency_metaserviceChild_relation " . + "VALUES (:maxId, :metaId)"); while ($ms = $dbResult->fetch()) { - $query = "INSERT INTO dependency_metaserviceChild_relation VALUES ('" . - $maxId["MAX(dep_id)"] . "', '" . $ms["meta_service_meta_id"] . "')"; - $pearDB->query($query); + $childStatement->bindValue(':maxId', (int) $maxId["MAX(dep_id)"], \PDO::PARAM_INT); + $childStatement->bindValue(':metaId', (int) $ms["meta_service_meta_id"], \PDO::PARAM_INT); + $childStatement->execute(); } $dbResult->closeCursor(); } diff --git a/www/include/configuration/configObject/service_dependency/DB-Func.php b/www/include/configuration/configObject/service_dependency/DB-Func.php index 501d43c5f2a..573e2b5e62b 100644 --- a/www/include/configuration/configObject/service_dependency/DB-Func.php +++ b/www/include/configuration/configObject/service_dependency/DB-Func.php @@ -127,10 +127,12 @@ function multipleServiceDependencyInDB($dependencies = array(), $nbrDup = array( $query = "SELECT * FROM dependency_hostChild_relation WHERE dependency_dep_id = '" . $key . "'"; $dbResult = $pearDB->query($query); $fields["dep_hostPar"] = ""; + $query = "INSERT INTO dependency_hostChild_relation VALUES (:dep_id, :host_host_id)"; + $statement = $pearDB->prepare($query); while ($host = $dbResult->fetch()) { - $query = "INSERT INTO dependency_hostChild_relation VALUES ('" . $maxId["MAX(dep_id)"] . - "', '" . $host["host_host_id"] . "')"; - $pearDB->query($query); + $statement->bindValue(':dep_id', (int) $maxId["MAX(dep_id)"], \PDO::PARAM_INT); + $statement->bindValue(':host_host_id', (int) $host["host_host_id"], \PDO::PARAM_INT); + $statement->execute(); $fields["dep_hostPar"] .= $host["host_host_id"] . ","; } $fields["dep_hostPar"] = trim($fields["dep_hostPar"], ","); @@ -138,21 +140,36 @@ function multipleServiceDependencyInDB($dependencies = array(), $nbrDup = array( $query = "SELECT * FROM dependency_serviceParent_relation WHERE dependency_dep_id = '" . $key . "'"; $dbResult = $pearDB->query($query); $fields["dep_hSvPar"] = ""; + $query = "INSERT INTO dependency_serviceParent_relation + VALUES (:dep_id, :service_service_id, :host_host_id)"; + $statement = $pearDB->prepare($query); while ($service = $dbResult->fetch()) { - $query = "INSERT INTO dependency_serviceParent_relation VALUES ('" . - $maxId["MAX(dep_id)"] . "', '" . $service["service_service_id"] . "', '" . - $service["host_host_id"] . "')"; - $pearDB->query($query); + $statement->bindValue(':dep_id', (int) $maxId["MAX(dep_id)"], \PDO::PARAM_INT); + $statement->bindValue( + ':service_service_id', + (int) $service["service_service_id"], + \PDO::PARAM_INT + ); + $statement->bindValue(':host_host_id', (int) $service["host_host_id"], \PDO::PARAM_INT); + $statement->execute(); $fields["dep_hSvPar"] .= $service["service_service_id"] . ","; } $fields["dep_hSvPar"] = trim($fields["dep_hSvPar"], ","); $query = "SELECT * FROM dependency_serviceChild_relation WHERE dependency_dep_id = '" . $key . "'"; $dbResult = $pearDB->query($query); $fields["dep_hSvChi"] = ""; + $query = "INSERT INTO dependency_serviceChild_relation + VALUES (:dep_id, :service_service_id, :host_host_id)"; + $statement = $pearDB->prepare($query); while ($service = $dbResult->fetch()) { - $query = "INSERT INTO dependency_serviceChild_relation VALUES ('" . $maxId["MAX(dep_id)"] . - "', '" . $service["service_service_id"] . "', '" . $service["host_host_id"] . "')"; - $pearDB->query($query); + $statement->bindValue(':dep_id', (int) $maxId["MAX(dep_id)"], \PDO::PARAM_INT); + $statement->bindValue( + ':service_service_id', + (int) $service["service_service_id"], + \PDO::PARAM_INT + ); + $statement->bindValue(':host_host_id', (int) $service["host_host_id"], \PDO::PARAM_INT); + $statement->execute(); $fields["dep_hSvChi"] .= $service["service_service_id"] . ","; } $fields["dep_hSvChi"] = trim($fields["dep_hSvChi"], ","); diff --git a/www/include/configuration/configObject/service_template_model/listServiceTemplateModel.php b/www/include/configuration/configObject/service_template_model/listServiceTemplateModel.php index ebcf25df37f..68ea6f745fb 100644 --- a/www/include/configuration/configObject/service_template_model/listServiceTemplateModel.php +++ b/www/include/configuration/configObject/service_template_model/listServiceTemplateModel.php @@ -49,10 +49,7 @@ $o = ""; -$search = filter_var( - $_POST['searchST'] ?? $_GET['searchST'] ?? $centreon->historySearch[$url]['search'] ?? '', - FILTER_SANITIZE_STRING -); +$search = htmlspecialchars($_POST['searchST'] ?? $_GET['searchST'] ?? $centreon->historySearch[$url]['search'] ?? ''); $displayLocked = filter_var( $_POST['displayLocked'] ?? $_GET['displayLocked'] ?? 'off', @@ -233,11 +230,11 @@ $elemArr[$i] = array( "MenuClass" => "list_" . $style, "RowMenu_select" => $selectedElements->toHtml(), - "RowMenu_desc" => CentreonUtils::escapeSecure($service["service_description"]), - "RowMenu_alias" => CentreonUtils::escapeSecure($service["service_alias"]), - "RowMenu_parent" => CentreonUtils::escapeSecure($tplStr), + "RowMenu_desc" => htmlentities($service["service_description"]), + "RowMenu_alias" => htmlentities($service["service_alias"]), + "RowMenu_parent" => htmlentities($tplStr), "RowMenu_icon" => $svc_icon, - "RowMenu_retry" => CentreonUtils::escapeSecure( + "RowMenu_retry" => htmlentities( "$normal_check_interval $normal_units / $retry_check_interval $retry_units" ), "RowMenu_attempts" => getMyServiceField($service['service_id'], "service_max_check_attempts"), diff --git a/www/include/configuration/configObject/traps/formTraps.php b/www/include/configuration/configObject/traps/formTraps.php index 73843509ad5..d1034154e6a 100644 --- a/www/include/configuration/configObject/traps/formTraps.php +++ b/www/include/configuration/configObject/traps/formTraps.php @@ -380,10 +380,8 @@ function myReplace() $form->addRule('traps_oid', _("Compulsory Name"), 'required'); $form->addRule('manufacturer_id', _("Compulsory Name"), 'required'); $form->addRule('traps_args', _("Compulsory Name"), 'required'); -$form->registerRule('exist', 'callback', [$trapObj, "testTrapExistence"]); $form->registerRule('wellFormated', 'callback', [$trapObj, "testOidFormat"]); $form->addRule('traps_oid', _("Bad OID Format"), 'wellFormated'); -$form->addRule('traps_oid', _("The same OID element already exists"), 'exist'); $form->setRequiredNote("* " . _("Required fields")); /* diff --git a/www/include/monitoring/comments/comments.php b/www/include/monitoring/comments/comments.php index d9761619ea6..11bfee39976 100644 --- a/www/include/monitoring/comments/comments.php +++ b/www/include/monitoring/comments/comments.php @@ -78,7 +78,7 @@ if (!empty($select)) { foreach ($select as $key => $value) { $res = explode(';', urldecode($key)); - DeleteComment($res[0], [(int)$res[1] . ';' . (int)$res[2] => 'on']); + DeleteComment($res[0], [$res[1] . ';' . (int)$res[2] => 'on']); } } } else { diff --git a/www/include/monitoring/comments/common-Func.php b/www/include/monitoring/comments/common-Func.php index 0cface9ab7b..2439ce74064 100644 --- a/www/include/monitoring/comments/common-Func.php +++ b/www/include/monitoring/comments/common-Func.php @@ -47,7 +47,6 @@ function DeleteComment($type = null, $hosts = []) foreach ($hosts as $key => $value) { $res = preg_split("/\;/", $key); - $res[0] = filter_var($res[0] ?? 0, FILTER_VALIDATE_INT); $res[1] = filter_var($res[1] ?? 0, FILTER_VALIDATE_INT); write_command(" DEL_" . $type . "_COMMENT;" . $res[1], GetMyHostPoller($pearDB, $res[0])); } diff --git a/www/include/options/accessLists/actionsACL/DB-Func.php b/www/include/options/accessLists/actionsACL/DB-Func.php index 10151912b7c..c2cb3a589d0 100644 --- a/www/include/options/accessLists/actionsACL/DB-Func.php +++ b/www/include/options/accessLists/actionsACL/DB-Func.php @@ -170,20 +170,24 @@ function multipleActionInDB($actions = array(), $nbrDup = array()) $query = "SELECT DISTINCT acl_group_id,acl_action_id FROM acl_group_actions_relations " . " WHERE acl_action_id = '" . $key . "'"; $dbResult = $pearDB->query($query); + $query = "INSERT INTO acl_group_actions_relations VALUES (:acl_action_id, :acl_group_id)"; + $statement = $pearDB->prepare($query); while ($cct = $dbResult->fetch()) { - $query = "INSERT INTO acl_group_actions_relations VALUES ('" . - $maxId["MAX(acl_action_id)"] . "', '" . $cct["acl_group_id"] . "')"; - $pearDB->query($query); + $statement->bindValue(':acl_action_id', (int) $maxId["MAX(acl_action_id)"], \PDO::PARAM_INT); + $statement->bindValue(':acl_group_id', (int) $cct["acl_group_id"], \PDO::PARAM_INT); + $statement->execute(); } # Duplicate Actions $query = "SELECT acl_action_rule_id,acl_action_name FROM acl_actions_rules " . "WHERE acl_action_rule_id = '" . $key . "'"; $dbResult = $pearDB->query($query); + $query = "INSERT INTO acl_actions_rules VALUES (NULL, :acl_action_id, :acl_action_name)"; + $statement = $pearDB->prepare($query); while ($acl = $dbResult->fetch()) { - $query = "INSERT INTO acl_actions_rules VALUES (NULL, '" . $maxId["MAX(acl_action_id)"] . - "', '" . $acl["acl_action_name"] . "')"; - $pearDB->query($query); + $statement->bindValue(':acl_action_id', (int) $maxId["MAX(acl_action_id)"], \PDO::PARAM_INT); + $statement->bindValue(':acl_action_name', $acl["acl_action_name"], \PDO::PARAM_STR); + $statement->execute(); } $dbResult->closeCursor(); @@ -298,8 +302,10 @@ function updateGroupActions($aclActionId, $ret = array()) } global $form, $pearDB; - $rq = "DELETE FROM acl_group_actions_relations WHERE acl_action_id = '" . $aclActionId . "'"; - $dbResult = $pearDB->query($rq); + $rq = "DELETE FROM acl_group_actions_relations WHERE acl_action_id = :acl_action_id"; + $statement = $pearDB->prepare($rq); + $statement->bindValue(':acl_action_id', (int) $aclActionId, \PDO::PARAM_INT); + $statement->execute(); if (isset($_POST["acl_groups"])) { foreach ($_POST["acl_groups"] as $id) { $rq = "INSERT INTO acl_group_actions_relations "; @@ -325,8 +331,10 @@ function updateRulesActions($aclActionId, $ret = array()) return; } - $rq = "DELETE FROM acl_actions_rules WHERE acl_action_rule_id = '" . $aclActionId . "'"; - $dbResult = $pearDB->query($rq); + $rq = "DELETE FROM acl_actions_rules WHERE acl_action_rule_id = :acl_action_rule_id"; + $statement = $pearDB->prepare($rq); + $statement->bindValue(':acl_action_rule_id', (int) $aclActionId, \PDO::PARAM_INT); + $statement->execute(); $actions = array(); $actions = listActions(); diff --git a/www/include/options/accessLists/menusACL/formMenusAccess.php b/www/include/options/accessLists/menusACL/formMenusAccess.php index 1939b23271c..6704e8b7ce8 100644 --- a/www/include/options/accessLists/menusACL/formMenusAccess.php +++ b/www/include/options/accessLists/menusACL/formMenusAccess.php @@ -209,9 +209,12 @@ $b = 0; $query = "SELECT topology_id, topology_page, topology_name, topology_parent, readonly FROM topology " . - "WHERE topology_parent = '" . $topo1["topology_page"] . "' ORDER BY topology_order"; - $DBRESULT2 = $pearDB->query($query); - while ($topo2 = $DBRESULT2->fetchRow()) { + "WHERE topology_parent = :topology_parent ORDER BY topology_order"; + + $statement2 = $pearDB->prepare($query); + $statement2->bindValue(':topology_parent', (int) $topo1["topology_page"], \PDO::PARAM_INT); + $statement2->execute(); + while ($topo2 = $statement2->fetchRow()) { $acl_topos2[$a]["childs"][$b] = array(); $acl_topos2[$a]["childs"][$b]["name"] = _($topo2["topology_name"]); $acl_topos2[$a]["childs"][$b]["id"] = $topo2["topology_id"]; @@ -231,10 +234,14 @@ $c = 0; $query = "SELECT topology_id, topology_name, topology_parent, topology_page, topology_group, readonly " . - "FROM topology WHERE topology_parent = '" . $topo2["topology_page"] . - "' AND topology_page IS NOT NULL ORDER BY topology_group, topology_order"; - $DBRESULT3 = $pearDB->query($query); - while ($topo3 = $DBRESULT3->fetchRow()) { + "FROM topology WHERE topology_parent = :topology_parent " . + "AND topology_page IS NOT NULL ORDER BY topology_group, topology_order"; + + $statement3 = $pearDB->prepare($query); + $statement3->bindValue(':topology_parent', (int) $topo2["topology_page"], \PDO::PARAM_INT); + $statement3->execute(); + + while ($topo3 = $statement3->fetchRow()) { $acl_topos2[$a]["childs"][$b]["childs"][$c] = array(); $acl_topos2[$a]["childs"][$b]["childs"][$c]["name"] = _($topo3["topology_name"]); @@ -264,10 +271,12 @@ $d = 0; $query = "SELECT topology_id, topology_name, topology_parent, readonly FROM topology " . - "WHERE topology_parent = '" . $topo3["topology_page"] . - "' AND topology_page IS NOT NULL ORDER BY topology_order"; - $DBRESULT4 = $pearDB->query($query); - while ($topo4 = $DBRESULT4->fetchRow()) { + "WHERE topology_parent = :topology_parent AND topology_page IS NOT NULL ORDER BY topology_order"; + $statement4 = $pearDB->prepare($query); + $statement4->bindValue(':topology_parent', (int) $topo3["topology_page"], \PDO::PARAM_INT); + $statement4->execute(); + + while ($topo4 = $statement4->fetchRow()) { $acl_topos2[$a]["childs"][$b]["childs"][$c]["childs"][$d] = array(); $acl_topos2[$a]["childs"][$b]["childs"][$c]["childs"][$d]["name"] = _($topo4["topology_name"]); $acl_topos2[$a]["childs"][$b]["childs"][$c]["childs"][$d]["id"] = $topo4["topology_id"]; diff --git a/www/include/options/media/images/syncDir.php b/www/include/options/media/images/syncDir.php index b9eee03bb0c..f6e2075a36a 100644 --- a/www/include/options/media/images/syncDir.php +++ b/www/include/options/media/images/syncDir.php @@ -173,12 +173,17 @@ function checkPicture($picture, $dirpath, $dir_id, $pearDB) $gdCounter++; } - $DBRESULT = $pearDB->query("SELECT img_id " . + $statement = $pearDB->prepare( + "SELECT img_id " . "FROM view_img, view_img_dir_relation vidh " . - "WHERE img_path = '" . $picture . "' " . - " AND vidh.dir_dir_parent_id = '" . $dir_id . "'" . - " AND vidh.img_img_id = img_id"); - if (!$DBRESULT->rowCount()) { + "WHERE img_path = :img_path " . + "AND vidh.dir_dir_parent_id = :dir_dir_parent_id " . + "AND vidh.img_img_id = img_id" + ); + $statement->bindValue(':img_path', $picture, \PDO::PARAM_STR); + $statement->bindValue(':dir_dir_parent_id', (int) $dir_id, \PDO::PARAM_INT); + $statement->execute(); + if (!$statement->rowCount()) { $DBRESULT = $pearDB->query( "INSERT INTO view_img (`img_name`, `img_path`) VALUES ('" . $img_info["filename"] . "', '" . $picture . "')" @@ -189,13 +194,16 @@ function checkPicture($picture, $dirpath, $dir_id, $pearDB) ); $data = $DBRESULT->fetchRow(); $regCounter++; - $DBRESULT = $pearDB->query( - "INSERT INTO view_img_dir_relation (`dir_dir_parent_id`, `img_img_id`) VALUES ('" - . $dir_id . "', '" . $data['img_id'] . "')" + $statement = $pearDB->prepare( + "INSERT INTO view_img_dir_relation (`dir_dir_parent_id`, `img_img_id`) + VALUES (:dir_dir_parent_id, :img_img_id)" ); + $statement->bindValue(':dir_dir_parent_id', (int) $dir_id, \PDO::PARAM_INT); + $statement->bindValue(':img_img_id', (int) $data['img_id'], \PDO::PARAM_INT); + $statement->execute(); return $data['img_id']; } else { - $data = $DBRESULT->fetchRow(); + $data = $statement->fetchRow(\PDO::FETCH_ASSOC); return 0; } } @@ -211,9 +219,11 @@ function DeleteOldPictures($pearDB) . "view_img_dir vid, view_img_dir_relation vidr " . "WHERE vidr.img_img_id = vi.img_id AND vid.dir_id = vidr.dir_dir_parent_id" ); + $statement = $pearDB->prepare("DELETE FROM view_img WHERE img_id = :img_id"); while ($row2 = $DBRESULT->fetchRow()) { if (!file_exists("./img/media/" . $row2["dir_alias"] . "/" . $row2["img_path"])) { - $pearDB->query("DELETE FROM view_img WHERE img_id = '" . $row2["img_id"] . "'"); + $statement->bindValue(':img_id', (int) $row2["img_id"], \PDO::PARAM_INT); + $statement->execute(); $fileRemoved++; } } diff --git a/www/include/reporting/dashboard/DB-Func.php b/www/include/reporting/dashboard/DB-Func.php index 8104f858a01..96a22a20aa8 100644 --- a/www/include/reporting/dashboard/DB-Func.php +++ b/www/include/reporting/dashboard/DB-Func.php @@ -467,7 +467,7 @@ function getServicesLogs(array $services, $startDate, $endDate, $reportTimePerio . $aclCondition . " " . $servicesSubquery . " " . "AND DATE_FORMAT(FROM_UNIXTIME(date_start), '%W') IN (" . $daysOfWeek . ") " - . "GROUP BY las.service_id"; + . "GROUP BY las.host_id, las.service_id"; $statement = $pearDBO->prepare($rq); foreach ($bindValues as $bindName => $bindParams) { diff --git a/www/include/views/componentTemplates/formComponentTemplate.ihtml b/www/include/views/componentTemplates/formComponentTemplate.ihtml index 8afbb317413..ede927f9029 100644 --- a/www/include/views/componentTemplates/formComponentTemplate.ihtml +++ b/www/include/views/componentTemplates/formComponentTemplate.ihtml @@ -35,6 +35,9 @@    + + + {/if} diff --git a/www/include/views/componentTemplates/formComponentTemplate.php b/www/include/views/componentTemplates/formComponentTemplate.php index faaec375c5b..4b27228c4e3 100644 --- a/www/include/views/componentTemplates/formComponentTemplate.php +++ b/www/include/views/componentTemplates/formComponentTemplate.php @@ -359,7 +359,7 @@ function insertValueQuery() { var e_input = document.Form.ds_name; var e_select = document.getElementById('sl_list_metrics'); var sd_o = e_select.selectedIndex; - if (sd_o != 0) { + if (sd_o != -1) { var chaineAj = ''; chaineAj = e_select.options[sd_o].text; chaineAj = chaineAj.replace(/\s(\[[CV]DEF\]|)\s*$/, ""); @@ -431,7 +431,6 @@ function popup_color_picker(t,name) } $vdef = 0; /* don't list VDEF in metrics list */ -include_once('./include/views/graphs/common/makeJS_formMetricsList.php'); if ($o === MODIFY_COMPONENT_TEMPLATE || $o === WATCH_COMPONENT_TEMPLATE) { $host_service_id = filter_var( $_POST['host_service_id'] ?? ($compo["host_id"] . '-' . $compo['service_id']), @@ -446,9 +445,20 @@ function popup_color_picker(t,name) ?> diff --git a/www/include/views/graphs/common/makeJS_formMetricsList.php b/www/include/views/graphs/common/makeJS_formMetricsList.php deleted file mode 100644 index b817ce94a11..00000000000 --- a/www/include/views/graphs/common/makeJS_formMetricsList.php +++ /dev/null @@ -1,177 +0,0 @@ -. - * - * Linking this program statically or dynamically with other modules is making a - * combined work based on this program. Thus, the terms and conditions of the GNU - * General Public License cover the whole combination. - * - * As a special exception, the copyright holders of this program give Centreon - * permission to link this program with independent modules to produce an executable, - * regardless of the license terms of these independent modules, and to copy and - * distribute the resulting executable under terms of Centreon choice, provided that - * Centreon also meet, for each linked independent module, the terms and conditions - * of the license of that module. An independent module is a module which is not - * derived from this program. If you modify this program, you may extend this - * exception to your version of the program, but you are not obliged to do so. If you - * do not wish to do so, delete this exception statement from your version. - * - * For more information : contact@centreon.com - * - * SVN : $URL$ - * SVN : $Id$ - * - */ - - /* - * Lang file - */ - $locale = $oreon->user->get_lang(); - putenv("LANG=$locale"); - setlocale(LC_ALL, $locale); - bindtextdomain("messages", _CENTREON_PATH_ . "www/locale/"); - bind_textdomain_codeset("messages", "UTF-8"); - textdomain("messages"); -?> diff --git a/www/include/views/graphs/common/makeXML_ListMetrics.php b/www/include/views/graphs/common/makeXML_ListMetrics.php deleted file mode 100644 index 5d7afe858b1..00000000000 --- a/www/include/views/graphs/common/makeXML_ListMetrics.php +++ /dev/null @@ -1,173 +0,0 @@ -. - * - * Linking this program statically or dynamically with other modules is making a - * combined work based on this program. Thus, the terms and conditions of the GNU - * General Public License cover the whole combination. - * - * As a special exception, the copyright holders of this program give Centreon - * permission to link this program with independent modules to produce an executable, - * regardless of the license terms of these independent modules, and to copy and - * distribute the resulting executable under terms of Centreon choice, provided that - * Centreon also meet, for each linked independent module, the terms and conditions - * of the license of that module. An independent module is a module which is not - * derived from this program. If you modify this program, you may extend this - * exception to your version of the program, but you are not obliged to do so. If you - * do not wish to do so, delete this exception statement from your version. - * - * For more information : contact@centreon.com - * - * SVN : $URL$ - * SVN : $Id$ - * - */ - - header('Content-Type: text/xml'); - header('Cache-Control: no-cache'); - - require_once realpath(dirname(__FILE__) . "/../../../../../config/centreon.config.php"); - require_once _CENTREON_PATH_."/www/class/centreonDB.class.php"; - require_once _CENTREON_PATH_."/www/class/centreonXML.class.php"; - -function compare($a, $b) -{ - if ($a["metric_name"] == $b["metric_name"]) { - return 0; - } - return ( $a["metric_name"] < $b["metric_name"] ) ? -1 : 1; -} - - $pearDB = new CentreonDB(); - $pearDBO = new CentreonDB("centstorage"); - - /* - * Get session - */ - require_once(_CENTREON_PATH_ . "www/class/centreonSession.class.php"); - require_once(_CENTREON_PATH_ . "www/class/centreon.class.php"); -if (!isset($_SESSION['centreon'])) { - CentreonSession::start(); -} - -if (isset($_SESSION['centreon'])) { - $oreon = $_SESSION['centreon']; -} else { - exit; -} - - /* - * Get language - */ - $locale = $oreon->user->get_lang(); - putenv("LANG=$locale"); - setlocale(LC_ALL, $locale); - bindtextdomain("messages", _CENTREON_PATH_ . "www/locale/"); -; - bind_textdomain_codeset("messages", "UTF-8"); - textdomain("messages"); - - # - # Existing Real Metric List comes from DBO -> Store in $rmetrics Array - # - $s_datas = array(); - $o_datas = array(""=> utf8_decode(_("List of known metrics"))); - $mx_l = strlen($o_datas[""]); - $where = ""; - $def_type = array(0=>"CDEF",1=>"VDEF"); - -if (isset($_GET['vdef']) && is_numeric($_GET['vdef']) && $_GET['vdef'] == 0) { - $where = " AND def_type='".$_GET["vdef"]."'"; -} - -if (isset($_GET["host_id"]) && $_GET["service_id"]) { - if (!is_numeric($_GET['host_id']) || !is_numeric($_GET['service_id'])) { - $buffer = new CentreonXML(); - $buffer->writeElement('error', 'Bad id format'); - $buffer->output(); - exit; - } - $host_id = $_GET["host_id"]; - $service_id = $_GET["service_id"]; - - $query = "SELECT id " - . "FROM index_data " - . "WHERE host_id = " . $pearDB->escape($host_id) . " " - . "AND service_id = " . $pearDB->escape($service_id) . " "; - - $index_id = 0; - $pq_sql = $pearDBO->query($query); - if ($row = $pq_sql->fetchRow()) { - $index_id = $row['id']; - } - - $query = "SELECT metric_id, metric_name " - . "FROM metrics " - . "WHERE index_id = " . $index_id . " "; - $pq_sql = $pearDBO->query($query); - while ($fw_sql = $pq_sql->fetchRow()) { - $sd_l = strlen($fw_sql["metric_name"]); - $fw_sql["metric_name"] = $fw_sql["metric_name"] . "   "; - $s_datas[] = $fw_sql; - if ($sd_l > $mx_l) { - $mx_l = $sd_l; - } - } - $pq_sql->closeCursor(); - $query = "SELECT vmetric_id, vmetric_name, def_type " - . "FROM virtual_metrics " - . "WHERE index_id = " . $index_id . " " - . $where . " "; - $pq_sql = $pearDB->query($query); - - while ($fw_sql = $pq_sql->fetchRow()) { - $sd_l = strlen($fw_sql["vmetric_name"]." [CDEF]"); - $fw_sql["metric_name"] = $fw_sql["vmetric_name"]." [".$def_type[$fw_sql["def_type"]]."]   "; - $fw_sql["metric_id"] = "v".$fw_sql["vmetric_id"]; - $s_datas[] = $fw_sql; - if ($sd_l > $mx_l) { - $mx_l = $sd_l; - } - $pq_sql->closeCursor(); - } -} - - usort($s_datas, "compare"); - -foreach ($s_datas as $key => $om) { - $o_datas[$om["metric_id"]] = $om["metric_name"]; -} - -for ($i = strlen($o_datas[""]); $i != $mx_l; $i++) { - $o_datas[""] .= " "; -} - - # The first element of the select is empty - $buffer = new CentreonXML(); - $buffer->startElement("options_data"); - $buffer->writeElement("td_id", "td_list_metrics"); - $buffer->writeElement("select_id", "sl_list_metrics"); - - # Now we fill out the select with templates id and names -foreach ($o_datas as $o_id => $o_alias) { - $buffer->startElement("option"); - $buffer->writeElement("o_id", $o_id); - $buffer->writeElement("o_alias", $o_alias); - $buffer->endElement(); -} - - $buffer->endElement(); - $buffer->output(); diff --git a/www/include/views/graphs/generateGraphs/generateImage.php b/www/include/views/graphs/generateGraphs/generateImage.php index 54632504a17..2d43aa60992 100644 --- a/www/include/views/graphs/generateGraphs/generateImage.php +++ b/www/include/views/graphs/generateGraphs/generateImage.php @@ -95,6 +95,8 @@ } else { die('Invalid token'); } +} else { + throw new \Exception('Username and token query strings must be set.'); } $index = filter_var( @@ -182,19 +184,37 @@ $dbstorage = new CentreonDB('centstorage'); $aclGroups = $acl->getAccessGroupsString(); - $sql = "SELECT host_id, service_id FROM index_data WHERE id = " .$pearDB->escape($index); - $res = $dbstorage->query($sql); - if (!$res->rowCount()) { + $sql = "SELECT host_id, service_id FROM index_data WHERE id = :index_data_id"; + $statement = $dbstorage->prepare($sql); + $statement->bindValue(':index_data_id', (int) $index, \PDO::PARAM_INT); + $statement->execute(); + if (!$statement->rowCount()) { die('Graph not found'); } - $row = $res->fetch(); - unset($res); + $row = $statement->fetch(\PDO::FETCH_ASSOC); + unset($statement); $hostId = $row['host_id']; $serviceId = $row['service_id']; - $sql = "SELECT service_id FROM centreon_acl WHERE host_id = $hostId AND service_id = $serviceId - AND group_id IN ($aclGroups)"; - $res = $pearDBO->query($sql); - if (!$res->rowCount()) { + $aclGroupsExploded = explode(',', $aclGroups); + if (empty($aclGroupsExploded)) { + throw new \Exception('Access denied'); + } + + $aclGroupsQueryBinds = []; + foreach ($aclGroupsExploded as $key => $value) { + $aclGroupsQueryBinds[':acl_group_' . $key] = $value; + } + $aclGroupBinds = implode(',', array_keys($aclGroupsQueryBinds)); + $sql = "SELECT service_id FROM centreon_acl WHERE host_id = :host_id AND service_id = :service_id + AND group_id IN ($aclGroupBinds)"; + $statement = $pearDBO->prepare($sql); + $statement->bindValue(':host_id', (int) $hostId, \PDO::PARAM_INT); + $statement->bindValue(':service_id', (int) $serviceId, \PDO::PARAM_INT); + foreach ($aclGroupsQueryBinds as $key => $value) { + $statement->bindValue($key, (int) $value, \PDO::PARAM_INT); + } + $statement->execute(); + if (!$statement->rowCount()) { die('Access denied'); } } diff --git a/www/include/views/virtualMetrics/formVirtualMetrics.ihtml b/www/include/views/virtualMetrics/formVirtualMetrics.ihtml index 86c044fee1a..98ea810739a 100644 --- a/www/include/views/virtualMetrics/formVirtualMetrics.ihtml +++ b/www/include/views/virtualMetrics/formVirtualMetrics.ihtml @@ -48,7 +48,10 @@ {$form.rpn_function.html} {if $o == "a" || $o == "c"} -    +    + + + {/if} diff --git a/www/include/views/virtualMetrics/formVirtualMetrics.php b/www/include/views/virtualMetrics/formVirtualMetrics.php index a90eb4cf6d6..4cf98e972b9 100644 --- a/www/include/views/virtualMetrics/formVirtualMetrics.php +++ b/www/include/views/virtualMetrics/formVirtualMetrics.php @@ -236,7 +236,7 @@ function insertValueQuery() { var e_txtarea = document.Form.rpn_function; var e_select = document.getElementById('sl_list_metrics'); var sd_o = e_select.selectedIndex; - if (sd_o != 0) { + if (sd_o != -1) { var chaineAj = ''; chaineAj = e_select.options[sd_o].text; //chaineAj = chaineAj.substring(0, chaineAj.length - 3); @@ -329,7 +329,7 @@ function manageVDEF() { $tpl->display("formVirtualMetrics.ihtml"); } $vdef = 1; /* Display VDEF too */ -include_once("./include/views/graphs/common/makeJS_formMetricsList.php"); + if ($o == METRIC_MODIFY || $o == METRIC_WATCH) { isset($_POST["host_id"]) && $_POST["host_id"] != null ? $host_service_id = $_POST["host_id"] @@ -340,11 +340,21 @@ function manageVDEF() { : $host_service_id = 0; } ?> - diff --git a/www/install/createTables.sql b/www/install/createTables.sql index aa1a86c661d..c72f2449beb 100644 --- a/www/install/createTables.sql +++ b/www/install/createTables.sql @@ -2321,7 +2321,6 @@ CREATE TABLE IF NOT EXISTS contact_feature ( CREATE TABLE IF NOT EXISTS `remote_servers` ( `id` INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, `ip` VARCHAR(255) NOT NULL, - `app_key` VARCHAR(40) NOT NULL, `version` VARCHAR(16) NOT NULL, `is_connected` TINYINT(1) NOT NULL DEFAULT 0, `created_at` TIMESTAMP NOT NULL, diff --git a/www/install/insertBaseConf.sql b/www/install/insertBaseConf.sql index ccc87787142..06481bb738f 100644 --- a/www/install/insertBaseConf.sql +++ b/www/install/insertBaseConf.sql @@ -2,7 +2,7 @@ -- Insert version -- -INSERT INTO `informations` (`key` ,`value`) VALUES ('version', '22.04.2'); +INSERT INTO `informations` (`key` ,`value`) VALUES ('version', '22.04.3'); -- -- Contenu de la table `contact` diff --git a/www/install/php/Update-22.04.2.php b/www/install/php/Update-22.04.2.php index 8572f2a05df..18f7e537d45 100644 --- a/www/install/php/Update-22.04.2.php +++ b/www/install/php/Update-22.04.2.php @@ -18,3 +18,34 @@ * For more information : contact@centreon.com * */ + +require_once __DIR__ . '/../../class/centreonLog.class.php'; + +$centreonLog = new CentreonLog(); + +//error specific content +$versionOfTheUpgrade = 'UPGRADE - 22.04.2: '; +$errorMessage = ''; + +try { + $pearDB->beginTransaction(); + + $errorMessage = "Unable to delete 'appKey' information from database"; + $pearDB->query("DELETE FROM `informations` WHERE `key` = 'appKey'"); + + $pearDB->commit(); +} catch (\Exception $e) { + if ($pearDB->inTransaction()) { + $pearDB->rollBack(); + } + + $centreonLog->insertLog( + 4, + $versionOfTheUpgrade . $errorMessage . + " - Code : " . (int)$e->getCode() . + " - Error : " . $e->getMessage() . + " - Trace : " . $e->getTraceAsString() + ); + + throw new \Exception($versionOfTheUpgrade . $errorMessage, (int) $e->getCode(), $e); +} diff --git a/www/install/php/Update-22.04.3.php b/www/install/php/Update-22.04.3.php new file mode 100644 index 00000000000..8572f2a05df --- /dev/null +++ b/www/install/php/Update-22.04.3.php @@ -0,0 +1,20 @@ +. + * http://www.apache.org/licenses/LICENSE-2.0 * - * Linking this program statically or dynamically with other modules is making a - * combined work based on this program. Thus, the terms and conditions of the GNU - * General Public License cover the whole combination. - * - * As a special exception, the copyright holders of this program give Centreon - * permission to link this program with independent modules to produce an executable, - * regardless of the license terms of these independent modules, and to copy and - * distribute the resulting executable under terms of Centreon choice, provided that - * Centreon also meet, for each linked independent module, the terms and conditions - * of the license of that module. An independent module is a module which is not - * derived from this program. If you modify this program, you may extend this - * exception to your version of the program, but you are not obliged to do so. If you - * do not wish to do so, delete this exception statement from your version. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. * * For more information : contact@centreon.com * */ session_start(); -require_once realpath(dirname(__FILE__) . "/../../../../config/centreon.config.php"); -require_once _CENTREON_PATH_ . '/www/class/centreonDB.class.php'; -require_once '../../steps/functions.php'; +require_once __DIR__ . '/../../../../bootstrap.php'; +require_once __DIR__ . '/../../../class/centreonDB.class.php'; +require_once __DIR__ . '/../../steps/functions.php'; + +use Core\Platform\Application\Repository\UpdateLockerRepositoryInterface; +use Core\Platform\Application\Repository\ReadUpdateRepositoryInterface; +use Core\Platform\Application\Repository\WriteUpdateRepositoryInterface; +use Core\Platform\Application\UseCase\UpdateVersions\UpdateVersionsException; $current = $_POST['current']; $next = $_POST['next']; $status = 0; -/** - * Variables for upgrade scripts - */ -try { - $pearDB = new CentreonDB('centreon', 3); - $pearDBO = new CentreonDB('centstorage', 3); -} catch (Exception $e) { - exitUpgradeProcess(1, $current, $next, $e->getMessage()); -} +$kernel = \App\Kernel::createForWeb(); -/** - * Upgrade storage sql - */ -$storageSql = '../../sql/centstorage/Update-CSTG-' . $next . '.sql'; -if (is_file($storageSql)) { - $result = splitQueries($storageSql, ';', $pearDBO, '../../tmp/Update-CSTG-' . $next); - if ("0" != $result) { - exitUpgradeProcess(1, $current, $next, $result); - } -} +$updateLockerRepository = $kernel->getContainer()->get(UpdateLockerRepositoryInterface::class); +$updateWriteRepository = $kernel->getContainer()->get(WriteUpdateRepositoryInterface::class); -/** - * Pre upgrade PHP - */ -$prePhp = '../../php/Update-' . $next . '.php'; -if (is_file($prePhp)) { - try { - include_once $prePhp; - } catch (Exception $e) { - exitUpgradeProcess(1, $current, $next, $e->getMessage()); +try { + if (! $updateLockerRepository->lock()) { + throw UpdateVersionsException::updateAlreadyInProgress(); } -} -/** - * Upgrade configuration sql - */ -$confSql = '../../sql/centreon/Update-DB-' . $next . '.sql'; -if (is_file($confSql)) { - $result = splitQueries($confSql, ';', $pearDB, '../../tmp/Update-DB-' . $next); - if ("0" != $result) { - exitUpgradeProcess(1, $current, $next, $result); - } -} + $updateWriteRepository->runUpdate($next); -/** - * Post upgrade PHP - */ -$postPhp = '../../php/Update-' . $next . '.post.php'; -if (is_file($postPhp)) { - try { - include_once $postPhp; - } catch (Exception $e) { - exitUpgradeProcess(1, $current, $next, $e->getMessage()); - } + $updateLockerRepository->unlock(); +} catch (\Throwable $e) { + exitUpgradeProcess(1, $current, $next, $e->getMessage()); } -/** - * Update version in database. - */ -$res = $pearDB->prepare("UPDATE `informations` SET `value` = ? WHERE `key` = 'version'"); -$res->execute(array($next)); $current = $next; -/* -** To find the next version that we should update to, we will look in -** the www/install/php directory where all PHP update scripts are -** stored. We will extract the target version from the filename and find -** the closest version to the current version. -*/ -$next = ''; -if ($handle = opendir('../../php')) { - while (false !== ($file = readdir($handle))) { - if (preg_match('/Update-([a-zA-Z0-9\-\.]+)\.php/', $file, $matches)) { - if ((version_compare($current, $matches[1]) < 0) && - (empty($next) || (version_compare($matches[1], $next) < 0))) { - $next = $matches[1]; - } - } - } - closedir($handle); -} +$updateReadRepository = $kernel->getContainer()->get(ReadUpdateRepositoryInterface::class); +$availableUpdates = $updateReadRepository->findOrderedAvailableUpdates($current); +$next = empty($availableUpdates) ? '' : array_shift($availableUpdates); + $_SESSION['CURRENT_VERSION'] = $current; $okMsg = "OK"; + exitUpgradeProcess($status, $current, $next, $okMsg); diff --git a/www/install/step_upgrade/process/process_step5.php b/www/install/step_upgrade/process/process_step5.php index df5d79e2174..c4a723a14f2 100644 --- a/www/install/step_upgrade/process/process_step5.php +++ b/www/install/step_upgrade/process/process_step5.php @@ -37,44 +37,15 @@ require_once __DIR__ . '/../../../../bootstrap.php'; require_once '../../steps/functions.php'; -function recurseRmdir($dir) -{ - $files = array_diff(scandir($dir), array('.', '..')); - foreach ($files as $file) { - (is_dir("$dir/$file")) ? recurseRmdir("$dir/$file") : unlink("$dir/$file"); - } - return rmdir($dir); -} - -function recurseCopy($source, $dest) -{ - if (is_link($source)) { - return symlink(readlink($source), $dest); - } +use Core\Platform\Application\Repository\WriteUpdateRepositoryInterface; +use Core\Platform\Application\UseCase\UpdateVersions\UpdateVersionsException; - if (is_file($source)) { - return copy($source, $dest); - } - - if (!is_dir($dest)) { - mkdir($dest); - } +$kernel = \App\Kernel::createForWeb(); - $dir = dir($source); - while (false !== $entry = $dir->read()) { - if ($entry == '.' || $entry == '..') { - continue; - } - - recurseCopy("$source/$entry", "$dest/$entry"); - } - - $dir->close(); - return true; -} +$updateWriteRepository = $kernel->getContainer()->get(WriteUpdateRepositoryInterface::class); $parameters = filter_input_array(INPUT_POST); -$current = filter_var($_POST['current'] ?? "step 5", FILTER_SANITIZE_STRING); +$current = filter_var($_POST['current'] ?? "step 5", FILTER_SANITIZE_FULL_SPECIAL_CHARS); if ($parameters) { if ((int)$parameters["send_statistics"] === 1) { @@ -88,16 +59,19 @@ function recurseCopy($source, $dest) $db->query($query); } -$name = 'install-' . $_SESSION['CURRENT_VERSION'] . '-' . date('Ymd_His'); -$completeName = _CENTREON_VARLIB_ . '/installs/' . $name; -$sourceInstallDir = str_replace('step_upgrade', '', realpath(dirname(__FILE__) . '/../')); - try { - if (recurseCopy($sourceInstallDir, $completeName)) { - recurseRmdir($sourceInstallDir); + if (!isset($_SESSION['CURRENT_VERSION']) || ! preg_match('/^\d+\.\d+\.\d+/', $_SESSION['CURRENT_VERSION'])) { + throw new \Exception('Cannot get current version'); } -} catch (Exception $e) { - exitUpgradeProcess(1, $current, '', $e->getMessage()); + + $updateWriteRepository->runPostUpdate($_SESSION['CURRENT_VERSION']); +} catch (\Throwable $e) { + exitUpgradeProcess( + 1, + $current, + '', + UpdateVersionsException::errorWhenApplyingPostUpdate($e)->getMessage() + ); } session_destroy(); diff --git a/www/install/steps/process/insertBaseConf.php b/www/install/steps/process/insertBaseConf.php index 5a2fe96e73a..95f3e2bab70 100644 --- a/www/install/steps/process/insertBaseConf.php +++ b/www/install/steps/process/insertBaseConf.php @@ -138,9 +138,7 @@ $link->exec("INSERT INTO `options` (`key`, `value`) VALUES ('gmt','" . $timezoneId . "')"); # Generate random key for this instance and set it to be not central and not remote -$uniqueKey = md5(uniqid(rand(), true)); $informationsTableInsert = "INSERT INTO `informations` (`key`,`value`) VALUES - ('appKey', '{$uniqueKey}'), ('isRemote', 'no'), ('isCentral', 'yes')"; From fe86ab853eb8ea64c2291cb844764ed539ca390d Mon Sep 17 00:00:00 2001 From: Charles Gautier <33026375+chgautier@users.noreply.github.com> Date: Fri, 2 Sep 2022 17:31:54 +0200 Subject: [PATCH 2/7] chore(release): merge hotfix-MON-14893-index-data (#11681) * fix(upgrade): Correctly Parse SQL Comments (#11658) (#11668) Refs: MON-14848 Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> * fix invalid values for index_data.special (#11669) * chore(install):update version to 22.04.4 Co-authored-by: Kevin Duret Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> --- .../Repository/DbWriteUpdateRepository.php | 2 +- www/install/insertBaseConf.sql | 2 +- www/install/php/Update-22.04.4.php | 19 +++++++++++++++++++ .../sql/centstorage/Update-CSTG-22.04.4.sql | 1 + 4 files changed, 22 insertions(+), 2 deletions(-) create mode 100644 www/install/php/Update-22.04.4.php create mode 100644 www/install/sql/centstorage/Update-CSTG-22.04.4.sql diff --git a/src/Core/Platform/Infrastructure/Repository/DbWriteUpdateRepository.php b/src/Core/Platform/Infrastructure/Repository/DbWriteUpdateRepository.php index 1255ee9ecc8..a973e23e181 100644 --- a/src/Core/Platform/Infrastructure/Repository/DbWriteUpdateRepository.php +++ b/src/Core/Platform/Infrastructure/Repository/DbWriteUpdateRepository.php @@ -287,7 +287,7 @@ private function writeExecutedQueriesCountInTemporaryFile(string $tmpFile, int $ */ private function isSqlComment(string $line): bool { - return str_starts_with('--', trim($line)); + return str_starts_with(trim($line), '--'); } /** diff --git a/www/install/insertBaseConf.sql b/www/install/insertBaseConf.sql index 06481bb738f..df57294e767 100644 --- a/www/install/insertBaseConf.sql +++ b/www/install/insertBaseConf.sql @@ -2,7 +2,7 @@ -- Insert version -- -INSERT INTO `informations` (`key` ,`value`) VALUES ('version', '22.04.3'); +INSERT INTO `informations` (`key` ,`value`) VALUES ('version', '22.04.4'); -- -- Contenu de la table `contact` diff --git a/www/install/php/Update-22.04.4.php b/www/install/php/Update-22.04.4.php new file mode 100644 index 00000000000..d32c63228e5 --- /dev/null +++ b/www/install/php/Update-22.04.4.php @@ -0,0 +1,19 @@ + '1'; \ No newline at end of file From b709503d3629a334e9ea4dba92b33e807fe64a94 Mon Sep 17 00:00:00 2001 From: tuntoja <58987095+tuntoja@users.noreply.github.com> Date: Wed, 21 Sep 2022 08:58:07 +0200 Subject: [PATCH 3/7] chore(release): merge release-22.04.next into 22.04.x (#11821) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(git): resync 22.04.x to dev-22.04.x (#11503) * [SNYK] Sanitize and bind ACL host dependency queries (#11389) (#11394) * Sanitize and bind ACL host dependency queries * fix issues * removed old variable userCrypted and the use of it (#11334) (#11352) Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> * enh(Header/userMenu):reduce spacing user menu (#11393) * update user menu * fix(hostgroup): fix display of hostgroups in select2 (#11431) (#11443) * fix(ci): fix debian packaging with freshly instanciated jenkins slave (#11398) (#11399) Refs: MON-14377 * Sanitized and bound queries (#11413) (#11445) lines : 130 -142 * Snyk: Sanitize and bind media sync queries 22.04.x (#11418) * sanitizing and binding sync dir file queries * Applying some fixes * Snyk: Sanitize and bind ACL service dependency queries dev-22.04.x (#11395) * Snyk: Sanitize and bind Auth class queries 22.04.x (#11448) * [Backport/need review] fix(UI): Fix layout for Safari and form validation (#11440) * fix(UI): Fix layout for Safari and form validation (#11373) * Fix form validation * Fix padlock layout for safari * Update centreon-frontend * Remove debug variable * Fix test * Fix page respsoniveness * Rename variable * update deps * Fix package-lock * Fix package-lock * Add debug statement for debian * Install nodejs rather npm * Attempt fix * Attempt to fix nodejs installation * add sudo * Fix redoc-cli usage * Try to fix permission on npm * Fix * Fix permission * Fix permission (please work) * Fix source * Stop using npx because..... * Allow legacy-peer-deps * Remove nodejs installation * Fix image to pull for debian 11 * [SNYK] Sanitize and bind centreonGraph class queries (#11409) (#11421) 1122 1153 1134 * [Snyk] Sanitize and bind ACL action access queries (#11385) (#11402) * Sanitize and bind ACL action access queries _ sanitize if possible each variables inserted in a query _ use PDO prepared statement and bind() method _ Do not use $pearDB->escape on which is for examples useless on integers and on non closed HTML tags (svg, img, etc) * fix line length * fix failed checks * feat(api): implement endpoint to update centreon web (#11391) (#11401) Refs: MON-12296 * Clean(platform): Clean appKey method and usage 22.04.x (#11452) * Clean(platform): Clean appKey method and usage (#11336) * removing appKey from information table in baseConf and 22.10 update script * removing appKey from NotifyMasterService.php * removing appKey from CentreonRemoteServer.php * applying suggested changes * Applying suggested changes Co-authored-by: Kevin Duret * adding 22.04.2 update script file with changes * revert 22.04 beta 1 script to its original Co-authored-by: Kevin Duret * enh(platform): Use API to select metrics in virtual metrics configuration form 22.04.x (#11461) * changing select with select2 of metrics * fix alignement * remove unecessary files and replace selec by select2 in formComponentTemplate * fix select id name for acceptance tests * update composer for acceptance tests * fix acceptance test 2 * add allow clear to metrics select2 * applying suggested changes * final changes for merging * remove unecessary select tag * [SNYK] Sanitize and bind ACL class queries (#11392) (#11472) * Sanitize and bind ACL class queries Queries sanitized and bound using PDO statement * fix spaces spaces between (int) cast and variables * update file delete spaces after comma * change variables names due to a review * Line exceeds 120 characters; contains 123 characters * fix(conf) fix broker conf name display in listing (#11372) (#11376) Co-authored-by: Elmahdi ABBASSI <108519266+emabassi-ext@users.noreply.github.com> Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> Co-authored-by: Nouha-ElAbrouki <97687698+Noha-ElAbrouki@users.noreply.github.com> Co-authored-by: Kevin Duret Co-authored-by: hyahiaoui-ext <97593234+hyahiaoui-ext@users.noreply.github.com> Co-authored-by: Tom Darneix Co-authored-by: alaunois * fix(cron): Escape database name in CentACL 22.04.x (#11510) * fix(test): wait 8s before checking downtime is active in rest api v1 test (#11498) (#11504) Refs: MON-14585 * fix(UI): Include host_id when selecting ServiceGroups on dashreports (#11428) (#11519) Co-authored-by: VHS Co-authored-by: VHS * fix(Resources/Graph): export graph image after selecting png (#11491) * [SNYK] Sanitize and bind ACL host dependency queries (#11389) (#11394) * Sanitize and bind ACL host dependency queries * fix issues * removed old variable userCrypted and the use of it (#11334) (#11352) Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> * enh(Header/userMenu):reduce spacing user menu (#11393) * update user menu * fix(hostgroup): fix display of hostgroups in select2 (#11431) (#11443) * fix(ci): fix debian packaging with freshly instanciated jenkins slave (#11398) (#11399) Refs: MON-14377 * Sanitized and bound queries (#11413) (#11445) lines : 130 -142 * Snyk: Sanitize and bind media sync queries 22.04.x (#11418) * sanitizing and binding sync dir file queries * Applying some fixes * Snyk: Sanitize and bind ACL service dependency queries dev-22.04.x (#11395) * Snyk: Sanitize and bind Auth class queries 22.04.x (#11448) * [Backport/need review] fix(UI): Fix layout for Safari and form validation (#11440) * fix(UI): Fix layout for Safari and form validation (#11373) * Fix form validation * Fix padlock layout for safari * Update centreon-frontend * Remove debug variable * Fix test * Fix page respsoniveness * Rename variable * update deps * Fix package-lock * Fix package-lock * Add debug statement for debian * Install nodejs rather npm * Attempt fix * Attempt to fix nodejs installation * add sudo * Fix redoc-cli usage * Try to fix permission on npm * Fix * Fix permission * Fix permission (please work) * Fix source * Stop using npx because..... * Allow legacy-peer-deps * Remove nodejs installation * Fix image to pull for debian 11 * [SNYK] Sanitize and bind centreonGraph class queries (#11409) (#11421) 1122 1153 1134 * [Snyk] Sanitize and bind ACL action access queries (#11385) (#11402) * Sanitize and bind ACL action access queries _ sanitize if possible each variables inserted in a query _ use PDO prepared statement and bind() method _ Do not use $pearDB->escape on which is for examples useless on integers and on non closed HTML tags (svg, img, etc) * fix line length * fix failed checks * feat(api): implement endpoint to update centreon web (#11391) (#11401) Refs: MON-12296 * Clean(platform): Clean appKey method and usage 22.04.x (#11452) * Clean(platform): Clean appKey method and usage (#11336) * removing appKey from information table in baseConf and 22.10 update script * removing appKey from NotifyMasterService.php * removing appKey from CentreonRemoteServer.php * applying suggested changes * Applying suggested changes Co-authored-by: Kevin Duret * adding 22.04.2 update script file with changes * revert 22.04 beta 1 script to its original Co-authored-by: Kevin Duret * enh(platform): Use API to select metrics in virtual metrics configuration form 22.04.x (#11461) * changing select with select2 of metrics * fix alignement * remove unecessary files and replace selec by select2 in formComponentTemplate * fix select id name for acceptance tests * update composer for acceptance tests * fix acceptance test 2 * add allow clear to metrics select2 * applying suggested changes * final changes for merging * remove unecessary select tag * [SNYK] Sanitize and bind ACL class queries (#11392) (#11472) * Sanitize and bind ACL class queries Queries sanitized and bound using PDO statement * fix spaces spaces between (int) cast and variables * update file delete spaces after comma * change variables names due to a review * Line exceeds 120 characters; contains 123 characters * fix(conf) fix broker conf name display in listing (#11372) (#11376) * fix export graph image after selecting png Co-authored-by: Elmahdi ABBASSI <108519266+emabassi-ext@users.noreply.github.com> Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> Co-authored-by: Kevin Duret Co-authored-by: hyahiaoui-ext <97593234+hyahiaoui-ext@users.noreply.github.com> Co-authored-by: Tom Darneix Co-authored-by: alaunois * Fix(platform): Removing appkey key (#11511) * fix(trap): Removal of the restriction on the uniqueness of the OID of a trap (#11327) Currently, an error appears when we try to save an existing trap because a test is performed on the uniqueness of the OID. This PR aims to remove the restriction on the uniqueness of the OID of a trap. * fix(pendo): correctly set locale when language is detection by browser (#11484) (#11528) * fix(test): fix random fails on virtual metric test (#11523) Refs: MON-14359 * fix(autoload): Add classmap to fix autoload with legacy classes (#11492) (#11532) Refs: MON-14496 * fix(ldap): small refacto of ldap authentication and log failures (#11422) (#11534) Refs: MON-7417 * fix(api): allow api platform updates from installed 22.04.0 (#11495) (#11533) Refs: MON-12296 * fix(api): fix call to api on fresh install (#11536) (#11537) Refs: MON-12296 * doc(ack): acknowledge Hakaï security (#11540) * fix(api): do not init db connection in event subscriber (#11543) (#11545) Refs: MON-12296 * fix(web): fix the comment deletion for host monitored by poller (#11138) (#11556) Refs: MON-12828 Co-authored-by: Stéphane Duret * SNYK: Sanitize and bind ACL actions queries (#11547) * sanitizing and binding acl actions queries * fix missing bind * SNYK: Sanitize and bind Broker listing queries (#11550) * Sanitizing and binding broker listing queries * applying suggested changes * fix(conf) fix encoding in template service listing (#11558) (#11564) * fix encoding * remove useless function * SNYK: Sanitize and bind generateImage queries (#11561) * sanitize and bind generate image queries * adding throw exception * applying suggested changes * Update www/include/views/graphs/generateGraphs/generateImage.php Co-authored-by: Kevin Duret Co-authored-by: Kevin Duret * MON-14501 - sanitize query in centreonXmlbgRequest class (#11570) * sanitize query in centreonXmlbgRequest class * add closeCursor func to resolve conv * SNYK: Sanitize and bind Meta-Services dependency queries (#11567) * sanityze 2 insert queries * spaces removed in a query * chore(release):rebase dev-22.04.x on 22.04.x (#11627) * Merge release-22.04.3 into 22.04.x (#11623) * fix(git): resync 22.04.x to dev-22.04.x (#11503) * [SNYK] Sanitize and bind ACL host dependency queries (#11389) (#11394) * Sanitize and bind ACL host dependency queries * fix issues * removed old variable userCrypted and the use of it (#11334) (#11352) Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> * enh(Header/userMenu):reduce spacing user menu (#11393) * update user menu * fix(hostgroup): fix display of hostgroups in select2 (#11431) (#11443) * fix(ci): fix debian packaging with freshly instanciated jenkins slave (#11398) (#11399) Refs: MON-14377 * Sanitized and bound queries (#11413) (#11445) lines : 130 -142 * Snyk: Sanitize and bind media sync queries 22.04.x (#11418) * sanitizing and binding sync dir file queries * Applying some fixes * Snyk: Sanitize and bind ACL service dependency queries dev-22.04.x (#11395) * Snyk: Sanitize and bind Auth class queries 22.04.x (#11448) * [Backport/need review] fix(UI): Fix layout for Safari and form validation (#11440) * fix(UI): Fix layout for Safari and form validation (#11373) * Fix form validation * Fix padlock layout for safari * Update centreon-frontend * Remove debug variable * Fix test * Fix page respsoniveness * Rename variable * update deps * Fix package-lock * Fix package-lock * Add debug statement for debian * Install nodejs rather npm * Attempt fix * Attempt to fix nodejs installation * add sudo * Fix redoc-cli usage * Try to fix permission on npm * Fix * Fix permission * Fix permission (please work) * Fix source * Stop using npx because..... * Allow legacy-peer-deps * Remove nodejs installation * Fix image to pull for debian 11 * [SNYK] Sanitize and bind centreonGraph class queries (#11409) (#11421) 1122 1153 1134 * [Snyk] Sanitize and bind ACL action access queries (#11385) (#11402) * Sanitize and bind ACL action access queries _ sanitize if possible each variables inserted in a query _ use PDO prepared statement and bind() method _ Do not use $pearDB->escape on which is for examples useless on integers and on non closed HTML tags (svg, img, etc) * fix line length * fix failed checks * feat(api): implement endpoint to update centreon web (#11391) (#11401) Refs: MON-12296 * Clean(platform): Clean appKey method and usage 22.04.x (#11452) * Clean(platform): Clean appKey method and usage (#11336) * removing appKey from information table in baseConf and 22.10 update script * removing appKey from NotifyMasterService.php * removing appKey from CentreonRemoteServer.php * applying suggested changes * Applying suggested changes Co-authored-by: Kevin Duret * adding 22.04.2 update script file with changes * revert 22.04 beta 1 script to its original Co-authored-by: Kevin Duret * enh(platform): Use API to select metrics in virtual metrics configuration form 22.04.x (#11461) * changing select with select2 of metrics * fix alignement * remove unecessary files and replace selec by select2 in formComponentTemplate * fix select id name for acceptance tests * update composer for acceptance tests * fix acceptance test 2 * add allow clear to metrics select2 * applying suggested changes * final changes for merging * remove unecessary select tag * [SNYK] Sanitize and bind ACL class queries (#11392) (#11472) * Sanitize and bind ACL class queries Queries sanitized and bound using PDO statement * fix spaces spaces between (int) cast and variables * update file delete spaces after comma * change variables names due to a review * Line exceeds 120 characters; contains 123 characters * fix(conf) fix broker conf name display in listing (#11372) (#11376) Co-authored-by: Elmahdi ABBASSI <108519266+emabassi-ext@users.noreply.github.com> Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> Co-authored-by: Nouha-ElAbrouki <97687698+Noha-ElAbrouki@users.noreply.github.com> Co-authored-by: Kevin Duret Co-authored-by: hyahiaoui-ext <97593234+hyahiaoui-ext@users.noreply.github.com> Co-authored-by: Tom Darneix Co-authored-by: alaunois * fix(cron): Escape database name in CentACL 22.04.x (#11510) * fix(test): wait 8s before checking downtime is active in rest api v1 test (#11498) (#11504) Refs: MON-14585 * fix(UI): Include host_id when selecting ServiceGroups on dashreports (#11428) (#11519) Co-authored-by: VHS Co-authored-by: VHS * fix(Resources/Graph): export graph image after selecting png (#11491) * [SNYK] Sanitize and bind ACL host dependency queries (#11389) (#11394) * Sanitize and bind ACL host dependency queries * fix issues * removed old variable userCrypted and the use of it (#11334) (#11352) Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> * enh(Header/userMenu):reduce spacing user menu (#11393) * update user menu * fix(hostgroup): fix display of hostgroups in select2 (#11431) (#11443) * fix(ci): fix debian packaging with freshly instanciated jenkins slave (#11398) (#11399) Refs: MON-14377 * Sanitized and bound queries (#11413) (#11445) lines : 130 -142 * Snyk: Sanitize and bind media sync queries 22.04.x (#11418) * sanitizing and binding sync dir file queries * Applying some fixes * Snyk: Sanitize and bind ACL service dependency queries dev-22.04.x (#11395) * Snyk: Sanitize and bind Auth class queries 22.04.x (#11448) * [Backport/need review] fix(UI): Fix layout for Safari and form validation (#11440) * fix(UI): Fix layout for Safari and form validation (#11373) * Fix form validation * Fix padlock layout for safari * Update centreon-frontend * Remove debug variable * Fix test * Fix page respsoniveness * Rename variable * update deps * Fix package-lock * Fix package-lock * Add debug statement for debian * Install nodejs rather npm * Attempt fix * Attempt to fix nodejs installation * add sudo * Fix redoc-cli usage * Try to fix permission on npm * Fix * Fix permission * Fix permission (please work) * Fix source * Stop using npx because..... * Allow legacy-peer-deps * Remove nodejs installation * Fix image to pull for debian 11 * [SNYK] Sanitize and bind centreonGraph class queries (#11409) (#11421) 1122 1153 1134 * [Snyk] Sanitize and bind ACL action access queries (#11385) (#11402) * Sanitize and bind ACL action access queries _ sanitize if possible each variables inserted in a query _ use PDO prepared statement and bind() method _ Do not use $pearDB->escape on which is for examples useless on integers and on non closed HTML tags (svg, img, etc) * fix line length * fix failed checks * feat(api): implement endpoint to update centreon web (#11391) (#11401) Refs: MON-12296 * Clean(platform): Clean appKey method and usage 22.04.x (#11452) * Clean(platform): Clean appKey method and usage (#11336) * removing appKey from information table in baseConf and 22.10 update script * removing appKey from NotifyMasterService.php * removing appKey from CentreonRemoteServer.php * applying suggested changes * Applying suggested changes Co-authored-by: Kevin Duret * adding 22.04.2 update script file with changes * revert 22.04 beta 1 script to its original Co-authored-by: Kevin Duret * enh(platform): Use API to select metrics in virtual metrics configuration form 22.04.x (#11461) * changing select with select2 of metrics * fix alignement * remove unecessary files and replace selec by select2 in formComponentTemplate * fix select id name for acceptance tests * update composer for acceptance tests * fix acceptance test 2 * add allow clear to metrics select2 * applying suggested changes * final changes for merging * remove unecessary select tag * [SNYK] Sanitize and bind ACL class queries (#11392) (#11472) * Sanitize and bind ACL class queries Queries sanitized and bound using PDO statement * fix spaces spaces between (int) cast and variables * update file delete spaces after comma * change variables names due to a review * Line exceeds 120 characters; contains 123 characters * fix(conf) fix broker conf name display in listing (#11372) (#11376) * fix export graph image after selecting png Co-authored-by: Elmahdi ABBASSI <108519266+emabassi-ext@users.noreply.github.com> Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> Co-authored-by: Kevin Duret Co-authored-by: hyahiaoui-ext <97593234+hyahiaoui-ext@users.noreply.github.com> Co-authored-by: Tom Darneix Co-authored-by: alaunois * Fix(platform): Removing appkey key (#11511) * fix(trap): Removal of the restriction on the uniqueness of the OID of a trap (#11327) Currently, an error appears when we try to save an existing trap because a test is performed on the uniqueness of the OID. This PR aims to remove the restriction on the uniqueness of the OID of a trap. * fix(pendo): correctly set locale when language is detection by browser (#11484) (#11528) * fix(test): fix random fails on virtual metric test (#11523) Refs: MON-14359 * fix(autoload): Add classmap to fix autoload with legacy classes (#11492) (#11532) Refs: MON-14496 * fix(ldap): small refacto of ldap authentication and log failures (#11422) (#11534) Refs: MON-7417 * fix(api): allow api platform updates from installed 22.04.0 (#11495) (#11533) Refs: MON-12296 * fix(api): fix call to api on fresh install (#11536) (#11537) Refs: MON-12296 * doc(ack): acknowledge Hakaï security (#11540) * fix(api): do not init db connection in event subscriber (#11543) (#11545) Refs: MON-12296 * fix(web): fix the comment deletion for host monitored by poller (#11138) (#11556) Refs: MON-12828 Co-authored-by: Stéphane Duret * SNYK: Sanitize and bind ACL actions queries (#11547) * sanitizing and binding acl actions queries * fix missing bind * SNYK: Sanitize and bind Broker listing queries (#11550) * Sanitizing and binding broker listing queries * applying suggested changes * fix(conf) fix encoding in template service listing (#11558) (#11564) * fix encoding * remove useless function * SNYK: Sanitize and bind generateImage queries (#11561) * sanitize and bind generate image queries * adding throw exception * applying suggested changes * Update www/include/views/graphs/generateGraphs/generateImage.php Co-authored-by: Kevin Duret Co-authored-by: Kevin Duret * MON-14501 - sanitize query in centreonXmlbgRequest class (#11570) * sanitize query in centreonXmlbgRequest class * add closeCursor func to resolve conv * SNYK: Sanitize and bind Meta-Services dependency queries (#11567) * sanityze 2 insert queries * spaces removed in a query * chore(install):Update version to 22.04.3 * fix(sql): fix query to select contact during ldap import (#11578) Refs: MON-14263 * fix(UI): Fix layout for Safari and form validation (#11373) (#11604) * Fix form validation * Fix padlock layout for safari * Update centreon-frontend * Remove debug variable * Fix test * Fix page respsoniveness * Rename variable * update deps * Fix package-lock Co-authored-by: Elmahdi ABBASSI <108519266+emabassi-ext@users.noreply.github.com> Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> Co-authored-by: Nouha-ElAbrouki <97687698+Noha-ElAbrouki@users.noreply.github.com> Co-authored-by: Kevin Duret Co-authored-by: hyahiaoui-ext <97593234+hyahiaoui-ext@users.noreply.github.com> Co-authored-by: Tom Darneix Co-authored-by: alaunois Co-authored-by: VHS Co-authored-by: Laurent Calvet Co-authored-by: Stéphane Chapron <34628915+sc979@users.noreply.github.com> Co-authored-by: Stéphane Duret * fix(api): fix call to api on fresh install (#11536) (#11537) Refs: MON-12296 * fix(api): do not init db connection in event subscriber (#11543) (#11545) Refs: MON-12296 Co-authored-by: Elmahdi ABBASSI <108519266+emabassi-ext@users.noreply.github.com> Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> Co-authored-by: Nouha-ElAbrouki <97687698+Noha-ElAbrouki@users.noreply.github.com> Co-authored-by: Kevin Duret Co-authored-by: hyahiaoui-ext <97593234+hyahiaoui-ext@users.noreply.github.com> Co-authored-by: Tom Darneix Co-authored-by: alaunois Co-authored-by: VHS Co-authored-by: Laurent Calvet Co-authored-by: Stéphane Chapron <34628915+sc979@users.noreply.github.com> Co-authored-by: Stéphane Duret * fix(partition): adapt control of database version (#11609) (#11610) * fix(openid): correctly set contact_location while creating session (#11613) (#11614) * fix(lang): Fixed FR typo (#11621) * enh(UI): Add a “Parent alias“ column on the monitoring resources sta… (#11542) * enh(UI): Add a “Parent alias“ column on the monitoring resources status page (#11190) * Add column ParentAlias * Add new label ParentAlias * Add column ParentAlias and new column component * Add new card to display Parent Alias * Remove tile in Details Panel, enhancement not expected * FIx eslint issue * Fix naming on label parent alias * Add translation * Add line at the end of files * Add line at the end of file * fix issues * Update lang/fr_FR.UTF-8/LC_MESSAGES/messages.po Co-authored-by: Tom Darneix * Update lang/es_ES.UTF-8/LC_MESSAGES/messages.po Co-authored-by: Tom Darneix * Update lang/pt_PT.UTF-8/LC_MESSAGES/messages.po Co-authored-by: Tom Darneix * Update lang/es_ES.UTF-8/LC_MESSAGES/messages.po Co-authored-by: Jérémy Delpierre * Update lang/pt_BR.UTF-8/LC_MESSAGES/messages.po Co-authored-by: Jérémy Delpierre * Update lang/fr_FR.UTF-8/LC_MESSAGES/messages.po Co-authored-by: Bruno d'Auria * Fix issue on messages.po file Co-authored-by: Tom Darneix Co-authored-by: Jérémy Delpierre Co-authored-by: Bruno d'Auria * query sanitized in listServiceCategoriesà (#11597) (#11632) * MON-14797 reorganizes dependencies (#11612) * Fix encoding issue on status serviceXML (#11581) * sanitize and bind in centreon connector query (#11635) * sanitize insrert queries in db-func (#11650) MON-14667 * chore(git): update codeowners (#11594) * chore(release):rebase dev-22.04.x on 22.04.x (#11688) * Merge release-22.04.3 into 22.04.x (#11623) * fix(git): resync 22.04.x to dev-22.04.x (#11503) * [SNYK] Sanitize and bind ACL host dependency queries (#11389) (#11394) * Sanitize and bind ACL host dependency queries * fix issues * removed old variable userCrypted and the use of it (#11334) (#11352) Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> * enh(Header/userMenu):reduce spacing user menu (#11393) * update user menu * fix(hostgroup): fix display of hostgroups in select2 (#11431) (#11443) * fix(ci): fix debian packaging with freshly instanciated jenkins slave (#11398) (#11399) Refs: MON-14377 * Sanitized and bound queries (#11413) (#11445) lines : 130 -142 * Snyk: Sanitize and bind media sync queries 22.04.x (#11418) * sanitizing and binding sync dir file queries * Applying some fixes * Snyk: Sanitize and bind ACL service dependency queries dev-22.04.x (#11395) * Snyk: Sanitize and bind Auth class queries 22.04.x (#11448) * [Backport/need review] fix(UI): Fix layout for Safari and form validation (#11440) * fix(UI): Fix layout for Safari and form validation (#11373) * Fix form validation * Fix padlock layout for safari * Update centreon-frontend * Remove debug variable * Fix test * Fix page respsoniveness * Rename variable * update deps * Fix package-lock * Fix package-lock * Add debug statement for debian * Install nodejs rather npm * Attempt fix * Attempt to fix nodejs installation * add sudo * Fix redoc-cli usage * Try to fix permission on npm * Fix * Fix permission * Fix permission (please work) * Fix source * Stop using npx because..... * Allow legacy-peer-deps * Remove nodejs installation * Fix image to pull for debian 11 * [SNYK] Sanitize and bind centreonGraph class queries (#11409) (#11421) 1122 1153 1134 * [Snyk] Sanitize and bind ACL action access queries (#11385) (#11402) * Sanitize and bind ACL action access queries _ sanitize if possible each variables inserted in a query _ use PDO prepared statement and bind() method _ Do not use $pearDB->escape on which is for examples useless on integers and on non closed HTML tags (svg, img, etc) * fix line length * fix failed checks * feat(api): implement endpoint to update centreon web (#11391) (#11401) Refs: MON-12296 * Clean(platform): Clean appKey method and usage 22.04.x (#11452) * Clean(platform): Clean appKey method and usage (#11336) * removing appKey from information table in baseConf and 22.10 update script * removing appKey from NotifyMasterService.php * removing appKey from CentreonRemoteServer.php * applying suggested changes * Applying suggested changes Co-authored-by: Kevin Duret * adding 22.04.2 update script file with changes * revert 22.04 beta 1 script to its original Co-authored-by: Kevin Duret * enh(platform): Use API to select metrics in virtual metrics configuration form 22.04.x (#11461) * changing select with select2 of metrics * fix alignement * remove unecessary files and replace selec by select2 in formComponentTemplate * fix select id name for acceptance tests * update composer for acceptance tests * fix acceptance test 2 * add allow clear to metrics select2 * applying suggested changes * final changes for merging * remove unecessary select tag * [SNYK] Sanitize and bind ACL class queries (#11392) (#11472) * Sanitize and bind ACL class queries Queries sanitized and bound using PDO statement * fix spaces spaces between (int) cast and variables * update file delete spaces after comma * change variables names due to a review * Line exceeds 120 characters; contains 123 characters * fix(conf) fix broker conf name display in listing (#11372) (#11376) Co-authored-by: Elmahdi ABBASSI <108519266+emabassi-ext@users.noreply.github.com> Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> Co-authored-by: Nouha-ElAbrouki <97687698+Noha-ElAbrouki@users.noreply.github.com> Co-authored-by: Kevin Duret Co-authored-by: hyahiaoui-ext <97593234+hyahiaoui-ext@users.noreply.github.com> Co-authored-by: Tom Darneix Co-authored-by: alaunois * fix(cron): Escape database name in CentACL 22.04.x (#11510) * fix(test): wait 8s before checking downtime is active in rest api v1 test (#11498) (#11504) Refs: MON-14585 * fix(UI): Include host_id when selecting ServiceGroups on dashreports (#11428) (#11519) Co-authored-by: VHS Co-authored-by: VHS * fix(Resources/Graph): export graph image after selecting png (#11491) * [SNYK] Sanitize and bind ACL host dependency queries (#11389) (#11394) * Sanitize and bind ACL host dependency queries * fix issues * removed old variable userCrypted and the use of it (#11334) (#11352) Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> * enh(Header/userMenu):reduce spacing user menu (#11393) * update user menu * fix(hostgroup): fix display of hostgroups in select2 (#11431) (#11443) * fix(ci): fix debian packaging with freshly instanciated jenkins slave (#11398) (#11399) Refs: MON-14377 * Sanitized and bound queries (#11413) (#11445) lines : 130 -142 * Snyk: Sanitize and bind media sync queries 22.04.x (#11418) * sanitizing and binding sync dir file queries * Applying some fixes * Snyk: Sanitize and bind ACL service dependency queries dev-22.04.x (#11395) * Snyk: Sanitize and bind Auth class queries 22.04.x (#11448) * [Backport/need review] fix(UI): Fix layout for Safari and form validation (#11440) * fix(UI): Fix layout for Safari and form validation (#11373) * Fix form validation * Fix padlock layout for safari * Update centreon-frontend * Remove debug variable * Fix test * Fix page respsoniveness * Rename variable * update deps * Fix package-lock * Fix package-lock * Add debug statement for debian * Install nodejs rather npm * Attempt fix * Attempt to fix nodejs installation * add sudo * Fix redoc-cli usage * Try to fix permission on npm * Fix * Fix permission * Fix permission (please work) * Fix source * Stop using npx because..... * Allow legacy-peer-deps * Remove nodejs installation * Fix image to pull for debian 11 * [SNYK] Sanitize and bind centreonGraph class queries (#11409) (#11421) 1122 1153 1134 * [Snyk] Sanitize and bind ACL action access queries (#11385) (#11402) * Sanitize and bind ACL action access queries _ sanitize if possible each variables inserted in a query _ use PDO prepared statement and bind() method _ Do not use $pearDB->escape on which is for examples useless on integers and on non closed HTML tags (svg, img, etc) * fix line length * fix failed checks * feat(api): implement endpoint to update centreon web (#11391) (#11401) Refs: MON-12296 * Clean(platform): Clean appKey method and usage 22.04.x (#11452) * Clean(platform): Clean appKey method and usage (#11336) * removing appKey from information table in baseConf and 22.10 update script * removing appKey from NotifyMasterService.php * removing appKey from CentreonRemoteServer.php * applying suggested changes * Applying suggested changes Co-authored-by: Kevin Duret * adding 22.04.2 update script file with changes * revert 22.04 beta 1 script to its original Co-authored-by: Kevin Duret * enh(platform): Use API to select metrics in virtual metrics configuration form 22.04.x (#11461) * changing select with select2 of metrics * fix alignement * remove unecessary files and replace selec by select2 in formComponentTemplate * fix select id name for acceptance tests * update composer for acceptance tests * fix acceptance test 2 * add allow clear to metrics select2 * applying suggested changes * final changes for merging * remove unecessary select tag * [SNYK] Sanitize and bind ACL class queries (#11392) (#11472) * Sanitize and bind ACL class queries Queries sanitized and bound using PDO statement * fix spaces spaces between (int) cast and variables * update file delete spaces after comma * change variables names due to a review * Line exceeds 120 characters; contains 123 characters * fix(conf) fix broker conf name display in listing (#11372) (#11376) * fix export graph image after selecting png Co-authored-by: Elmahdi ABBASSI <108519266+emabassi-ext@users.noreply.github.com> Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> Co-authored-by: Kevin Duret Co-authored-by: hyahiaoui-ext <97593234+hyahiaoui-ext@users.noreply.github.com> Co-authored-by: Tom Darneix Co-authored-by: alaunois * Fix(platform): Removing appkey key (#11511) * fix(trap): Removal of the restriction on the uniqueness of the OID of a trap (#11327) Currently, an error appears when we try to save an existing trap because a test is performed on the uniqueness of the OID. This PR aims to remove the restriction on the uniqueness of the OID of a trap. * fix(pendo): correctly set locale when language is detection by browser (#11484) (#11528) * fix(test): fix random fails on virtual metric test (#11523) Refs: MON-14359 * fix(autoload): Add classmap to fix autoload with legacy classes (#11492) (#11532) Refs: MON-14496 * fix(ldap): small refacto of ldap authentication and log failures (#11422) (#11534) Refs: MON-7417 * fix(api): allow api platform updates from installed 22.04.0 (#11495) (#11533) Refs: MON-12296 * fix(api): fix call to api on fresh install (#11536) (#11537) Refs: MON-12296 * doc(ack): acknowledge Hakaï security (#11540) * fix(api): do not init db connection in event subscriber (#11543) (#11545) Refs: MON-12296 * fix(web): fix the comment deletion for host monitored by poller (#11138) (#11556) Refs: MON-12828 Co-authored-by: Stéphane Duret * SNYK: Sanitize and bind ACL actions queries (#11547) * sanitizing and binding acl actions queries * fix missing bind * SNYK: Sanitize and bind Broker listing queries (#11550) * Sanitizing and binding broker listing queries * applying suggested changes * fix(conf) fix encoding in template service listing (#11558) (#11564) * fix encoding * remove useless function * SNYK: Sanitize and bind generateImage queries (#11561) * sanitize and bind generate image queries * adding throw exception * applying suggested changes * Update www/include/views/graphs/generateGraphs/generateImage.php Co-authored-by: Kevin Duret Co-authored-by: Kevin Duret * MON-14501 - sanitize query in centreonXmlbgRequest class (#11570) * sanitize query in centreonXmlbgRequest class * add closeCursor func to resolve conv * SNYK: Sanitize and bind Meta-Services dependency queries (#11567) * sanityze 2 insert queries * spaces removed in a query * chore(install):Update version to 22.04.3 * fix(sql): fix query to select contact during ldap import (#11578) Refs: MON-14263 * fix(UI): Fix layout for Safari and form validation (#11373) (#11604) * Fix form validation * Fix padlock layout for safari * Update centreon-frontend * Remove debug variable * Fix test * Fix page respsoniveness * Rename variable * update deps * Fix package-lock Co-authored-by: Elmahdi ABBASSI <108519266+emabassi-ext@users.noreply.github.com> Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> Co-authored-by: Nouha-ElAbrouki <97687698+Noha-ElAbrouki@users.noreply.github.com> Co-authored-by: Kevin Duret Co-authored-by: hyahiaoui-ext <97593234+hyahiaoui-ext@users.noreply.github.com> Co-authored-by: Tom Darneix Co-authored-by: alaunois Co-authored-by: VHS Co-authored-by: Laurent Calvet Co-authored-by: Stéphane Chapron <34628915+sc979@users.noreply.github.com> Co-authored-by: Stéphane Duret * chore(release): merge hotfix-MON-14893-index-data (#11681) * fix(upgrade): Correctly Parse SQL Comments (#11658) (#11668) Refs: MON-14848 Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> * fix invalid values for index_data.special (#11669) * chore(install):update version to 22.04.4 Co-authored-by: Kevin Duret Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> * fix(api): fix call to api on fresh install (#11536) (#11537) Refs: MON-12296 * fix(api): do not init db connection in event subscriber (#11543) (#11545) Refs: MON-12296 * fix(partition): adapt control of database version (#11609) (#11610) * fix(openid): correctly set contact_location while creating session (#11613) (#11614) * fix(lang): Fixed FR typo (#11621) * enh(UI): Add a “Parent alias“ column on the monitoring resources sta… (#11542) * enh(UI): Add a “Parent alias“ column on the monitoring resources status page (#11190) * Add column ParentAlias * Add new label ParentAlias * Add column ParentAlias and new column component * Add new card to display Parent Alias * Remove tile in Details Panel, enhancement not expected * FIx eslint issue * Fix naming on label parent alias * Add translation * Add line at the end of files * Add line at the end of file * fix issues * Update lang/fr_FR.UTF-8/LC_MESSAGES/messages.po Co-authored-by: Tom Darneix * Update lang/es_ES.UTF-8/LC_MESSAGES/messages.po Co-authored-by: Tom Darneix * Update lang/pt_PT.UTF-8/LC_MESSAGES/messages.po Co-authored-by: Tom Darneix * Update lang/es_ES.UTF-8/LC_MESSAGES/messages.po Co-authored-by: Jérémy Delpierre * Update lang/pt_BR.UTF-8/LC_MESSAGES/messages.po Co-authored-by: Jérémy Delpierre * Update lang/fr_FR.UTF-8/LC_MESSAGES/messages.po Co-authored-by: Bruno d'Auria * Fix issue on messages.po file Co-authored-by: Tom Darneix Co-authored-by: Jérémy Delpierre Co-authored-by: Bruno d'Auria * query sanitized in listServiceCategoriesà (#11597) (#11632) * MON-14797 reorganizes dependencies (#11612) * Fix encoding issue on status serviceXML (#11581) * sanitize and bind in centreon connector query (#11635) * sanitize insrert queries in db-func (#11650) MON-14667 Co-authored-by: Elmahdi ABBASSI <108519266+emabassi-ext@users.noreply.github.com> Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> Co-authored-by: Nouha-ElAbrouki <97687698+Noha-ElAbrouki@users.noreply.github.com> Co-authored-by: Kevin Duret Co-authored-by: hyahiaoui-ext <97593234+hyahiaoui-ext@users.noreply.github.com> Co-authored-by: Tom Darneix Co-authored-by: alaunois Co-authored-by: VHS Co-authored-by: Laurent Calvet Co-authored-by: Stéphane Chapron <34628915+sc979@users.noreply.github.com> Co-authored-by: Stéphane Duret Co-authored-by: Laurent Pinsivy Co-authored-by: jcaro Co-authored-by: Jérémy Delpierre Co-authored-by: Bruno d'Auria Co-authored-by: Luiz Costa Co-authored-by: TamazC <103252125+TamazC@users.noreply.github.com> * fix(details): remove dead code (#11672) (#11686) * fix(conf) fix parent template display in service template listing (#11671) (#11676) * fix(poller): fix remote server duplication (#11552) (#11674) * fix(poller): fix remote server duplication (#11552) Refs: MON-14579 Co-authored-by: Jérémy Jaouen * fix translation for host and service category (#11626) * fix(clapi): Check that user is admin to use clapi (#11631) (#11640) * Sanitized and bound queries in service argumentsXml fil (#11653) MON-14669 * Sanitize and bind listVirtualMetrics queries (#11647) * sanitize and bind host categories queries (#11645) * Ãbind queries an fix array binding(#11656) * fix(ui): fix svg display in legacy monitoring pages (#11659) (#11690) Refs: MON-14869 * Sanitize and bind service group dependecies queries 22.04.x (#11665) * MON-14425 fix centreon.ini and autoconfigure timezone (#11608) * enh(Resources/header): Display the 2 access pictograms logs and report on details panel (#11618) * Display the 2 access pictograms logs and report on details panel * Update www/front_src/src/Resources/Details/Header.tsx Co-authored-by: JKancel * Update www/front_src/src/Resources/Details/Header.tsx Co-authored-by: JKancel Co-authored-by: JKancel * fix(resource-status): add missing alias to Host detail factory (#11642) * fix(widgets): retrieve possibility to not select poller in pref (#11696) (#11698) Refs: MON-14919 * fix(install): fix source install with quiet mode related to gorgone vars (#11694) (#11701) Refs: MON-14806 Co-authored-by: Eric Coquard * Fix: In Acces group the second select not working [ACL] 22.04.x (#11709) * fix second select not working * applying suggested changes * fix(details): second part of code cleanup for "tools" (#11718) (#11721) * fix (#11724) * FIX: Sanitize and bind graph configuration queries 22.04.x (#11729) * [Fix]:Sanitize and bind queries in template of service listing (#11746) * [Fix]:Sanitize and bind queries in template of service listing * work on tamazC suggestion * fix(resource): Fix bad SQL request (#11702) (#11749) * FIX: Sanitize and bind Meta Service configuration 22.04.x (#11733) * sanitize and bind meta service config * applying suggested changes * Fix: Sanitize and bind CLAPI poller configuration 22.04.x (#11731) * sanitize and bind CLAPI poller config * remove unecessary comment * revert deleted imports * FIX: Sanitize and bind command configuration queries 22.04.x (#11754) * fix(partition): fix condition for database version (#11657) (#11756) Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> Co-authored-by: Charles Gautier <33026375+chgautier@users.noreply.github.com> Co-authored-by: Elmahdi ABBASSI <108519266+emabassi-ext@users.noreply.github.com> Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> Co-authored-by: Nouha-ElAbrouki <97687698+Noha-ElAbrouki@users.noreply.github.com> Co-authored-by: Kevin Duret Co-authored-by: hyahiaoui-ext <97593234+hyahiaoui-ext@users.noreply.github.com> Co-authored-by: Tom Darneix Co-authored-by: alaunois Co-authored-by: VHS Co-authored-by: Laurent Calvet Co-authored-by: Stéphane Chapron <34628915+sc979@users.noreply.github.com> Co-authored-by: Stéphane Duret Co-authored-by: Laurent Pinsivy Co-authored-by: jcaro Co-authored-by: Jérémy Delpierre Co-authored-by: Bruno d'Auria Co-authored-by: Luiz Costa Co-authored-by: TamazC <103252125+TamazC@users.noreply.github.com> Co-authored-by: Adrien Morais-Mestre <31647811+adr-mo@users.noreply.github.com> Co-authored-by: Jérémy Jaouen Co-authored-by: JKancel Co-authored-by: Eric Coquard --- .github/CODEOWNERS | 3 - bin/registerServerTopology.sh | 2 +- ci/debian/centreon-web.postinst | 13 +++ ci/debian/control | 11 +- ci/debian/extra/centreon-web/centreon.ini | 6 +- .../Centreon/PlatformInformation/Update.json | 3 + doc/API/centreon-api-v22.04.yaml | 4 + install.sh | 28 ++--- lang/es_ES.UTF-8/LC_MESSAGES/messages.po | 12 ++- lang/fr_FR.UTF-8/LC_MESSAGES/messages.po | 10 +- lang/pt_BR.UTF-8/LC_MESSAGES/messages.po | 6 +- lang/pt_PT.UTF-8/LC_MESSAGES/messages.po | 6 +- src/Centreon/Application/ApiPlatform.php | 10 +- src/Centreon/Domain/Contact/Contact.php | 24 +++++ .../Contact/Interfaces/ContactInterface.php | 5 + .../Model/PlatformInformation.php | 24 +++++ .../Model/PlatformInformationFactory.php | 3 + .../UpdatePartiallyPlatformInformation.php | 1 + .../Model/PlatformPending.php | 14 ++- .../Model/PlatformRegistered.php | 13 +-- .../PlatformTopologyService.php | 14 ++- .../RemoteServerRepositoryInterface.php | 4 +- .../RemoteServer/RemoteServerService.php | 4 + .../Contact/ContactRepositoryRDB.php | 1 + .../RemoteServerRepositoryRDB.php | 8 +- .../CentreonConfigurationRemote.php | 69 +++++++----- .../Webservice/CentreonRemoteServer.php | 29 ++--- .../LinkedPollerConfigurationService.php | 22 ++-- .../Repository/Host/DbHostFactory.php | 3 +- .../LoginOpenIdSession/LoginOpenIdSession.php | 2 +- .../CentreonEventSubscriber.php | 6 +- tests/api/features/PlatformTopology.feature | 8 +- tmpl/vardistrib/defaults | 4 + www/api/class/centreon_clapi.class.php | 2 +- .../centreon_configuration_poller.class.php | 4 +- .../centreon.Config.Poller.class.php | 36 ++++--- .../centreon-partition/partEngine.class.php | 6 +- www/class/centreonConnector.class.php | 30 +++--- www/class/centreonGraph.class.php | 10 +- www/class/centreonMeta.class.php | 19 ++-- www/class/centreonStatistics.class.php | 2 +- .../Params/Connector/Poller.class.php | 1 + .../src/Resources/Details/Header.tsx | 84 +++++++++++---- .../Resources/Details/ShortcutsTooltip.tsx | 94 ---------------- .../src/Resources/Details/index.test.tsx | 34 +++--- .../tabs/Details/DetailsCard/cards.tsx | 5 + .../Resources/Listing/columns/ParentAlias.tsx | 25 +++++ .../src/Resources/Listing/columns/index.tsx | 12 +++ www/front_src/src/Resources/helpers.ts | 16 +++ .../src/Resources/translatedLabels.ts | 1 + .../commandGetArgs/cmdGetExample.php | 11 +- .../configObject/contactgroup/DB-Func.php | 16 +-- .../configObject/host_categories/DB-Func.php | 7 +- .../configObject/service/xml/argumentsXml.php | 22 ++-- .../listServiceCategories.php | 8 +- .../listServiceTemplateModel.ihtml | 2 +- .../listServiceTemplateModel.php | 31 +++--- .../servicegroup_dependency/DB-Func.php | 18 ++-- .../configuration/configResources/DB-Func.php | 45 +++++--- .../configuration/configServers/DB-Func.php | 100 ++++++++++++++--- .../configServers/popup/popup.php | 26 ++--- .../monitoring/objectDetails/hostDetails.php | 34 ------ .../objectDetails/serviceDetails.php | 29 ----- .../objectDetails/template/hostDetails.ihtml | 13 --- .../template/serviceDetails.ihtml | 25 ----- .../status/Services/xml/serviceXML.php | 19 ++-- .../status/Services/xsl/serviceGrid.xsl | 5 +- .../status/Services/xsl/serviceSummary.xsl | 5 +- .../xsl/serviceGridByHG.xsl | 13 ++- .../xsl/serviceSummaryByHG.xsl | 13 ++- .../xsl/serviceGridBySG.xsl | 13 ++- .../xsl/serviceSummaryBySG.xsl | 13 ++- .../accessLists/groupsACL/groupsConfig.php | 10 +- .../virtualMetrics/listVirtualMetrics.php | 30 +++--- www/install/createTables.sql | 4 +- www/install/insertBaseConf.sql | 2 +- www/install/php/Update-22.04.0-beta.1.php | 32 +++--- www/install/php/Update-22.04.5.php | 102 ++++++++++++++++++ 78 files changed, 867 insertions(+), 534 deletions(-) mode change 100755 => 100644 src/CentreonRemote/Application/Webservice/CentreonConfigurationRemote.php delete mode 100644 www/front_src/src/Resources/Details/ShortcutsTooltip.tsx create mode 100644 www/front_src/src/Resources/Listing/columns/ParentAlias.tsx create mode 100644 www/front_src/src/Resources/helpers.ts create mode 100644 www/install/php/Update-22.04.5.php diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index f80446fcc43..fc96a5ca211 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -6,9 +6,6 @@ /project/ @centreon/centreon-devops *.sh @centreon/centreon-devops -/.snyk @centreon/centreon-security -/sonar-project.properties @centreon/centreon-security - *.po @centreon/centreon-documentation /src/ @centreon/centreon-php diff --git a/bin/registerServerTopology.sh b/bin/registerServerTopology.sh index 7ddbbb81111..99688d8f242 100755 --- a/bin/registerServerTopology.sh +++ b/bin/registerServerTopology.sh @@ -431,7 +431,7 @@ function request_to_remote() { fi # Prepare Remote Payload - REMOTE_PAYLOAD='{"isRemote":true,"platformName":"'"${CURRENT_NODE_NAME}"'","centralServerAddress":"'"${PARSED_URL[HOST]}"'","apiUsername":"'"${API_USERNAME}"'","apiCredentials":"'"${API_TARGET_PASSWORD}"'","apiScheme":"'"${PARSED_URL[SCHEME]}"'","apiPort":'"${PARSED_URL[PORT]}"',"apiPath":"'"${CENTREON_BASE_URI}"'",'"${PEER_VALIDATION}" + REMOTE_PAYLOAD='{"isRemote":true,"address":"'${PARSED_CURRENT_NODE_URL[HOST]}'","platformName":"'"${CURRENT_NODE_NAME}"'","centralServerAddress":"'"${PARSED_URL[HOST]}"'","apiUsername":"'"${API_USERNAME}"'","apiCredentials":"'"${API_TARGET_PASSWORD}"'","apiScheme":"'"${PARSED_URL[SCHEME]}"'","apiPort":'"${PARSED_URL[PORT]}"',"apiPath":"'"${CENTREON_BASE_URI}"'",'"${PEER_VALIDATION}" if [[ -n PROXY_PAYLOAD ]]; then REMOTE_PAYLOAD="${REMOTE_PAYLOAD}""${PROXY_PAYLOAD}" fi diff --git a/ci/debian/centreon-web.postinst b/ci/debian/centreon-web.postinst index 8a557942674..0a0fc487bbc 100644 --- a/ci/debian/centreon-web.postinst +++ b/ci/debian/centreon-web.postinst @@ -63,4 +63,17 @@ if [ -n "$2" ]; then su - www-data -s /bin/bash -c "/usr/share/centreon/bin/console cache:clear --no-warmup" fi +# Try auto configure timezone for php +timezone=$(/usr/bin/php -r ' + $timezoneName = timezone_name_from_abbr(trim(shell_exec("date \"+%Z\""))); + if (preg_match("/Time zone: (\S+)/", shell_exec("timedatectl"), $matches)) { + $timezoneName = $matches[1]; + } + if (date_default_timezone_set($timezoneName) === false) { + $timezoneName = "UTC"; + } + echo $timezoneName; +' 2>/dev/null) +sed -i "s#^date.timezone = .*#date.timezone = ${timezone}#" /etc/php/8.0/mods-available/centreon.ini + exit 0 diff --git a/ci/debian/control b/ci/debian/control index 2d9ccc49746..b5d0b11bce0 100644 --- a/ci/debian/control +++ b/ci/debian/control @@ -17,8 +17,7 @@ Package: centreon Architecture: all Depends: centreon-central (>= ${centreon:version}~), - centreon-database (>= ${centreon:version}~), - sudo + centreon-database (>= ${centreon:version}~) Description: Centreon is a network, system, applicative supervision and monitoring tool, it is based upon the most effective Open Source monitoring engine : Nagios. Centreon provides a new frontend and new functionnalities to Nagios. @@ -124,11 +123,9 @@ Depends: php8.0-readline, php8.0-sqlite3, php-pear, - ntp, - rrdtool, - bsd-mailx, - sudo, - nagios-images + rrdtool +Recommends: ntp | bsd-mailx +Suggests: nagios-images Description: This package contains WebUI files. Package: centreon-perl-libs diff --git a/ci/debian/extra/centreon-web/centreon.ini b/ci/debian/extra/centreon-web/centreon.ini index ced3e0d7056..71c00730140 100644 --- a/ci/debian/extra/centreon-web/centreon.ini +++ b/ci/debian/extra/centreon-web/centreon.ini @@ -1 +1,5 @@ -date.timezone = UTC \ No newline at end of file +max_execution_time = 300 +session.use_strict_mode = 1 +session.gc_maxlifetime = 7200 +expose_php = Off +date.timezone = UTC diff --git a/config/json_validator/latest/Centreon/PlatformInformation/Update.json b/config/json_validator/latest/Centreon/PlatformInformation/Update.json index 53c44fcc20d..6f7e93d6bd1 100644 --- a/config/json_validator/latest/Centreon/PlatformInformation/Update.json +++ b/config/json_validator/latest/Centreon/PlatformInformation/Update.json @@ -10,6 +10,9 @@ "isRemote": { "type": "boolean" }, + "address": { + "type": "string" + }, "centralServerAddress": { "type": "string" }, diff --git a/doc/API/centreon-api-v22.04.yaml b/doc/API/centreon-api-v22.04.yaml index 34f82120597..5f7227d9367 100644 --- a/doc/API/centreon-api-v22.04.yaml +++ b/doc/API/centreon-api-v22.04.yaml @@ -6730,6 +6730,10 @@ components: type: boolean example: true description: "Platform is a remote server" + address: + type: string + example: "10.0.0.1" + description: "The address of the platform" centralServerAddress: type: string example: "192.168.0.1" diff --git a/install.sh b/install.sh index f0f857377f5..ba012476a94 100755 --- a/install.sh +++ b/install.sh @@ -210,19 +210,21 @@ for binary in $BINARIES; do fi done -###### Mandatory step -# ask if gorgone is already installed -echo -e "\n$line" -echo -e "\t$(gettext "Check mandatory gorgone service status")" -echo -e "$line" - -yes_no_default "$(gettext "Is the Gorgone module already installed?")" -if [ "$?" -ne 0 ] ; then - echo_failure "\n$(gettext "Gorgone is required.\nPlease install it before launching this script")" "$fail" - echo -e "\n\t$(gettext "Please read the documentation to manage the Gorgone daemon installation")" - echo -e "\t$(gettext "Available on github") : https://github.com/centreon/centreon-gorgone" - echo -e "\t$(gettext "or on the centreon documentation") : https://documentation.centreon.com/\n" - exit 1 +if [ "$silent_install" -ne 1 ] ; then + ###### Mandatory step + # ask if gorgone is already installed + echo -e "\n$line" + echo -e "\t$(gettext "Check mandatory gorgone service status")" + echo -e "$line" + + yes_no_default "$(gettext "Is the Gorgone module already installed?")" + if [ "$?" -ne 0 ] ; then + echo_failure "\n$(gettext "Gorgone is required.\nPlease install it before launching this script")" "$fail" + echo -e "\n\t$(gettext "Please read the documentation to manage the Gorgone daemon installation")" + echo -e "\t$(gettext "Available on github") : https://github.com/centreon/centreon-gorgone" + echo -e "\t$(gettext "or on the centreon documentation") : https://documentation.centreon.com/\n" + exit 1 + fi fi # Script stop if one binary wasn't found diff --git a/lang/es_ES.UTF-8/LC_MESSAGES/messages.po b/lang/es_ES.UTF-8/LC_MESSAGES/messages.po index c2938b35436..fa5c6d848dc 100644 --- a/lang/es_ES.UTF-8/LC_MESSAGES/messages.po +++ b/lang/es_ES.UTF-8/LC_MESSAGES/messages.po @@ -13125,11 +13125,11 @@ msgstr "cubo de basura" #~ msgid "No downtime scheduled for services" #~ msgstr "No hay tiempo de inactividad planificado para los servicios" -#~ msgid "Host category" -#~ msgstr "Categoría de anfitriones" + msgid "Host category" + msgstr "Categoría de anfitriones" -#~ msgid "Service category" -#~ msgstr "Categorias de servicio" + msgid "Service category" + msgstr "Categoria de servicio" #~ msgid "Inclusion" #~ msgstr "Inclusión" @@ -15162,3 +15162,7 @@ msgstr "" # msgid "Warning, maximum size exceeded for input '%s' (max: %d), it will be truncated upon saving" # msgstr "" + +# msgid "Parent alias" +# msgstr "" + diff --git a/lang/fr_FR.UTF-8/LC_MESSAGES/messages.po b/lang/fr_FR.UTF-8/LC_MESSAGES/messages.po index ae774523348..7155128e4d9 100644 --- a/lang/fr_FR.UTF-8/LC_MESSAGES/messages.po +++ b/lang/fr_FR.UTF-8/LC_MESSAGES/messages.po @@ -4408,7 +4408,7 @@ msgstr "Sauvegarde du mot de passe LDAP" #: centreon-web/www/include/Administration/parameters/ldap/form.php:78 msgid "Auto import users" -msgstr "Import automatiques des utilisateurs" +msgstr "Import automatique des utilisateurs" #: centreon-web/www/include/Administration/parameters/ldap/form.php:96 msgid "Use service DNS" @@ -13649,11 +13649,11 @@ msgstr "Configurer une plage de maintenance pour les services des hôtes" #~ msgid "No downtime scheduled for services" #~ msgstr "Aucune plage de maintenance planifiée pour les services" -#~ msgid "Host category" -#~ msgstr "Catégorie d'hôtes" + msgid "Host category" + msgstr "Catégorie d'hôtes" -#~ msgid "Service category" -#~ msgstr "Catégories de service" + msgid "Service category" + msgstr "Catégorie de service" #~ msgid "Inclusion" #~ msgstr "Inclusion" diff --git a/lang/pt_BR.UTF-8/LC_MESSAGES/messages.po b/lang/pt_BR.UTF-8/LC_MESSAGES/messages.po index 9e76be908f9..d08e0b4d30f 100644 --- a/lang/pt_BR.UTF-8/LC_MESSAGES/messages.po +++ b/lang/pt_BR.UTF-8/LC_MESSAGES/messages.po @@ -11796,7 +11796,7 @@ msgstr "Escala" #: centreon-web/www/install/smarty_translate.php:414 msgid "Service category" -msgstr "Categoria do Serviço" +msgstr "Categoria de Serviço" #: centreon-web/www/install/smarty_translate.php:438 msgid "Service Scheduling Options" @@ -15613,3 +15613,7 @@ msgstr "" # msgid "Warning, maximum size exceeded for input '%s' (max: %d), it will be truncated upon saving" # msgstr "" +# msgid "Parent alias" +# msgstr "" + + diff --git a/lang/pt_PT.UTF-8/LC_MESSAGES/messages.po b/lang/pt_PT.UTF-8/LC_MESSAGES/messages.po index 664500c9dc4..15a5fe9cd61 100644 --- a/lang/pt_PT.UTF-8/LC_MESSAGES/messages.po +++ b/lang/pt_PT.UTF-8/LC_MESSAGES/messages.po @@ -11781,7 +11781,7 @@ msgstr "Grupo de traps SNMP" #: centreon-web/www/install/smarty_translate.php:387 msgid "Host category" -msgstr "Categoria do Host" +msgstr "Categoria de Host" #: centreon-web/www/install/smarty_translate.php:393 msgid "Informations" @@ -15601,3 +15601,7 @@ msgstr "" # msgid "Warning, maximum size exceeded for input '%s' (max: %d), it will be truncated upon saving" # msgstr "" + +# msgid "Parent alias +# msgstr "" + diff --git a/src/Centreon/Application/ApiPlatform.php b/src/Centreon/Application/ApiPlatform.php index 4b80b3cac34..89f4d02e48a 100644 --- a/src/Centreon/Application/ApiPlatform.php +++ b/src/Centreon/Application/ApiPlatform.php @@ -28,16 +28,16 @@ class ApiPlatform { /** - * @var float + * @var string */ private $version; /** * Get the API version * - * @return float + * @return string */ - public function getVersion(): float + public function getVersion(): string { return $this->version; } @@ -45,10 +45,10 @@ public function getVersion(): float /** * Set the API version * - * @param float $version + * @param string $version * @return $this */ - public function setVersion(float $version): self + public function setVersion(string $version): self { $this->version = $version; return $this; diff --git a/src/Centreon/Domain/Contact/Contact.php b/src/Centreon/Domain/Contact/Contact.php index a1d543e49a8..6afcb4bb164 100644 --- a/src/Centreon/Domain/Contact/Contact.php +++ b/src/Centreon/Domain/Contact/Contact.php @@ -162,6 +162,11 @@ class Contact implements UserInterface, ContactInterface */ private $timezone; + /** + * @var int + */ + private int $timezoneId; + /** * @var string|null $locale locale of the user */ @@ -189,6 +194,25 @@ class Contact implements UserInterface, ContactInterface */ private $theme; + /** + * @param int $timezoneId + * @return self + */ + public function setTimezoneId(int $timezoneId): self + { + $this->timezoneId = $timezoneId; + + return $this; + } + + /** + * @return int + */ + public function getTimezoneId(): int + { + return $this->timezoneId; + } + /** * @return int */ diff --git a/src/Centreon/Domain/Contact/Interfaces/ContactInterface.php b/src/Centreon/Domain/Contact/Interfaces/ContactInterface.php index e56d672413e..525b6f3c2cc 100644 --- a/src/Centreon/Domain/Contact/Interfaces/ContactInterface.php +++ b/src/Centreon/Domain/Contact/Interfaces/ContactInterface.php @@ -26,6 +26,11 @@ interface ContactInterface { + /** + * @return int Returns the timezone id + */ + public function getTimezoneId(): int; + /** * @return int Returns the contact id */ diff --git a/src/Centreon/Domain/PlatformInformation/Model/PlatformInformation.php b/src/Centreon/Domain/PlatformInformation/Model/PlatformInformation.php index ef5ac50725e..fa363f39863 100644 --- a/src/Centreon/Domain/PlatformInformation/Model/PlatformInformation.php +++ b/src/Centreon/Domain/PlatformInformation/Model/PlatformInformation.php @@ -40,6 +40,11 @@ class PlatformInformation */ private $platformName; + /** + * @var string server address + */ + private string $address = '127.0.0.1'; + /** * @var string|null central's address */ @@ -126,6 +131,25 @@ public function setPlatformName(?string $name): self return $this; } + /** + * @return string + */ + public function getAddress(): string + { + return $this->address; + } + + /** + * @param string $address + * @return $this + */ + public function setAddress(string $address): self + { + $this->address = $address; + + return $this; + } + /** * @return string|null */ diff --git a/src/Centreon/Domain/PlatformInformation/Model/PlatformInformationFactory.php b/src/Centreon/Domain/PlatformInformation/Model/PlatformInformationFactory.php index 226a63b5521..ab11808e97d 100644 --- a/src/Centreon/Domain/PlatformInformation/Model/PlatformInformationFactory.php +++ b/src/Centreon/Domain/PlatformInformation/Model/PlatformInformationFactory.php @@ -54,6 +54,9 @@ public function createRemoteInformation(array $information): PlatformInformation $platformInformation = new PlatformInformation($isRemote); foreach ($information as $key => $value) { switch ($key) { + case 'address': + $platformInformation->setAddress($value); + break; case 'centralServerAddress': $platformInformation->setCentralServerAddress($value); break; diff --git a/src/Centreon/Domain/PlatformInformation/UseCase/V20/UpdatePartiallyPlatformInformation.php b/src/Centreon/Domain/PlatformInformation/UseCase/V20/UpdatePartiallyPlatformInformation.php index 20bcb7e0082..408a6bf88bf 100644 --- a/src/Centreon/Domain/PlatformInformation/UseCase/V20/UpdatePartiallyPlatformInformation.php +++ b/src/Centreon/Domain/PlatformInformation/UseCase/V20/UpdatePartiallyPlatformInformation.php @@ -241,6 +241,7 @@ private function convertCentralToRemote( $platformInformationToUpdate, $currentPlatformInformation ); + $this->remoteServerService->convertCentralToRemote( $platformInformationToUpdate ); diff --git a/src/Centreon/Domain/PlatformTopology/Model/PlatformPending.php b/src/Centreon/Domain/PlatformTopology/Model/PlatformPending.php index 0e217dd3a17..be2675480c7 100644 --- a/src/Centreon/Domain/PlatformTopology/Model/PlatformPending.php +++ b/src/Centreon/Domain/PlatformTopology/Model/PlatformPending.php @@ -196,13 +196,11 @@ private function checkIpAddress(?string $address): ?string { // Check for valid IPv4 or IPv6 IP // or not sent address (in the case of Central's "parent_address") - if (null === $address || false !== filter_var($address, FILTER_VALIDATE_IP)) { - return $address; - } - - // check for DNS to be resolved - $addressResolved = filter_var(gethostbyname($address), FILTER_VALIDATE_IP); - if (false === $addressResolved) { + if ( + $address !== null + && ! filter_var($address, FILTER_VALIDATE_IP) + && ! filter_var($address, FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME) + ) { throw new \InvalidArgumentException( sprintf( _("The address '%s' of '%s' is not valid or not resolvable"), @@ -212,7 +210,7 @@ private function checkIpAddress(?string $address): ?string ); } - return $addressResolved; + return $address; } /** diff --git a/src/Centreon/Domain/PlatformTopology/Model/PlatformRegistered.php b/src/Centreon/Domain/PlatformTopology/Model/PlatformRegistered.php index ba3d275aa17..5eac82c5d2a 100644 --- a/src/Centreon/Domain/PlatformTopology/Model/PlatformRegistered.php +++ b/src/Centreon/Domain/PlatformTopology/Model/PlatformRegistered.php @@ -194,14 +194,11 @@ public function setHostname(?string $hostname): PlatformInterface */ private function checkIpAddress(?string $address): ?string { - // Check for valid IPv4 or IPv6 IP - // or not sent address (in the case of Central's "parent_address") - if (null === $address || false !== filter_var($address, FILTER_VALIDATE_IP)) { - return $address; - } - - // check for DNS to be resolved - if (false === filter_var(gethostbyname($address), FILTER_VALIDATE_IP)) { + if ( + $address !== null + && ! filter_var($address, FILTER_VALIDATE_IP) + && ! filter_var($address, FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME) + ) { throw new \InvalidArgumentException( sprintf( _("The address '%s' of '%s' is not valid or not resolvable"), diff --git a/src/Centreon/Domain/PlatformTopology/PlatformTopologyService.php b/src/Centreon/Domain/PlatformTopology/PlatformTopologyService.php index 5df7e808762..8a6978789b9 100644 --- a/src/Centreon/Domain/PlatformTopology/PlatformTopologyService.php +++ b/src/Centreon/Domain/PlatformTopology/PlatformTopologyService.php @@ -482,9 +482,14 @@ private function findParentPlatform(PlatformInterface $platform): ?PlatformInter return null; } - $registeredParentInTopology = $this->platformTopologyRepository->findPlatformByAddress( - $platform->getParentAddress() - ); + if ($platform->getType() === PlatformPending::TYPE_REMOTE) { + $registeredParentInTopology = $this->platformTopologyRepository->findTopLevelPlatform(); + } else { + $registeredParentInTopology = $this->platformTopologyRepository->findPlatformByAddress( + $platform->getParentAddress() + ); + } + if (null === $registeredParentInTopology) { throw new EntityNotFoundException( sprintf( @@ -553,6 +558,7 @@ public function getPlatformTopology(): array ); if (null !== $platformParent) { $platform->setParentAddress($platformParent->getAddress()); + $platform->setParentId($platformParent->getId()); } } @@ -614,7 +620,7 @@ public function deletePlatformAndReallocateChildren(int $serverId): void */ if ($deletedPlatform->getServerId() !== null) { if ($deletedPlatform->getType() === PlatformPending::TYPE_REMOTE) { - $this->remoteServerRepository->deleteRemoteServerByAddress($deletedPlatform->getAddress()); + $this->remoteServerRepository->deleteRemoteServerByServerId($deletedPlatform->getServerId()); $this->remoteServerRepository->deleteAdditionalRemoteServer($deletedPlatform->getServerId()); } diff --git a/src/Centreon/Domain/RemoteServer/Interfaces/RemoteServerRepositoryInterface.php b/src/Centreon/Domain/RemoteServer/Interfaces/RemoteServerRepositoryInterface.php index d87e6168bce..b2680409c7b 100644 --- a/src/Centreon/Domain/RemoteServer/Interfaces/RemoteServerRepositoryInterface.php +++ b/src/Centreon/Domain/RemoteServer/Interfaces/RemoteServerRepositoryInterface.php @@ -28,9 +28,9 @@ interface RemoteServerRepositoryInterface /** * Delete a Remote Server. * - * @param string $address + * @param int $serverId */ - public function deleteRemoteServerByAddress(string $address): void; + public function deleteRemoteServerByServerId(int $serverId): void; /** * Delete an Additional Remote Server, for pollers linked to multiple Remote Servers. diff --git a/src/Centreon/Domain/RemoteServer/RemoteServerService.php b/src/Centreon/Domain/RemoteServer/RemoteServerService.php index 105204a26f4..4e905d00d0c 100644 --- a/src/Centreon/Domain/RemoteServer/RemoteServerService.php +++ b/src/Centreon/Domain/RemoteServer/RemoteServerService.php @@ -137,16 +137,20 @@ public function convertCentralToRemote(PlatformInformation $platformInformation) if ($platformInformation->getPlatformName() !== null) { $topLevelPlatform->setName($platformInformation->getPlatformName()); } + $topLevelPlatform->setAddress($platformInformation->getAddress()); + /** * Find any children platform and forward them to Central Parent. */ $platforms = $this->platformTopologyRepository->findChildrenPlatformsByParentId( $topLevelPlatform->getId() ); + /** * Insert the Top Level Platform at the beginning of array, as it need to be registered first. */ array_unshift($platforms, $topLevelPlatform); + /** * Register the platforms on the Parent Central */ diff --git a/src/Centreon/Infrastructure/Contact/ContactRepositoryRDB.php b/src/Centreon/Infrastructure/Contact/ContactRepositoryRDB.php index 0cc69d33dda..80a453402d8 100644 --- a/src/Centreon/Infrastructure/Contact/ContactRepositoryRDB.php +++ b/src/Centreon/Infrastructure/Contact/ContactRepositoryRDB.php @@ -421,6 +421,7 @@ private function createContact(array $contact): Contact ->setAccessToApiRealTime($contact['reach_api_rt'] === '1') ->setAccessToApiConfiguration($contact['reach_api'] === '1') ->setTimezone(new \DateTimeZone($contactTimezoneName)) + ->setTimezoneId((int) $contact['contact_location']) ->setLocale($contactLocale) ->setDefaultPage($page) ->setUseDeprecatedPages($contact['show_deprecated_pages'] === '1') diff --git a/src/Centreon/Infrastructure/RemoteServer/RemoteServerRepositoryRDB.php b/src/Centreon/Infrastructure/RemoteServer/RemoteServerRepositoryRDB.php index f6df3a3b396..70693a9c58b 100644 --- a/src/Centreon/Infrastructure/RemoteServer/RemoteServerRepositoryRDB.php +++ b/src/Centreon/Infrastructure/RemoteServer/RemoteServerRepositoryRDB.php @@ -41,10 +41,12 @@ public function __construct(DatabaseConnection $db) /** * @inheritDoc */ - public function deleteRemoteServerByAddress(string $address): void + public function deleteRemoteServerByServerId(int $serverId): void { - $statement = $this->db->prepare($this->translateDbName("DELETE FROM remote_servers WHERE ip = :address")); - $statement->bindValue(':address', $address, \PDO::PARAM_STR); + $statement = $this->db->prepare( + $this->translateDbName("DELETE FROM remote_servers WHERE server_id = :server_id") + ); + $statement->bindValue(':server_id', $serverId, \PDO::PARAM_INT); $statement->execute(); } diff --git a/src/CentreonRemote/Application/Webservice/CentreonConfigurationRemote.php b/src/CentreonRemote/Application/Webservice/CentreonConfigurationRemote.php old mode 100755 new mode 100644 index 1ff417403b2..c08a3bac795 --- a/src/CentreonRemote/Application/Webservice/CentreonConfigurationRemote.php +++ b/src/CentreonRemote/Application/Webservice/CentreonConfigurationRemote.php @@ -211,7 +211,7 @@ public function getList(): array 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.ip = ns.ns_ip_address ' . + 'JOIN remote_servers as rs ON rs.server_id = ns.id ' . 'WHERE rs.is_connected = 1'; $statement = $this->pearDB->query($query); @@ -469,6 +469,7 @@ public function postLinkCentreonRemoteServer(): array // add server to the list of remote servers in database (table remote_servers) $this->addServerToListOfRemotes( + (int) $serverId, $serverIP, $centreonPath, $httpMethod, @@ -532,6 +533,7 @@ public function authorize($action, $user, $isInternal = false): bool /** * 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) @@ -540,6 +542,7 @@ public function authorize($action, $user, $isInternal = false): bool * @param bool $noProxy to do not use configured proxy */ private function addServerToListOfRemotes( + int $serverId, string $serverIP, string $centreonPath, string $httpMethod, @@ -547,34 +550,46 @@ private function addServerToListOfRemotes( bool $noCheckCertificate, bool $noProxy ): void { - $dbAdapter = $this->getDi()[\Centreon\ServiceProvider::CENTREON_DB_MANAGER]->getAdapter('configuration_db'); - $date = date('Y-m-d H:i:s'); - - $sql = 'SELECT * FROM `remote_servers` WHERE `ip` = ?'; - $dbAdapter->query($sql, [$serverIP]); - $hasIpInTable = (bool)$dbAdapter->count(); + $currentDate = date('Y-m-d H:i:s'); - if ($hasIpInTable) { - $sql = 'UPDATE `remote_servers` SET - `is_connected` = ?, `connected_at` = ?, `centreon_path` = ?, - `no_check_certificate` = ?, `no_proxy` = ? - WHERE `ip` = ?'; - $data = ['1', $date, $centreonPath, ($noCheckCertificate ?: 0), ($noProxy ?: 0), $serverIP]; - $dbAdapter->query($sql, $data); + $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 { - $data = [ - 'ip' => $serverIP, - 'version' => '', - 'is_connected' => '1', - 'created_at' => $date, - 'connected_at' => $date, - 'centreon_path' => $centreonPath, - 'http_method' => $httpMethod, - 'http_port' => $httpPort ?: null, - 'no_check_certificate' => $noCheckCertificate ?: 0, - 'no_proxy' => $noProxy ?: 0 - ]; - $dbAdapter->insert('remote_servers', $data); + $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(); } } diff --git a/src/CentreonRemote/Application/Webservice/CentreonRemoteServer.php b/src/CentreonRemote/Application/Webservice/CentreonRemoteServer.php index 8bfd90de78f..b5f4309ec4c 100644 --- a/src/CentreonRemote/Application/Webservice/CentreonRemoteServer.php +++ b/src/CentreonRemote/Application/Webservice/CentreonRemoteServer.php @@ -112,7 +112,7 @@ public function postAddToWaitList(): string if ( !isset($_POST['version']) || !$_POST['version'] - || empty($version = filter_var($_POST['version'], FILTER_SANITIZE_STRING)) + || empty($version = filter_var($_POST['version'], FILTER_SANITIZE_FULL_SPECIAL_CHARS)) ) { throw new \RestBadRequestException('Please send \'version\' in the request.'); } @@ -138,20 +138,21 @@ public function postAddToWaitList(): string throw new \RestConflictException('Address already in wait list.'); } - $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, '{$createdAt}', - :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(':http_method', $httpScheme, \PDO::PARAM_STR); - $insert->bindValue(':http_port', $httpPort, \PDO::PARAM_INT); - $insert->bindValue(':no_check_certificate', $noCheckCertificate, \PDO::PARAM_STR); 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.'); diff --git a/src/CentreonRemote/Domain/Service/ConfigurationWizard/LinkedPollerConfigurationService.php b/src/CentreonRemote/Domain/Service/ConfigurationWizard/LinkedPollerConfigurationService.php index 47b581aebb8..1ec14f7259e 100644 --- a/src/CentreonRemote/Domain/Service/ConfigurationWizard/LinkedPollerConfigurationService.php +++ b/src/CentreonRemote/Domain/Service/ConfigurationWizard/LinkedPollerConfigurationService.php @@ -354,16 +354,26 @@ private function triggerExportForOldRemotes(array $pollerIDs): void $alreadyExportedRemotes[] = $remoteID; // Get all linked pollers of the remote - $queryPollersOfRemote = "SELECT id FROM nagios_server WHERE remote_id = {$remoteID}"; - $linkedStatement = $this->db->query($queryPollersOfRemote); + $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->query("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.ip = ns.ns_ip_address - WHERE ns.id = {$remoteID}"); + $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 diff --git a/src/Core/Infrastructure/RealTime/Repository/Host/DbHostFactory.php b/src/Core/Infrastructure/RealTime/Repository/Host/DbHostFactory.php index ee62ab4f976..26f8338417d 100644 --- a/src/Core/Infrastructure/RealTime/Repository/Host/DbHostFactory.php +++ b/src/Core/Infrastructure/RealTime/Repository/Host/DbHostFactory.php @@ -65,7 +65,8 @@ public static function createFromRecord(array $data): Host ->setLastCheck(self::createDateTimeFromTimestamp((int) $data['last_check'])) ->setLastTimeUp(self::createDateTimeFromTimestamp((int) $data['last_time_up'])) ->setMaxCheckAttempts(self::getIntOrNull($data['max_check_attempts'])) - ->setCheckAttempts(self::getIntOrNull($data['check_attempt'])); + ->setCheckAttempts(self::getIntOrNull($data['check_attempt'])) + ->setAlias($data['alias']); $nextCheck = self::createDateTimeFromTimestamp( (int) $data['active_checks'] === 1 ? (int) $data['next_check'] : null diff --git a/src/Core/Security/Application/UseCase/LoginOpenIdSession/LoginOpenIdSession.php b/src/Core/Security/Application/UseCase/LoginOpenIdSession/LoginOpenIdSession.php index f447fdc06e2..8a70c1513b9 100644 --- a/src/Core/Security/Application/UseCase/LoginOpenIdSession/LoginOpenIdSession.php +++ b/src/Core/Security/Application/UseCase/LoginOpenIdSession/LoginOpenIdSession.php @@ -106,7 +106,7 @@ public function __invoke(LoginOpenIdSessionRequest $request, LoginOpenIdSessionP 'contact_autologin_key' => '', 'contact_admin' => $user->isAdmin() ? '1' : '0', 'default_page' => $user->getDefaultPage(), - 'contact_location' => $user->getLocale(), + 'contact_location' => (string) $user->getTimezoneId(), 'show_deprecated_pages' => $user->isUsingDeprecatedPages(), 'reach_api' => $user->hasAccessToApiConfiguration() ? 1 : 0, 'reach_api_rt' => $user->hasAccessToApiRealTime() ? 1 : 0 diff --git a/src/EventSubscriber/CentreonEventSubscriber.php b/src/EventSubscriber/CentreonEventSubscriber.php index 80358f8dfa5..97d4808f1bf 100644 --- a/src/EventSubscriber/CentreonEventSubscriber.php +++ b/src/EventSubscriber/CentreonEventSubscriber.php @@ -319,11 +319,11 @@ public function defineApiVersionInAttributes(RequestEvent $event): void * @todo We need to use an other name because after routing, * its value is overwritten by the value of the 'version' property from uri */ - $event->getRequest()->attributes->set('version', (float) $requestApiVersion); + $event->getRequest()->attributes->set('version', $requestApiVersion); // Used for controllers - $event->getRequest()->attributes->set('version_number', (float) $requestApiVersion); - $this->apiPlatform->setVersion((float) $requestApiVersion); + $event->getRequest()->attributes->set('version_number', $requestApiVersion); + $this->apiPlatform->setVersion($requestApiVersion); } } diff --git a/tests/api/features/PlatformTopology.feature b/tests/api/features/PlatformTopology.feature index 0e0ed386cf1..64f2a273831 100644 --- a/tests/api/features/PlatformTopology.feature +++ b/tests/api/features/PlatformTopology.feature @@ -84,14 +84,14 @@ Feature: { "name": "inconsistent_address", "type": "poller", - "address": "666.", + "address": "666_", "parent_address": "127.0.0.1" } """ Then the response code should be "400" And the response should be equal to: """ - {"message":"The address '666.' of 'inconsistent_address' is not valid or not resolvable"} + {"message":"The address '666_' of 'inconsistent_address' is not valid or not resolvable"} """ # Register a platform using name with illegal characters / Should fail and an error should be returned @@ -150,14 +150,14 @@ Feature: "name": "inconsistent_parent_address", "type": "poller", "address": "6.6.6.1", - "parent_address": "666.", + "parent_address": "666_", "hostname": "poller.test.localhost.localdomain" } """ Then the response code should be "400" And the response should be equal to: """ - {"message":"The address '666.' of 'inconsistent_parent_address' is not valid or not resolvable"} + {"message":"The address '666_' of 'inconsistent_parent_address' is not valid or not resolvable"} """ # Register a poller linked to the Central. diff --git a/tmpl/vardistrib/defaults b/tmpl/vardistrib/defaults index 78cbce52a72..f72c2548b62 100644 --- a/tmpl/vardistrib/defaults +++ b/tmpl/vardistrib/defaults @@ -25,6 +25,10 @@ MONITORINGENGINE_LOG="/var/log/centreon-engine" MONITORINGENGINE_USER="centreon-engine" BROKER_ETC="/etc/centreon-broker" BROKER_USER="centreon-broker" +GORGONE_VARLIB="/var/lib/centreon-gorgone" +GORGONE_CONFIG="/etc/centreon-gorgone" +GORGONE_USER="centreon-gorgone" +GORGONE_GROUP="centreon-gorgone" SUDO_FILE="/etc/sudoers.d/centreon" SNMP_ETC="/etc/snmp" PEAR_PATH="/usr/share/pear" diff --git a/www/api/class/centreon_clapi.class.php b/www/api/class/centreon_clapi.class.php index 9a3759420bd..c29ca01bc85 100644 --- a/www/api/class/centreon_clapi.class.php +++ b/www/api/class/centreon_clapi.class.php @@ -230,7 +230,7 @@ public function authorize($action, $user, $isInternal = false) { if ( parent::authorize($action, $user, $isInternal) - || ($user && $user->hasAccessRestApiConfiguration()) + || ($user && $user->is_admin()) ) { return true; } diff --git a/www/api/class/centreon_configuration_poller.class.php b/www/api/class/centreon_configuration_poller.class.php index d2b33623d06..f131d1eb186 100644 --- a/www/api/class/centreon_configuration_poller.class.php +++ b/www/api/class/centreon_configuration_poller.class.php @@ -81,14 +81,14 @@ public function getList() if (isset($this->arguments['t'])) { if ($this->arguments['t'] == 'remote') { - $queryPoller .= "JOIN remote_servers rs ON (ns.ns_ip_address = rs.ip) "; + $queryPoller .= "JOIN remote_servers rs ON ns.id = rs.server_id "; // Exclude selected master Remote Server if (isset($this->arguments['e'])) { $queryPoller .= 'WHERE ns.id <> :masterId '; $queryValues['masterId'] = (int)$this->arguments['e']; } } elseif ($this->arguments['t'] == 'poller') { - $queryPoller .= "LEFT JOIN remote_servers rs ON (ns.ns_ip_address = rs.ip) " + $queryPoller .= "LEFT JOIN remote_servers rs ON ns.id = rs.server_id " . "WHERE rs.ip IS NULL " . "AND ns.localhost = '0' "; } elseif ($this->arguments['t'] == 'central') { diff --git a/www/class/centreon-clapi/centreon.Config.Poller.class.php b/www/class/centreon-clapi/centreon.Config.Poller.class.php index cf5e2576828..216e29b9eef 100644 --- a/www/class/centreon-clapi/centreon.Config.Poller.class.php +++ b/www/class/centreon-clapi/centreon.Config.Poller.class.php @@ -192,11 +192,13 @@ public function pollerReload($variables) $poller_id = $this->getPollerId($variables); $this->testPollerId($poller_id); - $result = $this->DB->query( - "SELECT * FROM `nagios_server` WHERE `id` = '" . $this->DB->escape($poller_id) . "' LIMIT 1" + $statement = $this->DB->prepare( + "SELECT * FROM `nagios_server` WHERE `id` = :poller_id LIMIT 1" ); - $host = $result->fetch(); - $result->closeCursor(); + $statement->bindValue(':poller_id', (int) $poller_id, \PDO::PARAM_INT); + $statement->execute(); + $host = $statement->fetch(\PDO::FETCH_ASSOC); + $statement->closeCursor(); $this->commandGenerator = $this->container->get(EngineCommandGenerator::class); $reloadCommand = $this->commandGenerator->getEngineCommand('RELOAD'); @@ -208,10 +210,12 @@ public function pollerReload($variables) exec("echo 'RELOADBROKER:" . $host["id"] . "' >> " . $this->centcore_pipe, $stdout, $return_code); $msg_restart = _("OK: A reload signal has been sent to '" . $host["name"] . "'"); print $msg_restart . "\n"; - $this->DB->query( - "UPDATE `nagios_server` SET `last_restart` = '" . time() - . "' WHERE `id` = '" . $this->DB->escape($poller_id) . "' LIMIT 1" + $statement = $this->DB->prepare( + "UPDATE `nagios_server` SET `last_restart` = :last_restart WHERE `id` = :poller_id LIMIT 1" ); + $statement->bindValue(':last_restart', time(), \PDO::PARAM_INT); + $statement->bindValue(':poller_id', (int) $poller_id, \PDO::PARAM_INT); + $statement->execute(); return $return_code; } @@ -266,11 +270,13 @@ public function pollerRestart($variables) $this->testPollerId($variables); $poller_id = $this->getPollerId($variables); - $result = $this->DB->query( - "SELECT * FROM `nagios_server` WHERE `id` = '" . $this->DB->escape($poller_id) . "' LIMIT 1" + $statement = $this->DB->prepare( + "SELECT * FROM `nagios_server` WHERE `id` = :poller_id LIMIT 1" ); - $host = $result->fetch(); - $result->closeCursor(); + $statement->bindValue(':poller_id', (int) $poller_id, \PDO::PARAM_INT); + $statement->execute(); + $host = $statement->fetch(\PDO::FETCH_ASSOC); + $statement->closeCursor(); $this->commandGenerator = $this->container->get(EngineCommandGenerator::class); $restartCommand = $this->commandGenerator->getEngineCommand('RESTART'); @@ -282,10 +288,12 @@ public function pollerRestart($variables) exec("echo 'RELOADBROKER:" . $host["id"] . "' >> " . $this->centcore_pipe, $stdout, $return_code); $msg_restart = _("OK: A restart signal has been sent to '" . $host["name"] . "'"); print $msg_restart . "\n"; - $this->DB->query( - "UPDATE `nagios_server` SET `last_restart` = '" . time() - . "' WHERE `id` = '" . $this->DB->escape($poller_id) . "' LIMIT 1" + $statement = $this->DB->prepare( + "UPDATE `nagios_server` SET `last_restart` = :last_restart WHERE `id` = :poller_id LIMIT 1" ); + $statement->bindValue(':last_restart', time(), \PDO::PARAM_INT); + $statement->bindValue(':poller_id', (int) $poller_id, \PDO::PARAM_INT); + $statement->execute(); return $return_code; } diff --git a/www/class/centreon-partition/partEngine.class.php b/www/class/centreon-partition/partEngine.class.php index bf488a95e58..a7bd5b3c788 100644 --- a/www/class/centreon-partition/partEngine.class.php +++ b/www/class/centreon-partition/partEngine.class.php @@ -613,7 +613,11 @@ public function isCompatible($db) } $dbResult->closeCursor(); - if (stristr($dbType, "MySQL") + if ( + ( + stristr($dbType, "MySQL") + || stristr($dbType, "Source distribution") + ) && (version_compare($dbVersion, '8.0.0', '>=')) ) { unset($config, $row); diff --git a/www/class/centreonConnector.class.php b/www/class/centreonConnector.class.php index fc2756ed98b..69963cf3922 100644 --- a/www/class/centreonConnector.class.php +++ b/www/class/centreonConnector.class.php @@ -35,40 +35,40 @@ /* * Class that contains various methods for managing connectors - * + * * Usage example: - * + * * create(array( * // 'name' => 'jackyse', * // 'description' => 'some jacky', * // 'command_line' => 'ls -la', * // 'enabled' => true * // ), true); - * + * * //$connector->update(10, array( * // 'name' => 'soapy', * // 'description' => 'Lorem ipsum', * // 'enabled' => true, * // 'command_line' => 'ls -laph --color' * //)); - * + * * //$connector->getList(false, 20, false); - * + * * //$connector->delete(10); - * + * * //$connector->read(7); - * + * * //$connector->copy(1, 5, true); - * + * * //$connector->count(false); - * + * * //$connector->isNameAvailable('norExists'); */ @@ -165,11 +165,13 @@ public function create(array $connector, $returnId = false) throw new RuntimeException('Field id for connector not selected in query or connector not inserted'); } else { if (isset($connector["command_id"])) { + $statement = $this->dbConnection->prepare("UPDATE `command` " . + "SET connector_id = :conId WHERE `command_id` = :value"); foreach ($connector["command_id"] as $key => $value) { try { - $query = "UPDATE `command` SET connector_id = '" . $lastId['id'] . "' " . - "WHERE `command_id` = '" . $value . "'"; - $this->dbConnection->query($query); + $statement->bindValue(':conId', (int) $lastId['id'], \PDO::PARAM_INT); + $statement->bindValue(':value', (int) $value, \PDO::PARAM_INT); + $statement->execute(); } catch (\PDOException $e) { throw new RuntimeException('Cannot update connector'); } diff --git a/www/class/centreonGraph.class.php b/www/class/centreonGraph.class.php index 4ae3ef297d8..6eadab1b33e 100644 --- a/www/class/centreonGraph.class.php +++ b/www/class/centreonGraph.class.php @@ -1133,13 +1133,15 @@ public function setTemplate($template_id = null) } else { $this->templateId = htmlentities($_GET["template_id"], ENT_QUOTES, "UTF-8"); } - $DBRESULT = $this->DB->query( + $statement = $this->DB->prepare( "SELECT * FROM giv_graphs_template - WHERE graph_id = '" . $this->templateId . "' LIMIT 1" + WHERE graph_id = :graph_id LIMIT 1" ); - $this->templateInformations = $DBRESULT->fetch(); - $DBRESULT->closeCursor(); + $statement->bindValue(':graph_id', (int) $this->templateId, \PDO::PARAM_INT); + $statement->execute(); + $this->templateInformations = $statement->fetch(\PDO::FETCH_ASSOC); + $statement->closeCursor(); } /** diff --git a/www/class/centreonMeta.class.php b/www/class/centreonMeta.class.php index ed279a68e88..3290127b337 100644 --- a/www/class/centreonMeta.class.php +++ b/www/class/centreonMeta.class.php @@ -305,8 +305,11 @@ public function insertVirtualService($metaId, $metaName) $row = $res->fetchRow(); $serviceId = $row['service_id']; if ($row['display_name'] !== $metaName) { - $query = 'UPDATE service SET display_name = "' . $metaName . '" WHERE service_id = ' . $serviceId; - $this->db->query($query); + $query = 'UPDATE service SET display_name = :display_name WHERE service_id = :service_id'; + $statement = $this->db->prepare($query); + $statement->bindValue(':display_name', $metaName, \PDO::PARAM_STR); + $statement->bindValue(':service_id', (int) $serviceId, \PDO::PARAM_INT); + $statement->execute(); } } else { $query = 'INSERT INTO service (service_description, display_name, service_register) ' @@ -314,11 +317,15 @@ public function insertVirtualService($metaId, $metaName) . '("' . $composedName . '", "' . $metaName . '", "2")'; $this->db->query($query); $query = 'INSERT INTO host_service_relation(host_host_id, service_service_id) ' - . 'VALUES (' - . $hostId . ',' - . '(SELECT service_id FROM service WHERE service_description = "' . $composedName . '" AND service_register = "2" LIMIT 1)' + . 'VALUES (:host_id,' + . '(SELECT service_id + FROM service + WHERE service_description = :service_description AND service_register = "2" LIMIT 1)' . ')'; - $this->db->query($query); + $statement = $this->db->prepare($query); + $statement->bindValue(':host_id', (int) $hostId, \PDO::PARAM_INT); + $statement->bindValue(':service_description', $composedName, \PDO::PARAM_STR); + $statement->execute(); $res = $this->db->query($queryService); if ($res->rowCount()) { $row = $res->fetchRow(); diff --git a/www/class/centreonStatistics.class.php b/www/class/centreonStatistics.class.php index 9bb2612f959..50a8eb332df 100644 --- a/www/class/centreonStatistics.class.php +++ b/www/class/centreonStatistics.class.php @@ -87,7 +87,7 @@ public function getPlatformInfo() "(SELECT COUNT(sg.sg_id) FROM servicegroup sg " . "WHERE sg.sg_activate = '1') as nb_sg, " . "@nb_remotes:=(SELECT COUNT(ns.id) FROM nagios_server ns, remote_servers rs WHERE ns.ns_activate = '1' " . - "AND rs.ip = ns.ns_ip_address) as nb_remotes , " . + "AND rs.server_id = ns.id) as nb_remotes , " . "((SELECT COUNT(ns2.id) FROM nagios_server ns2 WHERE ns2.ns_activate = '1')-@nb_remotes-1) as nb_pollers," . " '1' as nb_central " . "FROM host h WHERE h.host_activate = '1' AND h.host_register = '1'"; diff --git a/www/class/centreonWidget/Params/Connector/Poller.class.php b/www/class/centreonWidget/Params/Connector/Poller.class.php index fa21c43c247..bb3b2aba393 100644 --- a/www/class/centreonWidget/Params/Connector/Poller.class.php +++ b/www/class/centreonWidget/Params/Connector/Poller.class.php @@ -48,6 +48,7 @@ public function getListValues($paramId) static $tab; if (! isset($tab)) { + $tab = [null => null]; $userACL = new CentreonACL($this->userId); $isContactAdmin = $userACL->admin; $request = 'SELECT SQL_CALC_FOUND_ROWS id, name FROM nagios_server ns'; diff --git a/www/front_src/src/Resources/Details/Header.tsx b/www/front_src/src/Resources/Details/Header.tsx index 2a6c9580112..1ea9d3e243b 100644 --- a/www/front_src/src/Resources/Details/Header.tsx +++ b/www/front_src/src/Resources/Details/Header.tsx @@ -1,5 +1,6 @@ import { useTranslation } from 'react-i18next'; import { hasPath, isNil, not, path, prop } from 'ramda'; +import { useNavigate } from 'react-router-dom'; import { Grid, @@ -13,6 +14,9 @@ import makeStyles from '@mui/styles/makeStyles'; import CopyIcon from '@mui/icons-material/FileCopy'; import SettingsIcon from '@mui/icons-material/Settings'; import { CreateCSSProperties } from '@mui/styles'; +import LogsIcon from '@mui/icons-material/Assignment'; +import ReportIcon from '@mui/icons-material/Assessment'; +import Divider from '@mui/material/Divider'; import { StatusChip, @@ -27,13 +31,14 @@ import { labelConfigure, labelCopyLink, labelLinkCopied, - labelShortcuts, + labelViewLogs, + labelViewReport, labelSomethingWentWrong, } from '../translatedLabels'; import { Parent, ResourceUris } from '../models'; +import { replaceBasename } from '../helpers'; import SelectableResourceName from './tabs/Details/SelectableResourceName'; -import ShortcutsTooltip from './ShortcutsTooltip'; import { DetailsSectionProps } from '.'; @@ -42,15 +47,23 @@ interface MakeStylesProps { } const useStyles = makeStyles((theme) => ({ + containerIcons: { + alignItems: 'center', + display: 'flex', + }, + divider: { + borderColor: theme.palette.text.secondary, + margin: theme.spacing(1, 0.5), + }, header: ({ displaySeverity }): CreateCSSProperties => ({ alignItems: 'center', display: 'grid', gridGap: theme.spacing(2), gridTemplateColumns: `${ displaySeverity ? 'auto' : '' - } auto minmax(0, 1fr) auto auto`, + } auto minmax(0, 1fr) auto`, height: 43, - padding: theme.spacing(0, 1), + padding: theme.spacing(0, 2.5, 0, 1), }), parent: { alignItems: 'center', @@ -58,6 +71,9 @@ const useStyles = makeStyles((theme) => ({ gridGap: theme.spacing(1), gridTemplateColumns: 'auto minmax(0, 1fr)', }, + report: { + marginLeft: theme.spacing(0.5), + }, resourceName: { alignItems: 'center', columnGap: theme.spacing(1), @@ -109,6 +125,7 @@ const Header = ({ details, onSelectParent }: Props): JSX.Element => { displaySeverity: not(isNil(details?.severity_level)), }); const { t } = useTranslation(); + const navigate = useNavigate(); const { showSuccessMessage, showErrorMessage } = useSnackbar(); const copyResourceLink = (): void => { @@ -120,7 +137,20 @@ const Header = ({ details, onSelectParent }: Props): JSX.Element => { } }; - if (details === undefined) { + const navigateToResourceUris = ( + category: keyof ResourceUris, + ): (() => void) => { + return (): void => { + const url = replaceBasename({ + endpoint: prop(category, resourceUris) || '', + newWord: '/', + }); + + navigate(url); + }; + }; + + if (!details) { return ; } @@ -196,19 +226,37 @@ const Header = ({ details, onSelectParent }: Props): JSX.Element => {
)}
- - - - +
+ + + + + + + + + + +
); }; diff --git a/www/front_src/src/Resources/Details/ShortcutsTooltip.tsx b/www/front_src/src/Resources/Details/ShortcutsTooltip.tsx deleted file mode 100644 index 804275ca452..00000000000 --- a/www/front_src/src/Resources/Details/ShortcutsTooltip.tsx +++ /dev/null @@ -1,94 +0,0 @@ -import { isNil, prop } from 'ramda'; -import { useTranslation } from 'react-i18next'; - -import MoreHorizIcon from '@mui/icons-material/MoreHoriz'; -import LogsIcon from '@mui/icons-material/Assignment'; -import ReportIcon from '@mui/icons-material/Assessment'; -import { - Link, - List, - ListItem, - ListItemIcon, - ListItemText, - Tooltip, -} from '@mui/material'; -import makeStyles from '@mui/styles/makeStyles'; - -import { PopoverMenu } from '@centreon/ui'; - -import { ResourceUris } from '../models'; -import { - labelActionNotPermitted, - labelShortcuts, - labelViewLogs, - labelViewReport, -} from '../translatedLabels'; - -interface Props { - resourceUris: ResourceUris; -} - -const useStyles = makeStyles((theme) => ({ - iconContainer: { - minWidth: theme.spacing(4.5), - }, - link: { - display: 'contents', - }, -})); - -const ShortcutsTooltip = ({ resourceUris }: Props): JSX.Element => { - const classes = useStyles(); - const { t } = useTranslation(); - - const shortcuts = [ - { - Icon: LogsIcon, - id: 'Logs', - name: labelViewLogs, - uri: prop('logs', resourceUris), - }, - { - Icon: ReportIcon, - id: 'Reporting', - name: labelViewReport, - uri: prop('reporting', resourceUris), - }, - ]; - - return ( - } - title={t(labelShortcuts)} - > - {(): JSX.Element => ( - - {shortcuts.map(({ Icon, uri, name, id }) => ( - -
- - - - - - {t(name)} - - -
-
- ))} -
- )} -
- ); -}; - -export default ShortcutsTooltip; diff --git a/www/front_src/src/Resources/Details/index.test.tsx b/www/front_src/src/Resources/Details/index.test.tsx index 53543304a89..20ff9c0226f 100644 --- a/www/front_src/src/Resources/Details/index.test.tsx +++ b/www/front_src/src/Resources/Details/index.test.tsx @@ -38,6 +38,7 @@ import { labelCurrentNotificationNumber, labelPerformanceData, label7Days, + labelDetails, label1Day, label31Days, labelCopy, @@ -46,7 +47,6 @@ import { labelConfigure, labelViewLogs, labelViewReport, - labelDetails, labelCopyLink, labelServices, labelFqdn, @@ -64,7 +64,6 @@ import { labelAvg, labelCompactTimePeriod, labelCheck, - labelShortcuts, labelMonitoringServer, labelToday, labelYesterday, @@ -558,6 +557,13 @@ const DetailsWithJotai = (): JSX.Element => ( ); +const mockedNavigate = jest.fn(); + +jest.mock('react-router-dom', () => ({ + ...jest.requireActual('react-router-dom'), + useNavigate: (): jest.Mock => mockedNavigate, +})); + const renderDetails = (): RenderResult => render(); const mockedLocalStorageGetItem = jest.fn(); @@ -980,15 +986,15 @@ describe(Details, () => { ); }); - it('displays the shortcut links when the More icon is clicked', async () => { + it('navigates to logs and report pages when the corresponding icons are clicked', async () => { mockedAxios.get.mockResolvedValueOnce({ data: { ...retrievedDetails, links: { ...retrievedDetails.links, uris: { - logs: '/logs', - reporting: '/reporting', + logs: 'logs', + reporting: 'reporting', }, }, }, @@ -998,26 +1004,22 @@ describe(Details, () => { { name: 'details', value: serviceDetailsUrlParameters }, ]); - const { getByLabelText, getAllByLabelText } = renderDetails(); + const { getByLabelText, getByTestId } = renderDetails(); await waitFor(() => { expect(mockedAxios.get).toHaveBeenCalled(); }); await waitFor(() => - expect(getByLabelText(labelShortcuts)).toBeInTheDocument(), + expect(getByLabelText(labelViewLogs)).toBeInTheDocument(), ); + userEvent.click(getByTestId(labelViewLogs)); - userEvent.click(getByLabelText(labelShortcuts).firstChild as HTMLElement); + expect(mockedNavigate).toHaveBeenCalledWith('/logs'); - expect(getAllByLabelText(labelViewLogs)[0]).toHaveAttribute( - 'href', - '/logs', - ); - expect(getAllByLabelText(labelViewReport)[0]).toHaveAttribute( - 'href', - '/reporting', - ); + userEvent.click(getByTestId(labelViewReport)); + + expect(mockedNavigate).toHaveBeenCalledWith('/reporting'); }); it('sets the details according to the details URL query parameter when given', async () => { diff --git a/www/front_src/src/Resources/Details/tabs/Details/DetailsCard/cards.tsx b/www/front_src/src/Resources/Details/tabs/Details/DetailsCard/cards.tsx index c00a5b0b179..136fefc279f 100644 --- a/www/front_src/src/Resources/Details/tabs/Details/DetailsCard/cards.tsx +++ b/www/front_src/src/Resources/Details/tabs/Details/DetailsCard/cards.tsx @@ -183,6 +183,11 @@ const getDetailCardLines = ({ shouldBeDisplayed: !isNil(details.calculation_type), title: labelCalculationType, }, + { + line: , + shouldBeDisplayed: !isNil(details.calculation_type), + title: labelCalculationType, + }, { isCustomCard: true, line: , diff --git a/www/front_src/src/Resources/Listing/columns/ParentAlias.tsx b/www/front_src/src/Resources/Listing/columns/ParentAlias.tsx new file mode 100644 index 00000000000..c0c34e2c461 --- /dev/null +++ b/www/front_src/src/Resources/Listing/columns/ParentAlias.tsx @@ -0,0 +1,25 @@ +import { Typography } from '@mui/material'; + +import { ComponentColumnProps } from '@centreon/ui'; + +import { useColumnStyles } from '.'; + +const ParentAliasColumn = ({ + row, +}: ComponentColumnProps): JSX.Element | null => { + const classes = useColumnStyles(); + + if (!row.parent) { + return null; + } + + return ( +
+
+ {row.parent.alias} +
+
+ ); +}; + +export default ParentAliasColumn; diff --git a/www/front_src/src/Resources/Listing/columns/index.tsx b/www/front_src/src/Resources/Listing/columns/index.tsx index 48d75a9b400..b415e2918ab 100644 --- a/www/front_src/src/Resources/Listing/columns/index.tsx +++ b/www/front_src/src/Resources/Listing/columns/index.tsx @@ -22,6 +22,7 @@ import { labelNotification, labelCheck, labelSeverity, + labelParentAlias, } from '../../translatedLabels'; import truncate from '../../truncate'; @@ -35,6 +36,7 @@ import ResourceColumn from './Resource'; import ParentResourceColumn from './Parent'; import NotificationColumn from './Notification'; import ChecksColumn from './Checks'; +import ParentAliasColumn from './ParentAlias'; const useStyles = makeStyles((theme) => ({ resourceDetailsCell: { @@ -194,6 +196,16 @@ export const getColumns = ({ actions, t }: ColumnProps): Array => [ sortable: true, type: ColumnType.string, }, + { + Component: ParentAliasColumn, + getRenderComponentOnRowUpdateCondition: T, + id: 'parent_alias', + label: t(labelParentAlias), + rowMemoProps: ['parent'], + sortField: 'parent_alias', + sortable: true, + type: ColumnType.component, + }, { getFormattedString: ({ fqdn }): string => fqdn, id: 'fqdn', diff --git a/www/front_src/src/Resources/helpers.ts b/www/front_src/src/Resources/helpers.ts new file mode 100644 index 00000000000..25a4d1afbd3 --- /dev/null +++ b/www/front_src/src/Resources/helpers.ts @@ -0,0 +1,16 @@ +interface ReplaceBasename { + endpoint: string; + newWord: string; +} + +export const replaceBasename = ({ + newWord, + endpoint, +}: ReplaceBasename): string => { + const basename = + (document + .getElementsByTagName('base')[0] + ?.getAttribute('href') as string) || ''; + + return endpoint.replace(basename, newWord); +}; diff --git a/www/front_src/src/Resources/translatedLabels.ts b/www/front_src/src/Resources/translatedLabels.ts index 2013eab5575..75fbdd3ed02 100644 --- a/www/front_src/src/Resources/translatedLabels.ts +++ b/www/front_src/src/Resources/translatedLabels.ts @@ -249,3 +249,4 @@ export const labelNoContactIsConfiguredForThisResource = 'No contacts are configured for this resource'; export const labelNoContactGroupsIsConfiguredForThisResource = 'No contact groups are configured for this resource'; +export const labelParentAlias = 'Parent alias'; diff --git a/www/include/common/javascript/commandGetArgs/cmdGetExample.php b/www/include/common/javascript/commandGetArgs/cmdGetExample.php index ce4a7d9722f..787f949d34a 100644 --- a/www/include/common/javascript/commandGetArgs/cmdGetExample.php +++ b/www/include/common/javascript/commandGetArgs/cmdGetExample.php @@ -58,13 +58,14 @@ function myDecodeService($arg) exit(); } - $DBRESULT = $pearDB->query( - "SELECT `command_example` FROM `command` WHERE `command_id` = '". $pearDB->escape($_POST["index"]) ."'" + $statement = $pearDB->prepare( + "SELECT `command_example` FROM `command` WHERE `command_id` = :command_id" ); - while ($arg = $DBRESULT->fetchRow()) { + $statement->bindValue(':command_id', (int) $_POST["index"], \PDO::PARAM_INT); + $statement->execute(); + while ($arg = $statement->fetch(\PDO::FETCH_ASSOC)) { echo myDecodeService($arg["command_example"]); } - unset($arg); - unset($DBRESULT); + unset($arg, $statement); $pearDB = null; } diff --git a/www/include/configuration/configObject/contactgroup/DB-Func.php b/www/include/configuration/configObject/contactgroup/DB-Func.php index e992c843004..d83370741fe 100644 --- a/www/include/configuration/configObject/contactgroup/DB-Func.php +++ b/www/include/configuration/configObject/contactgroup/DB-Func.php @@ -144,20 +144,24 @@ function multipleContactGroupInDB($contactGroups = array(), $nbrDup = array()) "WHERE `cg_cg_id` = " . (int)$key; $dbResult = $pearDB->query($query); $fields["cg_aclRelation"] = ""; + $aclContactStatement = $pearDB->prepare("INSERT INTO `acl_group_contactgroups_relations` " . + "VALUES (:maxId, :cgAcl)"); while ($cgAcl = $dbResult->fetch()) { - $query = "INSERT INTO `acl_group_contactgroups_relations` VALUES ('" . - $maxId["MAX(cg_id)"] . "', '" . $cgAcl['acl_group_id'] . "')"; - $pearDB->query($query); + $aclContactStatement->bindValue(":maxId", (int) $maxId["MAX(cg_id)"], PDO::PARAM_INT); + $aclContactStatement->bindValue(":cgAcl", (int) $cgAcl['acl_group_id'], PDO::PARAM_INT); + $aclContactStatement->execute(); $fields["cg_aclRelation"] .= $cgAcl["acl_group_id"] . ","; } $query = "SELECT DISTINCT `cgcr`.`contact_contact_id` FROM `contactgroup_contact_relation` `cgcr`" . " WHERE `cgcr`.`contactgroup_cg_id` = '" . (int)$key . "'"; $dbResult = $pearDB->query($query); $fields["cg_contacts"] = ""; + $contactStatement = $pearDB->prepare("INSERT INTO `contactgroup_contact_relation` " . + "VALUES (:cct, :maxId)"); while ($cct = $dbResult->fetch()) { - $query = "INSERT INTO `contactgroup_contact_relation` " . - "VALUES ('" . $cct["contact_contact_id"] . "', '" . $maxId["MAX(cg_id)"] . "')"; - $pearDB->query($query); + $contactStatement->bindValue(":cct", (int) $cct["contact_contact_id"], \PDO::PARAM_INT); + $contactStatement->bindValue(":maxId", (int) $maxId["MAX(cg_id)"], \PDO::PARAM_INT); + $contactStatement->execute(); $fields["cg_contacts"] .= $cct["contact_contact_id"] . ","; } $fields["cg_contacts"] = trim($fields["cg_contacts"], ","); diff --git a/www/include/configuration/configObject/host_categories/DB-Func.php b/www/include/configuration/configObject/host_categories/DB-Func.php index 63473a17c6c..a544e74d90c 100644 --- a/www/include/configuration/configObject/host_categories/DB-Func.php +++ b/www/include/configuration/configObject/host_categories/DB-Func.php @@ -249,10 +249,11 @@ function multipleHostCategoriesInDB($hostCategories = [], $nbrDup = []) $statement3->bindValue(':hc_id', $hcId, \PDO::PARAM_INT); $statement3->execute(); $fields["hc_hosts"] = ""; + $hrstatement = $pearDB->prepare("INSERT INTO hostcategories_relation VALUES (:maxId, :hostId)"); while ($host = $statement3->fetch()) { - $query = "INSERT INTO hostcategories_relation VALUES ('" . $maxId["MAX(hc_id)"] . - "', '" . $host["host_host_id"] . "')"; - $pearDB->query($query); + $hrstatement->bindValue(':maxId', (int) $maxId["MAX(hc_id)"], \PDO::PARAM_INT); + $hrstatement->bindValue(':hostId', (int) $host["host_host_id"], \PDO::PARAM_INT); + $hrstatement->execute(); $fields["hc_hosts"] .= $host["host_host_id"] . ","; } $fields["hc_hosts"] = trim($fields["hc_hosts"], ","); diff --git a/www/include/configuration/configObject/service/xml/argumentsXml.php b/www/include/configuration/configObject/service/xml/argumentsXml.php index caa01087633..bd3ff8ecdad 100644 --- a/www/include/configuration/configObject/service/xml/argumentsXml.php +++ b/www/include/configuration/configObject/service/xml/argumentsXml.php @@ -133,12 +133,13 @@ } } - $query3 = "SELECT command_command_id_arg " . + $cmdStatement = $db->prepare("SELECT command_command_id_arg " . "FROM service " . - "WHERE service_id = '" . $svcId . "' LIMIT 1"; - $res3 = $db->query($query3); - if ($res3->rowCount()) { - $row3 = $res3->fetchRow(); + "WHERE service_id = :svcId LIMIT 1"); + $cmdStatement->bindValue(':svcId', (int) $svcId, PDO::PARAM_INT); + $cmdStatement->execute(); + if ($cmdStatement->rowCount()) { + $row3 = $cmdStatement->fetchRow(); $valueTab = preg_split('/(? $value) { @@ -151,14 +152,15 @@ } } - $query = "SELECT macro_name, macro_description " . + $macroStatement = $db->prepare("SELECT macro_name, macro_description " . "FROM command_arg_description " . - "WHERE cmd_id = '" . $cmdId . "' ORDER BY macro_name"; - $res = $db->query($query); - while ($row = $res->fetchRow()) { + "WHERE cmd_id = :cmdId ORDER BY macro_name"); + $macroStatement->bindValue(':cmdId', (int) $cmdId, \PDO::PARAM_INT); + $macroStatement->execute(); + while ($row = $macroStatement->fetchRow()) { $argTab[$row['macro_name']] = $row['macro_description']; } - $res->closeCursor(); + $macroStatement->closeCursor(); /* * Write XML diff --git a/www/include/configuration/configObject/service_categories/listServiceCategories.php b/www/include/configuration/configObject/service_categories/listServiceCategories.php index 6db22ec44ea..5826517d427 100644 --- a/www/include/configuration/configObject/service_categories/listServiceCategories.php +++ b/www/include/configuration/configObject/service_categories/listServiceCategories.php @@ -119,12 +119,12 @@ $elemArr = array(); $centreonToken = createCSRFToken(); +$statement = $pearDB->prepare("SELECT COUNT(*) FROM `service_categories_relation` WHERE `sc_id` = :sc_id"); for ($i = 0; $sc = $dbResult->fetch(); $i++) { $moptions = ""; - $dbResult2 = $pearDB->query( - "SELECT COUNT(*) FROM `service_categories_relation` WHERE `sc_id` = '" . $sc['sc_id'] . "'" - ); - $nb_svc = $dbResult2->fetch(); + $statement->bindValue(':sc_id', (int) $sc['sc_id'], \PDO::PARAM_INT); + $statement->execute(); + $nb_svc = $statement->fetch(); $selectedElements = $form->addElement('checkbox', "select[" . $sc['sc_id'] . "]"); diff --git a/www/include/configuration/configObject/service_template_model/listServiceTemplateModel.ihtml b/www/include/configuration/configObject/service_template_model/listServiceTemplateModel.ihtml index 49b551569d0..46765e86559 100644 --- a/www/include/configuration/configObject/service_template_model/listServiceTemplateModel.ihtml +++ b/www/include/configuration/configObject/service_template_model/listServiceTemplateModel.ihtml @@ -62,7 +62,7 @@ {$elemArr[elem].RowMenu_alias} {$elemArr[elem].RowMenu_retry} - {$elemArr[elem].RowMenu_parent} + {$elemArr[elem].RowMenu_parent} {$elemArr[elem].RowMenu_status} {if $mode_access == 'w'}{$elemArr[elem].RowMenu_options}{else} {/if} diff --git a/www/include/configuration/configObject/service_template_model/listServiceTemplateModel.php b/www/include/configuration/configObject/service_template_model/listServiceTemplateModel.php index 68ea6f745fb..cc9cddbba3e 100644 --- a/www/include/configuration/configObject/service_template_model/listServiceTemplateModel.php +++ b/www/include/configuration/configObject/service_template_model/listServiceTemplateModel.php @@ -77,22 +77,22 @@ //Service Template Model list if ($search) { - $query = "SELECT SQL_CALC_FOUND_ROWS sv.service_id, sv.service_description, sv.service_alias, " . - "sv.service_activate, sv.service_template_model_stm_id " . - "FROM service sv " . - "WHERE (sv.service_description LIKE '%" . $search . "%' OR sv.service_alias LIKE '%" . $search . "%') " . + $statement = $pearDB->prepare("SELECT SQL_CALC_FOUND_ROWS sv.service_id, sv.service_description," . + " sv.service_alias, sv.service_activate, sv.service_template_model_stm_id FROM service sv " . + "WHERE (sv.service_description LIKE :search OR sv.service_alias LIKE :search) " . "AND sv.service_register = '0' " . $lockedFilter . - "ORDER BY service_description LIMIT " . $num * $limit . ", " . $limit; + "ORDER BY service_description LIMIT :offset, :limit"); + $statement->bindValue(':search', '%' . $search . '%', \PDO::PARAM_STR); } else { - $query = "SELECT SQL_CALC_FOUND_ROWS sv.service_id, sv.service_description, sv.service_alias, " . - "sv.service_activate, sv.service_template_model_stm_id " . - "FROM service sv " . - "WHERE sv.service_register = '0' " . - $lockedFilter . - "ORDER BY service_description LIMIT " . $num * $limit . ", " . $limit; + $statement = $pearDB->prepare("SELECT SQL_CALC_FOUND_ROWS sv.service_id, sv.service_description," . + " sv.service_alias, sv.service_activate, sv.service_template_model_stm_id FROM service sv " . + "WHERE sv.service_register = '0' " . $lockedFilter . + "ORDER BY service_description LIMIT :offset, :limit"); } -$dbResult = $pearDB->query($query); +$statement->bindValue(':limit', (int) $limit, \PDO::PARAM_INT); +$statement->bindValue(':offset', (int) $num * (int) $limit, \PDO::PARAM_INT); +$statement->execute(); $rows = $pearDB->query("SELECT FOUND_ROWS()")->fetchColumn(); include "./include/common/checkPagination.php"; @@ -137,7 +137,7 @@ $centreonToken = createCSRFToken(); -for ($i = 0; $service = $dbResult->fetch(); $i++) { +for ($i = 0; $service = $statement->fetch(); $i++) { $moptions = ""; $selectedElements = $form->addElement('checkbox', "select[" . $service['service_id'] . "]"); if (isset($lockedElements[$service['service_id']])) { @@ -176,7 +176,8 @@ foreach ($tplArr as $key => $value) { $value = str_replace('#S#', "/", $value); $value = str_replace('#BS#', "\\", $value); - $tplStr .= " -> " . $value . ""; + $tplStr .= " -> " + . htmlentities($value) . ""; } } @@ -232,7 +233,7 @@ "RowMenu_select" => $selectedElements->toHtml(), "RowMenu_desc" => htmlentities($service["service_description"]), "RowMenu_alias" => htmlentities($service["service_alias"]), - "RowMenu_parent" => htmlentities($tplStr), + "RowMenu_parent" => $tplStr, "RowMenu_icon" => $svc_icon, "RowMenu_retry" => htmlentities( "$normal_check_interval $normal_units / $retry_check_interval $retry_units" diff --git a/www/include/configuration/configObject/servicegroup_dependency/DB-Func.php b/www/include/configuration/configObject/servicegroup_dependency/DB-Func.php index 8d25f9e6f26..aaf61e1edb0 100644 --- a/www/include/configuration/configObject/servicegroup_dependency/DB-Func.php +++ b/www/include/configuration/configObject/servicegroup_dependency/DB-Func.php @@ -128,10 +128,13 @@ function multipleServiceGroupDependencyInDB($dependencies = array(), $nbrDup = a "WHERE dependency_dep_id = '" . $key . "'"; $dbResult = $pearDB->query($query); $fields["dep_sgParents"] = ""; + $query = "INSERT INTO dependency_servicegroupParent_relation " . + "VALUES (:dep_id, :servicegroup_sg_id)"; + $statement = $pearDB->prepare($query); while ($sg = $dbResult->fetch()) { - $query = "INSERT INTO dependency_servicegroupParent_relation " . - "VALUES ('" . $maxId["MAX(dep_id)"] . "', '" . $sg["servicegroup_sg_id"] . "')"; - $pearDB->query($query); + $statement->bindValue(':dep_id', (int) $maxId["MAX(dep_id)"], \PDO::PARAM_INT); + $statement->bindValue(':servicegroup_sg_id', (int) $sg["servicegroup_sg_id"], \PDO::PARAM_INT); + $statement->execute(); $fields["dep_sgParents"] .= $sg["servicegroup_sg_id"] . ","; } $fields["dep_sgParents"] = trim($fields["dep_sgParents"], ","); @@ -140,10 +143,13 @@ function multipleServiceGroupDependencyInDB($dependencies = array(), $nbrDup = a "WHERE dependency_dep_id = '" . $key . "'"; $dbResult = $pearDB->query($query); $fields["dep_sgChilds"] = ""; + $query = "INSERT INTO dependency_servicegroupChild_relation " . + "VALUES (:dep_id, :servicegroup_sg_id)"; + $statement = $pearDB->prepare($query); while ($sg = $dbResult->fetch()) { - $query = "INSERT INTO dependency_servicegroupChild_relation " . - "VALUES ('" . $maxId["MAX(dep_id)"] . "', '" . $sg["servicegroup_sg_id"] . "')"; - $pearDB->query($query); + $statement->bindValue(':dep_id', (int) $maxId["MAX(dep_id)"], \PDO::PARAM_INT); + $statement->bindValue(':servicegroup_sg_id', (int) $sg["servicegroup_sg_id"], \PDO::PARAM_INT); + $statement->execute(); $fields["dep_sgChilds"] .= $sg["servicegroup_sg_id"] . ","; } $fields["dep_sgChilds"] = trim($fields["dep_sgChilds"], ","); diff --git a/www/include/configuration/configResources/DB-Func.php b/www/include/configuration/configResources/DB-Func.php index 7f9e7f5fc9f..92ac3cd0bdc 100644 --- a/www/include/configuration/configResources/DB-Func.php +++ b/www/include/configuration/configResources/DB-Func.php @@ -294,23 +294,34 @@ function insertResource($ret = array()) if (!count($ret)) { $ret = $form->getSubmitValues(); } - $rq = "INSERT INTO cfg_resource "; - $rq .= "(resource_name, resource_line, resource_comment, resource_activate) "; - $rq .= "VALUES ("; - isset($ret["resource_name"]) && $ret["resource_name"] != null - ? $rq .= "'" . $pearDB->escape($ret["resource_name"]) . "', " - : $rq .= "NULL, "; - isset($ret["resource_line"]) && $ret["resource_line"] != null - ? $rq .= "'" . $pearDB->escape($ret["resource_line"]) . "', " - : $rq .= "NULL, "; - isset($ret["resource_comment"]) && $ret["resource_comment"] != null - ? $rq .= "'" . $pearDB->escape($ret["resource_comment"]) . "', " - : $rq .= "NULL, "; - isset($ret["resource_activate"]["resource_activate"]) && $ret["resource_activate"]["resource_activate"] != null - ? $rq .= "'" . $ret["resource_activate"]["resource_activate"] . "'" - : $rq .= "NULL"; - $rq .= ")"; - $pearDB->query($rq); + $statement = $pearDB->prepare( + "INSERT INTO cfg_resource + (resource_name, resource_line, resource_comment, resource_activate) + VALUES (:name, :line, :comment, :is_activated)" + ); + $statement->bindValue( + ':name', + ! empty($ret["resource_name"]) + ? $ret["resource_name"] + : null + ); + $statement->bindValue( + ':line', + ! empty($ret["resource_line"]) + ? $ret["resource_line"] + : null + ); + $statement->bindValue( + ':comment', + ! empty($ret["resource_comment"]) + ? $ret["resource_comment"] + : null + ); + $isActivated = isset($ret["resource_activate"]["resource_activate"]) + && (bool) (int) $ret["resource_activate"]["resource_activate"]; + $statement->bindValue(':is_activated', (string) (int) $isActivated); + $statement->execute(); + $dbResult = $pearDB->query("SELECT MAX(resource_id) FROM cfg_resource"); $resource_id = $dbResult->fetch(); diff --git a/www/include/configuration/configServers/DB-Func.php b/www/include/configuration/configServers/DB-Func.php index 5e800693fc7..1a2a39c0190 100644 --- a/www/include/configuration/configServers/DB-Func.php +++ b/www/include/configuration/configServers/DB-Func.php @@ -285,17 +285,17 @@ function deleteServerInDB(array $serverIds): void // Is a Remote Server? $statement = $pearDB->prepare( - 'SELECT * FROM remote_servers WHERE ip = :ip' + 'SELECT * FROM remote_servers WHERE server_id = :id' ); - $statement->bindValue(':ip', $row['ip'], \PDO::PARAM_STR); + $statement->bindValue(':id', $serverId, \PDO::PARAM_INT); $statement->execute(); if ($statement->rowCount() > 0) { // Delete entry from remote_servers $statement = $pearDB->prepare( - 'DELETE FROM remote_servers WHERE ip = :ip' + 'DELETE FROM remote_servers WHERE server_id = :id' ); - $statement->bindValue(':ip', $row['ip'], \PDO::PARAM_STR); + $statement->bindValue(':id', $serverId, \PDO::PARAM_INT); $statement->execute(); // Delete all relation between this Remote Server and pollers $pearDB->query( @@ -437,6 +437,8 @@ function duplicateServer(array $server, array $nbrDup): void $statement->bindValue(':poller_id', (int) $row['id'], \PDO::PARAM_INT); $statement->bindValue(':b_poller_id', (int) $serverId, \PDO::PARAM_INT); $statement->execute(); + + duplicateRemoteServerInformation((int) $serverId, (int) $row['id']); } } catch (\PDOException $e) { // Nothing to do @@ -768,14 +770,14 @@ function addUserRessource(int $serverId): bool * Update Remote Server information * * @param array $data - * @param string|null $oldIpAddress Old IP address of the server before the upgrade + * @param int $id remote server id */ -function updateRemoteServerInformation(array $data, string $oldIpAddress = null) +function updateRemoteServerInformation(array $data, int $id) { global $pearDB; - $statement = $pearDB->prepare("SELECT COUNT(*) AS total FROM remote_servers WHERE ip = :ip"); - $statement->bindValue(':ip', $oldIpAddress ?? $data["ns_ip_address"]); + $statement = $pearDB->prepare("SELECT COUNT(*) AS total FROM remote_servers WHERE server_id = :id"); + $statement->bindValue(':id', $id, \PDO::PARAM_INT); $statement->execute(); $total = (int) $statement->fetch(\PDO::FETCH_ASSOC)['total']; @@ -784,14 +786,14 @@ function updateRemoteServerInformation(array $data, string $oldIpAddress = null) UPDATE remote_servers SET http_method = :http_method, http_port = :http_port, no_check_certificate = :no_check_certificate, no_proxy = :no_proxy, ip = :new_ip - WHERE ip = :ip + WHERE server_id = :id "); $statement->bindValue(':http_method', $data["http_method"]); $statement->bindValue(':http_port', $data["http_port"] ?? null, \PDO::PARAM_INT); $statement->bindValue(':no_proxy', $data["no_proxy"]["no_proxy"]); $statement->bindValue(':no_check_certificate', $data["no_check_certificate"]["no_check_certificate"]); $statement->bindValue(':new_ip', $data["ns_ip_address"]); - $statement->bindValue(':ip', $oldIpAddress ?? $data["ns_ip_address"]); + $statement->bindValue(':id', $id, \PDO::PARAM_INT); $statement->execute(); } } @@ -1011,13 +1013,13 @@ function updateServer(int $id, array $data): void $stmt->bindValue($key, $value); } $stmt->execute(); + + updateRemoteServerInformation($data, $id); try { updateServerIntoPlatformTopology($retValue, $id); } catch (\Exception $e) { // catch exception but don't return anything to avoid blank pages on form } - - updateRemoteServerInformation($data, $ipAddressBeforeChanges); additionnalRemoteServersByPollerId( $id, $data["remote_additional_id"] ?? null @@ -1348,8 +1350,8 @@ function updateServerIntoPlatformTopology(array $pollerInformations, int $server /** * Check if we are updating a Remote Server */ - $statement = $pearDB->prepare("SELECT * FROM remote_servers WHERE ip = :address"); - $statement->bindValue(':address', $pollerIp, \PDO::PARAM_STR); + $statement = $pearDB->prepare("SELECT 1 FROM remote_servers WHERE server_id = :id"); + $statement->bindValue(':id', $serverId, \PDO::PARAM_INT); $statement->execute(); $isRemote = $statement->fetch(\PDO::FETCH_ASSOC); if ($isRemote) { @@ -1496,3 +1498,73 @@ function ipCanBeUpdated(array $options): bool } return true; } + +/** + * Get Remote servers information + * + * @param integer $serverId + * @return array + */ +function getRemoteServerInformation(int $serverId): array +{ + global $pearDB; + + $statement = $pearDB->prepare("SELECT * FROM remote_servers WHERE server_id = :id LIMIT 1"); + $statement->bindValue(':id', $serverId, \PDO::PARAM_INT); + $statement->execute(); + if (($result = $statement->fetch(\PDO::FETCH_ASSOC)) !== false) { + return $result; + } + + return []; +} + +/** + * Duplicate information for remote server + * + * @param int $duplicatedId + * @param int $newId + */ +function duplicateRemoteServerInformation(int $duplicatedId, int $newId): void +{ + global $pearDB; + $remoteServerInformation = getRemoteServerInformation($duplicatedId); + if (! empty($remoteServerInformation)) { + $insertRemoteServerStatement = $pearDB->prepare( + "INSERT INTO `remote_servers` (ip, `version`, is_connected, + centreon_path, http_method, http_port, no_check_certificate, no_proxy, server_id) VALUES + (:ip, :version, :isConnected, :centreonPath, :httpMethod, :httpPort, + :noCheckCertificate, :noProxy, :serverId)" + ); + $insertRemoteServerStatement->bindValue(":ip", $remoteServerInformation["ip"], \PDO::PARAM_STR); + $insertRemoteServerStatement->bindValue(":version", $remoteServerInformation["version"], \PDO::PARAM_STR); + $insertRemoteServerStatement->bindValue( + ":isConnected", + (int) $remoteServerInformation["is_connected"], + \PDO::PARAM_INT + ); + $insertRemoteServerStatement->bindValue( + ":centreonPath", + $remoteServerInformation["centreon_path"], + \PDO::PARAM_STR + ); + $insertRemoteServerStatement->bindValue( + ":httpMethod", + $remoteServerInformation["http_method"], + \PDO::PARAM_STR + ); + $insertRemoteServerStatement->bindValue( + ":httpPort", + $remoteServerInformation["http_port"] !== null ? (int) $remoteServerInformation["http_port"] : null, + \PDO::PARAM_INT + ); + $insertRemoteServerStatement->bindValue( + ":noCheckCertificate", + $remoteServerInformation["no_check_certificate"], + \PDO::PARAM_STR + ); + $insertRemoteServerStatement->bindValue(":noProxy", $remoteServerInformation["no_proxy"], \PDO::PARAM_STR); + $insertRemoteServerStatement->bindValue(":serverId", $newId, \PDO::PARAM_INT); + $insertRemoteServerStatement->execute(); + } +} diff --git a/www/include/configuration/configServers/popup/popup.php b/www/include/configuration/configServers/popup/popup.php index de70b9d67d4..acaa3f6ad06 100644 --- a/www/include/configuration/configServers/popup/popup.php +++ b/www/include/configuration/configServers/popup/popup.php @@ -60,19 +60,21 @@ $dbResult = $pearDB->query($query); $remotesServerIPs = $dbResult->fetchAll(PDO::FETCH_COLUMN); $dbResult->closeCursor(); -//get poller informations -$query = " -SELECT ns.`id`, ns.`name`, ns.`gorgone_port`, ns.`ns_ip_address`, ns.`localhost`, ns.remote_id, -remote_server_use_as_proxy, cn.`command_file`, GROUP_CONCAT( pr.`remote_server_id` ) AS list_remote_server_id -FROM nagios_server AS ns - LEFT JOIN remote_servers AS rs ON (rs.ip = ns.ns_ip_address) - LEFT JOIN cfg_nagios AS cn ON (cn.`nagios_id` = ns.`id`) - LEFT JOIN rs_poller_relation AS pr ON (pr.`poller_server_id` = ns.`id`) -WHERE ns.ns_activate = '1' -AND ns.`id` =" . (int)$pollerId; -$dbResult = $pearDB->query($query); -$server = $dbResult->fetch(); +//get poller informations +$statement = $pearDB->prepare( + "SELECT ns.`id`, ns.`name`, ns.`gorgone_port`, ns.`ns_ip_address`, ns.`localhost`, ns.remote_id, + remote_server_use_as_proxy, cn.`command_file`, GROUP_CONCAT( pr.`remote_server_id` ) AS list_remote_server_id + FROM nagios_server AS ns + LEFT JOIN remote_servers AS rs ON rs.server_id = ns.id + LEFT JOIN cfg_nagios AS cn ON cn.`nagios_id` = ns.`id` + LEFT JOIN rs_poller_relation AS pr ON pr.`poller_server_id` = ns.`id` + WHERE ns.ns_activate = '1' + AND ns.`id` = :server_id" +); +$statement->bindValue(':server_id', (int) $pollerId, \PDO::PARAM_INT); +$statement->execute(); +$server = $statement->fetch(); //get gorgone api informations $gorgoneApi = []; diff --git a/www/include/monitoring/objectDetails/hostDetails.php b/www/include/monitoring/objectDetails/hostDetails.php index fb5a9ca0d32..eb5031bdb54 100644 --- a/www/include/monitoring/objectDetails/hostDetails.php +++ b/www/include/monitoring/objectDetails/hostDetails.php @@ -725,40 +725,6 @@ $tpl->assign("h_ext_icon_image_alt", getMyHostExtendedInfoField($hostDB["host_id"], "ehi_icon_image_alt")); } - /* - * Dynamics tools - */ - $tools = array(); - $DBRESULT = $pearDB->query("SELECT * FROM modules_informations"); - while ($module = $DBRESULT->fetchrow()) { - if ( - isset($module['host_tools']) && $module['host_tools'] == 1 - && file_exists('modules/' . $module['name'] . '/host_tools.php') - ) { - include('modules/' . $module['name'] . '/host_tools.php'); - } - } - $DBRESULT->closeCursor(); - - foreach ($tools as $key => $tab) { - $tools[$key]['url'] = str_replace("@host_id@", $host_id, $tools[$key]['url']); - $tools[$key]['url'] = str_replace("@host_name@", $host_name, $tools[$key]['url']); - $tools[$key]['url'] = str_replace( - "@current_state@", - $host_status[$host_name]["current_state"], - $tools[$key]['url'] - ); - $tools[$key]['url'] = str_replace( - "@plugin_output@", - $host_status[$host_name]["plugin_output"], - $tools[$key]['url'] - ); - } - - if (count($tools) > 0) { - $tpl->assign("tools", $tools); - } - // Check if central or remote server $DBRESULT = $pearDB->query("SELECT `value` FROM `informations` WHERE `key` = 'isRemote'"); $result = $DBRESULT->fetchRow(); diff --git a/www/include/monitoring/objectDetails/serviceDetails.php b/www/include/monitoring/objectDetails/serviceDetails.php index 95ac677bdbd..cf71401d922 100644 --- a/www/include/monitoring/objectDetails/serviceDetails.php +++ b/www/include/monitoring/objectDetails/serviceDetails.php @@ -879,35 +879,6 @@ $tpl->assign("index_data", $index_data); $tpl->assign("options2", CentreonUtils::escapeSecure($optionsURL2)); - /* - * Dynamics tools - */ - $tools = array(); - $DBRESULT = $pearDB->query("SELECT * FROM modules_informations"); - while ($module = $DBRESULT->fetchrow()) { - if ( - isset($module['svc_tools']) - && $module['svc_tools'] == 1 - && file_exists('modules/' . $module['name'] . '/svc_tools.php') - ) { - include('modules/' . $module['name'] . '/svc_tools.php'); - } - } - $DBRESULT->closeCursor(); - - foreach ($tools as $key => $tab) { - $tools[$key]['url'] = str_replace("@host_id@", $host_id, $tools[$key]['url']); - $tools[$key]['url'] = str_replace("@host_name@", $host_name, $tools[$key]['url']); - $tools[$key]['url'] = str_replace("@svc_description@", $svc_description, $tools[$key]['url']); - $tools[$key]['url'] = str_replace("@svc_id@", $service_id, $tools[$key]['url']); - $tools[$key]['url'] = str_replace("@current_state@", $service_status["current_state"], $tools[$key]['url']); - $tools[$key]['url'] = str_replace("@plugin_output@", $service_status["plugin_output"], $tools[$key]['url']); - } - - if (count($tools) > 0) { - $tpl->assign("tools", CentreonUtils::escapeSecure($tools)); - } - /** * Build the service detail URI that will be used in the * deprecated banner diff --git a/www/include/monitoring/objectDetails/template/hostDetails.ihtml b/www/include/monitoring/objectDetails/template/hostDetails.ihtml index d6fd686a427..5509d125394 100644 --- a/www/include/monitoring/objectDetails/template/hostDetails.ihtml +++ b/www/include/monitoring/objectDetails/template/hostDetails.ihtml @@ -505,19 +505,6 @@ {/if} - {section name=tool loop=$tools} - {if !empty(tool)} - - - {if $tools[tool].popup == ""} - - {else} - - {/if} - ● {$tools[tool].name} - - {/if} - {/section} diff --git a/www/include/monitoring/objectDetails/template/serviceDetails.ihtml b/www/include/monitoring/objectDetails/template/serviceDetails.ihtml index dbe729ec117..1328487c7d3 100644 --- a/www/include/monitoring/objectDetails/template/serviceDetails.ihtml +++ b/www/include/monitoring/objectDetails/template/serviceDetails.ihtml @@ -154,31 +154,6 @@ - - - - {if isset($tools)} - - - - - {if isset($tools)} - {section name=tool loop=$tools} - - - - {/section} - {/if} -
{$m_mon_tools}
- {if $tools[tool].popup == ""} - - {else} - - {/if} - ● {$tools[tool].name}
- {/if} - - {if $index_data} diff --git a/www/include/monitoring/status/Services/xml/serviceXML.php b/www/include/monitoring/status/Services/xml/serviceXML.php index 0bcf8fb9e4e..202a1e04def 100644 --- a/www/include/monitoring/status/Services/xml/serviceXML.php +++ b/www/include/monitoring/status/Services/xml/serviceXML.php @@ -1,4 +1,5 @@ XML->writeElement("sc", $obj->colorService[$data["state"]]); $obj->XML->writeElement("cs", _($obj->statusService[$data["state"]]), false); $obj->XML->writeElement("ssc", $data["state"]); - $obj->XML->writeElement("po", CentreonUtils::escapeSecure($pluginShortOuput)); + $obj->XML->writeElement("po", htmlspecialchars(htmlspecialchars($pluginShortOuput))); $obj->XML->writeElement( "ca", $data["current_attempt"] . "/" . $data["max_check_attempts"] diff --git a/www/include/monitoring/status/Services/xsl/serviceGrid.xsl b/www/include/monitoring/status/Services/xsl/serviceGrid.xsl index d570b37bf3a..e3c085db290 100644 --- a/www/include/monitoring/status/Services/xsl/serviceGrid.xsl +++ b/www/include/monitoring/status/Services/xsl/serviceGrid.xsl @@ -38,7 +38,10 @@ true - + + svgs + + main.php?p=204&mode=0&svc_id= diff --git a/www/include/monitoring/status/Services/xsl/serviceSummary.xsl b/www/include/monitoring/status/Services/xsl/serviceSummary.xsl index 56ad24d20fe..ef5a125620d 100644 --- a/www/include/monitoring/status/Services/xsl/serviceSummary.xsl +++ b/www/include/monitoring/status/Services/xsl/serviceSummary.xsl @@ -32,7 +32,10 @@ true - + + svgs + + main.php?p=204&mode=0&svc_id= diff --git a/www/include/monitoring/status/ServicesHostGroups/xsl/serviceGridByHG.xsl b/www/include/monitoring/status/ServicesHostGroups/xsl/serviceGridByHG.xsl index 14eee0539a1..a7d03725925 100644 --- a/www/include/monitoring/status/ServicesHostGroups/xsl/serviceGridByHG.xsl +++ b/www/include/monitoring/status/ServicesHostGroups/xsl/serviceGridByHG.xsl @@ -87,11 +87,17 @@ true - + + svgs + + main.php?p=204&mode=0&svc_id= - + + svgs + + @@ -122,5 +128,8 @@ + \ No newline at end of file diff --git a/www/include/monitoring/status/ServicesHostGroups/xsl/serviceSummaryByHG.xsl b/www/include/monitoring/status/ServicesHostGroups/xsl/serviceSummaryByHG.xsl index bc73742313d..654f20014ac 100644 --- a/www/include/monitoring/status/ServicesHostGroups/xsl/serviceSummaryByHG.xsl +++ b/www/include/monitoring/status/ServicesHostGroups/xsl/serviceSummaryByHG.xsl @@ -97,11 +97,17 @@ true - + + svgs + + main.php?p=204&mode=0&svc_id= - + + svgs + + @@ -173,5 +179,8 @@
+ diff --git a/www/include/monitoring/status/ServicesServiceGroups/xsl/serviceGridBySG.xsl b/www/include/monitoring/status/ServicesServiceGroups/xsl/serviceGridBySG.xsl index 4c529faf3a8..3b004972c1c 100644 --- a/www/include/monitoring/status/ServicesServiceGroups/xsl/serviceGridBySG.xsl +++ b/www/include/monitoring/status/ServicesServiceGroups/xsl/serviceGridBySG.xsl @@ -49,11 +49,17 @@ true - + + svgs + + main.php?p=20401&mode=0&svc_id= - + + svgs + + @@ -90,5 +96,8 @@
+ \ No newline at end of file diff --git a/www/include/monitoring/status/ServicesServiceGroups/xsl/serviceSummaryBySG.xsl b/www/include/monitoring/status/ServicesServiceGroups/xsl/serviceSummaryBySG.xsl index 673ed837482..f908162f721 100644 --- a/www/include/monitoring/status/ServicesServiceGroups/xsl/serviceSummaryBySG.xsl +++ b/www/include/monitoring/status/ServicesServiceGroups/xsl/serviceSummaryBySG.xsl @@ -42,11 +42,17 @@ - + + svgs + + main.php?p=20401&mode=0&svc_id= - + + svgs + + @@ -119,5 +125,8 @@ + diff --git a/www/include/options/accessLists/groupsACL/groupsConfig.php b/www/include/options/accessLists/groupsACL/groupsConfig.php index 0962a1ec3d7..efca74051f9 100644 --- a/www/include/options/accessLists/groupsACL/groupsConfig.php +++ b/www/include/options/accessLists/groupsACL/groupsConfig.php @@ -71,8 +71,14 @@ function sanitize_input_array(array $inputArray): array $acl_group_id = filter_var($_GET['acl_group_id'] ?? $_POST['acl_group_id'] ?? null, FILTER_VALIDATE_INT) ?? null; // Caution $o may already be set from the GET or from the POST. -$postO = filter_var($_POST['o1'] ?? $_POST['o2'] ?? $o ?? null, FILTER_SANITIZE_STRING); -$o = ("" !== $postO) ? $postO : null; +$postO = filter_var( + $_POST['o1'] ?? $_POST['o2'] ?? $o ?? null, + FILTER_VALIDATE_REGEXP, + ["options" => ["regexp" => "/^(a|c|d|m|s|u|w)$/"]] +); +if ($postO !== false) { + $o = $postO; +} switch ($o) { case "a": diff --git a/www/include/views/virtualMetrics/listVirtualMetrics.php b/www/include/views/virtualMetrics/listVirtualMetrics.php index 533279620c3..38ea5717dfb 100644 --- a/www/include/views/virtualMetrics/listVirtualMetrics.php +++ b/www/include/views/virtualMetrics/listVirtualMetrics.php @@ -130,31 +130,37 @@ "\" maxlength=\"3\" size=\"3\" value='1' style=\"margin-bottom:0px;\" name='dupNbr[" . $vmetric['vmetric_id'] . "]' />"; + $indexDataStatement = $pearDBO->prepare("SELECT id,host_id,service_id FROM index_data " . + "WHERE id = :indexId "); try { - $query = "SELECT id,host_id,service_id FROM index_data WHERE id = '" . $vmetric['index_id'] . "'"; - $dbindd = $pearDBO->query($query); + $indexDataStatement->bindValue(':indexId', (int) $vmetric['index_id'], \PDO::PARAM_INT); + $indexDataStatement->execute(); } catch (\PDOException $e) { print "DB Error : " . $e->getMessage() . "
"; } - $indd = $dbindd->fetchRow(); - $dbindd->closeCursor(); + $indd = $indexDataStatement->fetchRow(); + + $indexDataStatement->closeCursor(); if ($indd !== false) { try { - $query = "(SELECT concat(h.host_name,' > ',s.service_description) full_name " . + $hsrStatement = $pearDB->prepare("(SELECT concat(h.host_name,' > ',s.service_description) full_name " . "FROM host_service_relation AS hsr, host AS h, service AS s WHERE hsr.host_host_id = h.host_id " . - "AND hsr.service_service_id = s.service_id AND h.host_id = '" . $indd["host_id"] . - "' AND s.service_id = '" . $indd["service_id"] . "') UNION " . + "AND hsr.service_service_id = s.service_id AND h.host_id = :hostId " . + "AND s.service_id = :serviceId ) UNION " . "(SELECT concat(h.host_name,' > ',s.service_description) full_name " . "FROM host_service_relation AS hsr, host AS h, service AS s, hostgroup_relation AS hr " . "WHERE hsr.hostgroup_hg_id = hr.hostgroup_hg_id AND hr.host_host_id = h.host_id " . - "AND hsr.service_service_id = s.Service_id AND h.host_id = '" . $indd["host_id"] . - "' AND s.service_id = '" . $indd["service_id"] . "') ORDER BY full_name"; - $dbhsrname = $pearDB->query($query); + "AND hsr.service_service_id = s.Service_id AND h.host_id = :hostId " . + "AND s.service_id = :serviceId ) ORDER BY full_name"); + + $hsrStatement->bindValue(':hostId', (int) $indd["host_id"], \PDO::PARAM_INT); + $hsrStatement->bindValue(':serviceId', (int) $indd["service_id"], \PDO::PARAM_INT); + $hsrStatement->execute(); } catch (\PDOException $e) { print "DB Error : " . $e->getMessage() . "
"; } - $hsrname = $dbhsrname->fetchRow(); - $dbhsrname->closeCursor(); + $hsrname = $hsrStatement->fetchRow(); + $hsrStatement->closeCursor(); $hsrname["full_name"] = str_replace('#S#', "/", $hsrname["full_name"]); $hsrname["full_name"] = str_replace('#BS#', "\\", $hsrname["full_name"]); } diff --git a/www/install/createTables.sql b/www/install/createTables.sql index c72f2449beb..b623f1f6f5a 100644 --- a/www/install/createTables.sql +++ b/www/install/createTables.sql @@ -2329,7 +2329,9 @@ CREATE TABLE IF NOT EXISTS `remote_servers` ( `http_method` enum('http','https') NOT NULL DEFAULT 'http', `http_port` int(11) DEFAULT NULL, `no_check_certificate` enum('0','1') NOT NULL DEFAULT '0', - `no_proxy` enum('0','1') NOT NULL DEFAULT '0' + `no_proxy` enum('0','1') NOT NULL DEFAULT '0', + `server_id` int(11) NOT NULL, + CONSTRAINT `remote_server_nagios_server_ibfk_1` FOREIGN KEY(`server_id`) REFERENCES `nagios_server` (`id`) ON DELETE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- Create rs_poller_relation for the additional relationship between poller and remote servers diff --git a/www/install/insertBaseConf.sql b/www/install/insertBaseConf.sql index df57294e767..02dd52d742e 100644 --- a/www/install/insertBaseConf.sql +++ b/www/install/insertBaseConf.sql @@ -2,7 +2,7 @@ -- Insert version -- -INSERT INTO `informations` (`key` ,`value`) VALUES ('version', '22.04.4'); +INSERT INTO `informations` (`key` ,`value`) VALUES ('version', '22.04.5'); -- -- Contenu de la table `contact` diff --git a/www/install/php/Update-22.04.0-beta.1.php b/www/install/php/Update-22.04.0-beta.1.php index 611ddf87ef4..5e4a9550566 100644 --- a/www/install/php/Update-22.04.0-beta.1.php +++ b/www/install/php/Update-22.04.0-beta.1.php @@ -528,26 +528,34 @@ function migrateBrokerConfigOutputsToUnifiedSql(CentreonDB $pearDB): void throw new \Exception("Cannot find max config group id in cfg_centreonbroker_info table"); } $nextConfigGroupId = (int) $maxConfigGroupId['max_config_group_id'] + 1; - + $blockIdsQueryBinds = []; + foreach ($blockIds as $key => $value) { + $blockIdsQueryBinds[':block_id_' . $key] = $value; + } + $blockIdBinds = implode(',', array_keys($blockIdsQueryBinds)); // Find config group ids of outputs to replace - $dbResult = $pearDB->query( - "SELECT config_group_id FROM cfg_centreonbroker_info - WHERE config_id = $configId AND config_key = 'blockId' - AND config_value IN ('" . implode('\', \'', $blockIds) . "')" - ); - $configGroupIds = $dbResult->fetchAll(\PDO::FETCH_COLUMN, 0); + $grpIdStatement = $pearDB->prepare("SELECT config_group_id FROM cfg_centreonbroker_info + WHERE config_id = :configId AND config_key = 'blockId' + AND config_value IN ($blockIdBinds)"); + $grpIdStatement->bindValue(':configId', (int) $configId, PDO::PARAM_INT); + foreach ($blockIdsQueryBinds as $key => $value) { + $grpIdStatement->bindValue($key, (int) $value, PDO::PARAM_INT); + } + $grpIdStatement->execute(); + $configGroupIds = $grpIdStatement->fetchAll(\PDO::FETCH_COLUMN, 0); if (empty($configGroupIds)) { throw new \Exception("Cannot find config group ids in cfg_centreonbroker_info table"); } // Build unified sql output config from outputs to replace $unifiedSqlOutput = []; + $statement = $pearDB->prepare("SELECT * FROM cfg_centreonbroker_info + WHERE config_id = :configId AND config_group = 'output' AND config_group_id = :configGroupId"); foreach ($configGroupIds as $configGroupId) { - $dbResult = $pearDB->query( - "SELECT * FROM cfg_centreonbroker_info - WHERE config_id = $configId AND config_group = 'output' AND config_group_id = $configGroupId" - ); - while ($row = $dbResult->fetch()) { + $statement->bindValue(':configId', (int) $configId, PDO::PARAM_INT); + $statement->bindValue(':configGroupId', (int) $configGroupId, PDO::PARAM_INT); + $statement->execute(); + while ($row = $statement->fetch()) { $unifiedSqlOutput[$row['config_key']] = array_merge($unifiedSqlOutput[$row['config_key']] ?? [], $row); $unifiedSqlOutput[$row['config_key']]['config_group_id'] = $nextConfigGroupId; } diff --git a/www/install/php/Update-22.04.5.php b/www/install/php/Update-22.04.5.php new file mode 100644 index 00000000000..33e05e73c9f --- /dev/null +++ b/www/install/php/Update-22.04.5.php @@ -0,0 +1,102 @@ +isColumnExist('remote_servers', 'server_id') === 0) { + $errorMessage = "Unable to add 'server_id' column to remote_servers table"; + $pearDB->query( + "ALTER TABLE remote_servers + ADD COLUMN `server_id` int(11) NOT NULL" + ); + + migrateRemoteServerRelations($pearDB); + + $errorMessage = "Unable to add foreign key constraint of remote_servers.server_id"; + $pearDB->query( + "ALTER TABLE remote_servers + ADD CONSTRAINT `remote_server_nagios_server_ibfk_1` + FOREIGN KEY(`server_id`) REFERENCES `nagios_server` (`id`) + ON DELETE CASCADE" + ); + } +} catch (\Exception $e) { + $centreonLog->insertLog( + 4, + $versionOfTheUpgrade . $errorMessage . + " - Code : " . (int)$e->getCode() . + " - Error : " . $e->getMessage() . + " - Trace : " . $e->getTraceAsString() + ); + + throw new \Exception($versionOfTheUpgrade . $errorMessage, (int) $e->getCode(), $e); +} + +/** + * Manage relations between remote servers and nagios servers + * + * @param \CentreonDB $pearDB + */ +function migrateRemoteServerRelations(\CentreonDB $pearDB): void +{ + $processedIps = []; + + $selectServerStatement = $pearDB->prepare( + "SELECT id FROM nagios_server WHERE ns_ip_address = :ip_address" + ); + $deleteRemoteStatement = $pearDB->prepare( + "DELETE FROM remote_servers WHERE id = :id" + ); + $updateRemoteStatement = $pearDB->prepare( + "UPDATE remote_servers SET server_id = :server_id WHERE id = :id" + ); + + $result = $pearDB->query( + "SELECT id, ip FROM remote_servers" + ); + while ($remote = $result->fetch()) { + $remoteIp = $remote['ip']; + $remoteId = $remote['id']; + if (in_array($remoteIp, $processedIps)) { + $deleteRemoteStatement->bindValue(':id', $remoteId, \PDO::PARAM_INT); + $deleteRemoteStatement->execute(); + } + + $processedIps[] = $remoteIp; + + $selectServerStatement->bindValue(':ip_address', $remoteIp, \PDO::PARAM_STR); + $selectServerStatement->execute(); + if ($server = $selectServerStatement->fetch()) { + $updateRemoteStatement->bindValue(':server_id', $server['id'], \PDO::PARAM_INT); + $updateRemoteStatement->bindValue(':id', $remoteId, \PDO::PARAM_INT); + $updateRemoteStatement->execute(); + } else { + $deleteRemoteStatement->bindValue(':id', $remoteId, \PDO::PARAM_INT); + $deleteRemoteStatement->execute(); + } + } +} From 94e15aa63dfe2d5fa14a1154b297084012d93a91 Mon Sep 17 00:00:00 2001 From: tuntoja <58987095+tuntoja@users.noreply.github.com> Date: Mon, 3 Oct 2022 09:09:03 +0200 Subject: [PATCH 4/7] chore(release): merge release-22.04.next in 22.04.x (#11911) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(git): resync 22.04.x to dev-22.04.x (#11503) * [SNYK] Sanitize and bind ACL host dependency queries (#11389) (#11394) * Sanitize and bind ACL host dependency queries * fix issues * removed old variable userCrypted and the use of it (#11334) (#11352) Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> * enh(Header/userMenu):reduce spacing user menu (#11393) * update user menu * fix(hostgroup): fix display of hostgroups in select2 (#11431) (#11443) * fix(ci): fix debian packaging with freshly instanciated jenkins slave (#11398) (#11399) Refs: MON-14377 * Sanitized and bound queries (#11413) (#11445) lines : 130 -142 * Snyk: Sanitize and bind media sync queries 22.04.x (#11418) * sanitizing and binding sync dir file queries * Applying some fixes * Snyk: Sanitize and bind ACL service dependency queries dev-22.04.x (#11395) * Snyk: Sanitize and bind Auth class queries 22.04.x (#11448) * [Backport/need review] fix(UI): Fix layout for Safari and form validation (#11440) * fix(UI): Fix layout for Safari and form validation (#11373) * Fix form validation * Fix padlock layout for safari * Update centreon-frontend * Remove debug variable * Fix test * Fix page respsoniveness * Rename variable * update deps * Fix package-lock * Fix package-lock * Add debug statement for debian * Install nodejs rather npm * Attempt fix * Attempt to fix nodejs installation * add sudo * Fix redoc-cli usage * Try to fix permission on npm * Fix * Fix permission * Fix permission (please work) * Fix source * Stop using npx because..... * Allow legacy-peer-deps * Remove nodejs installation * Fix image to pull for debian 11 * [SNYK] Sanitize and bind centreonGraph class queries (#11409) (#11421) 1122 1153 1134 * [Snyk] Sanitize and bind ACL action access queries (#11385) (#11402) * Sanitize and bind ACL action access queries _ sanitize if possible each variables inserted in a query _ use PDO prepared statement and bind() method _ Do not use $pearDB->escape on which is for examples useless on integers and on non closed HTML tags (svg, img, etc) * fix line length * fix failed checks * feat(api): implement endpoint to update centreon web (#11391) (#11401) Refs: MON-12296 * Clean(platform): Clean appKey method and usage 22.04.x (#11452) * Clean(platform): Clean appKey method and usage (#11336) * removing appKey from information table in baseConf and 22.10 update script * removing appKey from NotifyMasterService.php * removing appKey from CentreonRemoteServer.php * applying suggested changes * Applying suggested changes Co-authored-by: Kevin Duret * adding 22.04.2 update script file with changes * revert 22.04 beta 1 script to its original Co-authored-by: Kevin Duret * enh(platform): Use API to select metrics in virtual metrics configuration form 22.04.x (#11461) * changing select with select2 of metrics * fix alignement * remove unecessary files and replace selec by select2 in formComponentTemplate * fix select id name for acceptance tests * update composer for acceptance tests * fix acceptance test 2 * add allow clear to metrics select2 * applying suggested changes * final changes for merging * remove unecessary select tag * [SNYK] Sanitize and bind ACL class queries (#11392) (#11472) * Sanitize and bind ACL class queries Queries sanitized and bound using PDO statement * fix spaces spaces between (int) cast and variables * update file delete spaces after comma * change variables names due to a review * Line exceeds 120 characters; contains 123 characters * fix(conf) fix broker conf name display in listing (#11372) (#11376) Co-authored-by: Elmahdi ABBASSI <108519266+emabassi-ext@users.noreply.github.com> Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> Co-authored-by: Nouha-ElAbrouki <97687698+Noha-ElAbrouki@users.noreply.github.com> Co-authored-by: Kevin Duret Co-authored-by: hyahiaoui-ext <97593234+hyahiaoui-ext@users.noreply.github.com> Co-authored-by: Tom Darneix Co-authored-by: alaunois * fix(cron): Escape database name in CentACL 22.04.x (#11510) * fix(test): wait 8s before checking downtime is active in rest api v1 test (#11498) (#11504) Refs: MON-14585 * fix(UI): Include host_id when selecting ServiceGroups on dashreports (#11428) (#11519) Co-authored-by: VHS Co-authored-by: VHS * fix(Resources/Graph): export graph image after selecting png (#11491) * [SNYK] Sanitize and bind ACL host dependency queries (#11389) (#11394) * Sanitize and bind ACL host dependency queries * fix issues * removed old variable userCrypted and the use of it (#11334) (#11352) Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> * enh(Header/userMenu):reduce spacing user menu (#11393) * update user menu * fix(hostgroup): fix display of hostgroups in select2 (#11431) (#11443) * fix(ci): fix debian packaging with freshly instanciated jenkins slave (#11398) (#11399) Refs: MON-14377 * Sanitized and bound queries (#11413) (#11445) lines : 130 -142 * Snyk: Sanitize and bind media sync queries 22.04.x (#11418) * sanitizing and binding sync dir file queries * Applying some fixes * Snyk: Sanitize and bind ACL service dependency queries dev-22.04.x (#11395) * Snyk: Sanitize and bind Auth class queries 22.04.x (#11448) * [Backport/need review] fix(UI): Fix layout for Safari and form validation (#11440) * fix(UI): Fix layout for Safari and form validation (#11373) * Fix form validation * Fix padlock layout for safari * Update centreon-frontend * Remove debug variable * Fix test * Fix page respsoniveness * Rename variable * update deps * Fix package-lock * Fix package-lock * Add debug statement for debian * Install nodejs rather npm * Attempt fix * Attempt to fix nodejs installation * add sudo * Fix redoc-cli usage * Try to fix permission on npm * Fix * Fix permission * Fix permission (please work) * Fix source * Stop using npx because..... * Allow legacy-peer-deps * Remove nodejs installation * Fix image to pull for debian 11 * [SNYK] Sanitize and bind centreonGraph class queries (#11409) (#11421) 1122 1153 1134 * [Snyk] Sanitize and bind ACL action access queries (#11385) (#11402) * Sanitize and bind ACL action access queries _ sanitize if possible each variables inserted in a query _ use PDO prepared statement and bind() method _ Do not use $pearDB->escape on which is for examples useless on integers and on non closed HTML tags (svg, img, etc) * fix line length * fix failed checks * feat(api): implement endpoint to update centreon web (#11391) (#11401) Refs: MON-12296 * Clean(platform): Clean appKey method and usage 22.04.x (#11452) * Clean(platform): Clean appKey method and usage (#11336) * removing appKey from information table in baseConf and 22.10 update script * removing appKey from NotifyMasterService.php * removing appKey from CentreonRemoteServer.php * applying suggested changes * Applying suggested changes Co-authored-by: Kevin Duret * adding 22.04.2 update script file with changes * revert 22.04 beta 1 script to its original Co-authored-by: Kevin Duret * enh(platform): Use API to select metrics in virtual metrics configuration form 22.04.x (#11461) * changing select with select2 of metrics * fix alignement * remove unecessary files and replace selec by select2 in formComponentTemplate * fix select id name for acceptance tests * update composer for acceptance tests * fix acceptance test 2 * add allow clear to metrics select2 * applying suggested changes * final changes for merging * remove unecessary select tag * [SNYK] Sanitize and bind ACL class queries (#11392) (#11472) * Sanitize and bind ACL class queries Queries sanitized and bound using PDO statement * fix spaces spaces between (int) cast and variables * update file delete spaces after comma * change variables names due to a review * Line exceeds 120 characters; contains 123 characters * fix(conf) fix broker conf name display in listing (#11372) (#11376) * fix export graph image after selecting png Co-authored-by: Elmahdi ABBASSI <108519266+emabassi-ext@users.noreply.github.com> Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> Co-authored-by: Kevin Duret Co-authored-by: hyahiaoui-ext <97593234+hyahiaoui-ext@users.noreply.github.com> Co-authored-by: Tom Darneix Co-authored-by: alaunois * Fix(platform): Removing appkey key (#11511) * fix(trap): Removal of the restriction on the uniqueness of the OID of a trap (#11327) Currently, an error appears when we try to save an existing trap because a test is performed on the uniqueness of the OID. This PR aims to remove the restriction on the uniqueness of the OID of a trap. * fix(pendo): correctly set locale when language is detection by browser (#11484) (#11528) * fix(test): fix random fails on virtual metric test (#11523) Refs: MON-14359 * fix(autoload): Add classmap to fix autoload with legacy classes (#11492) (#11532) Refs: MON-14496 * fix(ldap): small refacto of ldap authentication and log failures (#11422) (#11534) Refs: MON-7417 * fix(api): allow api platform updates from installed 22.04.0 (#11495) (#11533) Refs: MON-12296 * fix(api): fix call to api on fresh install (#11536) (#11537) Refs: MON-12296 * doc(ack): acknowledge Hakaï security (#11540) * fix(api): do not init db connection in event subscriber (#11543) (#11545) Refs: MON-12296 * fix(web): fix the comment deletion for host monitored by poller (#11138) (#11556) Refs: MON-12828 Co-authored-by: Stéphane Duret * SNYK: Sanitize and bind ACL actions queries (#11547) * sanitizing and binding acl actions queries * fix missing bind * SNYK: Sanitize and bind Broker listing queries (#11550) * Sanitizing and binding broker listing queries * applying suggested changes * fix(conf) fix encoding in template service listing (#11558) (#11564) * fix encoding * remove useless function * SNYK: Sanitize and bind generateImage queries (#11561) * sanitize and bind generate image queries * adding throw exception * applying suggested changes * Update www/include/views/graphs/generateGraphs/generateImage.php Co-authored-by: Kevin Duret Co-authored-by: Kevin Duret * MON-14501 - sanitize query in centreonXmlbgRequest class (#11570) * sanitize query in centreonXmlbgRequest class * add closeCursor func to resolve conv * SNYK: Sanitize and bind Meta-Services dependency queries (#11567) * sanityze 2 insert queries * spaces removed in a query * chore(release):rebase dev-22.04.x on 22.04.x (#11627) * Merge release-22.04.3 into 22.04.x (#11623) * fix(git): resync 22.04.x to dev-22.04.x (#11503) * [SNYK] Sanitize and bind ACL host dependency queries (#11389) (#11394) * Sanitize and bind ACL host dependency queries * fix issues * removed old variable userCrypted and the use of it (#11334) (#11352) Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> * enh(Header/userMenu):reduce spacing user menu (#11393) * update user menu * fix(hostgroup): fix display of hostgroups in select2 (#11431) (#11443) * fix(ci): fix debian packaging with freshly instanciated jenkins slave (#11398) (#11399) Refs: MON-14377 * Sanitized and bound queries (#11413) (#11445) lines : 130 -142 * Snyk: Sanitize and bind media sync queries 22.04.x (#11418) * sanitizing and binding sync dir file queries * Applying some fixes * Snyk: Sanitize and bind ACL service dependency queries dev-22.04.x (#11395) * Snyk: Sanitize and bind Auth class queries 22.04.x (#11448) * [Backport/need review] fix(UI): Fix layout for Safari and form validation (#11440) * fix(UI): Fix layout for Safari and form validation (#11373) * Fix form validation * Fix padlock layout for safari * Update centreon-frontend * Remove debug variable * Fix test * Fix page respsoniveness * Rename variable * update deps * Fix package-lock * Fix package-lock * Add debug statement for debian * Install nodejs rather npm * Attempt fix * Attempt to fix nodejs installation * add sudo * Fix redoc-cli usage * Try to fix permission on npm * Fix * Fix permission * Fix permission (please work) * Fix source * Stop using npx because..... * Allow legacy-peer-deps * Remove nodejs installation * Fix image to pull for debian 11 * [SNYK] Sanitize and bind centreonGraph class queries (#11409) (#11421) 1122 1153 1134 * [Snyk] Sanitize and bind ACL action access queries (#11385) (#11402) * Sanitize and bind ACL action access queries _ sanitize if possible each variables inserted in a query _ use PDO prepared statement and bind() method _ Do not use $pearDB->escape on which is for examples useless on integers and on non closed HTML tags (svg, img, etc) * fix line length * fix failed checks * feat(api): implement endpoint to update centreon web (#11391) (#11401) Refs: MON-12296 * Clean(platform): Clean appKey method and usage 22.04.x (#11452) * Clean(platform): Clean appKey method and usage (#11336) * removing appKey from information table in baseConf and 22.10 update script * removing appKey from NotifyMasterService.php * removing appKey from CentreonRemoteServer.php * applying suggested changes * Applying suggested changes Co-authored-by: Kevin Duret * adding 22.04.2 update script file with changes * revert 22.04 beta 1 script to its original Co-authored-by: Kevin Duret * enh(platform): Use API to select metrics in virtual metrics configuration form 22.04.x (#11461) * changing select with select2 of metrics * fix alignement * remove unecessary files and replace selec by select2 in formComponentTemplate * fix select id name for acceptance tests * update composer for acceptance tests * fix acceptance test 2 * add allow clear to metrics select2 * applying suggested changes * final changes for merging * remove unecessary select tag * [SNYK] Sanitize and bind ACL class queries (#11392) (#11472) * Sanitize and bind ACL class queries Queries sanitized and bound using PDO statement * fix spaces spaces between (int) cast and variables * update file delete spaces after comma * change variables names due to a review * Line exceeds 120 characters; contains 123 characters * fix(conf) fix broker conf name display in listing (#11372) (#11376) Co-authored-by: Elmahdi ABBASSI <108519266+emabassi-ext@users.noreply.github.com> Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> Co-authored-by: Nouha-ElAbrouki <97687698+Noha-ElAbrouki@users.noreply.github.com> Co-authored-by: Kevin Duret Co-authored-by: hyahiaoui-ext <97593234+hyahiaoui-ext@users.noreply.github.com> Co-authored-by: Tom Darneix Co-authored-by: alaunois * fix(cron): Escape database name in CentACL 22.04.x (#11510) * fix(test): wait 8s before checking downtime is active in rest api v1 test (#11498) (#11504) Refs: MON-14585 * fix(UI): Include host_id when selecting ServiceGroups on dashreports (#11428) (#11519) Co-authored-by: VHS Co-authored-by: VHS * fix(Resources/Graph): export graph image after selecting png (#11491) * [SNYK] Sanitize and bind ACL host dependency queries (#11389) (#11394) * Sanitize and bind ACL host dependency queries * fix issues * removed old variable userCrypted and the use of it (#11334) (#11352) Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> * enh(Header/userMenu):reduce spacing user menu (#11393) * update user menu * fix(hostgroup): fix display of hostgroups in select2 (#11431) (#11443) * fix(ci): fix debian packaging with freshly instanciated jenkins slave (#11398) (#11399) Refs: MON-14377 * Sanitized and bound queries (#11413) (#11445) lines : 130 -142 * Snyk: Sanitize and bind media sync queries 22.04.x (#11418) * sanitizing and binding sync dir file queries * Applying some fixes * Snyk: Sanitize and bind ACL service dependency queries dev-22.04.x (#11395) * Snyk: Sanitize and bind Auth class queries 22.04.x (#11448) * [Backport/need review] fix(UI): Fix layout for Safari and form validation (#11440) * fix(UI): Fix layout for Safari and form validation (#11373) * Fix form validation * Fix padlock layout for safari * Update centreon-frontend * Remove debug variable * Fix test * Fix page respsoniveness * Rename variable * update deps * Fix package-lock * Fix package-lock * Add debug statement for debian * Install nodejs rather npm * Attempt fix * Attempt to fix nodejs installation * add sudo * Fix redoc-cli usage * Try to fix permission on npm * Fix * Fix permission * Fix permission (please work) * Fix source * Stop using npx because..... * Allow legacy-peer-deps * Remove nodejs installation * Fix image to pull for debian 11 * [SNYK] Sanitize and bind centreonGraph class queries (#11409) (#11421) 1122 1153 1134 * [Snyk] Sanitize and bind ACL action access queries (#11385) (#11402) * Sanitize and bind ACL action access queries _ sanitize if possible each variables inserted in a query _ use PDO prepared statement and bind() method _ Do not use $pearDB->escape on which is for examples useless on integers and on non closed HTML tags (svg, img, etc) * fix line length * fix failed checks * feat(api): implement endpoint to update centreon web (#11391) (#11401) Refs: MON-12296 * Clean(platform): Clean appKey method and usage 22.04.x (#11452) * Clean(platform): Clean appKey method and usage (#11336) * removing appKey from information table in baseConf and 22.10 update script * removing appKey from NotifyMasterService.php * removing appKey from CentreonRemoteServer.php * applying suggested changes * Applying suggested changes Co-authored-by: Kevin Duret * adding 22.04.2 update script file with changes * revert 22.04 beta 1 script to its original Co-authored-by: Kevin Duret * enh(platform): Use API to select metrics in virtual metrics configuration form 22.04.x (#11461) * changing select with select2 of metrics * fix alignement * remove unecessary files and replace selec by select2 in formComponentTemplate * fix select id name for acceptance tests * update composer for acceptance tests * fix acceptance test 2 * add allow clear to metrics select2 * applying suggested changes * final changes for merging * remove unecessary select tag * [SNYK] Sanitize and bind ACL class queries (#11392) (#11472) * Sanitize and bind ACL class queries Queries sanitized and bound using PDO statement * fix spaces spaces between (int) cast and variables * update file delete spaces after comma * change variables names due to a review * Line exceeds 120 characters; contains 123 characters * fix(conf) fix broker conf name display in listing (#11372) (#11376) * fix export graph image after selecting png Co-authored-by: Elmahdi ABBASSI <108519266+emabassi-ext@users.noreply.github.com> Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> Co-authored-by: Kevin Duret Co-authored-by: hyahiaoui-ext <97593234+hyahiaoui-ext@users.noreply.github.com> Co-authored-by: Tom Darneix Co-authored-by: alaunois * Fix(platform): Removing appkey key (#11511) * fix(trap): Removal of the restriction on the uniqueness of the OID of a trap (#11327) Currently, an error appears when we try to save an existing trap because a test is performed on the uniqueness of the OID. This PR aims to remove the restriction on the uniqueness of the OID of a trap. * fix(pendo): correctly set locale when language is detection by browser (#11484) (#11528) * fix(test): fix random fails on virtual metric test (#11523) Refs: MON-14359 * fix(autoload): Add classmap to fix autoload with legacy classes (#11492) (#11532) Refs: MON-14496 * fix(ldap): small refacto of ldap authentication and log failures (#11422) (#11534) Refs: MON-7417 * fix(api): allow api platform updates from installed 22.04.0 (#11495) (#11533) Refs: MON-12296 * fix(api): fix call to api on fresh install (#11536) (#11537) Refs: MON-12296 * doc(ack): acknowledge Hakaï security (#11540) * fix(api): do not init db connection in event subscriber (#11543) (#11545) Refs: MON-12296 * fix(web): fix the comment deletion for host monitored by poller (#11138) (#11556) Refs: MON-12828 Co-authored-by: Stéphane Duret * SNYK: Sanitize and bind ACL actions queries (#11547) * sanitizing and binding acl actions queries * fix missing bind * SNYK: Sanitize and bind Broker listing queries (#11550) * Sanitizing and binding broker listing queries * applying suggested changes * fix(conf) fix encoding in template service listing (#11558) (#11564) * fix encoding * remove useless function * SNYK: Sanitize and bind generateImage queries (#11561) * sanitize and bind generate image queries * adding throw exception * applying suggested changes * Update www/include/views/graphs/generateGraphs/generateImage.php Co-authored-by: Kevin Duret Co-authored-by: Kevin Duret * MON-14501 - sanitize query in centreonXmlbgRequest class (#11570) * sanitize query in centreonXmlbgRequest class * add closeCursor func to resolve conv * SNYK: Sanitize and bind Meta-Services dependency queries (#11567) * sanityze 2 insert queries * spaces removed in a query * chore(install):Update version to 22.04.3 * fix(sql): fix query to select contact during ldap import (#11578) Refs: MON-14263 * fix(UI): Fix layout for Safari and form validation (#11373) (#11604) * Fix form validation * Fix padlock layout for safari * Update centreon-frontend * Remove debug variable * Fix test * Fix page respsoniveness * Rename variable * update deps * Fix package-lock Co-authored-by: Elmahdi ABBASSI <108519266+emabassi-ext@users.noreply.github.com> Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> Co-authored-by: Nouha-ElAbrouki <97687698+Noha-ElAbrouki@users.noreply.github.com> Co-authored-by: Kevin Duret Co-authored-by: hyahiaoui-ext <97593234+hyahiaoui-ext@users.noreply.github.com> Co-authored-by: Tom Darneix Co-authored-by: alaunois Co-authored-by: VHS Co-authored-by: Laurent Calvet Co-authored-by: Stéphane Chapron <34628915+sc979@users.noreply.github.com> Co-authored-by: Stéphane Duret * fix(api): fix call to api on fresh install (#11536) (#11537) Refs: MON-12296 * fix(api): do not init db connection in event subscriber (#11543) (#11545) Refs: MON-12296 Co-authored-by: Elmahdi ABBASSI <108519266+emabassi-ext@users.noreply.github.com> Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> Co-authored-by: Nouha-ElAbrouki <97687698+Noha-ElAbrouki@users.noreply.github.com> Co-authored-by: Kevin Duret Co-authored-by: hyahiaoui-ext <97593234+hyahiaoui-ext@users.noreply.github.com> Co-authored-by: Tom Darneix Co-authored-by: alaunois Co-authored-by: VHS Co-authored-by: Laurent Calvet Co-authored-by: Stéphane Chapron <34628915+sc979@users.noreply.github.com> Co-authored-by: Stéphane Duret * fix(partition): adapt control of database version (#11609) (#11610) * fix(openid): correctly set contact_location while creating session (#11613) (#11614) * fix(lang): Fixed FR typo (#11621) * enh(UI): Add a “Parent alias“ column on the monitoring resources sta… (#11542) * enh(UI): Add a “Parent alias“ column on the monitoring resources status page (#11190) * Add column ParentAlias * Add new label ParentAlias * Add column ParentAlias and new column component * Add new card to display Parent Alias * Remove tile in Details Panel, enhancement not expected * FIx eslint issue * Fix naming on label parent alias * Add translation * Add line at the end of files * Add line at the end of file * fix issues * Update lang/fr_FR.UTF-8/LC_MESSAGES/messages.po Co-authored-by: Tom Darneix * Update lang/es_ES.UTF-8/LC_MESSAGES/messages.po Co-authored-by: Tom Darneix * Update lang/pt_PT.UTF-8/LC_MESSAGES/messages.po Co-authored-by: Tom Darneix * Update lang/es_ES.UTF-8/LC_MESSAGES/messages.po Co-authored-by: Jérémy Delpierre * Update lang/pt_BR.UTF-8/LC_MESSAGES/messages.po Co-authored-by: Jérémy Delpierre * Update lang/fr_FR.UTF-8/LC_MESSAGES/messages.po Co-authored-by: Bruno d'Auria * Fix issue on messages.po file Co-authored-by: Tom Darneix Co-authored-by: Jérémy Delpierre Co-authored-by: Bruno d'Auria * query sanitized in listServiceCategoriesà (#11597) (#11632) * MON-14797 reorganizes dependencies (#11612) * Fix encoding issue on status serviceXML (#11581) * sanitize and bind in centreon connector query (#11635) * sanitize insrert queries in db-func (#11650) MON-14667 * chore(git): update codeowners (#11594) * chore(release):rebase dev-22.04.x on 22.04.x (#11688) * Merge release-22.04.3 into 22.04.x (#11623) * fix(git): resync 22.04.x to dev-22.04.x (#11503) * [SNYK] Sanitize and bind ACL host dependency queries (#11389) (#11394) * Sanitize and bind ACL host dependency queries * fix issues * removed old variable userCrypted and the use of it (#11334) (#11352) Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> * enh(Header/userMenu):reduce spacing user menu (#11393) * update user menu * fix(hostgroup): fix display of hostgroups in select2 (#11431) (#11443) * fix(ci): fix debian packaging with freshly instanciated jenkins slave (#11398) (#11399) Refs: MON-14377 * Sanitized and bound queries (#11413) (#11445) lines : 130 -142 * Snyk: Sanitize and bind media sync queries 22.04.x (#11418) * sanitizing and binding sync dir file queries * Applying some fixes * Snyk: Sanitize and bind ACL service dependency queries dev-22.04.x (#11395) * Snyk: Sanitize and bind Auth class queries 22.04.x (#11448) * [Backport/need review] fix(UI): Fix layout for Safari and form validation (#11440) * fix(UI): Fix layout for Safari and form validation (#11373) * Fix form validation * Fix padlock layout for safari * Update centreon-frontend * Remove debug variable * Fix test * Fix page respsoniveness * Rename variable * update deps * Fix package-lock * Fix package-lock * Add debug statement for debian * Install nodejs rather npm * Attempt fix * Attempt to fix nodejs installation * add sudo * Fix redoc-cli usage * Try to fix permission on npm * Fix * Fix permission * Fix permission (please work) * Fix source * Stop using npx because..... * Allow legacy-peer-deps * Remove nodejs installation * Fix image to pull for debian 11 * [SNYK] Sanitize and bind centreonGraph class queries (#11409) (#11421) 1122 1153 1134 * [Snyk] Sanitize and bind ACL action access queries (#11385) (#11402) * Sanitize and bind ACL action access queries _ sanitize if possible each variables inserted in a query _ use PDO prepared statement and bind() method _ Do not use $pearDB->escape on which is for examples useless on integers and on non closed HTML tags (svg, img, etc) * fix line length * fix failed checks * feat(api): implement endpoint to update centreon web (#11391) (#11401) Refs: MON-12296 * Clean(platform): Clean appKey method and usage 22.04.x (#11452) * Clean(platform): Clean appKey method and usage (#11336) * removing appKey from information table in baseConf and 22.10 update script * removing appKey from NotifyMasterService.php * removing appKey from CentreonRemoteServer.php * applying suggested changes * Applying suggested changes Co-authored-by: Kevin Duret * adding 22.04.2 update script file with changes * revert 22.04 beta 1 script to its original Co-authored-by: Kevin Duret * enh(platform): Use API to select metrics in virtual metrics configuration form 22.04.x (#11461) * changing select with select2 of metrics * fix alignement * remove unecessary files and replace selec by select2 in formComponentTemplate * fix select id name for acceptance tests * update composer for acceptance tests * fix acceptance test 2 * add allow clear to metrics select2 * applying suggested changes * final changes for merging * remove unecessary select tag * [SNYK] Sanitize and bind ACL class queries (#11392) (#11472) * Sanitize and bind ACL class queries Queries sanitized and bound using PDO statement * fix spaces spaces between (int) cast and variables * update file delete spaces after comma * change variables names due to a review * Line exceeds 120 characters; contains 123 characters * fix(conf) fix broker conf name display in listing (#11372) (#11376) Co-authored-by: Elmahdi ABBASSI <108519266+emabassi-ext@users.noreply.github.com> Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> Co-authored-by: Nouha-ElAbrouki <97687698+Noha-ElAbrouki@users.noreply.github.com> Co-authored-by: Kevin Duret Co-authored-by: hyahiaoui-ext <97593234+hyahiaoui-ext@users.noreply.github.com> Co-authored-by: Tom Darneix Co-authored-by: alaunois * fix(cron): Escape database name in CentACL 22.04.x (#11510) * fix(test): wait 8s before checking downtime is active in rest api v1 test (#11498) (#11504) Refs: MON-14585 * fix(UI): Include host_id when selecting ServiceGroups on dashreports (#11428) (#11519) Co-authored-by: VHS Co-authored-by: VHS * fix(Resources/Graph): export graph image after selecting png (#11491) * [SNYK] Sanitize and bind ACL host dependency queries (#11389) (#11394) * Sanitize and bind ACL host dependency queries * fix issues * removed old variable userCrypted and the use of it (#11334) (#11352) Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> * enh(Header/userMenu):reduce spacing user menu (#11393) * update user menu * fix(hostgroup): fix display of hostgroups in select2 (#11431) (#11443) * fix(ci): fix debian packaging with freshly instanciated jenkins slave (#11398) (#11399) Refs: MON-14377 * Sanitized and bound queries (#11413) (#11445) lines : 130 -142 * Snyk: Sanitize and bind media sync queries 22.04.x (#11418) * sanitizing and binding sync dir file queries * Applying some fixes * Snyk: Sanitize and bind ACL service dependency queries dev-22.04.x (#11395) * Snyk: Sanitize and bind Auth class queries 22.04.x (#11448) * [Backport/need review] fix(UI): Fix layout for Safari and form validation (#11440) * fix(UI): Fix layout for Safari and form validation (#11373) * Fix form validation * Fix padlock layout for safari * Update centreon-frontend * Remove debug variable * Fix test * Fix page respsoniveness * Rename variable * update deps * Fix package-lock * Fix package-lock * Add debug statement for debian * Install nodejs rather npm * Attempt fix * Attempt to fix nodejs installation * add sudo * Fix redoc-cli usage * Try to fix permission on npm * Fix * Fix permission * Fix permission (please work) * Fix source * Stop using npx because..... * Allow legacy-peer-deps * Remove nodejs installation * Fix image to pull for debian 11 * [SNYK] Sanitize and bind centreonGraph class queries (#11409) (#11421) 1122 1153 1134 * [Snyk] Sanitize and bind ACL action access queries (#11385) (#11402) * Sanitize and bind ACL action access queries _ sanitize if possible each variables inserted in a query _ use PDO prepared statement and bind() method _ Do not use $pearDB->escape on which is for examples useless on integers and on non closed HTML tags (svg, img, etc) * fix line length * fix failed checks * feat(api): implement endpoint to update centreon web (#11391) (#11401) Refs: MON-12296 * Clean(platform): Clean appKey method and usage 22.04.x (#11452) * Clean(platform): Clean appKey method and usage (#11336) * removing appKey from information table in baseConf and 22.10 update script * removing appKey from NotifyMasterService.php * removing appKey from CentreonRemoteServer.php * applying suggested changes * Applying suggested changes Co-authored-by: Kevin Duret * adding 22.04.2 update script file with changes * revert 22.04 beta 1 script to its original Co-authored-by: Kevin Duret * enh(platform): Use API to select metrics in virtual metrics configuration form 22.04.x (#11461) * changing select with select2 of metrics * fix alignement * remove unecessary files and replace selec by select2 in formComponentTemplate * fix select id name for acceptance tests * update composer for acceptance tests * fix acceptance test 2 * add allow clear to metrics select2 * applying suggested changes * final changes for merging * remove unecessary select tag * [SNYK] Sanitize and bind ACL class queries (#11392) (#11472) * Sanitize and bind ACL class queries Queries sanitized and bound using PDO statement * fix spaces spaces between (int) cast and variables * update file delete spaces after comma * change variables names due to a review * Line exceeds 120 characters; contains 123 characters * fix(conf) fix broker conf name display in listing (#11372) (#11376) * fix export graph image after selecting png Co-authored-by: Elmahdi ABBASSI <108519266+emabassi-ext@users.noreply.github.com> Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> Co-authored-by: Kevin Duret Co-authored-by: hyahiaoui-ext <97593234+hyahiaoui-ext@users.noreply.github.com> Co-authored-by: Tom Darneix Co-authored-by: alaunois * Fix(platform): Removing appkey key (#11511) * fix(trap): Removal of the restriction on the uniqueness of the OID of a trap (#11327) Currently, an error appears when we try to save an existing trap because a test is performed on the uniqueness of the OID. This PR aims to remove the restriction on the uniqueness of the OID of a trap. * fix(pendo): correctly set locale when language is detection by browser (#11484) (#11528) * fix(test): fix random fails on virtual metric test (#11523) Refs: MON-14359 * fix(autoload): Add classmap to fix autoload with legacy classes (#11492) (#11532) Refs: MON-14496 * fix(ldap): small refacto of ldap authentication and log failures (#11422) (#11534) Refs: MON-7417 * fix(api): allow api platform updates from installed 22.04.0 (#11495) (#11533) Refs: MON-12296 * fix(api): fix call to api on fresh install (#11536) (#11537) Refs: MON-12296 * doc(ack): acknowledge Hakaï security (#11540) * fix(api): do not init db connection in event subscriber (#11543) (#11545) Refs: MON-12296 * fix(web): fix the comment deletion for host monitored by poller (#11138) (#11556) Refs: MON-12828 Co-authored-by: Stéphane Duret * SNYK: Sanitize and bind ACL actions queries (#11547) * sanitizing and binding acl actions queries * fix missing bind * SNYK: Sanitize and bind Broker listing queries (#11550) * Sanitizing and binding broker listing queries * applying suggested changes * fix(conf) fix encoding in template service listing (#11558) (#11564) * fix encoding * remove useless function * SNYK: Sanitize and bind generateImage queries (#11561) * sanitize and bind generate image queries * adding throw exception * applying suggested changes * Update www/include/views/graphs/generateGraphs/generateImage.php Co-authored-by: Kevin Duret Co-authored-by: Kevin Duret * MON-14501 - sanitize query in centreonXmlbgRequest class (#11570) * sanitize query in centreonXmlbgRequest class * add closeCursor func to resolve conv * SNYK: Sanitize and bind Meta-Services dependency queries (#11567) * sanityze 2 insert queries * spaces removed in a query * chore(install):Update version to 22.04.3 * fix(sql): fix query to select contact during ldap import (#11578) Refs: MON-14263 * fix(UI): Fix layout for Safari and form validation (#11373) (#11604) * Fix form validation * Fix padlock layout for safari * Update centreon-frontend * Remove debug variable * Fix test * Fix page respsoniveness * Rename variable * update deps * Fix package-lock Co-authored-by: Elmahdi ABBASSI <108519266+emabassi-ext@users.noreply.github.com> Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> Co-authored-by: Nouha-ElAbrouki <97687698+Noha-ElAbrouki@users.noreply.github.com> Co-authored-by: Kevin Duret Co-authored-by: hyahiaoui-ext <97593234+hyahiaoui-ext@users.noreply.github.com> Co-authored-by: Tom Darneix Co-authored-by: alaunois Co-authored-by: VHS Co-authored-by: Laurent Calvet Co-authored-by: Stéphane Chapron <34628915+sc979@users.noreply.github.com> Co-authored-by: Stéphane Duret * chore(release): merge hotfix-MON-14893-index-data (#11681) * fix(upgrade): Correctly Parse SQL Comments (#11658) (#11668) Refs: MON-14848 Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> * fix invalid values for index_data.special (#11669) * chore(install):update version to 22.04.4 Co-authored-by: Kevin Duret Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> * fix(api): fix call to api on fresh install (#11536) (#11537) Refs: MON-12296 * fix(api): do not init db connection in event subscriber (#11543) (#11545) Refs: MON-12296 * fix(partition): adapt control of database version (#11609) (#11610) * fix(openid): correctly set contact_location while creating session (#11613) (#11614) * fix(lang): Fixed FR typo (#11621) * enh(UI): Add a “Parent alias“ column on the monitoring resources sta… (#11542) * enh(UI): Add a “Parent alias“ column on the monitoring resources status page (#11190) * Add column ParentAlias * Add new label ParentAlias * Add column ParentAlias and new column component * Add new card to display Parent Alias * Remove tile in Details Panel, enhancement not expected * FIx eslint issue * Fix naming on label parent alias * Add translation * Add line at the end of files * Add line at the end of file * fix issues * Update lang/fr_FR.UTF-8/LC_MESSAGES/messages.po Co-authored-by: Tom Darneix * Update lang/es_ES.UTF-8/LC_MESSAGES/messages.po Co-authored-by: Tom Darneix * Update lang/pt_PT.UTF-8/LC_MESSAGES/messages.po Co-authored-by: Tom Darneix * Update lang/es_ES.UTF-8/LC_MESSAGES/messages.po Co-authored-by: Jérémy Delpierre * Update lang/pt_BR.UTF-8/LC_MESSAGES/messages.po Co-authored-by: Jérémy Delpierre * Update lang/fr_FR.UTF-8/LC_MESSAGES/messages.po Co-authored-by: Bruno d'Auria * Fix issue on messages.po file Co-authored-by: Tom Darneix Co-authored-by: Jérémy Delpierre Co-authored-by: Bruno d'Auria * query sanitized in listServiceCategoriesà (#11597) (#11632) * MON-14797 reorganizes dependencies (#11612) * Fix encoding issue on status serviceXML (#11581) * sanitize and bind in centreon connector query (#11635) * sanitize insrert queries in db-func (#11650) MON-14667 Co-authored-by: Elmahdi ABBASSI <108519266+emabassi-ext@users.noreply.github.com> Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> Co-authored-by: Nouha-ElAbrouki <97687698+Noha-ElAbrouki@users.noreply.github.com> Co-authored-by: Kevin Duret Co-authored-by: hyahiaoui-ext <97593234+hyahiaoui-ext@users.noreply.github.com> Co-authored-by: Tom Darneix Co-authored-by: alaunois Co-authored-by: VHS Co-authored-by: Laurent Calvet Co-authored-by: Stéphane Chapron <34628915+sc979@users.noreply.github.com> Co-authored-by: Stéphane Duret Co-authored-by: Laurent Pinsivy Co-authored-by: jcaro Co-authored-by: Jérémy Delpierre Co-authored-by: Bruno d'Auria Co-authored-by: Luiz Costa Co-authored-by: TamazC <103252125+TamazC@users.noreply.github.com> * fix(details): remove dead code (#11672) (#11686) * fix(conf) fix parent template display in service template listing (#11671) (#11676) * fix(poller): fix remote server duplication (#11552) (#11674) * fix(poller): fix remote server duplication (#11552) Refs: MON-14579 Co-authored-by: Jérémy Jaouen * fix translation for host and service category (#11626) * fix(clapi): Check that user is admin to use clapi (#11631) (#11640) * Sanitized and bound queries in service argumentsXml fil (#11653) MON-14669 * Sanitize and bind listVirtualMetrics queries (#11647) * sanitize and bind host categories queries (#11645) * Ãbind queries an fix array binding(#11656) * fix(ui): fix svg display in legacy monitoring pages (#11659) (#11690) Refs: MON-14869 * Sanitize and bind service group dependecies queries 22.04.x (#11665) * MON-14425 fix centreon.ini and autoconfigure timezone (#11608) * enh(Resources/header): Display the 2 access pictograms logs and report on details panel (#11618) * Display the 2 access pictograms logs and report on details panel * Update www/front_src/src/Resources/Details/Header.tsx Co-authored-by: JKancel * Update www/front_src/src/Resources/Details/Header.tsx Co-authored-by: JKancel Co-authored-by: JKancel * fix(resource-status): add missing alias to Host detail factory (#11642) * fix(widgets): retrieve possibility to not select poller in pref (#11696) (#11698) Refs: MON-14919 * fix(install): fix source install with quiet mode related to gorgone vars (#11694) (#11701) Refs: MON-14806 Co-authored-by: Eric Coquard * Fix: In Acces group the second select not working [ACL] 22.04.x (#11709) * fix second select not working * applying suggested changes * fix(details): second part of code cleanup for "tools" (#11718) (#11721) * fix (#11724) * FIX: Sanitize and bind graph configuration queries 22.04.x (#11729) * [Fix]:Sanitize and bind queries in template of service listing (#11746) * [Fix]:Sanitize and bind queries in template of service listing * work on tamazC suggestion * fix(resource): Fix bad SQL request (#11702) (#11749) * FIX: Sanitize and bind Meta Service configuration 22.04.x (#11733) * sanitize and bind meta service config * applying suggested changes * Fix: Sanitize and bind CLAPI poller configuration 22.04.x (#11731) * sanitize and bind CLAPI poller config * remove unecessary comment * revert deleted imports * FIX: Sanitize and bind command configuration queries 22.04.x (#11754) * fix(partition): fix condition for database version (#11657) (#11756) Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> * Rebase dev2204x on 2204x (#11824) * Merge release-22.04.3 into 22.04.x (#11623) * fix(git): resync 22.04.x to dev-22.04.x (#11503) * [SNYK] Sanitize and bind ACL host dependency queries (#11389) (#11394) * Sanitize and bind ACL host dependency queries * fix issues * removed old variable userCrypted and the use of it (#11334) (#11352) Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> * enh(Header/userMenu):reduce spacing user menu (#11393) * update user menu * fix(hostgroup): fix display of hostgroups in select2 (#11431) (#11443) * fix(ci): fix debian packaging with freshly instanciated jenkins slave (#11398) (#11399) Refs: MON-14377 * Sanitized and bound queries (#11413) (#11445) lines : 130 -142 * Snyk: Sanitize and bind media sync queries 22.04.x (#11418) * sanitizing and binding sync dir file queries * Applying some fixes * Snyk: Sanitize and bind ACL service dependency queries dev-22.04.x (#11395) * Snyk: Sanitize and bind Auth class queries 22.04.x (#11448) * [Backport/need review] fix(UI): Fix layout for Safari and form validation (#11440) * fix(UI): Fix layout for Safari and form validation (#11373) * Fix form validation * Fix padlock layout for safari * Update centreon-frontend * Remove debug variable * Fix test * Fix page respsoniveness * Rename variable * update deps * Fix package-lock * Fix package-lock * Add debug statement for debian * Install nodejs rather npm * Attempt fix * Attempt to fix nodejs installation * add sudo * Fix redoc-cli usage * Try to fix permission on npm * Fix * Fix permission * Fix permission (please work) * Fix source * Stop using npx because..... * Allow legacy-peer-deps * Remove nodejs installation * Fix image to pull for debian 11 * [SNYK] Sanitize and bind centreonGraph class queries (#11409) (#11421) 1122 1153 1134 * [Snyk] Sanitize and bind ACL action access queries (#11385) (#11402) * Sanitize and bind ACL action access queries _ sanitize if possible each variables inserted in a query _ use PDO prepared statement and bind() method _ Do not use $pearDB->escape on which is for examples useless on integers and on non closed HTML tags (svg, img, etc) * fix line length * fix failed checks * feat(api): implement endpoint to update centreon web (#11391) (#11401) Refs: MON-12296 * Clean(platform): Clean appKey method and usage 22.04.x (#11452) * Clean(platform): Clean appKey method and usage (#11336) * removing appKey from information table in baseConf and 22.10 update script * removing appKey from NotifyMasterService.php * removing appKey from CentreonRemoteServer.php * applying suggested changes * Applying suggested changes Co-authored-by: Kevin Duret * adding 22.04.2 update script file with changes * revert 22.04 beta 1 script to its original Co-authored-by: Kevin Duret * enh(platform): Use API to select metrics in virtual metrics configuration form 22.04.x (#11461) * changing select with select2 of metrics * fix alignement * remove unecessary files and replace selec by select2 in formComponentTemplate * fix select id name for acceptance tests * update composer for acceptance tests * fix acceptance test 2 * add allow clear to metrics select2 * applying suggested changes * final changes for merging * remove unecessary select tag * [SNYK] Sanitize and bind ACL class queries (#11392) (#11472) * Sanitize and bind ACL class queries Queries sanitized and bound using PDO statement * fix spaces spaces between (int) cast and variables * update file delete spaces after comma * change variables names due to a review * Line exceeds 120 characters; contains 123 characters * fix(conf) fix broker conf name display in listing (#11372) (#11376) Co-authored-by: Elmahdi ABBASSI <108519266+emabassi-ext@users.noreply.github.com> Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> Co-authored-by: Nouha-ElAbrouki <97687698+Noha-ElAbrouki@users.noreply.github.com> Co-authored-by: Kevin Duret Co-authored-by: hyahiaoui-ext <97593234+hyahiaoui-ext@users.noreply.github.com> Co-authored-by: Tom Darneix Co-authored-by: alaunois * fix(cron): Escape database name in CentACL 22.04.x (#11510) * fix(test): wait 8s before checking downtime is active in rest api v1 test (#11498) (#11504) Refs: MON-14585 * fix(UI): Include host_id when selecting ServiceGroups on dashreports (#11428) (#11519) Co-authored-by: VHS Co-authored-by: VHS * fix(Resources/Graph): export graph image after selecting png (#11491) * [SNYK] Sanitize and bind ACL host dependency queries (#11389) (#11394) * Sanitize and bind ACL host dependency queries * fix issues * removed old variable userCrypted and the use of it (#11334) (#11352) Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> * enh(Header/userMenu):reduce spacing user menu (#11393) * update user menu * fix(hostgroup): fix display of hostgroups in select2 (#11431) (#11443) * fix(ci): fix debian packaging with freshly instanciated jenkins slave (#11398) (#11399) Refs: MON-14377 * Sanitized and bound queries (#11413) (#11445) lines : 130 -142 * Snyk: Sanitize and bind media sync queries 22.04.x (#11418) * sanitizing and binding sync dir file queries * Applying some fixes * Snyk: Sanitize and bind ACL service dependency queries dev-22.04.x (#11395) * Snyk: Sanitize and bind Auth class queries 22.04.x (#11448) * [Backport/need review] fix(UI): Fix layout for Safari and form validation (#11440) * fix(UI): Fix layout for Safari and form validation (#11373) * Fix form validation * Fix padlock layout for safari * Update centreon-frontend * Remove debug variable * Fix test * Fix page respsoniveness * Rename variable * update deps * Fix package-lock * Fix package-lock * Add debug statement for debian * Install nodejs rather npm * Attempt fix * Attempt to fix nodejs installation * add sudo * Fix redoc-cli usage * Try to fix permission on npm * Fix * Fix permission * Fix permission (please work) * Fix source * Stop using npx because..... * Allow legacy-peer-deps * Remove nodejs installation * Fix image to pull for debian 11 * [SNYK] Sanitize and bind centreonGraph class queries (#11409) (#11421) 1122 1153 1134 * [Snyk] Sanitize and bind ACL action access queries (#11385) (#11402) * Sanitize and bind ACL action access queries _ sanitize if possible each variables inserted in a query _ use PDO prepared statement and bind() method _ Do not use $pearDB->escape on which is for examples useless on integers and on non closed HTML tags (svg, img, etc) * fix line length * fix failed checks * feat(api): implement endpoint to update centreon web (#11391) (#11401) Refs: MON-12296 * Clean(platform): Clean appKey method and usage 22.04.x (#11452) * Clean(platform): Clean appKey method and usage (#11336) * removing appKey from information table in baseConf and 22.10 update script * removing appKey from NotifyMasterService.php * removing appKey from CentreonRemoteServer.php * applying suggested changes * Applying suggested changes Co-authored-by: Kevin Duret * adding 22.04.2 update script file with changes * revert 22.04 beta 1 script to its original Co-authored-by: Kevin Duret * enh(platform): Use API to select metrics in virtual metrics configuration form 22.04.x (#11461) * changing select with select2 of metrics * fix alignement * remove unecessary files and replace selec by select2 in formComponentTemplate * fix select id name for acceptance tests * update composer for acceptance tests * fix acceptance test 2 * add allow clear to metrics select2 * applying suggested changes * final changes for merging * remove unecessary select tag * [SNYK] Sanitize and bind ACL class queries (#11392) (#11472) * Sanitize and bind ACL class queries Queries sanitized and bound using PDO statement * fix spaces spaces between (int) cast and variables * update file delete spaces after comma * change variables names due to a review * Line exceeds 120 characters; contains 123 characters * fix(conf) fix broker conf name display in listing (#11372) (#11376) * fix export graph image after selecting png Co-authored-by: Elmahdi ABBASSI <108519266+emabassi-ext@users.noreply.github.com> Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> Co-authored-by: Kevin Duret Co-authored-by: hyahiaoui-ext <97593234+hyahiaoui-ext@users.noreply.github.com> Co-authored-by: Tom Darneix Co-authored-by: alaunois * Fix(platform): Removing appkey key (#11511) * fix(trap): Removal of the restriction on the uniqueness of the OID of a trap (#11327) Currently, an error appears when we try to save an existing trap because a test is performed on the uniqueness of the OID. This PR aims to remove the restriction on the uniqueness of the OID of a trap. * fix(pendo): correctly set locale when language is detection by browser (#11484) (#11528) * fix(test): fix random fails on virtual metric test (#11523) Refs: MON-14359 * fix(autoload): Add classmap to fix autoload with legacy classes (#11492) (#11532) Refs: MON-14496 * fix(ldap): small refacto of ldap authentication and log failures (#11422) (#11534) Refs: MON-7417 * fix(api): allow api platform updates from installed 22.04.0 (#11495) (#11533) Refs: MON-12296 * fix(api): fix call to api on fresh install (#11536) (#11537) Refs: MON-12296 * doc(ack): acknowledge Hakaï security (#11540) * fix(api): do not init db connection in event subscriber (#11543) (#11545) Refs: MON-12296 * fix(web): fix the comment deletion for host monitored by poller (#11138) (#11556) Refs: MON-12828 Co-authored-by: Stéphane Duret * SNYK: Sanitize and bind ACL actions queries (#11547) * sanitizing and binding acl actions queries * fix missing bind * SNYK: Sanitize and bind Broker listing queries (#11550) * Sanitizing and binding broker listing queries * applying suggested changes * fix(conf) fix encoding in template service listing (#11558) (#11564) * fix encoding * remove useless function * SNYK: Sanitize and bind generateImage queries (#11561) * sanitize and bind generate image queries * adding throw exception * applying suggested changes * Update www/include/views/graphs/generateGraphs/generateImage.php Co-authored-by: Kevin Duret Co-authored-by: Kevin Duret * MON-14501 - sanitize query in centreonXmlbgRequest class (#11570) * sanitize query in centreonXmlbgRequest class * add closeCursor func to resolve conv * SNYK: Sanitize and bind Meta-Services dependency queries (#11567) * sanityze 2 insert queries * spaces removed in a query * chore(install):Update version to 22.04.3 * fix(sql): fix query to select contact during ldap import (#11578) Refs: MON-14263 * fix(UI): Fix layout for Safari and form validation (#11373) (#11604) * Fix form validation * Fix padlock layout for safari * Update centreon-frontend * Remove debug variable * Fix test * Fix page respsoniveness * Rename variable * update deps * Fix package-lock Co-authored-by: Elmahdi ABBASSI <108519266+emabassi-ext@users.noreply.github.com> Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> Co-authored-by: Nouha-ElAbrouki <97687698+Noha-ElAbrouki@users.noreply.github.com> Co-authored-by: Kevin Duret Co-authored-by: hyahiaoui-ext <97593234+hyahiaoui-ext@users.noreply.github.com> Co-authored-by: Tom Darneix Co-authored-by: alaunois Co-authored-by: VHS Co-authored-by: Laurent Calvet Co-authored-by: Stéphane Chapron <34628915+sc979@users.noreply.github.com> Co-authored-by: Stéphane Duret * chore(release): merge hotfix-MON-14893-index-data (#11681) * fix(upgrade): Correctly Parse SQL Comments (#11658) (#11668) Refs: MON-14848 Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> * fix invalid values for index_data.special (#11669) * chore(install):update version to 22.04.4 Co-authored-by: Kevin Duret Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> * chore(release): merge release-22.04.next into 22.04.x (#11821) * fix(git): resync 22.04.x to dev-22.04.x (#11503) * [SNYK] Sanitize and bind ACL host dependency queries (#11389) (#11394) * Sanitize and bind ACL host dependency queries * fix issues * removed old variable userCrypted and the use of it (#11334) (#11352) Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> * enh(Header/userMenu):reduce spacing user menu (#11393) * update user menu * fix(hostgroup): fix display of hostgroups in select2 (#11431) (#11443) * fix(ci): fix debian packaging with freshly instanciated jenkins slave (#11398) (#11399) Refs: MON-14377 * Sanitized and bound queries (#11413) (#11445) lines : 130 -142 * Snyk: Sanitize and bind media sync queries 22.04.x (#11418) * sanitizing and binding sync dir file queries * Applying some fixes * Snyk: Sanitize and bind ACL service dependency queries dev-22.04.x (#11395) * Snyk: Sanitize and bind Auth class queries 22.04.x (#11448) * [Backport/need review] fix(UI): Fix layout for Safari and form validation (#11440) * fix(UI): Fix layout for Safari and form validation (#11373) * Fix form validation * Fix padlock layout for safari * Update centreon-frontend * Remove debug variable * Fix test * Fix page respsoniveness * Rename variable * update deps * Fix package-lock * Fix package-lock * Add debug statement for debian * Install nodejs rather npm * Attempt fix * Attempt to fix nodejs installation * add sudo * Fix redoc-cli usage * Try to fix permission on npm * Fix * Fix permission * Fix permission (please work) * Fix source * Stop using npx because..... * Allow legacy-peer-deps * Remove nodejs installation * Fix image to pull for debian 11 * [SNYK] Sanitize and bind centreonGraph class queries (#11409) (#11421) 1122 1153 1134 * [Snyk] Sanitize and bind ACL action access queries (#11385) (#11402) * Sanitize and bind ACL action access queries _ sanitize if possible each variables inserted in a query _ use PDO prepared statement and bind() method _ Do not use $pearDB->escape on which is for examples useless on integers and on non closed HTML tags (svg, img, etc) * fix line length * fix failed checks * feat(api): implement endpoint to update centreon web (#11391) (#11401) Refs: MON-12296 * Clean(platform): Clean appKey method and usage 22.04.x (#11452) * Clean(platform): Clean appKey method and usage (#11336) * removing appKey from information table in baseConf and 22.10 update script * removing appKey from NotifyMasterService.php * removing appKey from CentreonRemoteServer.php * applying suggested changes * Applying suggested changes Co-authored-by: Kevin Duret * adding 22.04.2 update script file with changes * revert 22.04 beta 1 script to its original Co-authored-by: Kevin Duret * enh(platform): Use API to select metrics in virtual metrics configuration form 22.04.x (#11461) * changing select with select2 of metrics * fix alignement * remove unecessary files and replace selec by select2 in formComponentTemplate * fix select id name for acceptance tests * update composer for acceptance tests * fix acceptance test 2 * add allow clear to metrics select2 * applying suggested changes * final changes for merging * remove unecessary select tag * [SNYK] Sanitize and bind ACL class queries (#11392) (#11472) * Sanitize and bind ACL class queries Queries sanitized and bound using PDO statement * fix spaces spaces between (int) cast and variables * update file delete spaces after comma * change variables names due to a review * Line exceeds 120 characters; contains 123 characters * fix(conf) fix broker conf name display in listing (#11372) (#11376) Co-authored-by: Elmahdi ABBASSI <108519266+emabassi-ext@users.noreply.github.com> Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> Co-authored-by: Nouha-ElAbrouki <97687698+Noha-ElAbrouki@users.noreply.github.com> Co-authored-by: Kevin Duret Co-authored-by: hyahiaoui-ext <97593234+hyahiaoui-ext@users.noreply.github.com> Co-authored-by: Tom Darneix Co-authored-by: alaunois * fix(cron): Escape database name in CentACL 22.04.x (#11510) * fix(test): wait 8s before checking downtime is active in rest api v1 test (#11498) (#11504) Refs: MON-14585 * fix(UI): Include host_id when selecting ServiceGroups on dashreports (#11428) (#11519) Co-authored-by: VHS Co-authored-by: VHS * fix(Resources/Graph): export graph image after selecting png (#11491) * [SNYK] Sanitize and bind ACL host dependency queries (#11389) (#11394) * Sanitize and bind ACL host dependency queries * fix issues * removed old variable userCrypted and the use of it (#11334) (#11352) Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> * enh(Header/userMenu):reduce spacing user menu (#11393) * update user menu * fix(hostgroup): fix display of hostgroups in select2 (#11431) (#11443) * fix(ci): fix debian packaging with freshly instanciated jenkins slave (#11398) (#11399) Refs: MON-14377 * Sanitized and bound queries (#11413) (#11445) lines : 130 -142 * Snyk: Sanitize and bind media sync queries 22.04.x (#11418) * sanitizing and binding sync dir file queries * Applying some fixes * Snyk: Sanitize and bind ACL service dependency queries dev-22.04.x (#11395) * Snyk: Sanitize and bind Auth class queries 22.04.x (#11448) * [Backport/need review] fix(UI): Fix layout for Safari and form validation (#11440) * fix(UI): Fix layout for Safari and form validation (#11373) * Fix form validation * Fix padlock layout for safari * Update centreon-frontend * Remove debug variable * Fix test * Fix page respsoniveness * Rename variable * update deps * Fix package-lock * Fix package-lock * Add debug statement for debian * Install nodejs rather npm * Attempt fix * Attempt to fix nodejs installation * add sudo * Fix redoc-cli usage * Try to fix permission on npm * Fix * Fix permission * Fix permission (please work) * Fix source * Stop using npx because..... * Allow legacy-peer-deps * Remove nodejs installation * Fix image to pull for debian 11 * [SNYK] Sanitize and bind centreonGraph class queries (#11409) (#11421) 1122 1153 1134 * [Snyk] Sanitize and bind ACL action access queries (#11385) (#11402) * Sanitize and bind ACL action access queries _ sanitize if possible each variables inserted in a query _ use PDO prepared statement and bind() method _ Do not use $pearDB->escape on which is for examples useless on integers and on non closed HTML tags (svg, img, etc) * fix line length * fix failed checks * feat(api): implement endpoint to update centreon web (#11391) (#11401) Refs: MON-12296 * Clean(platform): Clean appKey method and usage 22.04.x (#11452) * Clean(platform): Clean appKey method and usage (#11336) * removing appKey from information table in baseConf and 22.10 update script * removing appKey from NotifyMasterService.php * removing appKey from CentreonRemoteServer.php * applying suggested changes * Applying suggested changes Co-authored-by: Kevin Duret * adding 22.04.2 update script file with changes * revert 22.04 beta 1 script to its original Co-authored-by: Kevin Duret * enh(platform): Use API to select metrics in virtual metrics configuration form 22.04.x (#11461) * changing select with select2 of metrics * fix alignement * remove unecessary files and replace selec by select2 in formComponentTemplate * fix select id name for acceptance tests * update composer for acceptance tests * fix acceptance test 2 * add allow clear to metrics select2 * applying suggested changes * final changes for merging * remove unecessary select tag * [SNYK] Sanitize and bind ACL class queries (#11392) (#11472) * Sanitize and bind ACL class queries Queries sanitized and bound using PDO statement * fix spaces spaces between (int) cast and variables * update file delete spaces after comma * change variables names due to a review * Line exceeds 120 characters; contains 123 characters * fix(conf) fix broker conf name display in listing (#11372) (#11376) * fix export graph image after selecting png Co-authored-by: Elmahdi ABBASSI <108519266+emabassi-ext@users.noreply.github.com> Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> Co-authored-by: Kevin Duret Co-authored-by: hyahiaoui-ext <97593234+hyahiaoui-ext@users.noreply.github.com> Co-authored-by: Tom Darneix Co-authored-by: alaunois * Fix(platform): Removing appkey key (#11511) * fix(trap): Removal of the restriction on the uniqueness of the OID of a trap (#11327) Currently, an error appears when we try to save an existing trap because a test is performed on the uniqueness of the OID. This PR aims to remove the restriction on the uniqueness of the OID of a trap. * fix(pendo): correctly set locale when language is detection by browser (#11484) (#11528) * fix(test): fix random fails on virtual metric test (#11523) Refs: MON-14359 * fix(autoload): Add classmap to fix autoload with legacy classes (#11492) (#11532) Refs: MON-14496 * fix(ldap): small refacto of ldap authentication and log failures (#11422) (#11534) Refs: MON-7417 * fix(api): allow api platform updates from installed 22.04.0 (#11495) (#11533) Refs: MON-12296 * fix(api): fix call to api on fresh install (#11536) (#11537) Refs: MON-12296 * doc(ack): acknowledge Hakaï security (#11540) * fix(api): do not init db connection in event subscriber (#11543) (#11545) Refs: MON-12296 * fix(web): fix the comment deletion for host monitored by poller (#11138) (#11556) Refs: MON-12828 Co-authored-by: Stéphane Duret * SNYK: Sanitize and bind ACL actions queries (#11547) * sanitizing and binding acl actions queries * fix missing bind * SNYK: Sanitize and bind Broker listing queries (#11550) * Sanitizing and binding broker listing queries * applying suggested changes * fix(conf) fix encoding in template service listing (#11558) (#11564) * fix encoding * remove useless function * SNYK: Sanitize and bind generateImage queries (#11561) * sanitize and bind generate image queries * adding throw exception * applying suggested changes * Update www/include/views/graphs/generateGraphs/generateImage.php Co-authored-by: Kevin Duret Co-authored-by: Kevin Duret * MON-14501 - sanitize query in centreonXmlbgRequest class (#11570) * sanitize query in centreonXmlbgRequest class * add closeCursor func to resolve conv * SNYK: Sanitize and bind Meta-Services dependency queries (#11567) * sanityze 2 insert queries * spaces removed in a query * chore(release):rebase dev-22.04.x on 22.04.x (#11627) * Merge release-22.04.3 into 22.04.x (#11623) * fix(git): resync 22.04.x to dev-22.04.x (#11503) * [SNYK] Sanitize and bind ACL host dependency queries (#11389) (#11394) * Sanitize and bind ACL host dependency queries * fix issues * removed old variable userCrypted and the use of it (#11334) (#11352) Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> * enh(Header/userMenu):reduce spacing user menu (#11393) * update user menu * fix(hostgroup): fix display of hostgroups in select2 (#11431) (#11443) * fix(ci): fix debian packaging with freshly instanciated jenkins slave (#11398) (#11399) Refs: MON-14377 * Sanitized and bound queries (#11413) (#11445) lines : 130 -142 * Snyk: Sanitize and bind media sync queries 22.04.x (#11418) * sanitizing and binding sync dir file queries * Applying some fixes * Snyk: Sanitize and bind ACL service dependency queries dev-22.04.x (#11395) * Snyk: Sanitize and bind Auth class queries 22.04.x (#11448) * [Backport/need review] fix(UI): Fix layout for Safari and form validation (#11440) * fix(UI): Fix layout for Safari and form validation (#11373) * Fix form validation * Fix padlock layout for safari * Update centreon-frontend * Remove debug variable * Fix test * Fix page respsoniveness * Rename variable * update deps * Fix package-lock * Fix package-lock * Add debug statement for debian * Install nodejs rather npm * Attempt fix * Attempt to fix nodejs installation * add sudo * Fix redoc-cli usage * Try to fix permission on npm * Fix * Fix permission * Fix permission (please work) * Fix source * Stop using npx because..... * Allow legacy-peer-deps * Remove nodejs installation * Fix image to pull for debian 11 * [SNYK] Sanitize and bind centreonGraph class queries (#11409) (#11421) 1122 1153 1134 * [Snyk] Sanitize and bind ACL action access queries (#11385) (#11402) * Sanitize and bind ACL action access queries _ sanitize if possible each variables inserted in a query _ use PDO prepared statement and bind() method _ Do not use $pearDB->escape on which is for examples useless on integers and on non closed HTML tags (svg, img, etc) * fix line length * fix failed checks * feat(api): implement endpoint to update centreon web (#11391) (#11401) Refs: MON-12296 * Clean(platform): Clean appKey method and usage 22.04.x (#11452) * Clean(platform): Clean appKey method and usage (#11336) * removing appKey from information table in baseConf and 22.10 update script * removing appKey from NotifyMasterService.php * removing appKey from CentreonRemoteServer.php * applying suggested changes * Applying suggested changes Co-authored-by: Kevin Duret * adding 22.04.2 update script file with changes * revert 22.04 beta 1 script to its original Co-authored-by: Kevin Duret * enh(platform): Use API to select metrics in virtual metrics configuration form 22.04.x (#11461) * changing select with select2 of metrics * fix alignement * remove unecessary files and replace selec by select2 in formComponentTemplate * fix select id name for acceptance tests * update composer for acceptance tests * fix acceptance test 2 * add allow clear to metrics select2 * applying suggested changes * final changes for merging * remove unecessary select tag * [SNYK] Sanitize and bind ACL class queries (#11392) (#11472) * Sanitize and bind ACL class queries Queries sanitized and bound using PDO statement * fix spaces spaces between (int) cast and variables * update file delete spaces after comma * change variables names due to a review * Line exceeds 120 characters; contains 123 characters * fix(conf) fix broker conf name display in listing (#11372) (#11376) Co-authored-by: Elmahdi ABBASSI <108519266+emabassi-ext@users.noreply.github.com> Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> Co-authored-by: Nouha-ElAbrouki <97687698+Noha-ElAbrouki@users.noreply.github.com> Co-authored-by: Kevin Duret Co-authored-by: hyahiaoui-ext <97593234+hyahiaoui-ext@users.noreply.github.com> Co-authored-by: Tom Darneix Co-authored-by: alaunois * fix(cron): Escape database name in CentACL 22.04.x (#11510) * fix(test): wait 8s before checking downtime is active in rest api v1 test (#11498) (#11504) Refs: MON-14585 * fix(UI): Include host_id when selecting ServiceGroups on dashreports (#11428) (#11519) Co-authored-by: VHS Co-authored-by: VHS * fix(Resources/Graph): export graph image after selecting png (#11491) * [SNYK] Sanitize and bind ACL host dependency queries (#11389) (#11394) * Sanitize and bind ACL host dependency queries * fix issues * removed old variable userCrypted and the use of it (#11334) (#11352) Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> * enh(Header/userMenu):reduce spacing user menu (#11393) * update user menu * fix(hostgroup): fix display of hostgroups in select2 (#11431) (#11443) * fix(ci): fix debian packaging with freshly instanciated jenkins slave (#11398) (#11399) Refs: MON-14377 * Sanitized and bound queries (#11413) (#11445) lines : 130 -142 * Snyk: Sanitize and bind media sync queries 22.04.x (#11418) * sanitizing and binding sync dir file queries * Applying some fixes * Snyk: Sanitize and bind ACL service dependency queries dev-22.04.x (#11395) * Snyk: Sanitize and bind Auth class queries 22.04.x (#11448) * [Backport/need review] fix(UI): Fix layout for Safari and form validation (#11440) * fix(UI): Fix layout for Safari and form validation (#11373) * Fix form validation * Fix padlock layout for safari * Update centreon-frontend * Remove debug variable * Fix test * Fix page respsoniveness * Rename variable * update deps * Fix package-lock * Fix package-lock * Add debug statement for debian * Install nodejs rather npm * Attempt fix * Attempt to fix nodejs installation * add sudo * Fix redoc-cli usage * Try to fix permission on npm * Fix * Fix permission * Fix permission (please work) * Fix source * Stop using npx because..... * Allow legacy-peer-deps * Remove nodejs installation * Fix image to pull for debian 11 * [SNYK] Sanitize and bind centreonGraph class queries (#11409) (#11421) 1122 1153 1134 * [Snyk] Sanitize and bind ACL action access queries (#11385) (#11402) * Sanitize and bind ACL action access queries _ sanitize if possible each variables inserted in a query _ use PDO prepared statement and bind() method _ Do not use $pearDB->escape on which is for examples useless on integers and on non closed HTML tags (svg, img, etc) * fix line length * fix failed checks * feat(api): implement endpoint to update centreon web (#11391) (#11401) Refs: MON-12296 * Clean(platform): Clean appKey method and usage 22.04.x (#11452) * Clean(platform): Clean appKey method and usage (#11336) * removing appKey from information table in baseConf and 22.10 update script * removing appKey from NotifyMasterService.php * removing appKey from CentreonRemoteServer.php * applying suggested changes * Applying suggested changes Co-authored-by: Kevin Duret * adding 22.04.2 update script file with changes * revert 22.04 beta 1 script to its original Co-authored-by: Kevin Duret * enh(platform): Use API to select metrics in virtual metrics configuration form 22.04.x (#11461) * changing select with select2 of metrics * fix alignement * remove unecessary files and replace selec by select2 in formComponentTemplate * fix select id name for acceptance tests * update composer for acceptance tests * fix acceptance test 2 * add allow clear to metrics select2 * applying suggested changes * final changes for merging * remove unecessary select tag * [SNYK] Sanitize and bind ACL class queries (#11392) (#11472) * Sanitize and bind ACL class queries Queries sanitized and bound using PDO statement * fix spaces spaces between (int) cast and variables * update file delete spaces after comma * change variables names due to a review * Line exceeds 120 characters; contains 123 characters * fix(conf) fix broker conf name display in listing (#11372) (#11376) * fix export graph image after selecting png Co-authored-by: Elmahdi ABBASSI <108519266+emabassi-ext@users.noreply.github.com> Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> Co-authored-by: Kevin Duret Co-authored-by: hyahiaoui-ext <97593234+hyahiaoui-ext@users.noreply.github.com> Co-authored-by: Tom Darneix Co-authored-by: alaunois * Fix(platform): Removing appkey key (#11511) * fix(trap): Removal of the restriction on the uniqueness of the OID of a trap (#11327) Currently, an error appears when we try to save an existing trap because a test is performed on the uniqueness of the OID. This PR aims to remove the restriction on the uniqueness of the OID of a trap. * fix(pendo): correctly set locale when language is detection by browser (#11484) (#11528) * fix(test): fix random fails on virtual metric test (#11523) Refs: MON-14359 * fix(autoload): Add classmap to fix autoload with legacy classes (#11492) (#11532) Refs: MON-14496 * fix(ldap): small refacto of ldap authentication and log failures (#11422) (#11534) Refs: MON-7417 * fix(api): allow api platform updates from installed 22.04.0 (#11495) (#11533) Refs: MON-12296 * fix(api): fix call to api on fresh install (#11536) (#11537) Refs: MON-12296 * doc(ack): acknowledge Hakaï security (#11540) * fix(api): do not init db connection in event subscriber (#11543) (#11545) Refs: MON-12296 * fix(web): fix the comment deletion for host monitored by poller (#11138) (#11556) Refs: MON-12828 Co-authored-by: Stéphane Duret * SNYK: Sanitize and bind ACL actions queries (#11547) * sanitizing and binding acl actions queries * fix missing bind * SNYK: Sanitize and bind Broker listing queries (#11550) * Sanitizing and binding broker listing queries * applying suggested changes * fix(conf) fix encoding in template service listing (#11558) (#11564) * fix encoding * remove useless function * SNYK: Sanitize and bind generateImage queries (#11561) * sanitize and bind generate image queries * adding throw exception * applying suggested changes * Update www/include/views/graphs/generateGraphs/generateImage.php Co-authored-by: Kevin Duret Co-authored-by: Kevin Duret * MON-14501 - sanitize query in centreonXmlbgRequest class (#11570) * sanitize query in centreonXmlbgRequest class * add closeCursor func to resolve conv * SNYK: Sanitize and bind Meta-Services dependency queries (#11567) * sanityze 2 insert queries * spaces removed in a query * chore(install):Update version to 22.04.3 * fix(sql): fix query to select contact during ldap import (#11578) Refs: MON-14263 * fix(UI): Fix layout for Safari and form validation (#11373) (#11604) * Fix form validation * Fix padlock layout for safari * Update centreon-frontend * Remove debug variable * Fix test * Fix page respsoniveness * Rename variable * update deps * Fix package-lock Co-authored-by: Elmahdi ABBASSI <108519266+emabassi-ext@users.noreply.github.com> Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> Co-authored-by: Nouha-ElAbrouki <97687698+Noha-ElAbrouki@users.noreply.github.com> Co-authored-by: Kevin Duret Co-authored-by: hyahiaoui-ext <97593234+hyahiaoui-ext@users.noreply.github.com> Co-authored-by: Tom Darneix Co-authored-by: alaunois Co-authored-by: VHS Co-authored-by: Laurent Calvet Co-authored-by: Stéphane Chapron <34628915+sc979@users.noreply.github.com> Co-authored-by: Stéphane Duret * fix(api): fix call to api on fresh install (#11536) (#11537) Refs: MON-12296 * fix(api): do not init db connection in event subscriber (#11543) (#11545) Refs: MON-12296 Co-authored-by: Elmahdi ABBASSI <108519266+emabassi-ext@users.noreply.github.com> Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> Co-authored-by: Nouha-ElAbrouki <97687698+Noha-ElAbrouki@users.noreply.github.com> Co-authored-by: Kevin Duret Co-authored-by: hyahiaoui-ext <97593234+hyahiaoui-ext@users.noreply.github.com> Co-authored-by: Tom Darneix Co-authored-by: alaunois Co-authored-by: VHS Co-authored-by: Laurent Calvet Co-authored-by: Stéphane Chapron <34628915+sc979@users.noreply.github.com> Co-authored-by: Stéphane Duret * fix(partition): adapt control of database version (#11609) (#11610) * fix(openid): correctly set contact_location while creating session (#11613) (#11614) * fix(lang): Fixed FR typo (#11621) * enh(UI): Add a “Parent alias“ column on the monitoring resources sta… (#11542) * enh(UI): Add a “Parent alias“ column on the monitoring resources status page (#11190) * Add column ParentAlias * Add new label ParentAlias * Add column ParentAlias and new column component * Add new card to display Parent Alias * Remove tile in Details Panel, enhancement not expected * FIx eslint issue * Fix naming on label parent alias * Add translation * Add line at the end of files * Add line at the end of file * fix issues * Update lang/fr_FR.UTF-8/LC_MESSAGES/messages.po Co-authored-by: Tom Darneix * Update lang/es_ES.UTF-8/LC_MESSAGES/messages.po Co-authored-by: Tom Darneix * Update lang/pt_PT.UTF-8/LC_MESSAGES/messages.po Co-authored-by: Tom Darneix * Update lang/es_ES.UTF-8/LC_MESSAGES/messages.po Co-authored-by: Jérémy Delpierre * Update lang/pt_BR.UTF-8/LC_MESSAGES/messages.po Co-authored-by: Jérémy Delpierre * Update lang/fr_FR.UTF-8/LC_MESSAGES/messages.po Co-authored-by: Bruno d'Auria * Fix issue on messages.po file Co-authored-by: Tom Darneix Co-authored-by: Jérémy Delpierre Co-authored-by: Bruno d'Auria * query sanitized in listServiceCategoriesà (#11597) (#11632) * MON-14797 reorganizes dependencies (#11612) * Fix encoding issue on status serviceXML (#11581) * sanitize and bind in centreon connector query (#11635) * sanitize insrert queries in db-func (#11650) MON-14667 * chore(git): update codeowners (#11594) * chore(release):rebase dev-22.04.x on 22.04.x (#11688) * Merge release-22.04.3 into 22.04.x (#11623) * fix(git): resync 22.04.x to dev-22.04.x (#11503) * [SNYK] Sanitize and bind ACL host dependency queries (#11389) (#11394) * Sanitize and bind ACL host dependency queries * fix issues * removed old variable userCrypted and the use of it (#11334) (#11352) Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> * enh(Header/userMenu):reduce spacing user menu (#11393) * update user menu * fix(hostgroup): fix display of hostgroups in select2 (#11431) (#11443) * fix(ci): fix debian packaging with freshly instanciated jenkins slave (#11398) (#11399) Refs: MON-14377 * Sanitized and bound queries (#11413) (#11445) lines : 130 -142 * Snyk: Sanitize and bind media sync queries 22.04.x (#11418) * sanitizing and binding sync dir file queries * Applying some fixes * Snyk: Sanitize and bind ACL service dependency queries dev-22.04.x (#11395) * Snyk: Sanitize and bind Auth class queries 22.04.x (#11448) * [Backport/need review] fix(UI): Fix layout for Safari and form validation (#11440) * fix(UI): Fix layout for Safari and form validation (#11373) * Fix form validation * Fix padlock layout for safari * Update centreon-frontend * Remove debug variable * Fix test * Fix page respsoniveness * Rename variable * update deps * Fix package-lock * Fix package-lock * Add debug statement for debian * Install nodejs rather npm * Attempt fix * Attempt to fix nodejs installation * add sudo * Fix redoc-cli usage * Try to fix permission on npm * Fix * Fix permission * Fix permission (please work) * Fix source * Stop using npx because..... * Allow legacy-peer-deps * Remove nodejs installation * Fix image to pull for debian 11 * [SNYK] Sanitize and bind centreonGraph class queries (#11409) (#11421) 1122 1153 1134 * [Snyk] Sanitize and bind ACL action access queries (#11385) (#11402) * Sanitize and bind ACL action access queries _ sanitize if possible each variables inserted in a query _ use PDO prepared statement and bind() method _ Do not use $pearDB->escape on which is for examples useless on integers and on non closed HTML tags (svg, img, etc) * fix line length * fix failed checks * feat(api): implement endpoint to update centreon web (#11391) (#11401) Refs: MON-12296 * Clean(platform): Clean appKey method and usage 22.04.x (#11452) * Clean(platform): Clean appKey method and usage (#11336) * removing appKey from information table in baseConf and 22.10 update script * removing appKey from NotifyMasterService.php * removing appKey from CentreonRemoteServer.php * applying suggested changes * Applying suggested changes Co-authored-by: Kevin Duret * adding 22.04.2 update script file with changes * revert 22.04 beta 1 script to its original Co-authored-by: Kevin Duret * enh(platform): Use API to select metrics in virtual metrics configuration form 22.04.x (#11461) * changing select with select2 of metrics * fix alignement * remove unecessary files and replace selec by select2 in formComponentTemplate * fix select id name for acceptance tests * update composer for acceptance tests * fix acceptance test 2 * add allow clear to metrics select2 * applying suggested changes * final changes for merging * remove unecessary select tag * [SNYK] Sanitize and bind ACL class queries (#11392) (#11472) * Sanitize and bind ACL class queries Queries sanitized and bound using PDO statement * fix spaces spaces between (int) cast and variables * update file delete spaces after comma * change variables names due to a review * Line exceeds 120 characters; contains 123 characters * fix(conf) fix broker conf name display in listing (#11372) (#11376) Co-authored-by: Elmahdi ABBASSI <108519266+emabassi-ext@users.noreply.github.com> Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> Co-authored-by: Nouha-ElAbrouki <97687698+Noha-ElAbrouki@users.noreply.github.com> Co-authored-by: Kevin Duret Co-authored-by: hyahiaoui-ext <97593234+hyahiaoui-ext@users.noreply.github.com> Co-authored-by: Tom Darneix Co-authored-by: alaunois * fix(cron): Escape database name in CentACL 22.04.x (#11510) * fix(test): wait 8s before checking downtime is active in rest api v1 test (#11498) (#11504) Refs: MON-14585 * fix(UI): Include host_id when selecting ServiceGroups on dashreports (#11428) (#11519) Co-authored-by: VHS Co-authored-by: VHS * fix(Resources/Graph): export graph image after selecting png (#11491) * [SNYK] Sanitize and bind ACL host dependency queries (#11389) (#11394) * Sanitize and bind ACL host dependency queries * fix issues * removed old variable userCrypted and the use of it (#11334) (#11352) Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> * enh(Header/userMenu):reduce spacing user menu (#11393) * update user menu * fix(hostgroup): fix display of hostgroups in select2 (#11431) (#11443) * fix(ci): fix debian packaging with freshly instanciated jenkins slave (#11398) (#11399) Refs: MON-14377 * Sanitized and bound queries (#11413) (#11445) lines : 130 -142 * Snyk: Sanitize and bind media sync queries 22.04.x (#11418) * sanitizing and binding sync dir file queries * Applying some fixes * Snyk: Sanitize and bind ACL service dependency queries dev-22.04.x (#11395) * Snyk: Sanitize and bind Auth class queries 22.04.x (#11448) * [Backport/need review] fix(UI): Fix layout for Safari and form validation (#11440) * fix(UI): Fix layout for Safari and form validation (#11373) * Fix form validation * Fix padlock layout for safari * Update centreon-frontend * Remove debug variable * Fix test * Fix page respsoniveness * Rename variable * update deps * Fix package-lock * Fix package-lock * Add debug statement for debian * Install nodejs rather npm * Attempt fix * Attempt to fix nodejs installation * add sudo * Fix redoc-cli usage * Try to fix permission on npm * Fix * Fix permission * Fix permission (please work) * Fix source * Stop using npx because..... * Allow legacy-peer-deps * Remove nodejs installation * Fix image to pull for debian 11 * [SNYK] Sanitize and bind centreonGraph class queries (#11409) (#11421) 1122 1153 1134 * [Snyk] Sanitize and bind ACL action access queries (#11385) (#11402) * Sanitize and bind ACL action access queries _ sanitize if possible each variables inserted in a query _ use PDO prepared statement and bind() method _ Do not use $pearDB->escape on which is for examples useless on integers and on non closed HTML tags (svg, img, etc) * fix line length * fix failed checks * feat(api): implement endpoint to update centreon web (#11391) (#11401) Refs: MON-12296 * Clean(platform): Clean appKey method and usage 22.04.x (#11452) * Clean(platform): Clean appKey method and usage (#11336) * removing appKey from information table in baseConf and 22.10 update script * removing appKey from NotifyMasterService.php * removing appKey from CentreonRemoteServer.php * applying suggested changes * Applying suggested changes Co-authored-by: Kevin Duret * adding 22.04.2 update script file with changes * revert 22.04 beta 1 script to its original Co-authored-by: Kevin Duret * enh(platform): Use API to select metrics in virtual metrics configuration form 22.04.x (#11461) * changing select with select2 of metrics * fix alignement * remove unecessary files and replace selec by select2 in formComponentTemplate * fix select id name for acceptance tests * update composer for acceptance tests * fix acceptance test 2 * add allow clear to metrics select2 * applying suggested changes * final changes for merging * remove unecessary select tag * [SNYK] Sanitize and bind ACL class queries (#11392) (#11472) * Sanitize and bind ACL class queries Queries sanitized and bound using PDO statement * fix spaces spaces between (int) cast and variables * update file delete spaces after comma * change variables names due to a review * Line exceeds 120 characters; contains 123 characters * fix(conf) fix broker conf name display in listing (#11372) (#11376) * fix export graph image after selecting png Co-authored-by: Elmahdi ABBASSI <108519266+emabassi-ext@users.noreply.github.com> Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> Co-authored-by: Kevin Duret Co-authored-by: hyahiaoui-ext <97593234+hyahiaoui-ext@users.noreply.github.com> Co-authored-by: Tom Darneix Co-authored-by: alaunois * Fix(platform): Removing appkey key (#11511) * fix(trap): Removal of the restriction on the uniqueness of the OID of a trap (#11327) Currently, an error appears when we try to save an existing trap because a test is performed on the uniqueness of the OID. This PR aims to remove the restriction on the uniqueness of the OID of a trap. * fix(pendo): correctly set locale when language is detection by browser (#11484) (#11528) * fix(test): fix random fails on virtual metric test (#11523) Refs: MON-14359 * fix(autoload): Add classmap to fix autoload with legacy classes (#11492) (#11532) Refs: MON-14496 * fix(ldap): small refacto of ldap authentication and log failures (#11422) (#11534) Refs: MON-7417 * fix(api): allow api platform updates from installed 22.04.0 (#11495) (#11533) Refs: MON-12296 * fix(api): fix call to api on fresh install (#11536) (#11537) Refs: MON-12296 * doc(ack): acknowledge Hakaï security (#11540) * fix(api): do not init db connection in event subscriber (#11543) (#11545) Refs: MON-12296 * fix(web): fix the comment deletion for host monitored by poller (#11138) (#11556) Refs: MON-12828 Co-authored-by: Stéphane Duret * SNYK: Sanitize and bind ACL actions queries (#11547) * sanitizing and binding acl actions queries * fix missing bind * SNYK: Sanitize and bind Broker listing queries (#11550) * Sanitizing and binding broker listing queries * applying suggested changes * fix(conf) fix encoding in template service listing (#11558) (#11564) * fix encoding * remove useless function * SNYK: Sanitize and bind generateImage queries (#11561) * sanitize and bind generate image queries * adding throw exception * applying suggested changes * Update www/include/views/graphs/generateGraphs/generateImage.php Co-authored-by: Kevin Duret Co-authored-by: Kevin Duret * MON-14501 - sanitize query in centreonXmlbgRequest class (#11570) * sanitize query in centreonXmlbgRequest class * add closeCursor func to resolve conv * SNYK: Sanitize and bind Meta-Services dependency queries (#11567) * sanityze 2 insert queries * spaces removed in a query * chore(install):Update version to 22.04.3 * fix(sql): fix query to select contact during ldap import (#11578) Refs: MON-14263 * fix(UI): Fix layout for Safari and form validation (#11373) (#11604) * Fix form validation * Fix padlock layout for safari * Update centreon-frontend * Remove debug variable * Fix test * Fix page respsoniveness * Rename variable * update deps * Fix package-lock Co-authored-by: Elmahdi ABBASSI <108519266+emabassi-ext@users.noreply.github.com> Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> Co-authored-by: Nouha-ElAbrouki <97687698+Noha-ElAbrouki@users.noreply.github.com> Co-authored-by: Kevin Duret Co-authored-by: hyahiaoui-ext <97593234+hyahiaoui-ext@users.noreply.github.com> Co-authored-by: Tom Darneix Co-authored-by: alaunois Co-authored-by: VHS Co-authored-by: Laurent Calvet Co-authored-by: Stéphane Chapron <34628915+sc979@users.noreply.github.com> Co-authored-by: Stéphane Duret * chore(release): merge hotfix-MON-14893-index-data (#11681) * fix(upgrade): Correctly Parse SQL Comments (#11658) (#11668) Refs: MON-14848 Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> * fix invalid values for index_data.special (#11669) * chore(install):update version to 22.04.4 Co-authored-by: Kevin Duret Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> * fix(api): fix call to api on fresh install (#11536) (#11537) Refs: MON-12296 * fix(api): do not init db connection in event subscriber (#11543) (#11545) Refs: MON-12296 * fix(partition): adapt control of database version (#11609) (#11610) * fix(openid): correctly set contact_location while creating session (#11613) (#11614) * fix(lang): Fixed FR typo (#11621) * enh(UI): Add a “Parent alias“ column on the monitoring resources sta… (#11542) * enh(UI): Add a “Parent alias“ column on the monitoring resources status page (#11190) * Add column ParentAlias * Add new label ParentAlias * Add column ParentAlias and new column component * Add new card to display Parent Alias * Remove tile in Details Panel, enhancement not expected * FIx eslint issue * Fix naming on label parent alias * Add translation * Add line at the end of files * Add line at the end of file * fix issues * Update lang/fr_FR.UTF-8/LC_MESSAGES/messages.po Co-authored-by: Tom Darneix * Update lang/es_ES.UTF-8/LC_MESSAGES/messages.po Co-authored-by: Tom Darneix * Update lang/pt_PT.UTF-8/LC_MESSAGES/messages.po Co-authored-by: Tom Darneix * Update lang/es_ES.UTF-8/LC_MESSAGES/messages.po Co-authored-by: Jérémy Delpierre * Update lang/pt_BR.UTF-8/LC_MESSAGES/messages.po Co-authored-by: Jérémy Delpierre * Update lang/fr_FR.UTF-8/LC_MESSAGES/messages.po Co-authored-by: Bruno d'Auria * Fix issue on messages.po file Co-authored-by: Tom Darneix Co-authored-by: Jérémy Delpierre Co-authored-by: Bruno d'Auria * query sanitized in listServiceCategoriesà (#11597) (#11632) * MON-14797 reorganizes dependencies (#11612) * Fix encoding issue on status serviceXML (#11581) * sanitize and bind in centreon connector query (#11635) * sanitize insrert queries in db-func (#11650) MON-14667 Co-authored-by: Elmahdi ABBASSI <108519266+emabassi-ext@users.noreply.github.com> Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> Co-authored-by: Nouha-ElAbrouki <97687698+Noha-ElAbrouki@users.noreply.github.com> Co-authored-by: Kevin Duret Co-authored-by: hyahiaoui-ext <97593234+hyahiaoui-ext@users.noreply.github.com> Co-authored-by: Tom Darneix Co-authored-by: alaunois Co-authored-by: VHS Co-authored-by: Laurent Calvet Co-authored-by: Stéphane Chapron <34628915+sc979@users.noreply.github.com> Co-authored-by: Stéphane Duret Co-authored-by: Laurent Pinsivy Co-authored-by: jcaro Co-authored-by: Jérémy Delpierre Co-authored-by: Bruno d'Auria Co-authored-by: Luiz Costa Co-authored-by: TamazC <103252125+TamazC@users.noreply.github.com> * fix(details): remove dead code (#11672) (#11686) * fix(conf) fix parent template display in service template listing (#11671) (#11676) * fix(poller): fix remote server duplication (#11552) (#11674) * fix(poller): fix remote server duplication (#11552) Refs: MON-14579 Co-authored-by: Jérémy Jaouen * fix translation for host and service category (#11626) * fix(clapi): Check that user is admin to use clapi (#11631) (#11640) * Sanitized and bound queries in service argumentsXml fil (#11653) MON-14669 * Sanitize and bind listVirtualMetrics queries (#11647) * sanitize and bind host categories queries (#11645) * Ãbind queries an fix array binding(#11656) * fix(ui): fix svg display in legacy monitoring pages (#11659) (#11690) Refs: MON-14869 * Sanitize and bind service group dependecies queries 22.04.x (#11665) * MON-14425 fix centreon.ini and autoconfigure timezone (#11608) * enh(Resources/header): Display the 2 access pictograms logs and report on details panel (#11618) * Display the 2 access pictograms logs and report on details panel * Update www/front_src/src/Resources/Details/Header.tsx Co-authored-by: JKancel * Update www/front_src/src/Resources/Details/Header.tsx Co-authored-by: JKancel Co-authored-by: JKancel * fix(resource-status): add missing alias to Host detail factory (#11642) * fix(widgets): retrieve possibility to not select poller in pref (#11696) (#11698) Refs: MON-14919 * fix(install): fix source install with quiet mode related to gorgone vars (#11694) (#11701) Refs: MON-14806 Co-authored-by: Eric Coquard * Fix: In Acces group the second select not working [ACL] 22.04.x (#11709) * fix second select not working * applying suggested changes * fix(details): second part of code cleanup for "tools" (#11718) (#11721) * fix (#11724) * FIX: Sanitize and bind graph configuration queries 22.04.x (#11729) * [Fix]:Sanitize and bind queries in template of service listing (#11746) * [Fix]:Sanitize and bind queries in template of service listing * work on tamazC suggestion * fix(resource): Fix bad SQL request (#11702) (#11749) * FIX: Sanitize and bind Meta Service configuration 22.04.x (#11733) * sanitize and bind meta service config * applying suggested changes * Fix: Sanitize and bind CLAPI poller configuration 22.04.x (#11731) * sanitize and bind CLAPI poller config * remove unecessary comment * revert deleted imports * FIX: Sanitize and bind command configuration queries 22.04.x (#11754) * fix(partition): fix condition for database version (#11657) (#11756) Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> Co-authored-by: Charles Gautier <33026375+chgautier@users.noreply.github.com> Co-authored-by: Elmahdi ABBASSI <108519266+emabassi-ext@users.noreply.github.com> Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> Co-authored-by: Nouha-ElAbrouki <97687698+Noha-ElAbrouki@users.noreply.github.com> Co-authored-by: Kevin Duret Co-authored-by: hyahiaoui-ext <97593234+hyahiaoui-ext@users.noreply.github.com> Co-authored-by: Tom Darneix Co-authored-by: alaunois Co-authored-by: VHS Co-authored-by: Laurent Calvet Co-authored-by: Stéphane Chapron <34628915+sc979@users.noreply.github.com> Co-authored-by: Stéphane Duret Co-authored-by: Laurent Pinsivy Co-authored-by: jcaro Co-authored-by: Jérémy Delpierre Co-authored-by: Bruno d'Auria Co-authored-by: Luiz Costa Co-authored-by: TamazC <103252125+TamazC@users.noreply.github.com> Co-authored-by: Adrien Morais-Mestre <31647811+adr-mo@users.noreply.github.com> Co-authored-by: Jérémy Jaouen Co-authored-by: JKancel Co-authored-by: Eric Coquard * fix(api): fix call to api on fresh install (#11536) (#11537) Refs: MON-12296 * fix(api): do not init db connection in event subscriber (#11543) (#11545) Refs: MON-12296 Co-authored-by: Charles Gautier <33026375+chgautier@users.noreply.github.com> Co-authored-by: Elmahdi ABBASSI <108519266+emabassi-ext@users.noreply.github.com> Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> Co-authored-by: Nouha-ElAbrouki <97687698+Noha-ElAbrouki@users.noreply.github.com> Co-authored-by: Kevin Duret Co-authored-by: hyahiaoui-ext <97593234+hyahiaoui-ext@users.noreply.github.com> Co-authored-by: Tom Darneix Co-authored-by: alaunois Co-authored-by: VHS Co-authored-by: Laurent Calvet Co-authored-by: Stéphane Chapron <34628915+sc979@users.noreply.github.com> Co-authored-by: Stéphane Duret Co-authored-by: Laurent Pinsivy Co-authored-by: jcaro Co-authored-by: Jérémy Delpierre Co-authored-by: Bruno d'Auria Co-authored-by: Luiz Costa Co-authored-by: TamazC <103252125+TamazC@users.noreply.github.com> Co-authored-by: Adrien Morais-Mestre <31647811+adr-mo@users.noreply.github.com> Co-authored-by: Jérémy Jaouen Co-authored-by: JKancel Co-authored-by: Eric Coquard * fix(websso): Correctly set contact theme while authenticating with WebSSO 22.04.x (#11830) * Fix: Sanitize and bind Media import (#11789) * Fix : Sanitize and bind centreon hostgroups class(#11798) * Fix: Sanitize and bind CLAPI Centreon Hostgroup class (#11803) * fix(conf/export) broker RRDcacheD export (#11811) (#11833) * fix(host) fix isActivated variable in updateHost (#11818) (#11835) * FIX: SQLi in poller's broker configuration 22.04 (#11776) * sanitize and bind pollers broker config queries * applying suggested changes * FIX: Sanitize and bind default configuration queries 22.04.x (#11786) * FIX: Sanitize and bind Centreon Notification class 22.04.x (#11790) * FIX: Sanitize and bind LDAP CLAPI listing 22.04.x (#11794) * sanitize and bind clapi LDAP listing * removing unecessary code * FIX: Sanitize and bind service listing 22.04.x (#11799) * sanitizing and binding service listing queries * removing var casting * [Fix]: Sanitize and bind service by hostgroups listing (#11796) * sanitize nad bind service by hostgroups listing * fix exceeded linee * Fix: Remove obsolete code in monitoring common functions (#11845) * Fix: Sanitize and bind SNMP Traps listing (#11843) * Fix: Remove obsolete code in Criticality class (#11840) * remove obsolete function getHostTplCriticality in criticality class * Update www/class/centreonCriticality.class.php Co-authored-by: TamazC <103252125+TamazC@users.noreply.github.com> Co-authored-by: TamazC <103252125+TamazC@users.noreply.github.com> * Fix: Sanitize and bind CALPI Centreon service class (#11837) * sanitize and bine clapi centreon service class * Update www/class/centreon-clapi/centreonService.class.php space added into query Co-authored-by: Kevin Duret Co-authored-by: Kevin Duret Co-authored-by: Kevin Duret * FIX: Remove unused mechanism for modules to add restart/reload actions after restart of pollers 22.04.x (#11854) * removing obsolet code * removing more useless code * FIX: Sanitize and bind SNMP Traps groups configuration 22.04.x (#11806) * FIX: Removing unused code and fixing bug of generating csv in multiple periods graphs 22.04.x (#11856) * FIX: Sanitize and bind Knowledge Base host listing 22.04.x (#11858) * Fix: Remove obsolete code in ACL configuration listing (#11791) * (fix) remove required parameters for openid (#11853) * FIX: Sanitize and bind Centreon Service class 22.04.x (#11864) * sanitize and bind service class queries and fix bug mediawiki links * fixing links host templates mediawiki * fix(db): change type of notification_number column dev-22.04.x (#11862) * backport MON-14223 -> dev-22.04.x * fix * Fix: Sanitize and bind host category listing (#11804) * Fix: Remove obsolete code in database partitioning functions (#11838) * FIX: Remove unused AppKey for Remote Server 22.04.x (#11876) * remove obselete files * refactoring code to clean up app key usage * FIX: SQLi in contact groups form 22.04.x (#11874) * replaced htmlentities() by filter_var to handle special chars (i.e. '&') (#11872) * Fix: Remove obsolete code in legacy service detail page (#11848) (#11879) * Remove obsolete code in legacy service detail page * restore deleted code * remove obsolete code in legacy service detail page and query sanitizeà * Fix: Sanitize and bind menu topology listing dev-22.04.x (#11882) * Fix: Sanitize and bind menu topology listing (#11832) * sanitize and bind menu topology listing * fix bug in query closing * editing TopologyRepositoryTest file and change the query * typo * changes in phpDoc of query method * fix timezone issue websso (#11900) * chore(release): update version to 22.04.6 Co-authored-by: Charles Gautier <33026375+chgautier@users.noreply.github.com> Co-authored-by: Elmahdi ABBASSI <108519266+emabassi-ext@users.noreply.github.com> Co-authored-by: jeremyjaouen <61694165+jeremyjaouen@users.noreply.github.com> Co-authored-by: Nouha-ElAbrouki <97687698+Noha-ElAbrouki@users.noreply.github.com> Co-authored-by: Kevin Duret Co-authored-by: hyahiaoui-ext <97593234+hyahiaoui-ext@users.noreply.github.com> Co-authored-by: Tom Darneix Co-authored-by: alaunois Co-authored-by: VHS Co-authored-by: Laurent Calvet Co-authored-by: Stéphane Chapron <34628915+sc979@users.noreply.github.com> Co-authored-by: Stéphane Duret Co-authored-by: Laurent Pinsivy Co-authored-by: jcaro Co-authored-by: Jérémy Delpierre Co-authored-by: Bruno d'Auria Co-authored-by: Luiz Costa Co-authored-by: TamazC <103252125+TamazC@users.noreply.github.com> Co-authored-by: Adrien Morais-Mestre <31647811+adr-mo@users.noreply.github.com> Co-authored-by: Jérémy Jaouen Co-authored-by: JKancel Co-authored-by: Eric Coquard Co-authored-by: wtermellil <110023866+wtermellil@users.noreply.github.com> Co-authored-by: Dmytro Iosypenko <108675430+dmyios@users.noreply.github.com> --- .../Contact/Interfaces/ContactInterface.php | 5 + .../Domain/Repository/TopologyRepository.php | 17 ++-- .../Domain/Service/AppKeyGeneratorService.php | 15 --- .../HostConfigurationRepositoryRDB.php | 2 +- src/Centreon/ServiceProvider.php | 7 -- .../Tests/AppKeyGeneratorServiceTest.php | 63 ------------- .../Repository/TopologyRepositoryTest.php | 2 +- src/Centreon/Tests/ServiceProviderTest.php | 1 - .../Domain/Service/TaskService.php | 8 -- src/CentreonRemote/ServiceProvider.php | 2 - .../UpdateOpenIdConfiguration.php | 15 +-- .../LoginOpenIdSession/LoginOpenIdSession.php | 3 +- src/EventSubscriber/WebSSOEventSubscriber.php | 5 +- .../centreon.Config.Poller.class.php | 1 - .../centreon-clapi/centreonAPI.class.php | 2 +- .../centreonHostGroup.class.php | 25 +++-- .../centreon-clapi/centreonLDAP.class.php | 8 +- .../centreon-clapi/centreonService.class.php | 12 +-- .../centreon-knowledge/procedures.class.php | 14 +-- .../centreon-partition/partEngine.class.php | 38 -------- www/class/centreon.class.php | 10 -- www/class/centreonConfigCentreonBroker.php | 8 +- www/class/centreonCriticality.class.php | 25 ----- www/class/centreonDB.class.php | 34 ++++++- www/class/centreonHostgroups.class.php | 15 +-- www/class/centreonMedia.class.php | 12 +-- www/class/centreonNotification.class.php | 11 ++- www/class/centreonService.class.php | 10 +- www/class/config-generate/broker.class.php | 18 ++-- .../configCentreonBroker/DB-Func.php | 91 ++++++++++++++----- .../configGenerate/xml/restartPollers.php | 12 --- .../configKnowledge/display-hostTemplates.php | 4 +- .../configKnowledge/display-hosts.php | 4 +- .../display-serviceTemplates.php | 4 +- .../configKnowledge/display-services.php | 2 +- .../contactgroup/formContactGroup.php | 6 +- .../host_categories/listHostCategories.php | 12 +-- .../service/listServiceByHost.php | 12 ++- .../service/listServiceByHostGroup.php | 47 ++++++++-- .../configObject/traps-groups/DB-Func.php | 8 +- .../configObject/traps/listTraps.php | 8 +- www/include/monitoring/common-Func.php | 20 ---- .../objectDetails/serviceDetails.php | 19 ++-- .../actionsACL/listsActionsAccess.php | 5 - .../accessLists/menusACL/listsMenusAccess.php | 4 - .../resourcesACL/listsResourcesAccess.php | 7 -- .../graphs/exportData/ExportCSVMetricData.php | 79 ---------------- www/include/views/graphs/graph-periods.html | 41 +++------ www/install/insertBaseConf.sql | 2 +- www/install/installBroker.sql | 4 +- www/install/php/Update-22.04.6.php | 49 ++++++++++ www/install/steps/process/insertBaseConf.php | 11 ++- 52 files changed, 361 insertions(+), 478 deletions(-) delete mode 100644 src/Centreon/Domain/Service/AppKeyGeneratorService.php delete mode 100644 src/Centreon/Tests/AppKeyGeneratorServiceTest.php delete mode 100644 www/include/views/graphs/exportData/ExportCSVMetricData.php create mode 100644 www/install/php/Update-22.04.6.php diff --git a/src/Centreon/Domain/Contact/Interfaces/ContactInterface.php b/src/Centreon/Domain/Contact/Interfaces/ContactInterface.php index 525b6f3c2cc..aef328a4bcb 100644 --- a/src/Centreon/Domain/Contact/Interfaces/ContactInterface.php +++ b/src/Centreon/Domain/Contact/Interfaces/ContactInterface.php @@ -207,4 +207,9 @@ public function hasAccessToApiRealTime(): bool; * @return static */ public function setAccessToApiRealTime(bool $hasAccessToApiRealTime): static; + + /** + * @return string|null + */ + public function getTheme(): ?string; } diff --git a/src/Centreon/Domain/Repository/TopologyRepository.php b/src/Centreon/Domain/Repository/TopologyRepository.php index dc682d3acb3..64506d925f7 100644 --- a/src/Centreon/Domain/Repository/TopologyRepository.php +++ b/src/Centreon/Domain/Repository/TopologyRepository.php @@ -105,14 +105,15 @@ public function getReactTopologiesPerUserWithAcl($user) if ($DBRESULT->rowCount()) { $topology = array(); $tmp_topo_page = array(); + $statement = $this->db->prepare("SELECT topology_topology_id, acl_topology_relations.access_right " + . "FROM acl_topology_relations, acl_topology " + . "WHERE acl_topology.acl_topo_activate = '1' " + . "AND acl_topology.acl_topo_id = acl_topology_relations.acl_topo_id " + . "AND acl_topology_relations.acl_topo_id = :acl_topo_id "); while ($topo_group = $DBRESULT->fetchRow()) { - $query2 = "SELECT topology_topology_id, acl_topology_relations.access_right " - . "FROM acl_topology_relations, acl_topology " - . "WHERE acl_topology.acl_topo_activate = '1' " - . "AND acl_topology.acl_topo_id = acl_topology_relations.acl_topo_id " - . "AND acl_topology_relations.acl_topo_id = '" . $topo_group["acl_topology_id"] . "' "; - $DBRESULT2 = $this->db->query($query2); - while ($topo_page = $DBRESULT2->fetchRow()) { + $statement->bindValue(':acl_topo_id', $topo_group["acl_topology_id"], \PDO::PARAM_INT); + $statement->execute(); + while ($topo_page = $statement->fetch(\PDO::FETCH_ASSOC)) { $topology[] = (int)$topo_page["topology_topology_id"]; if (!isset($tmp_topo_page[$topo_page['topology_topology_id']])) { $tmp_topo_page[$topo_page["topology_topology_id"]] = $topo_page["access_right"]; @@ -127,7 +128,7 @@ public function getReactTopologiesPerUserWithAcl($user) } } } - $DBRESULT2->closeCursor(); + $statement->closeCursor(); } $DBRESULT->closeCursor(); diff --git a/src/Centreon/Domain/Service/AppKeyGeneratorService.php b/src/Centreon/Domain/Service/AppKeyGeneratorService.php deleted file mode 100644 index 913ca66b18a..00000000000 --- a/src/Centreon/Domain/Service/AppKeyGeneratorService.php +++ /dev/null @@ -1,15 +0,0 @@ -bindValue(':ip_address', $host->getIpAddress(), \PDO::PARAM_STR); $statement->bindValue(':comment', $host->getComment(), \PDO::PARAM_STR); $statement->bindValue(':geo_coords', $host->getGeoCoords(), \PDO::PARAM_STR); - $statement->bindValue(':is_activate', $host->isActivated(), \PDO::PARAM_STR); + $statement->bindValue(':is_activate', $host->isActivated() ? '1' : '0', \PDO::PARAM_STR); $statement->bindValue(':host_register', '1', \PDO::PARAM_STR); $statement->bindValue(':active_check_status', Host::OPTION_DEFAULT, \PDO::PARAM_STR); $statement->bindValue(':passive_check_status', Host::OPTION_DEFAULT, \PDO::PARAM_STR); diff --git a/src/Centreon/ServiceProvider.php b/src/Centreon/ServiceProvider.php index 123d857c006..a330e16e4bf 100644 --- a/src/Centreon/ServiceProvider.php +++ b/src/Centreon/ServiceProvider.php @@ -34,7 +34,6 @@ use Centreon\Infrastructure\Service\CentreonDBManagerService; use Centreon\Domain\Service\I18nService; use Centreon\Domain\Service\FrontendComponentService; -use Centreon\Domain\Service\AppKeyGeneratorService; use Centreon\Domain\Service\BrokerConfigurationService; use Centreon\Domain\Repository\CfgCentreonBrokerRepository; use Centreon\Domain\Repository\CfgCentreonBrokerInfoRepository; @@ -171,12 +170,6 @@ public function register(Container $pimple): void return $_SESSION['centreon']->user; // @codeCoverageIgnoreEnd }; - $pimple['centreon.keygen'] = function (): AppKeyGeneratorService { - $service = new AppKeyGeneratorService(); - - return $service; - }; - $pimple[static::CENTREON_ACL] = function (Container $container): CentreonACL { $service = new CentreonACL($container); diff --git a/src/Centreon/Tests/AppKeyGeneratorServiceTest.php b/src/Centreon/Tests/AppKeyGeneratorServiceTest.php deleted file mode 100644 index a59df976afe..00000000000 --- a/src/Centreon/Tests/AppKeyGeneratorServiceTest.php +++ /dev/null @@ -1,63 +0,0 @@ -. - * - * Linking this program statically or dynamically with other modules is making a - * combined work based on this program. Thus, the terms and conditions of the GNU - * General Public License cover the whole combination. - * - * As a special exception, the copyright holders of this program give Centreon - * permission to link this program with independent modules to produce an executable, - * regardless of the license terms of these independent modules, and to copy and - * distribute the resulting executable under terms of Centreon choice, provided that - * Centreon also meet, for each linked independent module, the terms and conditions - * of the license of that module. An independent module is a module which is not - * derived from this program. If you modify this program, you may extend this - * exception to your version of the program, but you are not obliged to do so. If you - * do not wish to do so, delete this exception statement from your version. - * - * For more information : contact@centreon.com - * - * - */ - -namespace Centreon\Tests; - -use PHPUnit\Framework\TestCase; -use Centreon\Domain\Service\AppKeyGeneratorService; - -class AppKeyGeneratorServiceTest extends TestCase -{ - const MD5_REGEX = '/^[a-f0-9]{32}$/i'; - - public function testGenerateKey() - { - $service = new AppKeyGeneratorService; - $key = $service->generateKey(); - - /** - * string generated is an md5 - */ - $this->assertMatchesRegularExpression(self::MD5_REGEX, $key); - - /** - * second string different and matches format - */ - $key2 = $service->generateKey(); - $this->assertMatchesRegularExpression(self::MD5_REGEX, $key2); - $this->assertNotSame($key, $key2); - } -} diff --git a/src/Centreon/Tests/Domain/Repository/TopologyRepositoryTest.php b/src/Centreon/Tests/Domain/Repository/TopologyRepositoryTest.php index 9a13235a202..1c986ef6f0f 100644 --- a/src/Centreon/Tests/Domain/Repository/TopologyRepositoryTest.php +++ b/src/Centreon/Tests/Domain/Repository/TopologyRepositoryTest.php @@ -52,7 +52,7 @@ protected function setUp(): void . "FROM acl_topology_relations, acl_topology " . "WHERE acl_topology.acl_topo_activate = '1' " . "AND acl_topology.acl_topo_id = acl_topology_relations.acl_topo_id " - . "AND acl_topology_relations.acl_topo_id = '1' ", + . "AND acl_topology_relations.acl_topo_id = :acl_topo_id ", 'data' => [ [ 'topology_topology_id' => 1, diff --git a/src/Centreon/Tests/ServiceProviderTest.php b/src/Centreon/Tests/ServiceProviderTest.php index c299d0c64b7..6193ce456a8 100644 --- a/src/Centreon/Tests/ServiceProviderTest.php +++ b/src/Centreon/Tests/ServiceProviderTest.php @@ -83,7 +83,6 @@ public function testCheckServicesByList() ServiceProvider::CENTREON_DB_MANAGER => Service\CentreonDBManagerService::class, ServiceProvider::UPLOAD_MANGER => Service\UploadFileService::class, ServiceProvider::CENTREON_PAGINATION => Service\CentreonPaginationService::class, - 'centreon.keygen' => Domain\Service\AppKeyGeneratorService::class, 'centreon.acl' => CentreonACL::class, 'centreon.config' => Service\CentcoreConfigService::class, ServiceProvider::CENTREON_BROKER_CONFIGURATION_SERVICE => Domain\Service\BrokerConfigurationService::class, diff --git a/src/CentreonRemote/Domain/Service/TaskService.php b/src/CentreonRemote/Domain/Service/TaskService.php index cf38eb2d642..709aaa934fd 100644 --- a/src/CentreonRemote/Domain/Service/TaskService.php +++ b/src/CentreonRemote/Domain/Service/TaskService.php @@ -31,11 +31,6 @@ class TaskService { - /** - * @var KeyGeneratorInterface - */ - private $gen; - /** * @var CentreonDBManagerService */ @@ -101,15 +96,12 @@ public function getCentreonRestHttp(): \CentreonRestHttp /** * TaskService constructor - * @param KeyGeneratorInterface $generator * @param CentreonDBManagerService $dbManager */ public function __construct( - KeyGeneratorInterface $generator, CentreonDBManagerService $dbManager, CentcoreCommandService $cmdService ) { - $this->gen = $generator; $this->dbManager = $dbManager; $this->cmdService = $cmdService; } diff --git a/src/CentreonRemote/ServiceProvider.php b/src/CentreonRemote/ServiceProvider.php index f20bd285994..824c83edbf9 100644 --- a/src/CentreonRemote/ServiceProvider.php +++ b/src/CentreonRemote/ServiceProvider.php @@ -23,7 +23,6 @@ use Pimple\Container; use Pimple\Psr11\ServiceLocator; -use Centreon\Domain\Service\AppKeyGeneratorService; use Centreon\Infrastructure\Provider\AutoloadServiceProviderInterface; use Centreon\Infrastructure\Service\CentcoreCommandService; use CentreonRemote\Application\Webservice; @@ -85,7 +84,6 @@ function (array $cc, Container $pimple) { $pimple[static::CENTREON_TASKSERVICE] = function (Container $pimple): TaskService { $service = new TaskService( - new AppKeyGeneratorService(), $pimple[\Centreon\ServiceProvider::CENTREON_DB_MANAGER], new CentcoreCommandService() ); diff --git a/src/Core/Security/Application/ProviderConfiguration/OpenId/UseCase/UpdateOpenIdConfiguration/UpdateOpenIdConfiguration.php b/src/Core/Security/Application/ProviderConfiguration/OpenId/UseCase/UpdateOpenIdConfiguration/UpdateOpenIdConfiguration.php index f7ad538172f..14ad35d5953 100644 --- a/src/Core/Security/Application/ProviderConfiguration/OpenId/UseCase/UpdateOpenIdConfiguration/UpdateOpenIdConfiguration.php +++ b/src/Core/Security/Application/ProviderConfiguration/OpenId/UseCase/UpdateOpenIdConfiguration/UpdateOpenIdConfiguration.php @@ -154,6 +154,11 @@ private function createAuthorizationRules(array $authorizationRulesFromRequest): { $this->info('Creating Authorization Rules'); $accessGroupIds = $this->getAccessGroupIds($authorizationRulesFromRequest); + + if (empty($accessGroupIds)) { + return []; + } + $foundAccessGroups = $this->accessGroupRepository->findByIds($accessGroupIds); $this->logNonExistentAccessGroupsIds($accessGroupIds, $foundAccessGroups); @@ -241,12 +246,10 @@ private function updateConfiguration(Configuration $configuration): void } $this->info('Updating OpenID Configuration'); $this->repository->updateConfiguration($configuration); - if (! empty($configuration->getAuthorizationRules())) { - $this->info('Removing existent Authorization Rules'); - $this->repository->deleteAuthorizationRules(); - $this->info('Inserting new Authorization Rules'); - $this->repository->insertAuthorizationRules($configuration->getAuthorizationRules()); - } + $this->info('Removing existent Authorization Rules'); + $this->repository->deleteAuthorizationRules(); + $this->info('Inserting new Authorization Rules'); + $this->repository->insertAuthorizationRules($configuration->getAuthorizationRules()); if (! $isAlreadyInTransaction) { $this->dataStorageEngine->commitTransaction(); } diff --git a/src/Core/Security/Application/UseCase/LoginOpenIdSession/LoginOpenIdSession.php b/src/Core/Security/Application/UseCase/LoginOpenIdSession/LoginOpenIdSession.php index 8a70c1513b9..a7f203aae26 100644 --- a/src/Core/Security/Application/UseCase/LoginOpenIdSession/LoginOpenIdSession.php +++ b/src/Core/Security/Application/UseCase/LoginOpenIdSession/LoginOpenIdSession.php @@ -109,7 +109,8 @@ public function __invoke(LoginOpenIdSessionRequest $request, LoginOpenIdSessionP 'contact_location' => (string) $user->getTimezoneId(), 'show_deprecated_pages' => $user->isUsingDeprecatedPages(), 'reach_api' => $user->hasAccessToApiConfiguration() ? 1 : 0, - 'reach_api_rt' => $user->hasAccessToApiRealTime() ? 1 : 0 + 'reach_api_rt' => $user->hasAccessToApiRealTime() ? 1 : 0, + 'contact_theme' => $user->getTheme() ?? 'light' ]; $this->provider->setLegacySession(new \Centreon($sessionUserInfos)); $this->startLegacySession($this->provider->getLegacySession()); diff --git a/src/EventSubscriber/WebSSOEventSubscriber.php b/src/EventSubscriber/WebSSOEventSubscriber.php index b3d75f391c0..e47b7355844 100644 --- a/src/EventSubscriber/WebSSOEventSubscriber.php +++ b/src/EventSubscriber/WebSSOEventSubscriber.php @@ -252,10 +252,11 @@ private function createSession(Contact $user, Request $request): void 'contact_autologin_key' => '', 'contact_admin' => $user->isAdmin() ? '1' : '0', 'default_page' => $user->getDefaultPage(), - 'contact_location' => $user->getLocale(), + 'contact_location' => (string) $user->getTimezoneId(), 'show_deprecated_pages' => $user->isUsingDeprecatedPages(), 'reach_api' => $user->hasAccessToApiConfiguration() ? 1 : 0, - 'reach_api_rt' => $user->hasAccessToApiRealTime() ? 1 : 0 + 'reach_api_rt' => $user->hasAccessToApiRealTime() ? 1 : 0, + 'contact_theme' => $user->getTheme() ?? 'light' ]; $centreonSession = new \Centreon($sessionUserInfos); $request->getSession()->start(); diff --git a/www/class/centreon-clapi/centreon.Config.Poller.class.php b/www/class/centreon-clapi/centreon.Config.Poller.class.php index 216e29b9eef..5270c5efdbd 100644 --- a/www/class/centreon-clapi/centreon.Config.Poller.class.php +++ b/www/class/centreon-clapi/centreon.Config.Poller.class.php @@ -40,7 +40,6 @@ use Centreon\Domain\Entity\Task; use CentreonRemote\ServiceProvider; use CentreonRemote\Domain\Service\TaskService; -use Centreon\Domain\Service\AppKeyGeneratorService; use Centreon\Infrastructure\Service\CentcoreCommandService; use Centreon\Infrastructure\Service\CentreonDBManagerService; use Core\Domain\Engine\Model\EngineCommandGenerator; diff --git a/www/class/centreon-clapi/centreonAPI.class.php b/www/class/centreon-clapi/centreonAPI.class.php index dd4cbadda48..2b7332d2bf4 100644 --- a/www/class/centreon-clapi/centreonAPI.class.php +++ b/www/class/centreon-clapi/centreonAPI.class.php @@ -107,7 +107,7 @@ public function __construct( $this->login = htmlentities($user, ENT_QUOTES); } if (isset($password)) { - $this->password = htmlentities($password, ENT_QUOTES); + $this->password = filter_var($password, FILTER_SANITIZE_STRING); } if (isset($action)) { $this->action = htmlentities(strtoupper($action), ENT_QUOTES); diff --git a/www/class/centreon-clapi/centreonHostGroup.class.php b/www/class/centreon-clapi/centreonHostGroup.class.php index 56d254c49c1..fa722541278 100644 --- a/www/class/centreon-clapi/centreonHostGroup.class.php +++ b/www/class/centreon-clapi/centreonHostGroup.class.php @@ -174,6 +174,7 @@ public function getparam($parameters = null) $listParam = explode('|', $params[1]); $exportedFields = []; $resultString = ""; + $paramString = ""; foreach ($listParam as $paramSearch) { if (!$paramString) { $paramString = $paramSearch; @@ -257,20 +258,24 @@ public function initUpdateParameters($parameters = null) public function getIdIcon($path) { $iconData = explode('/', $path); - $query = 'SELECT dir_id FROM view_img_dir WHERE dir_name = "' . $iconData[0] . '"'; - $res = $this->db->query($query); - $row = $res->fetch(); + $dirStatement = $this->db->prepare("SELECT dir_id FROM view_img_dir WHERE dir_name = :IconData"); + $dirStatement->bindValue(':IconData', $iconData[0], \PDO::PARAM_STR); + $dirStatement->execute(); + $row = $dirStatement->fetch(); $dirId = $row['dir_id']; - $query = 'SELECT img_id FROM view_img WHERE img_path = "' . $iconData[1] . '"'; - $res = $this->db->query($query); - $row = $res->fetch(); + $imgStatement = $this->db->prepare("SELECT img_id FROM view_img WHERE img_path = :iconData"); + $imgStatement->bindValue(':iconData', $iconData[1], \PDO::PARAM_STR); + $imgStatement->execute(); + $row = $imgStatement->fetch(); $iconId = $row['img_id']; - $query = 'SELECT vidr_id FROM view_img_dir_relation ' . - 'WHERE dir_dir_parent_id = ' . $dirId . ' AND img_img_id = ' . $iconId; - $res = $this->db->query($query); - $row = $res->fetch(); + $vidrStatement = $this->db->prepare("SELECT vidr_id FROM view_img_dir_relation " . + "WHERE dir_dir_parent_id = :dirId AND img_img_id = :iconId"); + $vidrStatement->bindValue(':dirId', (int) $dirId, \PDO::PARAM_INT); + $vidrStatement->bindValue(':iconId', (int) $iconId, \PDO::PARAM_INT); + $vidrStatement->execute(); + $row = $vidrStatement->fetch(); return $row['vidr_id']; } diff --git a/www/class/centreon-clapi/centreonLDAP.class.php b/www/class/centreon-clapi/centreonLDAP.class.php index 67b6a702ba5..4aacbc33a45 100644 --- a/www/class/centreon-clapi/centreonLDAP.class.php +++ b/www/class/centreon-clapi/centreonLDAP.class.php @@ -184,10 +184,12 @@ public function showserver($arName = null) } $sql = "SELECT ldap_host_id, host_address, host_port, use_ssl, use_tls, host_order FROM auth_ressource_host - WHERE auth_ressource_id = " . $arId . " + WHERE auth_ressource_id = :auth_ressource_id ORDER BY host_order"; - $res = $this->db->query($sql); - $row = $res->fetchAll(); + $statement = $this->db->prepare($sql); + $statement->bindValue(':auth_ressource_id', (int) $arId, \PDO::PARAM_INT); + $statement->execute(); + $row = $statement->fetchAll(\PDO::FETCH_ASSOC); echo "id;address;port;ssl;tls;order\n"; foreach ($row as $srv) { echo $srv['ldap_host_id'] . $this->delim . diff --git a/www/class/centreon-clapi/centreonService.class.php b/www/class/centreon-clapi/centreonService.class.php index e02b0e76d0e..d3f8ec84b6f 100644 --- a/www/class/centreon-clapi/centreonService.class.php +++ b/www/class/centreon-clapi/centreonService.class.php @@ -1584,12 +1584,12 @@ public function getCustomMacroInDb($serviceId = null, $template = null) $arr = array(); $i = 0; if ($serviceId) { - $res = $this->db->query("SELECT svc_macro_name, svc_macro_value, is_password, description - FROM on_demand_macro_service - WHERE svc_svc_id = " . - $serviceId . " - ORDER BY macro_order ASC"); - while ($row = $res->fetch()) { + $statement = $this->db->prepare("SELECT svc_macro_name, svc_macro_value, is_password, description " . + "FROM on_demand_macro_service " . + "WHERE svc_svc_id = :serviceId ORDER BY macro_order ASC"); + $statement->bindValue(':serviceId', (int) $serviceId, \PDO::PARAM_INT); + $statement->execute(); + while ($row = $statement->fetch()) { if (preg_match('/\$_SERVICE(.*)\$$/', $row['svc_macro_name'], $matches)) { $arr[$i]['svc_macro_name'] = $matches[1]; $arr[$i]['svc_macro_value'] = $row['svc_macro_value']; diff --git a/www/class/centreon-knowledge/procedures.class.php b/www/class/centreon-knowledge/procedures.class.php index c20a0a99f7e..cc4feac9351 100644 --- a/www/class/centreon-knowledge/procedures.class.php +++ b/www/class/centreon-knowledge/procedures.class.php @@ -139,13 +139,15 @@ public function getMyHostMultipleTemplateModels($host_id = null) "WHERE host_host_id = '" . $host_id . "' " . "ORDER BY `order`" ); + $statement = $this->centreon_DB->prepare( + "SELECT host_name " . + "FROM host " . + "WHERE host_id = :host_id LIMIT 1" + ); while ($row = $dbResult->fetch()) { - $dbResult2 = $this->centreon_DB->query( - "SELECT host_name " . - "FROM host " . - "WHERE host_id = '" . $row['host_tpl_id'] . "' LIMIT 1" - ); - $hTpl = $dbResult2->fetch(); + $statement->bindValue(':host_id', $row['host_tpl_id'], \PDO::PARAM_INT); + $statement->execute(); + $hTpl = $statement->fetch(\PDO::FETCH_ASSOC); $tplArr[$row['host_tpl_id']] = html_entity_decode($hTpl["host_name"], ENT_QUOTES); } unset($row); diff --git a/www/class/centreon-partition/partEngine.class.php b/www/class/centreon-partition/partEngine.class.php index a7bd5b3c788..52c2e824ec6 100644 --- a/www/class/centreon-partition/partEngine.class.php +++ b/www/class/centreon-partition/partEngine.class.php @@ -426,44 +426,6 @@ public function updateParts($table, $db) } } - /** - * optimize all partitions for a table - * - * @param MysqlTable $table - */ - public function optimizeTablePartitions($table, $db) - { - $tableName = "`" . $table->getSchema() . "`." . $table->getName(); - if (!$table->exists()) { - throw new Exception("Optimize error: Table " . $tableName . " does not exists\n"); - } - - $request = "SELECT PARTITION_NAME FROM information_schema.`PARTITIONS` "; - $request .= "WHERE `TABLE_NAME`='" . $table->getName() . "' "; - $request .= "AND TABLE_SCHEMA='" . $table->getSchema() . "' "; - try { - $dbResult = $db->query($request); - } catch (\PDOException $e) { - throw new Exception( - "Error : Cannot get table schema information for " - . $tableName . ", " . $e->getMessage() . "\n" - ); - } - - while ($row = $dbResult->fetch()) { - $request = "ALTER TABLE " . $tableName . " OPTIMIZE PARTITION `" . $row["PARTITION_NAME"] . "`;"; - try { - $dbResult2 = $db->query($request); - } catch (\PDOException $e) { - throw new Exception( - "Optimize error : Cannot optimize partition " . $row["PARTITION_NAME"] - . " of table " . $tableName . ", " . $e->getMessage() . "\n" - ); - } - } - - $dbResult->closeCursor(); - } /** * list all partitions for a table diff --git a/www/class/centreon.class.php b/www/class/centreon.class.php index c2c09831cbc..07d440217bb 100644 --- a/www/class/centreon.class.php +++ b/www/class/centreon.class.php @@ -162,22 +162,12 @@ public function creatModuleList() $this->modules[$result["name"]] = array( "name" => $result["name"], "gen" => false, - "restart" => false, "license" => false ); if (is_dir("./modules/" . $result["name"] . "/generate_files/")) { $this->modules[$result["name"]]["gen"] = true; } - if (is_dir("./modules/" . $result["name"] . "/restart_pollers/")) { - $this->modules[$result["name"]]["restart"] = true; - } - if (is_dir("./modules/" . $result["name"] . "/restart_pollers/")) { - $this->modules[$result["name"]]["restart"] = true; - } - if (file_exists("./modules/" . $result["name"] . "/license/merethis_lic.zl")) { - $this->modules[$result["name"]]["license"] = true; - } } $dbResult = null; } diff --git a/www/class/centreonConfigCentreonBroker.php b/www/class/centreonConfigCentreonBroker.php index 78619cc3062..60ca6a87fae 100644 --- a/www/class/centreonConfigCentreonBroker.php +++ b/www/class/centreonConfigCentreonBroker.php @@ -790,13 +790,15 @@ public function insertConfig(array $values): bool /* * Get the ID */ - $query = "SELECT config_id FROM cfg_centreonbroker WHERE config_name = '" . $values['name'] . "'"; + $query = "SELECT config_id FROM cfg_centreonbroker WHERE config_name = :config_name"; try { - $res = $this->db->query($query); + $statement = $this->db->prepare($query); + $statement->bindValue(':config_name', $values['name'], \PDO::PARAM_STR); + $statement->execute(); } catch (\PDOException $e) { return false; } - $row = $res->fetch(); + $row = $statement->fetch(\PDO::FETCH_ASSOC); $id = $row['config_id']; /* diff --git a/www/class/centreonCriticality.class.php b/www/class/centreonCriticality.class.php index a64f673422f..4c45040b485 100644 --- a/www/class/centreonCriticality.class.php +++ b/www/class/centreonCriticality.class.php @@ -358,29 +358,4 @@ protected function getServiceCriticality($service_id) } return 0; } - - public function getHostTplCriticities($host_id, $cache) - { - global $pearDB; - - if (!$host_id) { - return null; - } - - $rq = "SELECT host_tpl_id " . - "FROM host_template_relation " . - "WHERE host_host_id = '".$host_id."' " . - "ORDER BY `order`"; - $DBRESULT = $pearDB->query($rq); - while ($row = $DBRESULT->fetchRow()) { - if (isset($cache[$row['host_tpl_id']])) { - return $this->getData($cache[$row['host_tpl_id']], false); - } else { - if ($result_field = $this->getHostTplCriticities($row['host_tpl_id'], $cache)) { - return $result_field; - } - } - } - return null; - } } diff --git a/www/class/centreonDB.class.php b/www/class/centreonDB.class.php index fd77f40a91f..d8195b79703 100644 --- a/www/class/centreonDB.class.php +++ b/www/class/centreonDB.class.php @@ -289,7 +289,7 @@ public static function escape($str, $htmlSpecialChars = false) /** * Query * - * @return PDOStatement|null + * @return CentreonDBStatement|false * @param string $queryString * @param mixed $parameters * @param mixed $parametersArgs @@ -501,4 +501,36 @@ private function logSqlError(string $query, string $message): void { $this->log->insertLog(2, $message . " QUERY : " . $query); } + + /** + * This method returns a column type from a given table and column. + * + * @param string $tableName + * @param string $columnName + * @return string + */ + public function getColumnType(string $tableName, string $columnName): string + { + $query = 'SELECT COLUMN_TYPE + FROM INFORMATION_SCHEMA.COLUMNS + WHERE TABLE_SCHEMA = :dbName + AND TABLE_NAME = :tableName + AND COLUMN_NAME = :columnName'; + + $stmt = $this->prepare($query); + + try { + $stmt->bindValue(':dbName', $this->dsn['database'], \PDO::PARAM_STR); + $stmt->bindValue(':tableName', $tableName, \PDO::PARAM_STR); + $stmt->bindValue(':columnName', $columnName, \PDO::PARAM_STR); + $stmt->execute(); + $result = $stmt->fetch(\PDO::FETCH_ASSOC); + if (! empty($result)) { + return $result['COLUMN_TYPE']; + } + throw new \PDOException("Unable to get column type"); + } catch (\PDOException $e) { + $this->logSqlError($query, $e->getMessage()); + } + } } diff --git a/www/class/centreonHostgroups.class.php b/www/class/centreonHostgroups.class.php index 34dd68d6947..81ff496279a 100644 --- a/www/class/centreonHostgroups.class.php +++ b/www/class/centreonHostgroups.class.php @@ -100,18 +100,19 @@ public function getHostGroupHosts($hg_id = null) } $hosts = array(); - $DBRESULT = $this->DB->query( - "SELECT hgr.host_host_id " . + $statement = $this->DB->prepare("SELECT hgr.host_host_id " . "FROM hostgroup_relation hgr, host h " . - "WHERE hgr.hostgroup_hg_id = '" . $this->DB->escape($hg_id) . "' " . + "WHERE hgr.hostgroup_hg_id = :hgId " . "AND h.host_id = hgr.host_host_id " . - "ORDER by h.host_name" - ); - while ($elem = $DBRESULT->fetchRow()) { + "ORDER by h.host_name"); + $statement->bindValue(':hgId', (int) $hg_id, \PDO::PARAM_INT); + $statement->execute(); + + while ($elem = $statement->fetchRow()) { $ref[$elem["host_host_id"]] = $elem["host_host_id"]; $hosts[] = $elem["host_host_id"]; } - $DBRESULT->closeCursor(); + $statement->closeCursor(); unset($elem); if (isset($hostgroups) && count($hostgroups)) { diff --git a/www/class/centreonMedia.class.php b/www/class/centreonMedia.class.php index afdbec5e3c2..a602b4a6752 100644 --- a/www/class/centreonMedia.class.php +++ b/www/class/centreonMedia.class.php @@ -413,14 +413,12 @@ public function addImage($parameters, $binary = null) $imageId = $row['img_id']; // Insert relation between directory and image - $query = 'INSERT INTO view_img_dir_relation ' - . '(dir_dir_parent_id, img_img_id) ' - . 'VALUES (' - . $directoryId . ', ' - . $imageId . ' ' - . ') '; + $statement = $this->db->prepare("INSERT INTO view_img_dir_relation (dir_dir_parent_id, img_img_id) " . + "VALUES (:dirId, :imgId) "); + $statement->bindValue(':dirId', (int) $directoryId, \PDO::PARAM_INT); + $statement->bindValue(':imgId', (int) $imageId, \PDO::PARAM_INT); try { - $this->db->query($query); + $statement->execute(); } catch (\PDOException $e) { throw new \Exception('Error while inserting relation between' . $imageName . ' and ' . $directoryName); } diff --git a/www/class/centreonNotification.class.php b/www/class/centreonNotification.class.php index 0875cbcb9b1..57003d925b5 100644 --- a/www/class/centreonNotification.class.php +++ b/www/class/centreonNotification.class.php @@ -35,6 +35,9 @@ class CentreonNotification { + /** + * @var CentreonDB $db + */ protected $db; protected $svcTpl; protected $svcNotifType; @@ -342,10 +345,12 @@ protected function getHostTemplateNotifications($hostId, $templates) FROM host_template_relation htr LEFT JOIN contact_host_relation ctr ON htr.host_host_id = ctr.host_host_id LEFT JOIN contactgroup_host_relation ctr2 ON htr.host_host_id = ctr2.host_host_id - WHERE htr.host_host_id = " . $hostId . " + WHERE htr.host_host_id = :host_id ORDER BY `order`"; - $res = $this->db->query($sql); - while ($row = $res->fetchRow()) { + $statement = $this->db->prepare($sql); + $statement->bindValue(':host_id', (int) $hostId, \PDO::PARAM_INT); + $statement->execute(); + while ($row = $statement->fetch(\PDO::FETCH_ASSOC)) { if ($row['contact_id']) { $this->hostBreak[1] = true; } diff --git a/www/class/centreonService.class.php b/www/class/centreonService.class.php index 67149a75a20..19b09c52d96 100644 --- a/www/class/centreonService.class.php +++ b/www/class/centreonService.class.php @@ -1727,12 +1727,14 @@ public function getTemplatesChain($svcId, $alreadyProcessed = array()) } else { $alreadyProcessed[] = $svcId; - $res = $this->db->query( - "SELECT service_template_model_stm_id FROM service WHERE service_id = " . $this->db->escape($svcId) + $statement = $this->db->prepare( + "SELECT service_template_model_stm_id FROM service WHERE service_id = :service_id" ); + $statement->bindValue(':service_id', (int) $svcId, \PDO::PARAM_INT); + $statement->execute(); - if ($res->rowCount()) { - $row = $res->fetchRow(); + if ($statement->rowCount()) { + $row = $statement->fetch(\PDO::FETCH_ASSOC); if (!empty($row['service_template_model_stm_id']) && $row['service_template_model_stm_id'] !== null) { $svcTmpl = array_merge( $svcTmpl, diff --git a/www/class/config-generate/broker.class.php b/www/class/config-generate/broker.class.php index 63e0f206510..68493d48a65 100644 --- a/www/class/config-generate/broker.class.php +++ b/www/class/config-generate/broker.class.php @@ -217,7 +217,8 @@ private function generate($poller_id, $localhost) } $subValuesToCastInArray = []; - $rrdCacheOption = 'disable'; + $rrdCacheOption = null; + $rrdCached = null; foreach ($value as $subvalue) { if ( !isset($subvalue['fieldIndex']) @@ -236,21 +237,20 @@ private function generate($poller_id, $localhost) } elseif ($subvalue['config_key'] === 'category') { $object[$key][$subvalue['config_group_id']]['filters'][$subvalue['config_key']][] = $subvalue['config_value']; - } else { + } elseif (in_array($subvalue['config_key'], ['rrd_cached_option', 'rrd_cached'])) { if ($subvalue['config_key'] === 'rrd_cached_option') { $rrdCacheOption = $subvalue['config_value']; - continue; + } elseif ($subvalue['config_key'] === 'rrd_cached') { + $rrdCached = $subvalue['config_value']; } - - if ($subvalue['config_key'] === 'rrd_cached') { + if ($rrdCached && $rrdCacheOption) { if ($rrdCacheOption === 'tcp') { - $object[$key][$subvalue['config_group_id']]['port'] = $subvalue['config_value']; + $object[$key][$subvalue['config_group_id']]['port'] = $rrdCached; } elseif ($rrdCacheOption === 'unix') { - $object[$key][$subvalue['config_group_id']]['path'] = $subvalue['config_value']; + $object[$key][$subvalue['config_group_id']]['path'] = $rrdCached; } - continue; } - + } else { $object[$key][$subvalue['config_group_id']][$subvalue['config_key']] = $subvalue['config_value']; diff --git a/www/include/configuration/configCentreonBroker/DB-Func.php b/www/include/configuration/configCentreonBroker/DB-Func.php index 5c8566ca17b..d522e6487e8 100644 --- a/www/include/configuration/configCentreonBroker/DB-Func.php +++ b/www/include/configuration/configCentreonBroker/DB-Func.php @@ -74,8 +74,10 @@ function enableCentreonBrokerInDB($id) return; } - $query = "UPDATE cfg_centreonbroker SET config_activate = '1' WHERE config_id = " . $id; - $pearDB->query($query); + $query = "UPDATE cfg_centreonbroker SET config_activate = '1' WHERE config_id = :config_id"; + $statement = $pearDB->prepare($query); + $statement->bindValue(':config_id', (int) $id, \PDO::PARAM_INT); + $statement->execute(); } /** @@ -91,8 +93,10 @@ function disablCentreonBrokerInDB($id) return; } - $query = "UPDATE cfg_centreonbroker SET config_activate = '0' WHERE config_id = " . $id; - $pearDB->query($query); + $query = "UPDATE cfg_centreonbroker SET config_activate = '0' WHERE config_id = :config_id"; + $statement = $pearDB->prepare($query); + $statement->bindValue(':config_id', (int) $id, \PDO::PARAM_INT); + $statement->execute(); } /** @@ -104,8 +108,10 @@ function deleteCentreonBrokerInDB($ids = array()) { global $pearDB; + $statement = $pearDB->prepare("DELETE FROM cfg_centreonbroker WHERE config_id = :config_id"); foreach ($ids as $key => $value) { - $pearDB->query("DELETE FROM cfg_centreonbroker WHERE config_id = " . $key); + $statement->bindValue(':config_id', (int) $key, \PDO::PARAM_INT); + $statement->execute(); } } @@ -195,13 +201,7 @@ function multipleCentreonBrokerInDB($ids, $nbrDup) foreach ($ids as $id => $value) { $cbObj = new CentreonConfigCentreonBroker($pearDB); - $query = "SELECT config_name, config_filename, config_activate, ns_nagios_server, - event_queue_max_size, cache_directory, daemon " - . "FROM cfg_centreonbroker " - . "WHERE config_id = " . $id . " "; - $dbResult = $pearDB->query($query); - $row = $dbResult->fetch(); - $dbResult->closeCursor(); + $row = getCfgBrokerData((int) $id); # Prepare values $values = array(); @@ -211,13 +211,10 @@ function multipleCentreonBrokerInDB($ids, $nbrDup) $values['event_queue_max_size'] = $row['event_queue_max_size']; $values['cache_directory'] = $row['cache_directory']; $values['activate_watchdog']['activate_watchdog'] = $row['daemon']; - $query = "SELECT config_key, config_value, config_group, config_group_id " - . "FROM cfg_centreonbroker_info " - . "WHERE config_id = " . $id . " "; - $dbResult = $pearDB->query($query); $values['output'] = array(); $values['input'] = array(); - while ($rowOpt = $dbResult->fetch()) { + $brokerCfgInfoData = getCfgBrokerInfoData((int) $id); + foreach ($brokerCfgInfoData as $rowOpt) { if ($rowOpt['config_key'] == 'filters') { continue; } elseif ($rowOpt['config_key'] == 'category') { @@ -228,7 +225,6 @@ function multipleCentreonBrokerInDB($ids, $nbrDup) $rowOpt['config_value']; } } - $dbResult->closeCursor(); # Convert values radio button foreach ($values as $group => $groups) { @@ -254,6 +250,8 @@ function multipleCentreonBrokerInDB($ids, $nbrDup) # Copy the configuration $j = 1; + $query = "SELECT COUNT(*) as nb FROM cfg_centreonbroker WHERE config_name = :config_name"; + $statement = $pearDB->prepare($query); for ($i = 1; $i <= $nbrDup[$id]; $i++) { $nameNOk = true; @@ -261,9 +259,9 @@ function multipleCentreonBrokerInDB($ids, $nbrDup) while ($nameNOk) { $newname = $row['config_name'] . '_' . $j; $newfilename = $j . '_' . $row['config_filename']; - $query = "SELECT COUNT(*) as nb FROM cfg_centreonbroker WHERE config_name = '" . $newname . "'"; - $res = $pearDB->query($query); - $rowNb = $res->fetch(); + $statement->bindValue(':config_name', $newname, \PDO::PARAM_STR); + $statement->execute(); + $rowNb = $statement->fetch(\PDO::FETCH_ASSOC); if ($rowNb['nb'] == 0) { $nameNOk = false; } @@ -293,3 +291,54 @@ function isPositiveNumeric($size): bool } return $isPositive; } + +/** + * Getting Centreon CFG broker data + * + * @param int $configId + * @return array + */ +function getCfgBrokerData(int $configId): array +{ + global $pearDB; + + $query = "SELECT config_name, config_filename, config_activate, ns_nagios_server, + event_queue_max_size, cache_directory, daemon " + . "FROM cfg_centreonbroker " + . "WHERE config_id = :config_id "; + try { + $statement = $pearDB->prepare($query); + $statement->bindValue(':config_id', $configId, \PDO::PARAM_INT); + $statement->execute(); + $cfgBrokerData = $statement->fetch(\PDO::FETCH_ASSOC); + } catch (PDOException $exception) { + throw new \Exception("Cannot fetch Broker config data"); + } + $statement->closeCursor(); + return $cfgBrokerData; +} + +/** + * Getting Centreon CFG broker Info data + * + * @param int $configId + * @return array + */ +function getCfgBrokerInfoData(int $configId): array +{ + global $pearDB; + + $query = "SELECT config_key, config_value, config_group, config_group_id " + . "FROM cfg_centreonbroker_info " + . "WHERE config_id = :config_id"; + try { + $statement = $pearDB->prepare($query); + $statement->bindValue(':config_id', $configId, \PDO::PARAM_INT); + $statement->execute(); + $cfgBrokerInfoData = $statement->fetchAll(\PDO::FETCH_ASSOC); + } catch (\PDOException $exception) { + throw new \Exception("Cannot fetch Broker info config data"); + } + $statement->closeCursor(); + return $cfgBrokerInfoData; +} diff --git a/www/include/configuration/configGenerate/xml/restartPollers.php b/www/include/configuration/configGenerate/xml/restartPollers.php index 9ac4415e907..f0f765eefa8 100644 --- a/www/include/configuration/configGenerate/xml/restartPollers.php +++ b/www/include/configuration/configGenerate/xml/restartPollers.php @@ -259,18 +259,6 @@ $msg_restart[$key] = str_replace("\n", "
", $str); } - /* Find restart / reload action from modules */ - foreach ($centreon->modules as $key => $value) { - if ( - $value["restart"] - && $files = glob(_CENTREON_PATH_ . "www/modules/" . $key . "/restart_pollers/*.php") - ) { - foreach ($files as $filename) { - include $filename; - } - } - } - $xml->startElement("response"); $xml->writeElement("status", $okMsg); $xml->writeElement("statuscode", STATUS_OK); diff --git a/www/include/configuration/configKnowledge/display-hostTemplates.php b/www/include/configuration/configKnowledge/display-hostTemplates.php index 9595a6560a4..c64be5baf06 100644 --- a/www/include/configuration/configKnowledge/display-hostTemplates.php +++ b/www/include/configuration/configKnowledge/display-hostTemplates.php @@ -167,11 +167,11 @@ foreach ($tplArr as $key1 => $value1) { if ($firstTpl) { $tplStr .= " " . $value1 . " "; + "/index.php?title=Host-Template_:_" . $value1 . "' target = '_blank' > " . $value1 . " "; $firstTpl = 0; } else { $tplStr .= " |  " . $value1 . " "; + "/index.php?title=Host-Template_:_" . $value1 . "' target = '_blank' > " . $value1 . " "; } } } diff --git a/www/include/configuration/configKnowledge/display-hosts.php b/www/include/configuration/configKnowledge/display-hosts.php index 0bc0e4d525a..bfa2e97dab6 100644 --- a/www/include/configuration/configKnowledge/display-hosts.php +++ b/www/include/configuration/configKnowledge/display-hosts.php @@ -192,11 +192,11 @@ foreach ($tplArr as $key1 => $value1) { if ($firstTpl) { $tplStr .= "" . $value1 . ""; + "/index.php?title=Host-Template_:_" . $value1 . "' target='_blank'>" . $value1 . ""; $firstTpl = 0; } else { $tplStr .= " | " . $value1 . ""; + "/index.php?title=Host-Template_:_" . $value1 . "' target='_blank'>" . $value1 . ""; } } } diff --git a/www/include/configuration/configKnowledge/display-serviceTemplates.php b/www/include/configuration/configKnowledge/display-serviceTemplates.php index a609fc22e54..fab6889c54b 100644 --- a/www/include/configuration/configKnowledge/display-serviceTemplates.php +++ b/www/include/configuration/configKnowledge/display-serviceTemplates.php @@ -170,11 +170,11 @@ foreach ($tplArr as $key1 => $value1) { if ($firstTpl) { $tplStr .= "" . $value1 . ""; + "/index.php?title=Service-Template_:_" . $value1 . "' target='_blank'>" . $value1 . ""; $firstTpl = 0; } else { $tplStr .= " | " . $value1 . ""; + "/index.php?title=Service-Template_:_" . $value1 . "' target='_blank'>" . $value1 . ""; } } } diff --git a/www/include/configuration/configKnowledge/display-services.php b/www/include/configuration/configKnowledge/display-services.php index d59f4ad69bf..87028122654 100644 --- a/www/include/configuration/configKnowledge/display-services.php +++ b/www/include/configuration/configKnowledge/display-services.php @@ -274,7 +274,7 @@ $tplStr .= " | "; } $tplStr .= "" . $value1 . ""; + "/index.php?title=Service-Template_:_" . $value1 . "' target='_blank'>" . $value1 . ""; } } $templateHostArray[$key] = $tplStr; diff --git a/www/include/configuration/configObject/contactgroup/formContactGroup.php b/www/include/configuration/configObject/contactgroup/formContactGroup.php index 4112ceb27b7..fa2bfb9215a 100644 --- a/www/include/configuration/configObject/contactgroup/formContactGroup.php +++ b/www/include/configuration/configObject/contactgroup/formContactGroup.php @@ -64,12 +64,14 @@ /* * Get host Group information */ - $DBRESULT = $pearDB->query("SELECT * FROM `contactgroup` WHERE `cg_id` = '" . $cg_id . "' LIMIT 1"); + $statement = $pearDB->prepare("SELECT * FROM `contactgroup` WHERE `cg_id` = :cg_id LIMIT 1"); + $statement->bindValue(':cg_id', (int) $cg_id, \PDO::PARAM_INT); + $statement->execute(); /* * Set base value */ - $cg = array_map("myDecode", $DBRESULT->fetchRow()); + $cg = array_map("myDecode", $statement->fetch(\PDO::FETCH_ASSOC)); } $attrsText = array("size" => "30"); diff --git a/www/include/configuration/configObject/host_categories/listHostCategories.php b/www/include/configuration/configObject/host_categories/listHostCategories.php index bc454267abe..81a3ae8c25a 100644 --- a/www/include/configuration/configObject/host_categories/listHostCategories.php +++ b/www/include/configuration/configObject/host_categories/listHostCategories.php @@ -141,16 +141,16 @@ $aclFrom = ", $aclDbName.centreon_acl acl "; $aclCond = " AND h.host_id = acl.host_id AND acl.group_id IN (" . $acl->getAccessGroupsString() . ") "; } - $DBRESULT2 = $pearDB->query( - "SELECT h.host_id, h.host_activate " . + $hcStatement = $pearDB->prepare("SELECT h.host_id, h.host_activate " . "FROM hostcategories_relation hcr, host h " . $aclFrom . - " WHERE hostcategories_hc_id = '" . $hc['hc_id'] . "'" . + " WHERE hostcategories_hc_id = :hcId" . " AND h.host_id = hcr.host_host_id " . $aclCond . - " AND h.host_register = '1' " - ); + " AND h.host_register = '1' "); + $hcStatement->bindValue(':hcId', (int) $hc['hc_id'], \PDO::PARAM_INT); + $hcStatement->execute(); $nbrhostActArr = array(); $nbrhostDeactArr = array(); - while ($row = $DBRESULT2->fetch()) { + while ($row = $hcStatement->fetch()) { if ($row['host_activate']) { $nbrhostActArr[$row['host_id']] = true; } else { diff --git a/www/include/configuration/configObject/service/listServiceByHost.php b/www/include/configuration/configObject/service/listServiceByHost.php index e1c9858a9b3..cb1eb092951 100644 --- a/www/include/configuration/configObject/service/listServiceByHost.php +++ b/www/include/configuration/configObject/service/listServiceByHost.php @@ -245,14 +245,16 @@ $centreonToken = createCSRFToken(); +$statement = $pearDB->prepare( + "SELECT COUNT(*) FROM host_service_relation WHERE service_service_id = :service_id" +); for ($i = 0; $service = $dbResult->fetch(); $i++) { //Get Number of Hosts linked to this one. - $dbResult2 = $pearDB->query( - "SELECT COUNT(*) FROM host_service_relation WHERE service_service_id = '" . $service["service_id"] . "'" - ); - $data = $dbResult2->fetch(); + $statement->bindValue(':service_id', $service["service_id"], \PDO::PARAM_INT); + $statement->execute(); + $data = $statement->fetch(\PDO::FETCH_ASSOC); $service["nbr"] = $data["COUNT(*)"]; - $dbResult2->closeCursor(); + $statement->closeCursor(); unset($data); /** diff --git a/www/include/configuration/configObject/service/listServiceByHostGroup.php b/www/include/configuration/configObject/service/listServiceByHostGroup.php index 2a41e12699d..a076bd80711 100644 --- a/www/include/configuration/configObject/service/listServiceByHostGroup.php +++ b/www/include/configuration/configObject/service/listServiceByHostGroup.php @@ -202,27 +202,56 @@ * HostGroup/service list */ if ($searchS || $searchHG) { + //preparing tmp binds + $tmpIds = explode(',', $tmp); + $tmpQueryBinds = []; + foreach ($tmpIds as $key => $value) { + $tmpQueryBinds[':tmp_id_' . $key] = $value; + } + $tmpBinds = implode(',', array_keys($tmpQueryBinds)); + //preparing tmp2 binds + $tmp2Ids = explode(',', $tmp2); + $tmp2QueryBinds = []; + foreach ($tmp2Ids as $key => $value) { + $tmp2QueryBinds[':tmp2_id_' . $key] = $value; + } + $tmp2Binds = implode(',', array_keys($tmp2QueryBinds)); + $query = "SELECT $distinct @nbr:=(SELECT COUNT(*) FROM host_service_relation " . "WHERE service_service_id = sv.service_id GROUP BY sv.service_id ) AS nbr, sv.service_id, " . "sv.service_description, sv.service_activate, sv.service_template_model_stm_id, hg.hg_id, hg.hg_name " . "FROM service sv, hostgroup hg, host_service_relation hsr $aclFrom " . - "WHERE sv.service_register = '1' $sqlFilterCase AND sv.service_id IN (" . ($tmp ? $tmp : 'NULL') . - ") AND hsr.hostgroup_hg_id IN (" . ($tmp2 ? $tmp2 : 'NULL') . ") " . - ((isset($template) && $template) ? " AND service_template_model_stm_id = '$template' " : "") . + "WHERE sv.service_register = '1' $sqlFilterCase AND sv.service_id " . + "IN ($tmpBinds) AND hsr.hostgroup_hg_id IN ($tmp2Binds) " . + ((isset($template) && $template) ? " AND service_template_model_stm_id = :template " : "") . " AND hsr.service_service_id = sv.service_id AND hg.hg_id = hsr.hostgroup_hg_id " . $aclCond . - "ORDER BY hg.hg_name, sv.service_description LIMIT " . $num * $limit . ", " . $limit; + "ORDER BY hg.hg_name, sv.service_description LIMIT :offset_, :limit"; + $statement = $pearDB->prepare($query); + //tmp bind values + foreach ($tmpQueryBinds as $key => $value) { + $statement->bindValue($key, (int) $value, PDO::PARAM_INT); + } + //tmp bind values + foreach ($tmp2QueryBinds as $key => $value) { + $statement->bindValue($key, (int) $value, PDO::PARAM_INT); + } } else { $query = "SELECT $distinct @nbr:=(SELECT COUNT(*) FROM host_service_relation " . "WHERE service_service_id = sv.service_id GROUP BY sv.service_id ) AS nbr, sv.service_id, " . "sv.service_description, sv.service_activate, sv.service_template_model_stm_id, hg.hg_id, hg.hg_name " . "FROM service sv, hostgroup hg, host_service_relation hsr $aclFrom " . "WHERE sv.service_register = '1' $sqlFilterCase " . - ((isset($template) && $template) ? " AND service_template_model_stm_id = '$template' " : "") . + ((isset($template) && $template) ? " AND service_template_model_stm_id = :template " : "") . " AND hsr.service_service_id = sv.service_id AND hg.hg_id = hsr.hostgroup_hg_id " . $aclCond . - "ORDER BY hg.hg_name, sv.service_description LIMIT " . $num * $limit . ", " . $limit; + "ORDER BY hg.hg_name, sv.service_description LIMIT :offset_, :limit"; + $statement = $pearDB->prepare($query); } -$dbResult = $pearDB->query($query); - +$statement->bindValue(':offset_', (int) $num * (int) $limit, \PDO::PARAM_INT); +$statement->bindValue(':limit', (int) $limit, \PDO::PARAM_INT); +if ((isset($template) && $template)) { + $statement->bindValue(':template', (int) $template, \PDO::PARAM_INT); +} +$statement->execute(); $form = new HTML_QuickFormCustom('select_form', 'POST', "?p=" . $p); // Different style between each lines @@ -263,7 +292,7 @@ $centreonToken = createCSRFToken(); -for ($i = 0; $service = $dbResult->fetch(); $i++) { +for ($i = 0; $service = $statement->fetch(); $i++) { $moptions = ""; $fgHostgroup["value"] != $service["hg_name"] ? ($fgHostgroup["print"] = true && $fgHostgroup["value"] = $service["hg_name"]) diff --git a/www/include/configuration/configObject/traps-groups/DB-Func.php b/www/include/configuration/configObject/traps-groups/DB-Func.php index b36febd1d22..fe45b6abc19 100644 --- a/www/include/configuration/configObject/traps-groups/DB-Func.php +++ b/www/include/configuration/configObject/traps-groups/DB-Func.php @@ -172,10 +172,12 @@ function insertTrapGroup($ret = array()) $fields = array(); if (isset($ret['traps'])) { + $query = "INSERT INTO traps_group_relation (traps_group_id, traps_id) VALUES (:traps_group_id, :traps_id)"; + $statement = $pearDB->prepare($query); foreach ($ret['traps'] as $trap_id) { - $query = "INSERT INTO traps_group_relation (traps_group_id, traps_id) VALUES (" . - $pearDB->escape($trap_group_id['max_id']) . ",'" . $pearDB->escape($trap_id) . "')"; - $pearDB->query($query); + $statement->bindValue(':traps_group_id', $trap_group_id['max_id'], \PDO::PARAM_INT); + $statement->bindValue(':traps_id', (int) $trap_id, \PDO::PARAM_INT); + $statement->execute(); } } diff --git a/www/include/configuration/configObject/traps/listTraps.php b/www/include/configuration/configObject/traps/listTraps.php index 9c96c83ced7..1dfafef18a1 100644 --- a/www/include/configuration/configObject/traps/listTraps.php +++ b/www/include/configuration/configObject/traps/listTraps.php @@ -200,9 +200,11 @@ "event.returnValue = false; if(event.which > 31 && (event.which < 45 || event.which > 57)) return false;" . "\" maxlength=\"3\" size=\"3\" value='1' style=\"margin-bottom:0px;\" name='dupNbr[" . $trap['traps_id'] . "]' />"; - $dbResult2 = $pearDB->query("select alias from traps_vendor where id='" . $trap['manufacturer_id'] . "' LIMIT 1"); - $mnftr = $dbResult2->fetch(); - $dbResult2->closeCursor(); + $statement = $pearDB->prepare("select alias from traps_vendor where id= :trap LIMIT 1"); + $statement->bindValue(':trap', (int) $trap['manufacturer_id'], \PDO::PARAM_INT); + $statement->execute(); + $mnftr = $statement->fetch(); + $statement->closeCursor(); $elemArr[$i] = array( "MenuClass" => "list_" . $style, "RowMenu_select" => $selectedElements->toHtml(), diff --git a/www/include/monitoring/common-Func.php b/www/include/monitoring/common-Func.php index cb8fb71330c..f940fcbf379 100644 --- a/www/include/monitoring/common-Func.php +++ b/www/include/monitoring/common-Func.php @@ -41,26 +41,6 @@ exit(); } -function getMyHostRow($host_id = null, $rowdata) -{ - global $pearDB; - if (!$host_id) { - exit(); - } - while (1) { - $DBRESULT = $pearDB->query("SELECT host_" . $rowdata . - ", host_template_model_htm_id FROM host WHERE host_id = '" . CentreonDB::escape($host_id) . "' LIMIT 1"); - $row = $DBRESULT->fetchRow(); - if ($row["host_" . $rowdata]) { - return $row["host_$rowdata"]; - } elseif ($row["host_template_model_htm_id"]) { - $host_id = $row["host_template_model_htm_id"]; - } else { - break; - } - } -} - function get_user_param($user_id, $pearDB) { $list_param = array( diff --git a/www/include/monitoring/objectDetails/serviceDetails.php b/www/include/monitoring/objectDetails/serviceDetails.php index cf71401d922..e0ac888e93c 100644 --- a/www/include/monitoring/objectDetails/serviceDetails.php +++ b/www/include/monitoring/objectDetails/serviceDetails.php @@ -621,18 +621,17 @@ $status .= "&value[" . $key . "]=" . $value; } - $optionsURL = "host_name=" . urlencode($host_name) . "&service_description=" . urlencode($svc_description); - - $query = "SELECT id FROM `index_data`, `metrics` WHERE host_name = '" . $pearDBO->escape($host_name) . - "' AND service_description = '" . $pearDBO->escape($svc_description) . "' AND id = index_id LIMIT 1"; - $DBRES = $pearDBO->query($query); + $query = "SELECT id FROM `index_data`, `metrics` WHERE host_name = :host_name" . + " AND service_description = :svc_description AND id = index_id LIMIT 1"; + $statement = $pearDBO->prepare($query); + $statement->bindValue(':host_name', $host_name, \PDO::PARAM_STR); + $statement->bindValue(':svc_description', $svc_description, \PDO::PARAM_STR); + $statement->execute(); $index_data = 0; - if ($DBRES->rowCount()) { - $row = $DBRES->fetchRow(); + if ($statement->rowCount()) { + $row = $statement->fetchRow(); $index_data = $row['id']; } - $optionsURL2 = "index=" . $index_data; - /* * Assign translations */ @@ -875,9 +874,7 @@ $tpl->assign("sv_ext_action_url_lang", _("Action URL")); $tpl->assign("sv_ext_action_url", CentreonUtils::escapeSecure($actionurl)); $tpl->assign("sv_ext_icon_image_alt", getMyServiceExtendedInfoField($service_id, "esi_icon_image_alt")); - $tpl->assign("options", $optionsURL); $tpl->assign("index_data", $index_data); - $tpl->assign("options2", CentreonUtils::escapeSecure($optionsURL2)); /** * Build the service detail URI that will be used in the diff --git a/www/include/options/accessLists/actionsACL/listsActionsAccess.php b/www/include/options/accessLists/actionsACL/listsActionsAccess.php index 156bee063e1..8427c6ade46 100644 --- a/www/include/options/accessLists/actionsACL/listsActionsAccess.php +++ b/www/include/options/accessLists/actionsACL/listsActionsAccess.php @@ -118,11 +118,6 @@ "return false;\" maxlength=\"3\" size=\"3\" value='1' style=\"margin-bottom:0px;\" name='dupNbr[" . $topo['acl_action_id'] . "]' />"; /* Contacts */ - $ctNbr = array(); - $rq = "SELECT COUNT(*) AS nbr FROM acl_group_actions_relations " . - "WHERE acl_action_id = '" . $topo['acl_action_id'] . "'"; - $DBRESULT2 = $pearDB->query($rq); - $ctNbr = $DBRESULT2->fetchRow(); $elemArr[$i] = array( "MenuClass" => "list_" . $style, "RowMenu_select" => $selectedElements->toHtml(), diff --git a/www/include/options/accessLists/menusACL/listsMenusAccess.php b/www/include/options/accessLists/menusACL/listsMenusAccess.php index b577522220e..f263f150c27 100644 --- a/www/include/options/accessLists/menusACL/listsMenusAccess.php +++ b/www/include/options/accessLists/menusACL/listsMenusAccess.php @@ -116,10 +116,6 @@ "return false;\" maxlength=\"3\" size=\"3\" value='1' style=\"margin-bottom:0px;\" name='dupNbr[" . $topo['acl_topo_id'] . "]' />"; /* Contacts */ - $ctNbr = array(); - $rq2 = "SELECT COUNT(*) AS nbr FROM acl_topology_relations WHERE acl_topo_id = '" . $topo['acl_topo_id'] . "'"; - $dbResult2 = $pearDB->query($rq2); - $ctNbr = $dbResult2->fetchRow(); $elemArr[$i] = array( "MenuClass" => "list_" . $style, "RowMenu_select" => $selectedElements->toHtml(), diff --git a/www/include/options/accessLists/resourcesACL/listsResourcesAccess.php b/www/include/options/accessLists/resourcesACL/listsResourcesAccess.php index ccf7b110d9c..9a32d81e659 100644 --- a/www/include/options/accessLists/resourcesACL/listsResourcesAccess.php +++ b/www/include/options/accessLists/resourcesACL/listsResourcesAccess.php @@ -130,13 +130,6 @@ . $resources['acl_res_id'] . "]'>"; /* Contacts */ - $ctNbr = array(); - $rq = "SELECT COUNT(*) AS nbr - FROM acl_resources_host_relations - WHERE acl_res_id = '" . $resources['acl_res_id'] . "'"; - $DBRESULT2 = $pearDB->query($rq); - $ctNbr = $DBRESULT2->fetchRow(); - $allHostgroups = (isset($resources["all_hostgroups"]) && $resources["all_hostgroups"] == 1 ? _("Yes") : _("No")); $allServicegroups = (isset($resources["all_servicegroups"]) && $resources["all_servicegroups"] == 1 ? _("Yes") : diff --git a/www/include/views/graphs/exportData/ExportCSVMetricData.php b/www/include/views/graphs/exportData/ExportCSVMetricData.php deleted file mode 100644 index ebb1f49a513..00000000000 --- a/www/include/views/graphs/exportData/ExportCSVMetricData.php +++ /dev/null @@ -1,79 +0,0 @@ -. - * - * Linking this program statically or dynamically with other modules is making a - * combined work based on this program. Thus, the terms and conditions of the GNU - * General Public License cover the whole combination. - * - * As a special exception, the copyright holders of this program give Centreon - * permission to link this program with independent modules to produce an executable, - * regardless of the license terms of these independent modules, and to copy and - * distribute the resulting executable under terms of Centreon choice, provided that - * Centreon also meet, for each linked independent module, the terms and conditions - * of the license of that module. An independent module is a module which is not - * derived from this program. If you modify this program, you may extend this - * exception to your version of the program, but you are not obliged to do so. If you - * do not wish to do so, delete this exception statement from your version. - * - * For more information : contact@centreon.com - * - */ - -function get_error($str) -{ - echo $str."
"; - exit(0); -} - -require_once realpath(dirname(__FILE__) . "/../../../../../config/centreon.config.php"); -require_once '../../../class/centreonDB.class.php'; - -$pearDB = new CentreonDB(); -$pearDBO = new CentreonDB("centstorage"); - -session_start(); -session_write_close(); - -$sid = session_id(); -if (isset($sid)) { - $res = $pearDB->query("SELECT * FROM session WHERE session_id = '".$sid."'"); - if (!$session = $res->fetchRow()) { - get_error('bad session id'); - } -} else { - get_error('need session identifiant !'); -} - -isset($_GET["metric_id"]) ? $mtrcs = htmlentities($_GET["metric_id"], ENT_QUOTES, "UTF-8") : $mtrcs = null; -isset($_POST["metric_id"]) ? $mtrcs = htmlentities($_POST["metric_id"], ENT_QUOTES, "UTF-8") : $mtrcs = $mtrcs; - -require_once '../../../class/centreonDuration.class.php'; -require_once '../../common/common-Func.php'; - -$period = (isset($_POST["period"])) ? htmlentities($_POST["period"], ENT_QUOTES, "UTF-8") : "today"; -$period = (isset($_GET["period"])) ? htmlentities($_GET["period"], ENT_QUOTES, "UTF-8") : $period; - -header("Content-Type: application/csv-tab-delimited-table"); -header("Content-disposition: filename=".$mhost.".csv"); - -print "Date;value\n"; -$begin = time() - 26000; - -$res = $pearDB->query("SELECT ctime, value FROM data_bin WHERE id_metric = '".$mtrcs."' AND CTIME >= '".$begin."'"); -while ($data = $res->fetchRow()) { - print $data["ctime"].";".$data["value"].";".date("Y-m-d H:i:s", $data["ctime"])."\n"; -} diff --git a/www/include/views/graphs/graph-periods.html b/www/include/views/graphs/graph-periods.html index b0524ae4700..3d2fdc6a3ee 100644 --- a/www/include/views/graphs/graph-periods.html +++ b/www/include/views/graphs/graph-periods.html @@ -11,7 +11,7 @@
{foreach from=$periods item=period} -
+
{$srv_name} during {$period.long} @@ -54,36 +54,21 @@ /* Add events on click on action download image/CSV */ jQuery('.graphZone').delegate('a.actions', 'click', function (e) { - var $a = jQuery(this); - var baseUrl = $a.data('href'); - var chartId = $a.parents('.graph').data('graphId'); - var start; - var end; - var timezone = localStorage.getItem('realTimezone') + let $a = jQuery(this); + let baseUrl = $a.data('href'); + let chartId = $a.parents('.graph').data('graphId'); + let start; + let end; + let timezone = localStorage.getItem('realTimezone') ? localStorage.getItem('realTimezone') : moment.tz.guess(); - /* Get the period */ - if (jQuery('select[name="period"]').val() === '') { - start = moment.tz( - jQuery('#StartDate').val() + ' ' + jQuery('#StartTime').val(), - timezone - ); - end = moment.tz( - jQuery('#EndDate').val() + ' ' + jQuery('#EndTime').val(), - timezone - ); - duration = moment.duration(end.diff(start)); - } else { - parseInterval = jQuery('select[name="period"]').val().match(/(\d+)([a-z]+)/i); - duration = moment.duration( - parseInt(parseInterval[1], 10), - parseInterval[2] - ); - start = moment().tz(timezone); - end = moment().tz(timezone); - start.subtract(parseInterval[1], parseInterval[2]); - } + //Defining the period + let graphPeriod = $a.parents('.graph').data('graphPeriod'); + let parseInterval = graphPeriod.match(/(\d+)([a-z]+)/i); + start = moment().tz(timezone); + end = moment().tz(timezone); + start.subtract(parseInterval[1], parseInterval[2]); e.preventDefault(); baseUrl += '?chartId=' + chartId + '&start=' + start.unix() + '&end=' + end.unix(); diff --git a/www/install/insertBaseConf.sql b/www/install/insertBaseConf.sql index 02dd52d742e..64c58364d05 100644 --- a/www/install/insertBaseConf.sql +++ b/www/install/insertBaseConf.sql @@ -2,7 +2,7 @@ -- Insert version -- -INSERT INTO `informations` (`key` ,`value`) VALUES ('version', '22.04.5'); +INSERT INTO `informations` (`key` ,`value`) VALUES ('version', '22.04.6'); -- -- Contenu de la table `contact` diff --git a/www/install/installBroker.sql b/www/install/installBroker.sql index 17683ae47d6..5fc59876a46 100644 --- a/www/install/installBroker.sql +++ b/www/install/installBroker.sql @@ -258,7 +258,7 @@ CREATE TABLE `hosts` ( `notes` varchar(512) DEFAULT NULL, `notes_url` varchar(2048) DEFAULT NULL, `notification_interval` double DEFAULT NULL, - `notification_number` smallint(6) DEFAULT NULL, + `notification_number` bigint(20) unsigned DEFAULT NULL, `notification_period` varchar(75) DEFAULT NULL, `notify` tinyint(1) DEFAULT NULL, `notify_on_down` tinyint(1) DEFAULT NULL, @@ -591,7 +591,7 @@ CREATE TABLE `services` ( `notes` varchar(512) DEFAULT NULL, `notes_url` varchar(2048) DEFAULT NULL, `notification_interval` double DEFAULT NULL, - `notification_number` smallint(6) DEFAULT NULL, + `notification_number` bigint(20) unsigned DEFAULT NULL, `notification_period` varchar(75) DEFAULT NULL, `notify` tinyint(1) DEFAULT NULL, `notify_on_critical` tinyint(1) DEFAULT NULL, diff --git a/www/install/php/Update-22.04.6.php b/www/install/php/Update-22.04.6.php new file mode 100644 index 00000000000..932a8d14d06 --- /dev/null +++ b/www/install/php/Update-22.04.6.php @@ -0,0 +1,49 @@ +getColumnType('hosts', 'notification_number')), 'bigint')) { + $pearDBO->query("ALTER TABLE `hosts` MODIFY `notification_number` BIGINT(20) UNSIGNED DEFAULT NULL"); + } + + $errorMessage = "Impossible to update 'services' table"; + if (! str_contains(strtolower($pearDBO->getColumnType('services', 'notification_number')), 'bigint')) { + $pearDBO->query("ALTER TABLE `services` MODIFY `notification_number` BIGINT(20) UNSIGNED DEFAULT NULL"); + } +} catch (\Exception $e) { + $centreonLog->insertLog( + 4, + $versionOfTheUpgrade . $errorMessage . + " - Code : " . (int)$e->getCode() . + " - Error : " . $e->getMessage() . + " - Trace : " . $e->getTraceAsString() + ); + + throw new \Exception($versionOfTheUpgrade . $errorMessage, (int) $e->getCode(), $e); +} diff --git a/www/install/steps/process/insertBaseConf.php b/www/install/steps/process/insertBaseConf.php index 95f3e2bab70..40b7e8b1f7b 100644 --- a/www/install/steps/process/insertBaseConf.php +++ b/www/install/steps/process/insertBaseConf.php @@ -124,18 +124,21 @@ // Manage timezone $timezone = date_default_timezone_get(); -$resTimezone = $link->query("SELECT timezone_id FROM timezone WHERE timezone_name= '" . $timezone . "'"); -if (!$resTimezone) { +$statement = $link->prepare("SELECT timezone_id FROM timezone WHERE timezone_name= :timezone_name"); +$statement->bindValue(':timezone_name', $timezone, \PDO::PARAM_STR); +if (!$statement->execute()) { $return['msg'] = _('Cannot get timezone information'); echo json_encode($return); exit; } -if ($row = $resTimezone->fetch()) { +if ($row = $statement->fetch(\PDO::FETCH_ASSOC)) { $timezoneId = $row['timezone_id']; } else { $timezoneId = '334'; # Europe/London timezone } -$link->exec("INSERT INTO `options` (`key`, `value`) VALUES ('gmt','" . $timezoneId . "')"); +$statement = $link->prepare("INSERT INTO `options` (`key`, `value`) VALUES ('gmt', :value)"); +$statement->bindValue(':value', $timezoneId, \PDO::PARAM_STR); +$statement->execute(); # Generate random key for this instance and set it to be not central and not remote $informationsTableInsert = "INSERT INTO `informations` (`key`,`value`) VALUES From de4fd06fdecd4f0501498b7d53af2d93c55d916b Mon Sep 17 00:00:00 2001 From: Kevin Duret Date: Mon, 8 Aug 2022 16:31:30 +0200 Subject: [PATCH 5/7] fix(api): fix call to api on fresh install (#11536) (#11537) Refs: MON-12296 --- src/EventSubscriber/UpdateEventSubscriber.php | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/EventSubscriber/UpdateEventSubscriber.php b/src/EventSubscriber/UpdateEventSubscriber.php index 9c629695103..dd5077576d8 100644 --- a/src/EventSubscriber/UpdateEventSubscriber.php +++ b/src/EventSubscriber/UpdateEventSubscriber.php @@ -66,6 +66,12 @@ public static function getSubscribedEvents(): array */ public function validateCentreonWebVersionOrFail(RequestEvent $event): void { + $this->debug('Checking if database configuration file exists to know if centreon is already installed'); + if (! file_exists(_CENTREON_ETC_ . DIRECTORY_SEPARATOR . 'centreon.conf.php')) { + $this->debug('Centreon database configuration file not found'); + return; + } + $this->debug('Checking if route matches updates endpoint'); if ( $event->getRequest()->getMethod() === Request::METHOD_PATCH From d9b9bec77e8648611ef4a2327d537affa1051e14 Mon Sep 17 00:00:00 2001 From: Kevin Duret Date: Tue, 9 Aug 2022 12:25:37 +0200 Subject: [PATCH 6/7] fix(api): do not init db connection in event subscriber (#11543) (#11545) Refs: MON-12296 --- src/EventSubscriber/UpdateEventSubscriber.php | 6 ------ 1 file changed, 6 deletions(-) diff --git a/src/EventSubscriber/UpdateEventSubscriber.php b/src/EventSubscriber/UpdateEventSubscriber.php index dd5077576d8..9c629695103 100644 --- a/src/EventSubscriber/UpdateEventSubscriber.php +++ b/src/EventSubscriber/UpdateEventSubscriber.php @@ -66,12 +66,6 @@ public static function getSubscribedEvents(): array */ public function validateCentreonWebVersionOrFail(RequestEvent $event): void { - $this->debug('Checking if database configuration file exists to know if centreon is already installed'); - if (! file_exists(_CENTREON_ETC_ . DIRECTORY_SEPARATOR . 'centreon.conf.php')) { - $this->debug('Centreon database configuration file not found'); - return; - } - $this->debug('Checking if route matches updates endpoint'); if ( $event->getRequest()->getMethod() === Request::METHOD_PATCH From 808591799b260e2ef783b8c08d5a10e3384fd1df Mon Sep 17 00:00:00 2001 From: hyahiaoui-ext <97593234+hyahiaoui-ext@users.noreply.github.com> Date: Thu, 22 Sep 2022 17:01:47 +0100 Subject: [PATCH 7/7] FIX: Removing unused code and fixing bug of generating csv in multiple periods graphs 22.04.x (#11856) --- www/include/views/graphs/generateGraphs/generateImage.php | 2 -- 1 file changed, 2 deletions(-) diff --git a/www/include/views/graphs/generateGraphs/generateImage.php b/www/include/views/graphs/generateGraphs/generateImage.php index 2d43aa60992..05ab19fb133 100644 --- a/www/include/views/graphs/generateGraphs/generateImage.php +++ b/www/include/views/graphs/generateGraphs/generateImage.php @@ -95,8 +95,6 @@ } else { die('Invalid token'); } -} else { - throw new \Exception('Username and token query strings must be set.'); } $index = filter_var(