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 f64f630d7d0..df317f236e6 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/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-v21.10.yaml b/doc/API/centreon-api-v21.10.yaml index a13a1dfdd12..6b352ce64b5 100644 --- a/doc/API/centreon-api-v21.10.yaml +++ b/doc/API/centreon-api-v21.10.yaml @@ -5993,6 +5993,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/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/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 65ae52eed10..6a1a0082ebe 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 c8c89e8ebff..44d3d72559d 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 1acd22711b6..5c002cc109b 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 15106abaa9a..376d969636a 100644 --- a/src/Centreon/Domain/RemoteServer/RemoteServerService.php +++ b/src/Centreon/Domain/RemoteServer/RemoteServerService.php @@ -138,16 +138,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/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 index 2a6be230b3d..f9c7c46ccb7 100755 --- 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) /** * 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) * @param bool $noProxy to do not use configured proxy */ private function addServerToListOfRemotes( + int $serverId, string $serverIP, string $centreonPath, string $httpMethod, @@ -547,35 +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, - 'app_key' => '', - '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`, `app_key`, `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 40768c67cfe..9c4075eb5d7 100644 --- a/src/CentreonRemote/Application/Webservice/CentreonRemoteServer.php +++ b/src/CentreonRemote/Application/Webservice/CentreonRemoteServer.php @@ -120,7 +120,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.'); } @@ -146,21 +146,22 @@ 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`, `app_key`, `version`, `is_connected`, - `created_at`, `http_method`, `http_port`, `no_check_certificate`) - VALUES (:ip, :app_key, :version, 0, '{$createdAt}', - :http_method, :http_port, :no_check_certificate - )"; - - $insert = $this->pearDB->prepare($insertQuery); - $insert->bindValue(':ip', $ip, \PDO::PARAM_STR); - $insert->bindValue(':app_key', $appKey, \PDO::PARAM_STR); - $insert->bindValue(':version', $version, \PDO::PARAM_STR); - $insert->bindValue(':http_method', $httpScheme, \PDO::PARAM_STR); - $insert->bindValue(':http_port', $httpPort, \PDO::PARAM_INT); - $insert->bindValue(':no_check_certificate', $noCheckCertificate, \PDO::PARAM_STR); try { + $createdAt = date('Y-m-d H:i:s'); + $insertQuery = "INSERT INTO `remote_servers` (`ip`, `app_key`, `version`, `is_connected`, + `created_at`, `http_method`, `http_port`, `no_check_certificate`) + VALUES (:ip, :app_key, :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(':app_key', $appKey, \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 f1845c5aa5b..4d45088e6c1 100644 --- a/src/CentreonRemote/Domain/Service/ConfigurationWizard/LinkedPollerConfigurationService.php +++ b/src/CentreonRemote/Domain/Service/ConfigurationWizard/LinkedPollerConfigurationService.php @@ -330,16 +330,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/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/www/api/class/centreon_clapi.class.php b/www/api/class/centreon_clapi.class.php index 9b3563c31ce..7eb3b83ff1f 100644 --- a/www/api/class/centreon_clapi.class.php +++ b/www/api/class/centreon_clapi.class.php @@ -231,7 +231,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 0d3b962c431..849f2e74b0e 100644 --- a/www/class/centreon-clapi/centreon.Config.Poller.class.php +++ b/www/class/centreon-clapi/centreon.Config.Poller.class.php @@ -175,20 +175,24 @@ 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(); exec("echo 'RELOAD:" . $host["id"] . "' >> " . $this->centcore_pipe, $stdout, $return_code); 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; } @@ -243,20 +247,24 @@ 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(); exec("echo 'RESTART:" . $host["id"] . "' >> " . $this->centcore_pipe, $stdout, $return_code); 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/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/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..148cd65ac81 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 :scope, :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 :scope, :limit"); } -$dbResult = $pearDB->query($query); +$statement->bindValue(':limit', (int) $limit, \PDO::PARAM_INT); +$statement->bindValue(':scope', (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 83b150d1c7f..1b7bc8f8b39 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( @@ -436,6 +436,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 @@ -766,14 +768,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']; @@ -782,14 +784,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(); } } @@ -1009,13 +1011,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 @@ -1346,8 +1348,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) { @@ -1494,3 +1496,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 9385017ea38..1c4e3ca334b 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 55858c861c2..7b3642ecdf7 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 92ea1182e14..bb6148db493 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/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 f07082a5f9d..5676f4c90f9 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 e594a988e0f..c08019ce84f 100644 --- a/www/install/insertBaseConf.sql +++ b/www/install/insertBaseConf.sql @@ -2,7 +2,7 @@ -- Insert version -- -INSERT INTO `informations` (`key` ,`value`) VALUES ('version', '21.10.9'); +INSERT INTO `informations` (`key` ,`value`) VALUES ('version', '21.10.10'); -- -- Contenu de la table `contact` diff --git a/www/install/php/Update-21.10.10.php b/www/install/php/Update-21.10.10.php new file mode 100644 index 00000000000..d22a8c06dca --- /dev/null +++ b/www/install/php/Update-21.10.10.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(); + } + } +}