<?
/*
使用频率少的操作函数
restorelsdb, backuplsdb, genRandomString
*/


/*
restoredb 从备份数据文件中恢复数据库
$headTag,$tailTag 首串和尾串
返回完成情况
$imgwidth=getStrbyTag('width=',' ',$newsImgStr,false);
*/

function restorelsdb($host,$username,$password,$restoredb,$backuplsSQLFile, $moreinfo=true)
{

	$conn=mysql_connect($host,$username,$password) or die ("restorelsdb: can't connect DBS $host,$username,$password,$restoredb ");
	$dropdb_sql="DROP DATABASE `".$restoredb."` ";
	mysql_query("SET character_set_client = utf8",$conn);
	mysql_query("SET character_set_results = utf8",$conn);
	mysql_query("SET character_set_connection = utf8",$conn);
	$dropdb_query=mysql_query($dropdb_sql,$conn);

	if($dropdb_query)
	{
		echo "<br/>已经删除数据库：".$restoredb;
	}
	else
	{echo "<br/>删除原有数据库：".$restoredb."失败！<br/>";}
	$creatdb_sql="CREATE DATABASE `".$restoredb."` default charset utf8 COLLATE utf8_general_ci";
	$creatdb_query=mysql_query($creatdb_sql,$conn);

	if($creatdb_query)
	{echo "<br/>重新创建数据库：".$restoredb."成功！<br/>";}
	else
	{die("<br/>重新创建数据库：".$restoredb."失败，数据库恢复终止！<br/>");}

	$restoredblink=mysql_select_db($restoredb,$conn);
	
	if($ls!=""){$filename=$ls;} //如果设置了文件名，则使用
	else
	{$filename=$backuplsSQLFile;}
	
	if (!file_exists ($filename))
	{ 
	   die( "数据库文件 ".$filename." 不存在!"); 	   
	}

	$strlength=$maxLenSQLStr;
	$allnum =0;
	$num =0;
	$handle = fopen ($filename,"r");
	$partstr="";
	$partstr0="";
	$j=0;
	
	while ($partstr0 =  fgets ($handle, 6000 )) 
	{
		//$partstr0=str_replace("\r\n","",$partstr0 );
		if( trim($partstr0)==""){continue;}
		//echo $partstr0. "ss";
		//echo substr(substr ($partstr0,-3),0,1);
		if(strpos($partstr0,"``~`ls_mysqlend`~``")===false)// get the end of line ;
		{
			$partstr.=$partstr0;
			continue;
		}
		else
		{
			$partstr0=str_replace("``~`ls_mysqlend`~``","",$partstr0);  //清空段落标志
			$partstr.=$partstr0;
	 	}
		$num=strlen($partstr);
   	 	$allnum += $num;
		$sqlstr=$partstr;
		$gettablename=$partstr;
		$tablename="";
		$iftablename=strpos($gettablename,"create table `");
		$tablenamestart=strlen("create table `");
		$tablenameend=strpos($gettablename,"` (`");
		$tablenamelen=$tablenameend-$tablenamestart;
		//echo $j.$tablename."--".$iftablename."oo";
		if($iftablename===0)
		{
			$j++;
			
			$tablename=substr($gettablename,$tablenamestart,$tablenamelen);
		}
		
		//echo $sqlstr. "ss-12334--<br/><br/>";
		$query=mysql_query($sqlstr);
		if($query)
		{
			if($tablename=="")
			{if($moreinfo) echo " 已经写入数据 ".$num." 字节!<br/>";}
			else
			{if($moreinfo) echo "$j"."  创建表 ".$tablename." OK! <br/>";}
			
		}
		$partstr="";
		//var_dump($moreinfo);
	}
	echo "恢复数据库 ".$restoredb." 完成,共恢复".$j."个表!<br/>";
	fclose ($handle);
}

/*
backuplsdb 备份数据库到文件中、
返回完成情况
backuplsdb($host,$username,$password,$dbname,$backuplsSQLFile)
*/

function backuplsdb($host,$username,$password,$dbname,$backuplsSQLFile,$moreinfo=true)
{

	$conn=@mysql_connect($host,$username,$password) or die ("backuplsdb: can't connect DBS $host,$username,$password,$dbname");
	$result= mysql_query("SHOW TABLES FROM `$dbname`");
	//echo "SHOW TABLES FROM `$dbname`";
	$dumpstr="";
	$echoinfo="";
	$j=1;
	while($table_rows=mysql_fetch_row($result))
	{
		$tablename=$table_rows[0];
		$dumpstradd="";
		//$fields=mysql_list_fields($dbname,$tablename,$conn);
		//$columns=mysql_num_fields($fields);
		$insertstr="\r\n"."insert into `".$tablename."` (";
		$dumpstr.="\r\n\r\n"."create table `".$tablename."` (";
		$echoinfo.="$j 备份 ".$tablename." ok!<br/>";
		$prikey1="";
		$resultfiedls= mysql_query("SHOW FULL COLUMNS FROM $tablename");
		while($fiels_rows=mysql_fetch_row($resultfiedls))
		{			
			$fieldname=$fiels_rows[0];
			
			//$flag=str_replace("not_null","NOT NULL",mysql_field_flags($fields, $i));	//change not null
			//if(strpos($flag,"primary_key"))
			//{
			//	$flag=str_replace("primary_key","",$flag); //clear the primary_key
			//	$dumpstradd=",PRIMARY KEY  (`".$fieldname."`)";	// set PRIMARY KEY 
			//}
			$fieldtype=$fiels_rows[1];
				if($fieldtype=="blob")
				{
					$fieldtype="text";
				}
			$ifnull=$fiels_rows[2];
			if($ifnull=="NO")
				{
					$ifnull="NOT NULL";
				}
				else
				{
					$ifnull="";
				}
			$prikey1=$fiels_rows[4];
			if($prikey1=="PRI")
				{

					$prikey=" PRIMARY KEY (`".$fieldname."`)";
				}
		
			$defaultvalue=$fiels_rows[5];
				if($defaultvalue!="")
				{
					$defaultvalue="  default '".$defaultvalue."'";
				}
		
			$auto=$fiels_rows[6];
				if($auto=="auto_increment")
				{
					$auto="AUTO_INCREMENT"."  ";
				}
			$comment=$fiels_rows[8];
				if($comment!="")
				{
					$comment="comment '".$comment."'";
				}
		//}
			
			$dumpstr.="`".$fieldname."` ".$fieldtype." ".$ifnull."  ".$defaultvalue." ".$auto." ".$comment.", ";
			$insertstr.="`".$fieldname."`,";	
		}
		//$dumpstr=substr($dumpstr,0,(strlen($dumpstr)-1));	//delete last ,
		$insertstr=substr($insertstr,0,(strlen($insertstr)-1));	//delete last ,

		//$insertstr.="\r\n<br>";
		$dumpstr.=$dumpstradd.$prikey. " ) ENGINE=MyISAM DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC ;``~`ls_mysqlend`~``\r\n<br>$insertstr";
		//echo $dumpstr;
		
		
		$dumpdata_sql="select * from $tablename";
		$dump_query=mysql_query($dumpdata_sql,$conn );
		$insertvalue=" values";
		$l=0;
		
		while($dump_row=mysql_fetch_row($dump_query))
		{
			$insertvalue.=" (";
			$nums=count($dump_row);
			for($k=0;$k<$nums;$k++)
			{
				switch($dump_row[$k])
				{
					
					case "":
					$insertvalue.=" NULL ,";
					break;
					
					default:
					if(is_string($dump_row[$k]))
					{
						$replacevalue=str_replace("'","\'",$dump_row[$k]);	// replace ' with \'
						$insertvalue.="'".$replacevalue."',";
					}
					else
					{$insertvalue.=$dump_row[$k].",";}
				}
			}
			$insertvalue=substr($insertvalue,0,(strlen($insertvalue)-1));	//delete last ,
			$insertvalue.="),\r\n<br>";
			$l++;
		}
		$insertvalue=substr($insertvalue,0,(strlen($insertvalue)-7)).";``~`ls_mysqlend`~``\r\n<br>";	//delete last ,
		if(strpos($insertvalue,"alu;")&&$l==0)
		{$insertvalue=";\r\n<br>";}
		$dumpstr.=")\r\n<br>$insertvalue";
		//dumpdata="select * from $tablename into outfile 'aa$j.sql'";
		//dump_query=$opendb->query($dumpdata);
		//echo $insertvalue;
		$j++;
	}
	$dumpstr=str_replace("<br>","",$dumpstr); //clear <br>
	$dumplen=strlen($dumpstr);
	if($ls!=""){$filename=$ls;} //如果设置了文件名，则使用
	else
	{$filename=$backuplsSQLFile;}
	writegeneralfile($filename,$dumpstr);  //write the backup sql file
	if($moreinfo)echo $echoinfo;
	echo "<br/>备份数据库内容".$dumplen."字节, 共".($j-1)."个表。";

	mysql_free_result($result);
	
//	$resule=shell_exec("mysqldump -opt test > backup-test.sql");
//	if($resule)
//	{echo "数据库备份成功";}
}

/*
genRandomString 获得随机数字字母字符串
$len 字符串长度
返回生成的串 
genRandomString(25);
*/

function genRandomString($len)
{
	$chars = array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k","l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v","w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G","H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R","S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2","3", "4", "5", "6", "7", "8", "9");
	$charsLen = count($chars) - 1;
	shuffle($chars);// 将数组打乱
	$output = "";
	for ($i=0; $i<$len; $i++)
	{
		$output .= $chars[mt_rand(0, $charsLen)];
	}
	return $output;	
}

?>