<?php
	!defined('DIRCMS_MANAGE') && exit('Access Denied!');
	@set_time_limit(0);
	$r=cache_read('module.cache.php',DIRCMS_ROOT.'data/cache_module/');
	$r=$r['database']['roleid']; 
	if(!in_array($_roleid,$r) && $_userid!=ADMIN_FOUNDERS)showmsg_nourl('您没有该操作的权限!');
	$action=empty($action)?'export':trim($action);
	switch($action)
	{
		case 'export':
			if(isset($do_submit))
			{
				if(!$name && !$page)showmsg('请选择要备份的数据表');
				if($name)
				{
					cache_write('bakup_table.cache_tmp'.$_userid.'.php',$name,DIRCMS_ROOT.'data/cache_tmp/'); //////// 临时文件
				}
				else{
					$name=cache_read('bakup_table.cache_tmp'.$_userid.'.php',DIRCMS_ROOT.'data/cache_tmp/');
				}

				$sql='';
				$tableid=isset($tableid)?$tableid-1:0;
				$tablecounts=count($name);
				$start=isset($start)?intval($start):0;

				for($i=$tableid;$i<$tablecounts && strlen($sql)<$sizelimit*1000;$i++)
				{				
					if(!$start)
					{
						$r=$db->fetch_one("SHOW CREATE TABLE `{$name[$i]}`"); 
						$sql.="DROP TABLE IF EXISTS `{$name[$i]}`;\n";
						$sql.=$r['Create Table'].";\n";
					}
					$numrows=$offset=5;

					while(strlen($sql)<$sizelimit*1000 && $numrows==$offset)  
					{
						$tmp_r=$db->fetch_all("SELECT * FROM `{$name[$i]}` LIMIT {$start},{$offset}");
						if($tmp_r)foreach($tmp_r as $val_r)
						{
							$val_r=array_map('mysql_escape_string',$val_r);
							foreach($val_r as $t_k => $t_v)
							{
								$val_r[$t_k]='\''.$t_v.'\'';
							}
							$sql.="REPLACE INTO `{$name[$i]}` VALUES(".implode(',',$val_r).");\n";
						}
						$numrows=count($tmp_r);
						$start+=$offset;
						$startrow=$start;
					}
					$start=0;
				}

				if(trim($sql))
				{
					$tableid=$i;
					$page=$page?$page:1;
					$rand=$rand?$rand:mt_rand(10000,99999);	
					@file_put_contents(DIRCMS_ROOT.'data/bakup/database_bakup_'.date('Ymd').'_'.$rand.'_'.$page.'.sql',$sql);
					showmsg('备份文件database_bakup_'.date('Ymd').'_'.$rand.'_'.$page.'.sql写入成功!',$DIRCMS['admin_file'].'?file=db&action=export&do_submit=1&tableid='.$tableid.'&page='.($page+1).'&rand='.$rand.'&sizelimit='.$sizelimit.'&start='.$startrow);
				}
				else
				{
					cache_delete('bakup_table.cache_tmp'.$_userid.'.php',DIRCMS_ROOT.'data/cache_tmp/');
					showmsg('数据库备份成功!',$DIRCMS['admin_file'].'?file=db&action=export');
				}
			}
			$result=$db->get_table_status(DB_NAME);
			foreach($result as $key => $value)
			{
				if(substr($value['Name'],0,strlen(DB_PRE))==DB_PRE)
				$result[$key]=$value;
				else unset($result[$key]);
			}
			include admin_tlp('db_export');
			break;
		case 'sql':
			if(isset($do_submit))
			{
				if(!DOSQL)showmsg('管理员已禁止后台执行SQL!');
				if(!$sql)showmsg('SQL语句不能为空!');
				$sql=explode(';',$sql);
				foreach($sql as $_sql)
				{
					if(trim($_sql))$db->query(trim($_sql));
				}
				showmsg('SQL语句成功执行!');
			}
			include admin_tlp('sql_db');
			break;
		case 'import':
			if(isset($do_submit))
			{
				if($time && $volume &&$no)
				{
					$filepath=DIRCMS_ROOT.'data/bakup/database_bakup_'.$time.'_'.$volume.'_'.$no.'.sql';
					if(file_exists($filepath))
					{
						$sqls=file_get_contents($filepath);
						$sqls=explode(";\n",trim($sqls));
						foreach($sqls as $sql)
						{
							$db->query($sql,true);
						}
						showmsg(basename($filepath).' 导入成功...',$DIRCMS['admin_file'].'?file=db&action=import&do_submit=1&time='.$time.'&volume='.$volume.'&no='.($no+1));
					}
					else
					{
						$c=new cache();
						$c->cache_all();
						showmsg('数据库还原成功!',$DIRCMS['admin_file'].'?file=db&action=import');
					}
					
				}
				else
				{
					$r=explode('_',$filename);
					showmsg('准备工作结束，开始还原数据...',$DIRCMS['admin_file'].'?file=db&action=import&do_submit=1&time='.$r[2].'&volume='.$r[3].'&no=1');
				}		
			}

			$r=glob(DIRCMS_ROOT.'data/bakup/*.sql');

			
			foreach($r as $k => $v)
			{
				$tarray=explode('_',substr(strrchr($v,'/'),1));
				$tarray=explode('.',$tarray[4]);
				$key=$tarray[0];
				$result[$k]['filename']=substr(strrchr($v,'/'),1);
				$result[$k]['filesize']=round((filesize($v)/1024)/1024,2).' M';
				$result[$k]['mtime']=date('Y-m-d H:i:s',filemtime($v));
				$result[$k]['volume']=$key;
			}
			ksort($result);
			include admin_tlp('db_import');
			break;
		case 'delete':
			if(!$name)showmsg('请选择要删除的备份文件!');
			foreach($name as $filename)
			{
				@unlink(DIRCMS_ROOT.'data/bakup/'.$filename);
			}
			showmsg('成功删除备份文件!','?file=db&action=import');
			break;
		case 'down':
			$filepath=DIRCMS_ROOT.'data/bakup/'.$filename;
			$filesize=sprintf("%u", filesize($filepath));
			$filetype=get_fileext($filename);
			if(ob_get_length() !== false) @ob_end_clean();
			header('Pragma: public');
			header('Last-Modified: '.gmdate('D, d M Y H:i:s') . ' GMT');
			header('Cache-Control: no-store, no-cache, must-revalidate');
			header('Cache-Control: pre-check=0, post-check=0, max-age=0');
			header('Content-Transfer-Encoding: binary');
			header('Content-Encoding: none');
			header('Content-type: '.$filetype);
			header('Content-Disposition: attachment; filename="'.$filename.'"');
			header('Content-length: '.$filesize);
			readfile($filepath);
			exit;
			break;
		case 'repair':
			if(isset($do_submit))
			{
				$manage=$operation=='repair'?'修复':'优化';
				if(!$name)showmsg('请选择要'.$manage.'的数据表');
				foreach($name as $table)
				{
					$db->query("{$operation} TABLE {$table}",true);
				}
				showmsg('数据表'.$manage.'完毕!');
			}
			$result=$db->get_table_status(DB_NAME);
			foreach($result as $key => $value)
			{
				if(substr($value['Name'],0,strlen(DB_PRE))==DB_PRE)
				$result[$key]=$value;
				else unset($result[$key]);
			}
			include admin_tlp('db_repair');
			break;
	}
?>