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(); + } + } +}