<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
	<title>PBDigg升级程序</title>
</head>

<body>
<?php
error_reporting(E_ERROR | E_WARNING | E_PARSE);
set_magic_quotes_runtime(0);
define('PBDIGG_ROOT',substr(dirname(__FILE__), 0, -6));
$timestamp = time();
$PHP_SELF = isset($_SERVER['PHP_SELF']) ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
$PB_URL = 'http://'.$_SERVER['HTTP_HOST'].dirname($PHP_SELF).'/';
if (file_exists('update.lock'))
{
	exit('PBDigg 升级程序已锁定。如要重新升级，请删除本目录的 update.lock 文件！');
}

@set_magic_quotes_runtime(0);

$action = $_GET['action'];
$step = $_GET['step'];

$upgrade = <<<EOT
CREATE TABLE `pb_applyinvite` (
`id` MEDIUMINT( 8 ) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
`uid` MEDIUMINT( 8 ) UNSIGNED NOT NULL DEFAULT '0',
`username` VARCHAR( 30 ) NOT NULL DEFAULT '',
`applyreason` VARCHAR( 255 ) NOT NULL DEFAULT '',
`applynum` SMALLINT( 5 ) UNSIGNED NOT NULL DEFAULT '0',
`applydate` INT( 10 ) UNSIGNED NOT NULL DEFAULT '0',
INDEX ( `uid` ) 
) ENGINE = MYISAM;
CREATE TABLE `pb_special` (
`sid` smallint(5) unsigned NOT NULL auto_increment,
`sname` varchar(30) NOT NULL default '',
`skeywords` varchar(255) NOT NULL default '',
`sdesc` text NOT NULL,
`slogo` varchar(255) NOT NULL default '',
`stpl` varchar(30) NOT NULL default '',
`createdate` int(10) unsigned NOT NULL default '0',
`ifopen` tinyint(1) unsigned NOT NULL default '1',
PRIMARY KEY  (`sid`)
) ENGINE=MyISAM;
CREATE TABLE `pb_splink` (
`spid` int(10) unsigned NOT NULL auto_increment,
`sid` smallint(5) unsigned NOT NULL default '0',
`tid` mediumint(8) unsigned NOT NULL default '0',
PRIMARY KEY  (`spid`),
KEY `sid` (`sid`),
KEY `tid` (`tid`)
) ENGINE=MyISAM;
CREATE TABLE `pb_fsession` (
`fsid` char(32) NOT NULL,
`attachment` text NOT NULL,
`cid` smallint(5) unsigned NOT NULL default '0',
`source` varchar(255) NOT NULL default '',
`uid` mediumint(8) unsigned NOT NULL default '0',
`ip` char(15) NOT NULL default '',
`exptime` int(10) unsigned NOT NULL default '0',
UNIQUE KEY `sid` (`fsid`,`uid`)
) ENGINE=MyISAM;
CREATE TABLE `pb_tinfo` (
`tid` mediumint(8) unsigned NOT NULL,
`skeywords` varchar(255) NOT NULL default '',
`sdesc` text NOT NULL,
`pbrank` tinyint(3) unsigned NOT NULL default '0',
`commend` tinyint(1) unsigned NOT NULL default '0',
`commendpic` varchar(255) NOT NULL default '',
`ishtml` tinyint(1) unsigned NOT NULL default '0',
`titlecolor` char(6) NOT NULL default '',
`titlestyle` tinyint(3) unsigned NOT NULL default '0',
`iffirst` tinyint(1) unsigned NOT NULL default '0',
`ainfo` text NOT NULL,
`iflock` tinyint(1) unsigned NOT NULL default '0',
`ifconvert` tinyint(1) unsigned NOT NULL default '1',
`anonsite` varchar(255) NOT NULL default '',
`anonymity` tinyint(1) unsigned NOT NULL default '0',
UNIQUE KEY `tid` (`tid`)
) ENGINE=MyISAM;
ALTER TABLE `pb_admingroups` ADD `allowcommend` TINYINT( 1 ) NOT NULL DEFAULT '0' AFTER `allowtopatc`;
ALTER TABLE `pb_admingroups` ADD `allowshield` TINYINT( 1 ) NOT NULL DEFAULT '0' AFTER `allowcommend`;
ALTER TABLE `pb_admingroups` ADD `setspecial` TINYINT( 1 ) NOT NULL DEFAULT '0';
ALTER TABLE `pb_categories` ADD `keywords` VARCHAR( 255 ) NOT NULL DEFAULT '' AFTER `name`;
ALTER TABLE `pb_comments` ADD INDEX `postdate` ( `postdate` , `digg` );
ALTER TABLE `pb_comments` DROP INDEX `tid` ,ADD INDEX `tid` ( `tid` , `postdate` );
ALTER TABLE `pb_configs` DROP `description`;
DELETE FROM `pb_configs` WHERE title = 'pb_topicimg';
DELETE FROM `pb_configs` WHERE title = 'pb_tubbsize';
DELETE FROM `pb_configs` WHERE title = 'pb_anonnick';
INSERT INTO `pb_configs` (`title`,`text`) VALUES ('pb_visitcache', '1');
INSERT INTO `pb_configs` (`title`,`text`) VALUES ('pb_ucenable', '0');
INSERT INTO `pb_configs` (`title`,`text`) VALUES ('pb_banlinks', '');
INSERT INTO `pb_configs` (`title`,`text`) VALUES ('pb_tagcolor', '1');
ALTER TABLE `pb_invitecode` DROP `ifused`;
ALTER TABLE `pb_invitecode` ADD INDEX ( `endtime` );
ALTER TABLE `pb_memberdata` ADD `realgroup` TINYINT( 3 ) UNSIGNED NOT NULL DEFAULT '7' AFTER `uid`;
ALTER TABLE `pb_memberdata` ADD `ucuid` MEDIUMINT( 8 ) UNSIGNED NOT NULL DEFAULT '0';
ALTER TABLE `pb_memberdata` ADD INDEX ( `ucuid` );
ALTER TABLE `pb_memberexp` ADD `ctsig` TINYINT( 1 ) UNSIGNED NOT NULL DEFAULT '1';
ALTER TABLE `pb_onlines` TYPE = HEAP;
ALTER TABLE `pb_scaches` DROP INDEX `keywords`;
ALTER TABLE `pb_scaches` ADD `khash` VARCHAR( 32 ) NOT NULL DEFAULT '' AFTER `keywords`;
ALTER TABLE `pb_scaches` ADD INDEX ( `exptime` );
ALTER TABLE `pb_scaches` ADD INDEX ( `khash` );
ALTER TABLE `pb_tags` ADD `ifsys` TINYINT( 1 ) UNSIGNED NOT NULL DEFAULT '0';
ALTER TABLE `pb_tags` ADD INDEX ( `tagname` );
ALTER TABLE `pb_templates` ADD `ifcommend` TINYINT( 1 ) UNSIGNED NOT NULL DEFAULT '0' AFTER `iftopicimg` , ADD `ifcommendpic` TINYINT( 1 ) UNSIGNED NOT NULL DEFAULT '0' AFTER `ifcommend` ;
ALTER TABLE `pb_threads` DROP INDEX `diggdate` , ADD INDEX `diggdate` ( `diggdate` , `ifcheck`, `postdate` );
ALTER TABLE `pb_threads` DROP INDEX `commentdate`;
ALTER TABLE `pb_threads` DROP INDEX `postdate`;
ALTER TABLE `pb_threads` DROP INDEX `cid` , ADD INDEX `cid` ( `cid` , `diggdate` , `ifcheck` );
INSERT INTO `pb_tplvar` ( `tplid` , `tplmark` , `tplname` , `tplcontent` ) VALUES (NULL , 'first', '头条新闻', '<li><span>{!--postdate--}</span>[{!--topped--}]<a href="{!--turl--}" title="{!--subject--}">{!--subject--}</a></li>');
INSERT INTO `pb_templates` (`tplname`, `tplmark`, `trancid`, `trannum`, `tranattribute`, `cotentlimit`, `titlelimit`, `iftopicimg`, `ifcommend`, `ifcommendpic`, `timelimit`, `timeformat`, `trantype`, `displayorder`, `ifself`, `tplcontent`) VALUES ('首页_活跃会员', 'tpl_680b7a23', '', 12, 'contribute', 0, 0, 0, 0, 0, 0, 'Y-m-d H:i:s', 'm', 1, 0, '<li><a href="{!--uurl--} " target="_blank"><img alt="{!--username--}" src="{!--avatar--}" /><br />{!--username--}</a></li>'),
('全局_最新文章', 'tpl_f63d001d', '', 10, 'postdate', 0, 0, 0, 0, 0, 0, 'Y-m-d H:i:s', 't', 1, 0, '<li><a href="{!--turl--}" target="_blank" title="{!--subject--}">{!--subject--}</a></li>'),
('全局_最新评论', 'tpl_6708bb12', '', 10, 'postdate', 100, 50, 0, 0, 0, 0, 'Y-m-d H:i:s', 'c', 1, 0, '<div class="com_box"><div class="com_box_z"><a href="{!--uurl--}" title="{!--author--}" target="_blank"><img src="{!--avatar--}" class="middle_user_avatar" /></a></div><div class="com_box_y"><h3><a href="{!--uurl--}" title="{!--author--}" target="_blank" class="b">{!--author--}</a> 评论 <a href="{!--turl--}">{!--subject--}</a></h3><span>{!--summary--}</span><em><a href="{!--turl--}">全文...</a></em></div></div>'),
('全局_1周点击排行', 'tpl_80cc8536', '', 10, 'views', 0, 0, 0, 0, 0, 604800, 'Y-m-d H:i:s', 't', 1, 0, '<li><a href="{!--turl--}" target="_blank" title="{!--subject--}">{!--subject--}</a>({!--views--})</li>'),
('首页图文', 'tpl_fe8f01a6', '', 8, 'digg', 0, 100, 1, 0, 0, 0, 'Y-m-d H:i:s', 't', 1, 0, '<li><div class="pink_img"><a href="{!--turl--}" title="{!--altsubject--}"><img src="{!--topicimg--}" alt="{!--altsubject--}"  border="0"/></a></div><div class="pink_img_title"><a href="{!--turl--}" title="{!--altsubject--}">{!--subject--}</a></div></li>'),
('首页推荐', 'tpl_daf657bf', '', 5, 'digg', 0, 50, 0, 1, 0, 0, 'Y-m-d H:i:s', 't', 1, 0, '<li>[推荐]<a href="{!--turl--}" target="_blank">{!--subject--}</a></li>');
EOT;


if(!$action)
{
	echo '本程序用于升级 PBDigg 2.0 RC2 到 PBDigg 2.0 正式版。<br /><br />';
	echo '<strong><font color="red">强烈建议您升级之前备份数据库资料!</font></strong><br /><br /><br />';
	echo '<a href="'.$PB_URL.'update2.php?action=upgrade&step=1">点这里开始完整升级（包括附件升级）</a><br /><br />';
	echo '<a href="'.$PB_URL.'update2.php?action=upgrade&step=3">点这里开始附件升级</a>';
}
else
{
	require_once(PBDIGG_ROOT.'data/sql.inc.php');
	require_once(PBDIGG_ROOT.'update/MySQL.class.php');
	$DB = new MySQL($db_host, $db_username, $db_password, $db_name, $db_pconnect);
	if ($step == '1')
	{
		echo '数据库表结构转换，请稍候...';
		$tablenum = 0;
		runquery($upgrade);
		echo '数据库表结构转换完成，进入主题数据转换...';
		echo '<script>location.href="'.$PB_URL.'update2.php?action=update&step=2";</script>';exit;
	}
	elseif ($step == '2')
	{
		$start = (int)$_GET['start'];
		$next = $start + 500;
		$query = $DB->db_query("SELECT tid FROM {$db_prefix}threads ORDER BY tid LIMIT $start, 500");
		if ($DB->db_num($query))
		{
			$tid = '';
			while ($r = $DB->db_fetch_array($query))
			{
				$tid .= "(".$r['tid']."),";
			}
			$tid && $DB->db_query("INSERT INTO {$db_prefix}tinfo (tid) VALUES ".substr($tid, 0, -1),0);
			echo $start.' - '.$next.'主题表记录转换完成，请耐心等待...';
			echo '<script>location.href="'.$PB_URL.'update2.php?action=update&step=2&start='.$next.'";</script>';exit;
		}
		else
		{
			echo '<script>location.href="'.$PB_URL.'update2.php?action=update&step=3";</script>';exit;
		}
	}
	elseif ($step == '3')
	{
		$start = (int)$_GET['start'];
		$next = $start + 500;
		$query = $DB->db_query("SELECT aid,cid,tid,uid,filename,filetype,filesize,description,filepath,downloads,isimg,uploaddate FROM {$db_prefix}attachments LIMIT $start, 500");
		if ($DB->db_num($query))
		{
			while ($r = $DB->db_fetch_array($query))
			{
				$ainfo = array();
				$att = $DB->db_fetch_one_array("SELECT ainfo FROM {$db_prefix}tinfo WHERE tid = ".$r['tid']);
				if ($att)
				{
					$ainfo[$r['aid']] = array('aid'=>$r['aid'],'filename'=>addslashes($r['filename']),'filesize'=>$r['filesize'],'filepath'=>$r['filepath'],'filetype'=>$r['filetype'],'isimg'=>$r['isimg']);
					$newa = $att['ainfo'] ? serialize($ainfo+unserialize($att['ainfo'])) : serialize($ainfo);
					$DB->db_query("UPDATE {$db_prefix}tinfo SET ainfo = '".addslashes($newa)."' WHERE tid = ".$r['tid'],0);
				}
			}
			echo $start.' - '.$next.'附件表记录转换完成，请耐心等待...';
			echo '<script>location.href="'.$PB_URL.'update2.php?action=update&step=3&start='.$next.'";</script>';exit;
		}
		else
		{
			echo '<script>location.href="'.$PB_URL.'update2.php?action=update&step=4";</script>';exit;
		}
	}
	elseif ($step == '4')
	{
		@fopen('update.lock', 'w');
		@fclose($fp);
		echo "恭喜您，升级成功！<br />请删除/data/cache目录下所有文件。登录后台，更新缓存。";
	}
}
function PWriteFile($filename, $content, $mode = 'ab')
{
	if (strpos($filename, '..') !== FALSE)
	{
		return FALSE;
	}
	$path = dirname($filename);
	if (!is_dir($path))
	{
		if (!mkdir($path, 0777))
		{
			return FALSE;
		}
	}
	$fp = @ fopen($filename, $mode);
	if ($fp)
	{
		flock($fp, LOCK_EX);
		fwrite($fp, $content);
		fclose($fp);
		@ chmod($filename, 0777);
		return TRUE;
	}
	return FALSE;
}
function runquery($sql) {
	global $db_charset, $db_prefix, $tablenum, $i_message;
	$sql = str_replace("\r", "\n", str_replace("`pb_", "`".$db_prefix, $sql));
	$ret = array();
	$num = 0;
	foreach(explode(";\n", trim($sql)) as $query) {
		$queries = explode("\n", trim($query));
		$sq = "";
		foreach($queries as $query) {
			$sq .= $query;
		}
		$ret[$num] = $sq;
		$num ++;
	}
	unset($sql);
	foreach($ret as $query) {
		$query = trim($query);
		if($query) {
			if(substr($query, 0, 12) == "CREATE TABLE") {
				$name = preg_replace("/CREATE TABLE `([a-z0-9_]+)` .*/is", "\\1", $query);
				@mysql_query(createtable($query, $db_charset));
				$tablenum ++;
			} else {
				@mysql_query($query);
			}
		}
	}
}
function createtable($sql, $db_charset) {
	$type = strtoupper(preg_replace("/^\s*CREATE TABLE\s+.+\s+\(.+?\).*(ENGINE|TYPE)\s*=\s*([a-z]+?).*$/isU", "\\2", $sql));
	$type = in_array($type, array("MYISAM", "HEAP")) ? $type : "MYISAM";
	return preg_replace("/^\s*(CREATE TABLE\s+.+\s+\(.+?\)).*$/isU", "\\1", $sql).
		(mysql_get_server_info() > "4.1" ? " ENGINE=$type DEFAULT CHARSET=$db_charset" : " TYPE=$type");
}
?>
</body>
</html>