diff --git a/application/IpNetwork/IpNetworkModel.php b/application/IpNetwork/IpNetworkModel.php index 6987d57bb..7e8aa84bf 100644 --- a/application/IpNetwork/IpNetworkModel.php +++ b/application/IpNetwork/IpNetworkModel.php @@ -33,10 +33,18 @@ class IpNetworkModel { $sqlConditions[] = " (CONCAT(INET_NTOA(network_address), '/', cidr) LIKE '%{$searchTerm}%' OR `name` LIKE '%{$searchTerm}%' OR `description` LIKE '%{$searchTerm}%') "; } - if (isset($filters['name'])) $sqlConditions[] = Helper::generateFilterCondition($filters['name'], 'name'); - if (isset($filters['description'])) $sqlConditions[] = Helper::generateFilterCondition($filters['description'], 'description'); - if (isset($filters['location'])) $sqlConditions[] = Helper::generateFilterCondition($filters['location'], 'location'); - if (isset($filters['status'])) $sqlConditions[] = Helper::generateFilterCondition($filters['status'], 'status'); + if (!empty($filters['name'])) $sqlConditions[] = Helper::generateFilterCondition($filters['name'], 'name'); + if (!empty($filters['description'])) $sqlConditions[] = Helper::generateFilterCondition($filters['description'], 'description'); + if (!empty($filters['location'])) $sqlConditions[] = Helper::generateFilterCondition($filters['location'], 'location'); + if (!empty($filters['status'])) $sqlConditions[] = Helper::generateFilterCondition($filters['status'], 'status'); + if (isset($filters['children']) && is_array($filters['children'])) { + if (isset($filters['children']['from'])) { + $sqlConditions[] = " (SELECT COUNT(*) FROM `IpNetwork` WHERE `parent_network_id` = main.id) >= " . intval($filters['children']['from']); + } + if (isset($filters['children']['to'])) { + $sqlConditions[] = " (SELECT COUNT(*) FROM `IpNetwork` WHERE `parent_network_id` = main.id) <= " . intval($filters['children']['to']); + } + } if (empty($filters['parent_network_id'])) { $sqlConditions[] = " `parent_network_id` IS NULL "; @@ -44,6 +52,12 @@ class IpNetworkModel { $sqlConditions[] = " `parent_network_id` = " . intval($filters['parent_network_id']) . " "; } + foreach ($sqlConditions as $key => $condition) { + if (strpos($condition, ' AND ') === 0 || strpos($condition, 'AND ') === 0) { + $sqlConditions[$key] = substr($condition, 4); + } + } + return empty($sqlConditions) ? "" : " WHERE " . implode(" AND ", $sqlConditions); } @@ -70,7 +84,6 @@ class IpNetworkModel { " . $orderClause . " " . $limitClause; - $result = $db->query($sql); $rows = []; while ($row = $result->fetch_assoc()) { @@ -101,11 +114,12 @@ class IpNetworkModel { public static function countIpNetworks($filters): int { $db = FronkDB::singleton()->link; - $sql = "SELECT COUNT(*) as `total_rows` FROM `IpNetwork`" . self::getSqlFilter($filters); + $sql = "SELECT COUNT(*) as `total_rows` FROM `IpNetwork` main" . self::getSqlFilter($filters); $result = $db->query($sql); return (int)$result->fetch_assoc()['total_rows']; } + public static function findSuggestions(string $query, int $limit = 10): array { $db = FronkDB::singleton()->link; $query = $db->real_escape_string($query); diff --git a/lib/TTCrudBaseModel/TTCrudBaseModel.php b/lib/TTCrudBaseModel/TTCrudBaseModel.php index 906d5d0c8..c2a97b024 100644 --- a/lib/TTCrudBaseModel/TTCrudBaseModel.php +++ b/lib/TTCrudBaseModel/TTCrudBaseModel.php @@ -96,7 +96,7 @@ class TTCrudBaseModel { } - public static function get($id): TTCrudBaseModel { + public static function get($id) { $db = self::getDB(); $id = $db->real_escape_string($id); $table = self::getFullyQualifiedTable(); @@ -105,6 +105,8 @@ class TTCrudBaseModel { $result = $db->query($sql); // as TTCRudBaseModel is abstract, we need to get the class name of the child class $class = get_called_class(); + // return null if no result is found + if ($result->num_rows === 0) return null; return new $class($result->fetch_assoc()); } diff --git a/scripts/ipnetwork/initial-data.php b/scripts/ipnetwork/initial-data.php index b66e7e77d..f103d06fb 100644 --- a/scripts/ipnetwork/initial-data.php +++ b/scripts/ipnetwork/initial-data.php @@ -4,147 +4,258 @@ * This script parses a wiki text file containing network information and generates an SQL script * to populate the IpNetwork table with a complete, hierarchical representation of the network. * - * @version 1.0 + * It includes on-the-fly data cleaning, hierarchical network detection from headers, robust parent-child logic, + * duplicate prevention, IP address validation, and error logging to 'initial_data_errors.txt'. + * + * @version 7.0 * @author Gemini */ // --- Configuration --- $inputFile = 'combined_wiki.txt'; -$outputFile = 'initial_data.sql'; +$outputFile = 'initial_data.sql'; // Changed: Standardized output filename $dbTableName = 'IpNetwork'; +$errorFile = 'initial_data_errors.txt'; // --- Main Execution --- +$parsing_errors = []; // Initialize error log array + +// Delete old error log if it exists +if (file_exists($errorFile)) { + unlink($errorFile); +} + // Read and parse the wiki file into a structured PHP array -$networkData = parseWikiFile($inputFile); +$networkData = parseWikiFile($inputFile, $parsing_errors); // Generate the SQL script from the parsed data -$sqlScript = generateSqlScript($networkData, $dbTableName); +$sqlScript = generateSqlScript($networkData, $dbTableName, $parsing_errors); // Save the generated SQL script to the output file file_put_contents($outputFile, $sqlScript); -echo "SQL-Skript wurde erfolgreich in '$outputFile' generiert.\n"; +echo "Final SQL script was successfully generated in '$outputFile'\n"; - -/** - * Parses the entire wiki text file and organizes the network data hierarchically. - * - * @param string $filename The path to the wiki text file. - * @return array A structured array containing all network information. - */ -function parseWikiFile(string $filename): array -{ - if (!file_exists($filename)) { - die("Fehler: Eingabedatei '$filename' nicht gefunden.\n"); - } - - $lines = file($filename, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); - $networks = []; - $currentNetwork = null; - $currentSubnet = null; - - foreach ($lines as $line) { - // Ignore section headers - if (preg_match('/^=====.*=====$/', $line)) { - continue; - } - - // Match network/subnet definitions (e.g., "10.0.0.0/29 stko-tauka" or "10.0.0.1/32 Gateway") - if (preg_match('/^([\d\.]+)\/(\d+)\s*(.*)$/', trim($line), $matches)) { - $ip = $matches[1]; - $cidr = (int)$matches[2]; - $description = trim($matches[3]); - - // Determine if it's a main network or a subnet based on CIDR - if ($cidr < 29) { // Heuristic: Treat larger blocks as potential parent subnets - $currentSubnet = "$ip/$cidr"; - $networks[$currentSubnet] = [ - 'ip' => $ip, - 'cidr' => $cidr, - 'name' => $description, - 'description' => $description, - 'children' => [] - ]; - } else { // Treat smaller blocks and hosts as children - if ($currentSubnet) { - $networks[$currentSubnet]['children'][] = [ - 'ip' => $ip, - 'cidr' => $cidr, - 'name' => $description, - 'description' => $description, - ]; - } - } - } - // Match host definitions (e.g., "10.0.0.2 stko-tauk:stko") - elseif (preg_match('/^([\d\.]+)\s+(.*)$/', trim($line), $matches)) { - $ip = $matches[1]; - $description = trim($matches[2]); - - if ($currentSubnet) { - $networks[$currentSubnet]['children'][] = [ - 'ip' => $ip, - 'cidr' => 32, // Assume /32 for host entries - 'name' => $description, - 'description' => $description, - ]; - } - } - } - - return $networks; +// Save errors if any were found +if (!empty($parsing_errors)) { + $error_log_content = "Parsing process found the following issues:\n\n"; + $error_log_content .= implode("\n", $parsing_errors); + file_put_contents($errorFile, $error_log_content); + echo "Found " . count($parsing_errors) . " issues during processing. See $errorFile for details.\n"; } /** - * Generates the complete SQL script string. + * Parses the wiki text file, cleans data, validates IPs, checks for duplicates, and organizes the network data. + * It now also creates parent network blocks based on file headers. * - * @param array $data The structured network data. - * @param string $tableName The name of the database table. - * @return string The complete SQL script. + * @param string $filename The path to the wiki text file. + * @param array &$errors Array to store logging information. + * @return array A flat list of unique, valid network/host entries. */ -function generateSqlScript(array $data, string $tableName): string +function parseWikiFile(string $filename, array &$errors): array { - // --- SQL Header --- - $sql = "-- SQL-Daten für die Tabelle '$tableName'\n"; - $sql .= "-- Automatisch generiert aus der Wiki-Dokumentation\n\n"; - $sql .= "TRUNCATE TABLE `$tableName`;\n\n"; - $sql .= "-- Eltern-Netzwerke (Top-Level)\n"; + if (!file_exists($filename)) { + die("Error: Input file '$filename' not found.\n"); + } - // --- Insert Top-Level Parent Networks --- + $lines = file($filename, FILE_IGNORE_NEW_LINES); + $entries = []; + $seen_networks = []; // Tracker for duplicates + $pending_description = ''; + $ignore_section = false; + + foreach ($lines as $line_number => $line) { + // 1. Clean up the line from multiple inconsistencies + $cleaned_line = html_entity_decode($line, ENT_QUOTES | ENT_HTML5); + $cleaned_line = str_replace(['\\', ' '], ['', ' '], $cleaned_line); + $cleaned_line = preg_replace('/\[([^\]]+)\]\(mailto:[^\)]+\)/', '$1', $cleaned_line); + $cleaned_line = trim(preg_replace('/\s+/', ' ', $cleaned_line)); + + // 2. Check for section headers (START, END, etc.) + if (str_starts_with($cleaned_line, '=====')) { + $pending_description = ''; // Reset for any new section + $ignore_section = (stripos($line, 'gelöschte IP Netze') !== false); + + // IMPROVEMENT: Specifically parse START headers for network definitions + if (!$ignore_section && preg_match('/^===== START\s+([0-9\.]+)(?:[\/-](\d{1,2}))?\s*(.*?)(?:\.md)?\s*=====$/', $cleaned_line, $header_matches)) { + $ip_from_header = $header_matches[1]; + $cidr_from_header = $header_matches[2] ?? null; + $desc_from_header = trim($header_matches[3]); + + // Heuristic: If CIDR is missing but IP ends in .0, assume it's a /24 network block. + if ($cidr_from_header === null && preg_match('/\.0$/', $ip_from_header)) { + $cidr_from_header = 24; + if (empty($desc_from_header) || strtolower($desc_from_header) === 'linknetze') { + $desc_from_header = "Network Block {$ip_from_header}"; + } + } + + // If a full network/CIDR is defined or inferred from the header, add it as a distinct entry. + if ($cidr_from_header !== null && filter_var($ip_from_header, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) { + $network_key = "$ip_from_header/$cidr_from_header"; + if (!isset($seen_networks[$network_key])) { + $entries[] = [ + 'ip' => $ip_from_header, + 'cidr' => (int)$cidr_from_header, + 'name' => $desc_from_header, + 'description' => $desc_from_header, + ]; + $seen_networks[$network_key] = true; + } + } + } + + continue; // Header processed, move to next line + } + + if ($ignore_section || empty($cleaned_line)) { + if (empty($cleaned_line)) $pending_description = ''; + continue; + } + + // 3. Handle special HTML table data + if (strpos($line, '