<?php
/*
 ########################################################################
#                                                                        #
#           Version 4       /                        /   /               #
#          -----------__---/__---__------__----__---/---/-               #
#           | /| /  /___) /   ) (_ `   /   ) /___) /   /                 #
#          _|/_|/__(___ _(___/_(__)___/___/_(___ _/___/___               #
#                       Free Content / Management System                 #
#                                   /                                    #
#                                                                        #
#                                                                        #
#   Copyright 2005-2006 by webspell.org                                  #
#                                                                        #
#   visit webSPELL.org, webspell.info to get webSPELL for free           #
#   - Script runs under the GNU GENERAL PUBLIC LICENSE                   #
#   - It's NOT allowed to remove this copyright-tag                      #
#   -- http://www.fsf.org/licensing/licenses/gpl.html                    #
#                                                                        #
#   Code based on WebSPELL Clanpackage (Michael Gruber - webspell.at),   #
#   Far Development by Development Team - webspell.org                   #
#                                                                        #
#   visit webspell.org                                                   #
#                                                                        #
 ########################################################################
*/

//Dont edit anything below this line!

include('../_mysql.php');

if($_POST['upload']) {

	if(!ispageadmin($userID) OR substr(basename($_SERVER[REQUEST_URI]),0,15) != "admincenter.php") die('Access denied.');
	$upload = $_FILES[sql];

	if($upload[name] != "") {

		//empty database
		$result = mysql_list_tables($db);

		while ($table = mysql_fetch_row($result)) safe_query("DROP TABLE `".$table[0]."`");

		move_uploaded_file($upload[tmp_name], '../tmp/'.$upload[name]);
		$new_query = file('../tmp/'.$upload[name]);
		foreach($new_query as $query) @mysql_query($query);
		@unlink('../tmp/'.$upload[name]);
		redirect('admincenter.php?site=database','SQL-Backup successful!');
	}

} elseif($_POST['query']) {

	if(!ispageadmin($userID) OR substr(basename($_SERVER[REQUEST_URI]),0,15) != "admincenter.php") die('Access denied.');
	$query = str_replace('PREFIX', PREFIX, $_POST['query']);
	if(stristr($query,'insert into') OR stristr($query,'alter table') OR stristr($query,'select'))	{
		safe_query($query);
		redirect('admincenter.php?site=database','Successful!');
	} else redirect('admincenter.php?site=database','Syntax not allowed!');

} elseif($_GET['action'] == "optimize") {

	$result = mysql_list_tables($db);

	while ($table = mysql_fetch_row($result)) safe_query("OPTIMIZE TABLE `".$table[0]."`");

	redirect('admincenter.php?site=database','Successful!');

} elseif($_GET['action'] == "write") {

include('../version.php');
include('../_settings.php');

//Get database information and write SQL-commands

$final = '--   #webSPELL '.$version.', visit webspell.org#
--   webSPELL.org database backup
--   Code: Florian Siegmund (webspell.org)
--
--   webSPELL version: '.$version.'
--   PHP version: '.phpversion().'
--   MySQL version: '.mysql_get_server_info().'
';

$result = mysql_list_tables($db);

	while ($table = mysql_fetch_row($result)) {

   $i = 0;
   $result2 = mysql_query("SHOW COLUMNS FROM $table[0]");
   $z = mysql_num_rows($result2);
   $final .= "\n--\n-- webSPELL - DB-Export: Table '".$table[0]."'\n--\n\nCREATE TABLE `".$table[0]."` (";

	   while ($row2 = mysql_fetch_assoc($result2)) {

           $i++;
           $final .= "`".$row2['Field']."` ".$row2['Type'];
           if($row2['Null'] != "YES") { $final .= " NOT NULL"; }
           if($row2['Default']) $final .= " DEFAULT '".$row2['Default']."'";

           if($i < $z) $final .= ", ";

	   }

    $final .= ");\n";

    $inhaltq = mysql_query("SELECT * FROM $table[0]");

    while($inhalt = mysql_fetch_array($inhaltq,MYSQL_BOTH)) {

        $final .= "\nINSERT INTO `$table[0]` (";
        $names = array_keys($inhalt);
        $az = count($inhalt)/2; //durch 2 teilen, da array mit numerischen UND assoziativen index

        for($i=0;$i<$az;$i++) {

           $final .= "`".$names[(2*$i+1)]."`"; //nur die ungeraden schlüssel darstellen (gerade schlüssel -> numerischer index)
           if(($i+1)<$az) $final .= ", ";

        }
        $final .= ") VALUES (";

        for($i=0;$i<$z;$i++) {

           $einschub = "'".str_replace("'","`", $inhalt[$i])."'";
           $final .= preg_replace('/\r\n|\r|\n/', '\r\n', $einschub);
           if(($i+1)<$z) $final .= ", ";

        }

        $final .= ");\n";

    }



    $final .= "\n";

	}

	systeminc('session');
	systeminc('login');

	$anz=mysql_num_rows(safe_query("SELECT userID FROM ".PREFIX."user_groups WHERE (page='1' OR super='1') AND userID='$userID'"));

	if($anz) {

		header("Expires: 0");
		header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
		header("Content-Type: application/force-download");
  	header("Content-Description: File Transfer");

		if(is_integer(strpos(strtolower($_SERVER["HTTP_USER_AGENT"]), "msie")) AND is_integer(strpos(strtolower($_SERVER["HTTP_USER_AGENT"]), "win" ))) header("Content-Disposition: filename=backup.sql;");
		else header("Content-Disposition: attachment; filename=backup.sql;");
		header("Content-Transfer-Encoding: binary");
		echo $final;

	}

} else {

	if(!ispageadmin($userID) OR substr(basename($_SERVER[REQUEST_URI]),0,15) != "admincenter.php") die('Access denied.');
	echo '<h2>database</h2>
<table width="100%" cellpadding="4" cellspacing="1" bgcolor="#999999">
	<tr bgcolor="#CCCCCC">
		<td class="title" colspan="2">&#8226; <a href="database.php?action=write">Export/Download backup (<font color="#F0000">experimental, dont use it! use phpmyadmin to make your backups!</font>)</a></td>
	</tr>
	<tr bgcolor="#FFFFFF">
		<td></td>
	</tr>
	<tr bgcolor="#CCCCCC">
		<td class="title" colspan="2">&#8226; <a href="admincenter.php?site=database&action=optimize">Optimize database</a></td>
	</tr>
	<tr bgcolor="#FFFFFF">
		<td></td>
	</tr>
	<tr bgcolor="#CCCCCC">
		<td class="title" colspan="2">&#8226; Import backup</td>
	</tr>
	<tr bgcolor="#FFFFFF">
		<td></td>
	</tr>
	<tr bgcolor="#FFFFFF">
		<td>Select a file where to import sql data from. <br><b>Important:</b> Create a backup before import another one!<br><br>
	   <form method="post" action="admincenter.php?site=database" enctype="multipart/form-data">
	     <table cellpadding="4" cellspacing="0">
		 <tr>
		   <td>backup file:</td>
 		   <td><input name="sql" type="file" class="form_off"></td>
		 </tr>
		 <tr>
		   <td>&nbsp;</td>
		   <td><input type="submit" name="upload" value="Upload"></td>
		</td>
		</tr>
		</table>
	 </td>
	</tr>
	<tr bgcolor="#FFFFFF">
		<td></td>
	</tr>
	<tr bgcolor="#CCCCCC">
		<td class="title" colspan="2">&#8226; SQL-Query</td>
	</tr>
	<tr bgcolor="#FFFFFF">
		<td></td>
	</tr>
	<tr bgcolor="#FFFFFF">
		<td>Allowed commands: insert, alter table, select
		  <form method="post" action="admincenter.php?site=database">
			<br>Enter SQL-Query:<br><textarea name="query" cols="100" rows="2" class="form_off" onFocus="this.className=\'form_on\'" onBlur="this.className=\'form_off\'"></textarea><br>
			<input type="submit" name="submit" value="Submit">
		</td>
	</tr>
</table>';



}
?>



