function do_backup()
{
if ($_POST['xsrf_token'] != $_SESSION['xsrf_token']) {
trigger_error('XSRF code incorrect', E_USER_ERROR);
}
// By David Walsh
$return = 'CREATE DATABASE `lhsmath-bak` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;' . "\n" . 'USE `lhsmath-bak`;' . "\n\n\n";
$tables = array();
$result = DB::queryRaw('SHOW TABLES');
while ($row = mysqli_fetch_row($result)) {
$tables[] = $row[0];
}
foreach ($tables as $table) {
$result = DB::queryRaw('SELECT * FROM ' . $table);
$num_fields = mysqli_num_fields($result);
$return .= 'DROP TABLE IF EXISTS ' . $table . ';';
$row2 = mysqli_fetch_row(DB::queryRaw('SHOW CREATE TABLE ' . $table));
$return .= "\n\n" . $row2[1] . ";\n\n";
for ($i = 0; $i < $num_fields; $i++) {
while ($row = mysqli_fetch_row($result)) {
$return .= 'INSERT INTO ' . $table . ' VALUES(';
for ($j = 0; $j < $num_fields; $j++) {
$row[$j] = addslashes($row[$j]);
$row[$j] = str_replace("\n", "\\n", $row[$j]);
if (isset($row[$j])) {
$return .= '"' . $row[$j] . '"';
} else {
$return .= '""';
}
if ($j < $num_fields - 1) {
$return .= ',';
}
}
$return .= ");\n";
}
}
$return .= "\n\n\n";
}
// LMT, also
global $DB_DATABASE, $LMT_DB_DATABASE;
DB::useDB($LMT_DB_DATABASE);
$return .= 'CREATE DATABASE `lmt-bak` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;' . "\n" . 'USE `lmt-bak`;' . "\n\n\n";
$tables = array();
$result = DB::queryRaw('SHOW TABLES');
while ($row = mysqli_fetch_row($result)) {
$tables[] = $row[0];
}
foreach ($tables as $table) {
$result = DB::queryRaw('SELECT * FROM ' . $table);
$num_fields = mysqli_num_fields($result);
$return .= 'DROP TABLE IF EXISTS ' . $table . ';';
$row2 = mysqli_fetch_row(DB::queryRaw('SHOW CREATE TABLE ' . $table));
$return .= "\n\n" . $row2[1] . ";\n\n";
for ($i = 0; $i < $num_fields; $i++) {
while ($row = mysqli_fetch_row($result)) {
$return .= 'INSERT INTO ' . $table . ' VALUES(';
for ($j = 0; $j < $num_fields; $j++) {
$row[$j] = addslashes($row[$j]);
$row[$j] = str_replace("\n", "\\n", $row[$j]);
if (isset($row[$j])) {
$return .= '"' . $row[$j] . '"';
} else {
$return .= '""';
}
if ($j < $num_fields - 1) {
$return .= ',';
}
}
$return .= ");\n";
}
}
$return .= "\n\n\n";
}
DB::useDB($DB_DATABASE);
// switch back database
//save file
$filename = 'db-backup-' . time() . '-' . generate_code(4) . '.sql';
file_put_contents($filename, $return);
$order = 1 + DB::queryFirstField('SELECT MAX(order_num) FROM files WHERE category=%i', $category_id);
$display_name = 'Database Backup: ' . date('Y-m-d');
DB::insert('files', array('name' => $display_name, 'filename' => $filename, 'permissions' => 'A', 'category' => '0', 'order_num' => $order));
alert('The file "' . $display_name . '" has been added', 1);
header('Location: Database');
}