<?php
//update from o-blog2.6 to 3.0

header("content-type:text/html; charset=gb2312;");
$action = $_POST['action'];
if (!$action) $action = $_GET['action'];
if (!$action)
{
	?>
	<html>
	<head>
	<title>O-blog update</title>
	</head>
	<body>
		<form action="?" method=post>
			<h2>O-blog 2.6 to 3.0 升级程序 </h2><br />
			注意:此操作将会清空 3.0 版本中的部分数据。
			<br/>
			<input type="hidden" name="action" value="test" />
			<table border=0>
				<tr>
					<td>
						数据库地址:
					</td>
					<td>
						<input type="text" name="server" value="localhost" />
					</td>
				</tr>
				<tr>
					<td>
						数据库名字:
					</td>
					<td>
						<input type="text" name="dbname" value="" />
					</td>
				</tr>
				<tr>
					<td>
						用户名:
					</td>
					<td>
						<input type="text" name="username" value="root" />
					</td>
				</tr>
				<tr>
					<td>
						密码:
					</td>
					<td>
						<input type="password" name="password" value="" />
					</td>
				</tr>
				<tr>
					<td>
						O-blog 2.6 数据表前缀:
					</td>
					<td>
						<input type="text" name="prefix26" value="ob_" />
					</td>
				</tr>
				<tr>
					<td>
						O-blog 3.0 数据表前缀:
					</td>
					<td>
						<input type="text" name="prefix30" value="ob3_" />
					</td>
				</tr>
				<tr>
					<td align=center>
						<input type="submit" value="转换" />
					</td>
					<td align=center>
						<input type="reset" value="重置" />
					</td>
				</tr>
				
			</table>
		</form>
		
	</body>
	</html>
	<?php
}
else if ($action == "test")
{
	?>
    请帮助我们检查下面的博客标题是否是乱码。<br/>
    <form method=post id='dataform'>
    	<input type=hidden name='action' value='doupdate' />
        <input type=hidden name='server' value='<?php echo $_POST['server'];?>' />
        <input type=hidden name='username' value='<?php echo $_POST['username'];?>' />
        <input type=hidden name='password' value='<?php echo $_POST['password'];?>' />
        <input type=hidden name='dbname' value='<?php echo $_POST['dbname'];?>' />
        <input type=hidden name='prefix26' value='<?php echo $_POST['prefix26'];?>' />
        <input type=hidden name='prefix30' value='<?php echo $_POST['prefix30'];?>' />
        <input type=hidden name='setgb2312' value='<?php echo $_POST['setgb2312'];?>' />
        <input type=submit value="没有乱码" />&nbsp;&nbsp;&nbsp;
        <input type=button value="有乱码" onClick=" with(document.getElementById('dataform'))
        	{
            	setgb2312.value = (setgb2312.value=='yes')?'no':'yes'; 
                action.value = 'test';
                submit();
            }" />
	
    </form>
    <?php
	$DB = new DB_MySQL();
	$DB->connect($_POST['server'], $_POST['username'], $_POST['password'], $_POST['dbname']);
	if ($_POST['setgb2312'] == "yes")
	{
		$DB->query("SET character_set_client = gb2312");
		$DB->query("SET character_set_results = gb2312");
		$DB->query("SET character_set_connection = gb2312");
	}
	$rows = $DB->query("SELECT * FROM ".$_POST['prefix26']."blog LIMIT 0,30");
	
	echo "<ul>";
	while ($row = $DB->fetch_array($rows)) 
	{
		echo "<li>".$row['title']."</li>";
	}
	echo "</ul>";
}
else if ($action == "doupdate")
{
	$DB = new DB_MySQL();
	$DB->connect($_POST['server'], $_POST['username'], $_POST['password'], $_POST['dbname']);
	if ($_POST['setgb2312'] == "yes")
	{
		$DB->query("SET character_set_client = gb2312");
		$DB->query("SET character_set_results = gb2312");
		$DB->query("SET character_set_connection = gb2312");
	}
	$update_tables = array(
		"blog",
		"class",
		"guestbook",
		"link",
		"note",
		"remark",
		"trackback"
	);
	
	$sql = array();
	foreach($update_tables as $table)
	{
		$table2 = $_POST['prefix30'].$table;
		$table = $_POST['prefix26'].$table;
		echo "$table -> $table2 ";
		$sql[] = "DELETE FROM $table2;";
		//get fields list
		$firstfield = 1;
		$fields = $DB->query("SHOW FIELDS FROM $table");
		$col_name_list = "";
		while ($field = $DB->fetch_array($fields)) 
		{
			if (!$firstfield) 
			{
				$col_name_list .= ",`$field[Field]`";
			}
			else
			{
				$firstfield = 0;
				$col_name_list .= "`$field[Field]`";
			}
		}
		$DB->free_result($fields);
		
		$rows      = $DB->query("SELECT * FROM $table");
		$numfields = mysql_num_fields($rows);
		$nnn = 0;
		while ($row = $DB->fetch_array($rows)) 
		{
			$nnn++;
			$tabledump    = "INSERT INTO $table2 ($col_name_list) VALUES(";
			$fieldcounter = -1;
			$firstfield   = 1;
			while (++$fieldcounter<$numfields) 
			{
				if (!$firstfield) 
				{
					$tabledump.=", ";
				} 
				else 
				{
					$firstfield=0;
				}

				if (!isset($row[$fieldcounter])) 
				{
					$tabledump .= "NULL";
				}
				else 
				{
					$tabledump .= "'".mysql_escape_string($row[$fieldcounter])."'";
				}
			}
			$tabledump .= ");";
			$sql[] = $tabledump;
		}
		echo "($nnn)<br />";
	}
	$DB->free_result($rows);
	$DB->close();
	$charset="utf8";
	$DB->connect2($_POST['server'], $_POST['username'], $_POST['password'], $_POST['dbname']);
	

	foreach($sql as $line)
	{
		$DB->query( mb_convert_encoding($line,"utf-8","gb2312") );
	}
	echo "转换成功!<br />现在可以检查数据是否转换成功。<br />如果成功，您可以<a href='?action=delete26&prefix=".$_POST['prefix26']."&server=".$_POST['server']."&dbname=".$_POST['dbname']."&username=".$_POST['username']."&password=".$_POST['password']."'>删除2.6的数据表</a>";
}
else if ($action == "delete26")
{
	$delete_tables = array(
		"admin",
		"adminlog",
		"config",
		"loginlog",
		"blog",
		"class",
		"guestbook",
		"link",
		"note",
		"remark",
		"trackback"
	);
	$DB = new DB_MySQL();
	$DB->connect($_GET['server'], $_GET['username'], $_GET['password'], $_GET['dbname']);

	foreach($delete_tables as $table)
	{
		$table = $_GET['prefix'].$table;
		$DB->query("DROP TABLE IF EXISTS `$table`;");
	}
	echo "删除数据表成功<br />";
	$filename = "upgrade_26to30.php";
	if (unlink($filename))
	{
		echo "删除升级文件成功<br />";
	}
	else
	{
		echo "升级文件删除失败，请手动删除";
	}
	
	
}

class DB_MySQL  {

	var $querycount = 0;

	function error() {
		return mysql_error();
	}

	function geterrno() {
		return mysql_errno();
	}

	function insert_id() {
		$id = mysql_insert_id();
		return $id;
	}

	function connect($servername, $dbusername, $dbpassword, $dbname, $usepconnect=0) {
		if($usepconnect) {
			if(!@mysql_pconnect($servername, $dbusername, $dbpassword)) {
				$this->halt("数据库链接失败");
			}
		} else {
			if(!@mysql_connect($servername, $dbusername, $dbpassword)) {
				$this->halt("数据库链接失败");
			}
		}

		mysql_select_db($dbname);
	}
	
	function connect2($servername, $dbusername, $dbpassword, $dbname, $usepconnect=0) {
		if($usepconnect) {
			if(!@mysql_pconnect($servername, $dbusername, $dbpassword)) {
				$this->halt("数据库链接失败");
			}
		} else {
			if(!@mysql_connect($servername, $dbusername, $dbpassword)) {
				$this->halt("数据库链接失败");
			}
		}
		$charset = "utf8";
		if(mysql_get_server_info() > '4.1' && $charset)
		{
			mysql_query("SET character_set_connection=$charset, character_set_results=$charset, character_set_client=binary");
		}
		if(mysql_get_server_info() > '5.0')
		{
			mysql_query('SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";');
		}
		if ($dbname)
		{
			if (!@mysql_select_db($dbname))
			{
				$this->halt("选择数据库失败");
			}
		}
	}

	function select_db($dbname) {
		return mysql_select_db($dbname);
	}

	function query($sql,$type = '') {
		$query = mysql_query($sql);
		if(!$query && $type != 'SILENT') {
			$this->halt('MySQL Query Error', $sql);
		}
		$this->querycount++;
		return $query;
	}

	function fetch_array($query) {
		return mysql_fetch_array($query);
	}

	function fetch_row($query) {
		$query = mysql_fetch_row($query);
		return $query;
	}

	function fetch_one_array($query) {
		$result = $this->query($query);
		$record = $this->fetch_array($result);
		return $record;
	}

	function fetch_one($query) {
		$record = $this->fetch_one_array($query);
		Return $record[0];
	}

	function num_rows($query) {
		$query = mysql_num_rows($query);
		return $query;
	}

	function free_result($query) {
		$query = mysql_free_result($query);
		return $query;
	}

	function close() {
		return mysql_close();
	}

	function version() {
		return mysql_get_server_info();
	}

	function halt($msg,$sql=""){
		$message = "<html>\n<head>\n";
		$message .= "<meta content=\"text/html; charset=gb2312\" http-equiv=\"Content-Type\">\n";
		$message .= "<STYLE TYPE=\"text/css\">\n";
		$message .=  "body,td,p,pre {\n";
		$message .=  "font-family : Verdana, sans-serif;font-size : 11px;\n";
		$message .=  "}\n";
		$message .=  "</STYLE>\n";
		$message .= "</head>\n";
		$message .= "<body bgcolor=\"#FFFFFF\" text=\"#000000\" link=\"#006699\" vlink=\"#5493B4\">\n";

		$message .= "数据库出错: ".htmlspecialchars($msg)."\n<p>";
		$message .= "<b>Mysql error description</b>: ".$this->error()."\n<br>";
		$message .= "<b>Mysql error number</b>: ".$this->geterrno()."\n<br>";
		$message .= "<b>Date</b>: ".date("Y-m-d @ H:i",time())."\n<br>";
		$message .= "<b>Query</b>: ".$sql."\n<br>";
		$message .= "<b>Script</b>: http://".$_SERVER['HTTP_HOST'].getenv("REQUEST_URI")."\n<br>";

		$message .= "</body>\n</html>";
		die($message);
		exit;
	}
}


function sqldumptable($table, $fp=0) {
	global $DB;
	//$tabledump  = "DROP TABLE IF EXISTS $table;\n";
	//$tabledump .= "CREATE TABLE $table (\n";
	$firstfield = 1;
	$fields = $DB->query("SHOW FIELDS FROM $table");
	$col_name_list = "";
	while ($field = $DB->fetch_array($fields)) {
		if (!$firstfield) {
			$tabledump .= ",\n";
			$col_name_list .= ",`$field[Field]`";
		} else {
			$firstfield = 0;
			$col_name_list .= "`$field[Field]`";
		}
		$tabledump .= "   $field[Field] $field[Type]";
		
		if (!empty($field["Default"])) {
			$tabledump .= " DEFAULT '$field[Default]'";
		}
		if ($field['Null'] != "YES") {
			$tabledump .= " NOT NULL";
		}
		if ($field['Extra'] != "") {
			$tabledump .= " $field[Extra]";
		}
	}
	$DB->free_result($fields);
	$keys = $DB->query("SHOW KEYS FROM $table");
	while ($key = $DB->fetch_array($keys)) {
		$kname = $key['Key_name'];
		if ($kname != "PRIMARY" and $key['Non_unique'] == 0) {
			$kname="UNIQUE|$kname";
		}
		if(!is_array($index[$kname])) {
			$index[$kname] = array();
		}
		$index[$kname][] = $key['Column_name'];
	}
	$DB->free_result($keys);

	while(list($kname, $columns) = @each($index)) {
		$tabledump .= ",\n";
		$colnames=implode($columns,",");
		if ($kname == "PRIMARY") {
			$tabledump .= "   PRIMARY KEY ($colnames)";
		} else {
			if (substr($kname,0,6) == "UNIQUE") {
				$kname=substr($kname,7);
			}
			$tabledump .= "   KEY $kname ($colnames)";
		}
	}
	$tabledump .= "\n);\n\n";
	if ($fp) {
		fwrite($fp,$tabledump);
	} else {
		echo $tabledump;
	}
	$rows      = $DB->query("SELECT * FROM $table");
	$numfields = mysql_num_fields($rows);
	while ($row = $DB->fetch_array($rows)) {
		$tabledump    = "INSERT INTO $table($col_name_list) VALUES(";
		$fieldcounter = -1;
		$firstfield   = 1;
		while (++$fieldcounter<$numfields) {
			if (!$firstfield) {
				$tabledump.=", ";
			} else {
				$firstfield=0;
			}

			if (!isset($row[$fieldcounter])) {
				$tabledump .= "NULL";
			} else {
				$tabledump .= "'".mysql_escape_string($row[$fieldcounter])."'";
			}
		}
		$tabledump .= ");\n";
		if ($fp) {
			fwrite($fp,$tabledump);
		} else {
			echo $tabledump;
		}
	}
	$DB->free_result($rows);
}
?>