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 @@
{$m_mon_tools} | -
- {if $tools[tool].popup == ""} - - {else} - - {/if} - ● {$tools[tool].name} | -