<?php
class Dbmanager_Core{
	var $db;
	var $lang;
	var $mod;
	var $file;

	function __construct()
	{
		$this->db = 	new Database();
	}
	function export($tables=false,$sqlcompat=false,$sqlcharset=false,$sizelimit=false,$fileid=false,$random=false,$tableid=false,$startfrom=false,$tabletype=false)
	{
		$dumpcharset = $sqlcharset ? $sqlcharset : str_replace('-', '', CHARSET);
		$fileid = $fileid ? $fileid : 1;
		if($fileid==1 && $tables)
		{
			$random = mt_rand(1000, 9999);
			file_put_contents(DATADIR."cache/bakup_tables.php","<?php \r\n return ".var_export($tables,true).";\r\n?>");
		}
		else {
			$tables	=	include(DATADIR."cache/bakup_tables.php");
		}

		if($this->db->version() > '4.1'){
			if($sqlcharset)
			{
				$this->db->query("SET NAMES '".$sqlcharset."';\n\n");
			}
			if($sqlcompat == 'MYSQL40')
			{
				$this->db->query("SET SQL_MODE='MYSQL40'");
			}
			elseif($sqlcompat == 'MYSQL41')
			{
				$this->db->query("SET SQL_MODE=''");
			}
		}
		$tabledump = '';
		$tableid = $tableid ? $tableid - 1 : 0;
		$startfrom = $startfrom ? intval($startfrom) : 0;
		for($i = $tableid; $i < count($tables) && strlen($tabledump) < $sizelimit * 1000; $i++)
		{
			global $startrow;
			$offset = 100;
			if(!$startfrom)
			{
				$tabledump .= "DROP TABLE IF EXISTS `$tables[$i]`;\r\n";
				$createtable	= 	$this->db->query("SHOW CREATE TABLE `$tables[$i]` ")->result_array(false);
				$create 		= 	$createtable;
				$tabledump 		.= 	preg_replace("#[\r\n]+#","\r\n",$create[0]["Create Table"]).";\r\n\n";
				if($sqlcompat == 'MYSQL41' && $this->db->version() < '4.1')
				{
					$tabledump = preg_replace("/TYPE\=([a-zA-Z0-9]+)/", "ENGINE=\\1 DEFAULT CHARSET=".$dumpcharset, $tabledump);
				}
				if($this->db->version() > '4.1' && $sqlcharset)
				{
					$tabledump = preg_replace("/(DEFAULT)*\s*CHARSET=[a-zA-Z0-9]+/", "DEFAULT CHARSET=".$sqlcharset, $tabledump);
				}
			}

			$numrows = $offset;
			while(strlen($tabledump) < $sizelimit * 1000 && $numrows == $offset){
				$result		= 	$this->db->query("SELECT * FROM `$tables[$i]` LIMIT $startfrom, $offset");
				$fields		=	$result->list_fields($tables[$i]);
				$numfields 	= 	$result->count_filed();
				$numrows 	= 	$result->count();
				while ($row = 	$result->fetch_row()){
					$comma 	= 	"";
					$tabledump .= "INSERT INTO `$tables[$i]` (`".implode("`,`",$fields)."`) VALUES(";
					foreach($fields as $field)
					{
						$tabledump .= $comma."'".mysql_escape_string($row[$field])."'";
						$comma = ",";
					}
					$tabledump .= ");\r\n";
				}
				$startfrom += $offset;
			}
			$tabledump .= "\r\n";
			$startrow = $startfrom;
			$startfrom = 0;
		}

		if(trim($tabledump))
		{
			$tabledump = "# lmpic bakfile\r\n# version:".LMPIC_VERSION."\r\n# time:".date('Y-m-d H:i:s')."\r\n# type:lmpic\r\n# lmpic:http://www.lmpic.cn\r\n# --------------------------------------------------------\r\n\n\n".$tabledump;
			$tableid = $i;
			$filename = date('Ymd').'_'.$random.'_'.$fileid.'.sql';
			$fileid++;
			$bakfile = 'data/bakup/'.$filename;
			file_put_contents($bakfile, $tabledump);
			@chmod($bakfile, 0777);
			//分卷备份数据
			echo "成功备份分卷".$filename;
			die("<script>window.location='".BASEURI."database/export/".($sqlcompat?$sqlcompat:0) ."/".($sqlcharset?$sqlcharset:0) ."/".($sizelimit?$sizelimit:0) ."/".($fileid?$fileid:0) ."/".($random?$random:0) ."/".($tableid?$tableid:0) ."/".($startrow?$startrow:0) ."/".($tabletype?$tabletype:0) ."';</script>");

		}
		else
		{
			return true;
		}
	}
	function import($filepath)
	{
		if($filepath && strtolower(pathinfo($filepath,PATHINFO_EXTENSION))=='sql')
		{
			if(!file_exists($filepath)) return false;
			$sql = file_get_contents($filepath);
			if($this->sql_execute($sql)){
				return true;
			}
			else{
				return false;
			}
		}
		else
		{
			$fileid = $fileid ? $fileid : 1;
			$pre = $filename;
			$filename = $filename.$fileid.'.sql';
			$filepath = 'data/bakup/'.$filename;
			if(file_exists($filepath))
			{
				$sql = file_get_contents($filepath);
				sql_execute($sql);
				$fileid++;
				showmessage($this->lang['data_file']." $filename ".$this->lang['load_success'],"?mod=".$this->mod."&file=".$this->file."&action=import&pre=".$pre."&fileid=".$fileid."&dosubmit=1");
			}
			else
			{
				showmessage($this->lang['database_recover_success'],'?mod=phpcms&file=database&action=import');
			}
		}
	}
	function sql_execute($sql)	{
		$sqls = $this->sql_split($sql);
		if(is_array($sqls)){
			foreach($sqls as $sql)
			{
				if(trim($sql) != '')
				{
					$this->db->query($sql);
				}
			}   
		}
		else{
			$this->db->query($sqls);
		}
		return true;
	}
	function sql_split($sql)
	{
		global $db;
		if($this->db->version() > '4.1' && CHARSET)
		{
			$sql = preg_replace("/TYPE=(InnoDB|MyISAM|MEMORY)( DEFAULT CHARSET=[^; ]+)?/", "TYPE=\\1 DEFAULT CHARSET=".CHARSET,$sql);
		}
		if(DBFIX != "phpcms_") $sql = str_replace("phpcms_", DBFIX, $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);
	}

	function repair($tables,$operation)
	{
		$tables = is_array($tables) ? implode(',',$tables) : $tables;
		if($tables && in_array($operation,array('repair','optimize')))
		{
			$this->db->query("$operation TABLE $tables");
			showmessage($this->lang['operation_success'],'?mod=phpcms&file=database&action=repair');
		}
		else
		{
			showmessage($this->lang['select_rep_table'],'?mod=phpcms&file=database&action=repair');
		}
	}
	function executesql($operation,$sql)
	{
		global $db;
		if($operation == 'file')
		{
			require_once 'include/upload.class.php';
			$savepath = 'data/bakup/';
			$upload = new upload('uploadfile',$savepath,'','sql','4096000',1);
			if(!$upload->up())
			{
				showmessage($upload->error());
			}
			$sql = file_get_contents($upload->uploadedfiles[0][saveto]);
			dir_delete($savepath.date('Y'));
			if(trim($sql) != '') sql_execute($sql);
		}
		if(empty($sql))
		{
			return false;
		}
		//sql鎵ц
		$sql = stripslashes($sql);
		$sql = str_replace("\\", "", $sql);
		$sql = str_replace("\r", "", $sql);
		$query_items = split(";[ \t]{0,}\n",$sql);
		foreach ($query_items as $key=>$value)
		{
			if (empty($value))
			{
				unset($query_items[$key]);
			}
		}
		if(count($query_items) > 1)
		{
			foreach ($query_items as $key=>$value)
			{
				if(!$result=$db->query($value, 'SILENT'))
				{
					return false;
				}
			}
			return true; //閫€鍑哄嚱鏁?
		}
		else
		{
			if (preg_match("/^(?:UPDATE|DELETE|TRUNCATE|ALTER|DROP|FLUSH|INSERT|REPLACE|SET|CREATE)\\s+/i", $sql))
			{
				$result = $db->query($sql);
				return $result;
			}
			else
			{
				$result = $db->query($sql);
				$data=array();
				while($r=$db->fetch_array($result))
				{
					$data[]=$r;
				}
				return $data;
			}
		}
	}
	function uploadsql()
	{
		require_once 'include/upload.class.php';
		$savepath = 'data/bakup/';
		$upload = new upload('uploadfile',$savepath,'','sql','4096000',1);
		if(!$upload->up())
		{
			showmessage($upload->error());
		}
		$name = basename($savepath.$upload->uploadedfiles[0][filepath]);
		copy($savepath.$upload->uploadedfiles[0][filepath],$savepath.$name);
		dir_delete($savepath.date('Y'));
		showmessage($this->lang['upload_success']);
	}
	function changecharset($tocharset, $filenames)
	{
		if(empty($tocharset)) showmessage($this->lang['select_charset_convert_type']);
		$charsets = explode('2',$tocharset);
		$from = $charsets[0];
		$to = $charsets[1];
		if($filenames)
		{
			if(is_array($filenames))
			{
				foreach($filenames as $filename)
				{
					if(fileext($filename)=='sql')
					{
						$str = file_get_contents('data/bakup/'.$filename);
						$str = str_charset($from, $to, $str);
						echo $from.' '.$to;
						file_put_contents('data/bakup/'.$to.$filename, $str);
						@chmod('data/bakup/'.$to.$filename, 0777);
					}
				}
			}
			else
			{
				if(fileext($filenames)=='sql')
				{
					$str = file_get_contents('data/bakup/'.$filenames);
					$str = str_charset($from, $to, $str);
					file_put_contents('data/bakup/'.$to.$filenames, $str);
					@chmod('data/bakup/'.$to.$filenames, 0777);
				}
			}
			showmessage($this->lang['operation_success']);
		}
		else
		showmessage($this->lang['select_charset_convert_type']);
	}
	function delete($filenames,$action)
	{
		if($filenames)
		{
			if(is_array($filenames))
			{
				foreach($filenames as $filename)
				{
					if(fileext($filename)=='sql')
					{
						@unlink('data/bakup/'.$filename);
					}
				}
				showmessage($this->lang['operation_success'], '?mod='.$this->mod.'&file='.$this->file.'&action='.$action);
			}
			else
			{
				if(fileext($filenames)=='sql')
				{
					@unlink('data/bakup/'.$filenames);
					showmessage($this->lang['operation_success'], '?mod='.$this->mod.'&file='.$this->file.'&action='.$action);
				}
			}
		}
		else
		showmessage($this->lang['select_delete_bak_file']);
	}
	function down($filename)
	{
		$fileext = fileext($filename);
		if($fileext != 'sql')
		{
			showmessage($this->lang['sorry_only_download_sql_file']);
		}
		file_down('data/bakup/'.$filename);

	}
	function status()
	{
		$results = $this->db->query("SHOW TABLE STATUS FROM `".DB_NAME."`")->result_array(false);
		$lmpic = array();
		$other = array();
		foreach($results as $table)
		{
			$name = $table['Name'];
			$row = array('name'=>$table['Name'],'rows'=>$table['Rows'],'size'=>$table['Data_length']+$table['Index_length']);
			if(strpos($name, DBFIX) === 0)
			$lmpic[] = $row;
			else
			$other[] = $row;
		}
		return array('lmpictables'=>$lmpic, 'othertables'=>$other);
	}
}
?>
