<?php
require_once('chk.php');
$pagepermission = 54;
require_once('netgou.php');
require_once "../include/ng_mysql_db.php";

if($ng_join_version == 'Y' and $ng_join_prime == ''){
	echo "<script language=\"JavaScript\">\r\n"; 
	echo " alert(\"您无权使用该功能\");\r\n"; 
	echo " history.go(-1);\r\n"; 
	echo "</script>"; 
	exit; 
}

ini_set('memory_limit', '-1');
$sql_pconnect = 1;
$db_charset = $sql_code;
$runsql = 1;				//是否允许执行SQL语句，较危险，建议在需要时开启，默认禁止
$uploadsql = 1;				//是否允许上传SQL文件，较危险，建议在需要时开启，默认禁止

if(!function_exists('file_put_contents'))
{
	function file_put_contents($file, $string, $append = '')
	{
		$mode = $append == '' ? 'wb' : 'ab';
		$fp = @fopen($file, $mode) or exit("Can not open file $file !");
		flock($fp, LOCK_EX);
		$stringlen = @fwrite($fp, $string);
		flock($fp, LOCK_UN);
		@fclose($fp);
		return $stringlen;
	}
}

$db = new db;
$db->connect($sql_host, $sql_user, $sql_password, $sql_db, $sql_pconnect);

switch($action)
{
	case 'export':
		if($dosubmit)
		{
			$fileid = isset($fileid) ? $fileid : 1;
			if($fileid==1 && $tables) 
			{
				if(!isset($tables) || !is_array($tables)) showmsg("请选择要备份的数据表","ng_db.php?action=export");
			    $random = mt_rand(1000, 9999);
			    cache_write('bakup_tables.php', $tables);
			}
			else
			{
			    if(!$tables = cache_read('bakup_tables.php')) showmsg("请选择要备份的数据表","ng_db.php?action=export");
			}
			$sqldump = '';
			$tableid = isset($tableid) ? $tableid - 1 : 0;
			$startfrom = isset($startfrom) ? intval($startfrom) : 0;
			$tablenumber = count($tables);
			for($i = $tableid; $i < $tablenumber && strlen($sqldump) < $sizelimit * 1000; $i++)
			{
				$sqldump .= sql_dumptable($tables[$i], $startfrom, strlen($sqldump));
				$startfrom = 0;
			}
			if(trim($sqldump))
			{
				$sqldump = "#Created by 通灵佛教网在线烧香程序\n# --------------------------------------------------------\n\n".$sqldump;
				$tableid = $i;
				$filename = $sql_db.'_'.date('Ymd').'_'.$random.'_'.$fileid.'.sql';
				$fileid++;

				$bakfile = './data/'.$filename;
				if(!is_writable('./data/')) showmsg("数据无法备份到服务器,请检查 data 目录是否可写", "ng_db.php?action=export");
				file_put_contents($bakfile, $sqldump);
				$txtmsg = "备份文件".$bakfile."写入成功";
				showmsg($txtmsg, '?action='.$action.'&sizelimit='.$sizelimit.'&tableid='.$tableid.'&fileid='.$fileid.'&startfrom='.$startrow.'&random='.$random.'&dosubmit=1');
			}
			else
			{
			   cache_delete('bakup_tables.php');
			   showmsg("数据库备份完毕","ng_db.php?action=export");
			}
			exit;
		}
		else
		{
			$size = $bktables = $bkresults = $results= array();
			$k = 0;
			$totalsize = 0;
			$totalrecords = 0;
			$query = $db->query("SHOW tableS FROM ".$sql_db);
			while($r = $db->fetch_row($query))
			{
				$tables[$k] = $r[0];
				$count = $db->GET_one("SELECT count(*) as number FROM $r[0] WHERE 1");
				$results[$k] = $count['number'];
				$bktables[$k] = $r[0];
				$bkresults[$k] = $count['number'];
                $q = $db->query("SHOW table STATUS FROM `".$sql_db."` LIKE '".$r[0]."'");
				$s = $db->fetch_array($q);
				$size[$k] = round($s['Data_length']/1024/1024, 2);
				$totalsize += $size[$k];
				$totalrecords += $bkresults[$k];
				$k++;
			}
			require_once PrintTemp('bakdb');
			require_once "./footer.php";
			flush;
			exit;
		}
	break;

	case 'import':
	 if($dosubmit)
	 {
		if($filename && fileext($filename)=='sql')
		{
			$filepath = './data/'.$filename;
			if(!file_exists($filepath)) showmsg("对不起， $filepath 不存在","ng_db.php?action=import");
			$sql = file_GET_contents($filepath);
			sql_execute($sql);
			showmsg("$filename 中的数据已经成功导入到数据库","ng_db.php?action=import");
		}
		else
		{
			$fileid = $fileid ? $fileid : 1;
			$filename = $pre.$fileid.'.sql';
			$filepath = './data/'.$filename;
			if(file_exists($filepath))
			{
				$sql = file_GET_contents($filepath);
				sql_execute($sql);
				$fileid++;
				showmsg("数据文件 $filename 导入成功!","?action=".$action."&pre=".$pre."&fileid=".$fileid."&dosubmit=1");
			}
			else
			{
				showmsg("数据库恢复成功","ng_db.php?action=import");
			}
		}
	 }
	 else
	 {
		 $sqlFILES = glob('./data/*.sql');
		 if(is_array($sqlFILES))
		 {
			 $prepre = '';
			 $info = $infos = array();
			 foreach($sqlFILES as $id=>$sqlfile)
			 {
				 preg_match("/([a-z0-9_]+_[0-9]{8}_[0-9a-z]{4}_)([0-9]+)\.sql/i",basename($sqlfile),$num);
				 $info['filename'] = basename($sqlfile);
				 $info['FILESize'] = round(FILESize($sqlfile)/(1024*1024), 2);
				 $info['maketime'] = date('Y-m-d H:i:s', filemtime($sqlfile));
				 $info['pre'] = $num[1];
				 $info['number'] = $num[2];
				 if(!$id) $prebgcolor = '#E4EDF9';
				 if($info['pre'] == $prepre)
				 {
					 $info['bgcolor'] = $prebgcolor;
				 }
				 else
				 {
					 $info['bgcolor'] = $prebgcolor == '#E4EDF9' ? '#F1F3F5' : '#E4EDF9';
				 }
				 $prebgcolor = $info['bgcolor'];
				 $prepre = $info['pre'];
				 $infos[] = $info;
			 }
		 }
		 require_once PrintTemp('restore');
		 require_once "./footer.php";
		 flush;
		 exit;
	 }
	 break;

	case 'repair':
	 if($dosubmit)
	 {
		 $tables = is_array($tables) ? implode(',',$tables) : $tables;
		 if($tables && in_array($operation,array('repair','optimize')) ) $db->query("$operation table $tables");
		 showmsg("数据表操作成功", "ng_db.php?action=repair");
	 }
	 else
	 {
		$tables = array();
		$query = $db->query("SHOW tableS FROM ".$sql_db);
		while($r = $db->fetch_row($query))
		{
			$tables[] = $r[0];
		}
		require_once PrintTemp('repair');
		require_once "./footer.php";
		flush;
		exit;
	 }
	 break;

	case 'query':
	 if(!$runsql) showmsg("运行语句功能已被管理员禁止","ng_db.php?action=query");
	 if($dosubmit)
	 {
		if($operation == 'file')
		{
			$savepath = './data/tmp_'.$uploadfile_name;
			copy($uploadfile, $savepath);
			$sql = file_GET_contents($savepath);
			@unlink($savepath);
		}
		else
		{
			$sql = stripslashes($sql);
		}
		if(trim($sql) != '') sql_execute($sql);
		showmsg("您的SQL语句已经成功运行了", "ng_db.php?action=query");
	 }
	 else
	 {
		  require_once PrintTemp('querysql');
		  require_once "./footer.php";
		  flush;
		  exit;
	 }
	 break;

	case 'uploadsql':
		if(!$uploadsql) showmsg("上传SQL功能已被管理员禁止","ng_db.php?action=query");
			if(fileext($uploadfile_name)!='sql') showmsg("只允许上传sql格式文件","ng_db.php?action=query");
				$savepath = './data/'.$uploadfile_name;
		if(copy($uploadfile, $savepath)){
			showmsg("文件上传成功", "ng_db.php?action=query");
		}else{
			showmsg("文件上传失败", "ng_db.php?action=query");
		}
	break;

	case 'delete':
		if(is_array($filenames)){
		 	foreach($filenames as $filename){
			 	if(fileext($filename)=='sql'){
				 	@unlink('./data/'.$filename);
			 	}
		 	}
	 	}else{
			 if(fileext($filenames)=='sql'){
				 @unlink('./data/'.$filenames);
			 }
		 }
		 showmsg("文件删除成功", "ng_db.php?action=import");
	 break;
	 
	case 'down':
		$filename or showmsg("文件名不能为空","ng_db.php?action=import");
		file_down('./data/'.$filename);
	break;

	case 'phpinfo':
		phpinfo();
		exit;
	break;

	case 'synimport':
		if($filename && fileext($filename)=='sql')
		{
			$filepath = './data/'.$filename;
			if(!file_exists($filepath)) showmsg("对不起， $filepath 不存在","ng_joing.php");
			$sql = file_GET_contents($filepath);
			sql_execute($sql);
			$filenames[] = $filename;
			@unlink('./data/'.$filename);
			db_query ("UPDATE $sql_tbl[joiner] SET last_login ='$curtime' WHERE login = '$joinername'");
			showmsg("$filename 中的数据已经成功同步到数据库","ng_cache.php");
		}
		else
		{
			$curtime = time();
			$fileid = $fileid ? $fileid : 1;
			$filename = $pre.$fileid.'.sql';
			$filepath = './data/'.$filename;
			if(file_exists($filepath))
			{
				$sql = file_GET_contents($filepath);
				sql_execute($sql);
				$fileid++;
				$filenames[] = $filename;
				@unlink('./data/'.$filename);
				db_query ("UPDATE $sql_tbl[joiner] SET last_login ='$curtime' WHERE login = '$joinername'");
				showmsg("数据文件 $filename 同步成功!","?action=".$action."&pre=".$pre."&fileid=".$fileid."&dosubmit=1");
			}
			else
			{
			
				
				if(is_array($filenames)){
					foreach($filenames as $filename){
						if(fileext($filename)=='sql'){
							@unlink('./data/'.$filename);
						}
					}
				}else{
					 if(fileext($filenames)=='sql'){
						 @unlink('./data/'.$filenames);
					 }
				}
		 		db_query ("UPDATE $sql_tbl[joiner] SET last_login ='$curtime' WHERE login = '$joinername'");
				showmsg("同步主站数据成功,请更新网站缓存","ng_cache.php");
			}
		}
	break;

	default:
		header("Location:?action=export");
	break;
}

function file_down($file,$filename='')
{
	file_exists($file) or showmsg("文件不存在","ng_db.php?action=import");
	$filename = $filename ? $filename : basename($file);
	$filetype = fileext($filename);
	$FILESize = FILESize($file);
	header('Cache-control: max-age=31536000');
	header('Expires: '.gmdate('D, d M Y H:i:s', time() + 31536000).' GMT');
	header('Content-Encoding: none');
	header('Content-Length: '.$FILESize);
	header('Content-Disposition: attachment; filename='.$filename);
	header('Content-Type: '.$filetype);
	readfile($file);
	exit;
}

function fileext($filename)
{
	return trim(substr(strrchr($filename, '.'), 1));
}

function cache_read($file, $mode = 'i')
{
	$cachefile = './data/'.$file;
	if(!file_exists($cachefile)) return array();
	return $mode == 'i' ? include $cachefile : file_GET_contents($cachefile);
}

function cache_write($file, $string, $type = 'array')
{
	if(is_array($string))
	{
		$type = strtolower($type);
		if($type == 'array')
		{
			$string = "<?php\n return ".var_export($string,trUE).";\n?>";
		}
		elseif($type == 'constant')
		{
			$data='';
			foreach($string as $key => $value) $data .= "define('".strtoupper($key)."','".addslashes($value)."');\n";
			$string = "<?php\n".$data."\n?>";
		}
	}
	file_put_contents('./data/'.$file, $string);
}
function cache_delete($file)
{
	return @unlink('./data/'.$file);
}
function sql_dumptable($table, $startfrom = 0, $currsize = 0)
{
	global $db, $sizelimit, $startrow;

	if(!isset($tabledump)) $tabledump = '';
	$offset = 100;
	if(!$startfrom)
	{
		$tabledump = "DROP table IF EXISTS $table;\n";
		$db->query("SET SQL_QUOTE_SHOW_CREATE = 0");
		$createtable = $db->query("SHOW CREATE table $table");
		$create = $db->fetch_row($createtable);
		$tabledump .= $create[1].";\n\n";
	}

	$tabledumped = 0;
	$numrows = $offset;
	while($currsize + strlen($tabledump) < $sizelimit * 1000 && $numrows == $offset)
	{
		$tabledumped = 1;
		$rows = $db->query("SELECT * FROM $table LIMIT $startfrom, $offset");
		$numfields = $db->num_fields($rows);
		$numrows = $db->num_rows($rows);
		while ($row = $db->fetch_row($rows))
		{
			$comma = "";
			$tabledump .= "INSERT INTO $table VALUES(";
			for($i = 0; $i < $numfields; $i++)
			{
				$tabledump .= $comma."'".mysql_escape_string($row[$i])."'";
				$comma = ",";
			}
			$tabledump .= ");\n";
		}
		$startfrom += $offset;
	}
	$startrow = $startfrom;
	$tabledump .= "\n";
	return $tabledump;
}

function sql_execute($sql)
{
	global $db;
    $sqls = sql_split($sql);
	if(is_array($sqls))
    {
		foreach($sqls as $sql)
		{
			if(trim($sql) != '') 
			{
				$db->query($sql);
			}
		}
	}
	else
	{
		$db->query($sqls);
	}
	return true;
}

function sql_split($sql)
{
	global $db_charset, $db;
	if($db->version() > '4.1' && $db_charset)
	{
		$sql = preg_replace("/TYPE=(InnoDB|MyISAM)( DEFAULT CHARSET=[^; ]+)?/", "TYPE=\\1 DEFAULT CHARSET=".$db_charset,$sql);
	}
	$sql = str_replace("\r", "\n", $sql);
	$ret = array();
	$num = 0;
	$queriesarray = explode(";\n", trim($sql));
	unset($sql);
	foreach($queriesarray as $query)
	{
		$ret[$num] = '';
		$queries = explode("\n", trim($query));
		$queries = array_filter($queries);
		foreach($queries as $query)
		{
			$str1 = substr($query, 0, 1);
			if($str1 != '#' && $str1 != '-') $ret[$num] .= $query;
		}
		$num++;
	}
	return($ret);
}
?>