<?php

#############################################################################
#           			                   Site@School
# Site@School is a website management system designed for primary schools.
#
# About Site@School:
# Comissioned by: City District 'de Baarsjes', Amsterdam, Netherlands
# Original idea, coding (version 1.0) and design : Mark de Haan (mark@starwave.nl)
# Ideas, improvements, expansions (version 1.1 - 2.3): Fred Stuurman 
# Current coder & maintainer: Fred Stuurman (fc.stuurman@hccnet.nl)
############################################################################
# backup.php: last changed 04/10/2006 version 2.4.10                                      
#             by Fred Stuurman (fc.stuurman@hccnet.nl)
#$Id: backup.php,v 1.2 2006/10/15 19:08:53 fstuurman Exp $
############################################################################
#                        LICENSE INFORMATION
# Copyright (C) 2002 - 2006 Municipality of Amsterdam, City District
#  'de Baarsjes', Amsterdam, the Netherlands.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
##############################################################################

define("VERBOSE", 1);
//
// This function returns the "CREATE TABLE" syntax for mysql dbms...
//

function gzip_PrintFourChars($Val)
{
	for ($i = 0; $i < 4; $i++)
	{
		$return .= chr($Val % 256);
		$Val = floor($Val / 256);
	}
	return $return;
}

function sql_fetchrow($query_id = 0)
{
	if (!$query_id)
	{
		$query_id = $this->query_result;
	}
	if ($query_id)
	{
		$row = mysql_fetch_array($query_id);
		//$this->row[$query_id] = @mysql_fetch_array($query_id);		
		//return $this->row[$query_id];
		return $row;
	}
	else
	{
		return false;
	}
}

function sql_numrows($query_id = 0)
{
	if (!$query_id)
	{
		$query_id = $this->query_result;
	}
	if ($query_id)
	{
		$count = @ mysql_num_rows($query_id);
		return $count;
	}
	else
	{
		return false;
	}
}

function sql_numfields($query_id = 0)
{
	if (!$query_id)
	{
		$query_id = $this->query_result;
	}
	if ($query_id)
	{
		$result = @ mysql_num_fields($query_id);
		return $result;
	}
	else
	{
		return false;
	}
}

function sql_fieldname($offset, $query_id = 0)
{
	if (!$query_id)
	{
		$query_id = $this->query_result;
	}
	if ($query_id)
	{
		$result = @ mysql_field_name($query_id, $offset);
		return $result;
	}
	else
	{
		return false;
	}
}

function get_table_def_mysql($table, $crlf)
{
	global $drop, $db;

	$schema_create = "";
	$field_query = "SHOW FIELDS FROM $table";
	$key_query = "SHOW KEYS FROM $table";

	//
	// If the user has selected to drop existing tables when doing a restore.
	// Then we add the statement to drop the tables....
	//
	if ($drop == 1)
	{
		$schema_create .= "DROP TABLE IF EXISTS $table;$crlf";
	}

	$schema_create .= "CREATE TABLE $table($crlf";

	//
	// Ok lets grab the fields...
	//
	$result = mysql_query($field_query);

	if (!$result)
	{
		message_die(GENERAL_ERROR, "Failed in get_table_def (show fields)", "", __LINE__, __FILE__, $field_query);
	}

	while ($row = sql_fetchrow($result))
	{
		$schema_create .= '	' . $row['Field'] . ' ' . $row['Type'];

		if (!empty ($row['Default']))
		{
			$schema_create .= ' DEFAULT \'' . $row['Default'] . '\'';
		}

		if ($row['Null'] != "YES")
		{
			$schema_create .= ' NOT NULL';
		}

		if ($row['Extra'] != "")
		{
			$schema_create .= ' ' . $row['Extra'];
		}

		$schema_create .= ",$crlf";
	}
	//
	// Drop the last ',$crlf' off ;)
	//
	$schema_create = ereg_replace(',' . $crlf . '$', "", $schema_create);

	//
	// Get any Indexed fields from the database...
	//
	$result = mysql_query($key_query);
	if (!$result)
	{
		message_die(GENERAL_ERROR, "FAILED IN get_table_def (show keys)", "", __LINE__, __FILE__, $key_query);
	}

	while ($row = sql_fetchrow($result))
	{
		$kname = $row['Key_name'];

		if (($kname != 'PRIMARY') && ($row['Non_unique'] == 0))
		{
			$kname = "UNIQUE|$kname";
		}

		if (!is_array($index[$kname]))
		{
			$index[$kname] = array ();
		}

		$index[$kname][] = $row['Column_name'];
	}

	while (list ($x, $columns) = @ each($index))
	{
		$schema_create .= ", $crlf";

		if ($x == 'PRIMARY')
		{
			$schema_create .= '	PRIMARY KEY (' . implode($columns, ', ') . ')';
		}
		elseif (substr($x, 0, 6) == 'UNIQUE')
		{
			$schema_create .= '	UNIQUE ' . substr($x, 7) . ' (' . implode($columns, ', ') . ')';
		}
		else
		{
			$schema_create .= "	KEY $x (" . implode($columns, ', ') . ')';
		}
	}

	$schema_create .= "$crlf);";

	if (get_magic_quotes_runtime())
	{
		return (stripslashes($schema_create));
	}
	else
	{
		return ($schema_create);
	}

} // End get_table_def_mysql

//
// This function is for getting the data from a mysql table.
//

function get_table_content_mysql($table, $handler)
{
	global $db;
	//
	// Grab the data from the table.
	//
	$result = mysql_query("SELECT * FROM $table");

	if (!$result)
	{
		message_die(GENERAL_ERROR, "Failed in get_table_content (select *)", "", __LINE__, __FILE__, "SELECT * FROM $table");
	}

	if (sql_numrows($result) > 0)
	{
		$schema_insert = "\n#\n# Table Data for $table\n#\n";
	}
	else
	{
		$schema_insert = "";
	}

	$handler ($schema_insert);

	//
	// Loop through the resulting rows and build the sql statement.
	//

	while ($row = sql_fetchrow($result))
	{
		$table_list = '(';
		$num_fields = sql_numfields($result);
		//
		// Grab the list of field names.
		//
		for ($j = 0; $j < $num_fields; $j++)
		{
			$table_list .= sql_fieldname($j, $result) . ', ';
		}
		//
		// Get rid of the last comma
		//
		$table_list = ereg_replace(', $', '', $table_list);
		$table_list .= ')';
		//
		// Start building the SQL statement.
		//
		$schema_insert = "INSERT INTO $table $table_list VALUES(";
		//
		// Loop through the rows and fill in data for each column
		//
		for ($j = 0; $j < $num_fields; $j++)
		{
			if (!isset ($row[$j]))
			{
				//
				// If there is no data for the column set it to null.
				// There was a problem here with an extra space causing the
				// sql file not to reimport if the last column was null in
				// any table.  Should be fixed now :) JLH
				//
				$schema_insert .= ' NULL,';
			}
			elseif ($row[$j] != '')
			{
				$schema_insert .= ' \'' . addslashes($row[$j]) . '\',';
			}
			else
			{
				$schema_insert .= '\'\',';
			}
		}
		//
		// Get rid of the the last comma.
		//
		$schema_insert = ereg_replace(',$', '', $schema_insert);
		$schema_insert .= ');';
		//
		// Go ahead and send the insert statement to the handler function.
		//
		$handler (trim($schema_insert));

	}
	return (true);
}

function output_table_content($content)
{
	global $tempfile;
	echo $content . "\n";
	return;
}
//
// End Functions
// -------------

include ("../configuration/database.inc.php");
mysql_connect("$db_server", "$db_username", "$db_password");
mysql_select_db("$db_name");
require ("../core/session.php"); //build a session

$query = "SELECT config_value FROM $table_configuration WHERE config_key='sessioncode'";
if ($result = mysql_query($query))
{
	$check_sessioncode = mysql_result($result, 0);
	unset ($query);
	unset ($result);
}
if ($_SESSION['sessioncode'] != "$check_sessioncode")
{
	//if we don't have a session present the login screen
	Header("Location: ../index.php");
	exit;
}
//put the date into the last_backup_date in config table
$today = time();
mysql_query("UPDATE $table_configuration SET config_value = '$today' WHERE config_key='last_backup_date'");

$result = mysql_list_tables($db_name);

header("Pragma: no-cache");
$file_date = date("Ymd_Gi");
if (extension_loaded("zlib"))
{
	@ ob_start();
	@ ob_implicit_flush(0);
	header("Content-Type: application/x-gzip; name=\"db_backup_$file_date.sql.gz\"");
	header("Content-disposition: attachment; filename=db_backup_$file_date.sql.gz");
	$do_gzip_compress = TRUE;
}
else
{
	header("Content-Type: text/x-delimtext; name=\"db_backup_$file_date.sql\"");
	header("Content-disposition: attachment; filename=db_backup_$file_date.sql");
}
$drop = 1;
echo "#\n";
echo "# Site@School Backup Script\n";
echo "# Dump of tables for $dbname\n";
echo "#\n# DATE : " . gmdate("d-m-Y H:i:s", time()) . " GMT\n";
echo "#\n";
echo "# DROP DATABASE IF EXISTS " . $db_name . ";\n";
echo "# CREATE DATABASE " . $db_name . ";\n";
echo "# USE " . $db_name . ";\n#\n";
$i = 0;
while ($tables = mysql_fetch_row($result))
{
	$table_name = $tables[$i];
	if ($table_name != $dbprefix . "stats") //leave out stats table because it can be big
	{
		echo "#\n# TABLE: " . $table_name . "\n#\n";
		echo get_table_def_mysql($table_name, "\n") . "\n";
		get_table_content_mysql($table_name, "output_table_content");
	}
}
if ($do_gzip_compress)
{
	$Size = ob_get_length();
	$Crc = crc32(ob_get_contents());
	$contents = gzcompress(ob_get_contents());
	ob_end_clean();
	echo "\x1f\x8b\x08\x00\x00\x00\x00\x00" . substr($contents, 0, strlen($contents) - 4) . gzip_PrintFourChars($Crc) . gzip_PrintFourChars($Size);
	$i++;
}
?>