getMessage(); } if (!$connection) { $error = $error !== '' ? $error : (mysqli_connect_error() ?: 'the server did not answer'); return null; } mysqli_set_charset($connection, 'utf8mb4'); return $connection; } /* The tables a database has - their names. */ function setupTables($connection) { $tables = []; try { $result = mysqli_query($connection, "SHOW TABLES"); while ($row = mysqli_fetch_row($result)) { $tables[] = $row[0]; } } catch (mysqli_sql_exception $e) { return []; } return $tables; } /* * Create ITFlow's tables from db.sql - one statement at a time, stopping at * the first that fails, with $error saying which and why. A failed import * takes the tables it made away again, so the database is left as it was * found: empty. */ function setupImportSchema($connection, $file, &$error = '') { $error = ''; $lines = @file($file); if ($lines === false) { $error = "db.sql could not be read from " . $file; return false; } $statement = ''; foreach ($lines as $line) { // Comments and blank lines between statements if ($statement === '' && (substr($line, 0, 2) === '--' || trim($line) === '')) { continue; } $statement .= $line; if (substr(rtrim($line), -1) !== ';') { continue; } try { $ok = mysqli_query($connection, $statement); } catch (mysqli_sql_exception $e) { $ok = false; $error = $e->getMessage(); } if (!$ok) { $error = ($error !== '' ? $error : mysqli_error($connection)) . ' - in: ' . mb_substr(trim(preg_replace('/\s+/', ' ', $statement)), 0, 120); setupDropTables($connection); return false; } $statement = ''; } if (!in_array('users', setupTables($connection), true)) { $error = "db.sql ran, but the tables are not there"; return false; } return true; } /* Every table in a database, dropped - after a failed import. */ function setupDropTables($connection) { try { mysqli_query($connection, "SET FOREIGN_KEY_CHECKS = 0"); foreach (setupTables($connection) as $table) { mysqli_query($connection, "DROP TABLE IF EXISTS `" . str_replace('`', '``', $table) . "`"); } mysqli_query($connection, "SET FOREIGN_KEY_CHECKS = 1"); } catch (mysqli_sql_exception $e) { // Left for whoever empties the database by hand } } /* What config.php says - the database to use, where ITFlow is reached, and this install's id. */ function setupConfigContents($host, $username, $password, $database, $base_url, $installation_id) { $config = "