<?php
/**
 *	[超级活动(xj_event.upgrade)] (C)2012-2099 Powered by 逍遥设计.
 *	Version: 1.1
 *	Date: 2012-11-5 08:25
 */

if(!defined('IN_DISCUZ')) {
	exit('Access Denied');
}

global $_G;
$plugin_xj_wxopen_login = DB::table('xj_wxopen_login');
$plugin_xj_wxopen_session = DB::table('xj_wxopen_session');



$sql = <<<EOF
CREATE TABLE IF NOT EXISTS `$plugin_xj_wxopen_login` (
  `id` int(10) NOT NULL,
  `sessionkey` varchar(32) NOT NULL,
  `openid` varchar(32) NOT NULL,
  `dateline` int(10) NOT NULL,
  `unionid` varchar(32) NOT NULL,
  `uid` int(10) NOT NULL DEFAULT '0'
) ENGINE=MyISAM;

CREATE TABLE `$plugin_xj_wxopen_session` (
  `threekey` varchar(32) NOT NULL,
  `sessionkey` varchar(32) NOT NULL,
  `openid` varchar(32) NOT NULL,
  `uid` int(10) NOT NULL DEFAULT '0',
  `unionid` varchar(32) NOT NULL,
  `dateline` int(10) NOT NULL DEFAULT '0'
) ENGINE=MEMORY;

ALTER TABLE `$plugin_xj_wxopen_login` ADD PRIMARY KEY (`id`);
ALTER TABLE `$plugin_xj_wxopen_session`  ADD KEY `threekey` (`threekey`);
ALTER TABLE `$plugin_xj_wxopen_login`  MODIFY `id` int(10) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;
EOF;

myrunquery($sql);
showmessage('Upgrade is complete');


function createtable($sql, $dbcharset) {
	$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=$dbcharset" : " TYPE=$type");
}

function myrunquery($sql) {
	global $_G;
	$tablepre = $_G['config']['db'][1]['tablepre'];
	$dbcharset = $_G['config']['db'][1]['dbcharset'];




	$sql = str_replace(array(' cdb_', ' `cdb_', ' pre_', ' `pre_'), array(' {tablepre}', ' `{tablepre}', ' {tablepre}', ' `{tablepre}'), $sql);
	$sql = str_replace("\r", "\n", str_replace(array(' {tablepre}', ' `{tablepre}'), array(' '.$tablepre, ' `'.$tablepre), $sql));

	$ret = array();
	$num = 0;
	foreach(explode(";\n", trim($sql)) as $query) {
		$queries = explode("\n", trim($query));
		foreach($queries as $query) {
			$ret[$num] .= $query[0] == '#' || $query[0].$query[1] == '--' ? '' : $query;
		}
		$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);
				DB::query(createtable($query, $dbcharset));

			} else {
				DB::query($query);
			}

		}
	}
}
?>