<?php
/**
 *      [Dzz!] (C)2010-2011 dzz.cc
 *      This is NOT a freeware, use is subject to license terms
 *
 *      $Id: admincp_index.php 1000 2011-6-31 15:41:43 by angelrain $
 */
 /**
 * ============================================================================
 * 版权所有 2010-2011 Dzz!Desktop，并保留所有权利。
 * 网站地址: http://dzz.cc；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式、任何目的的再发布。
 * ============================================================================
*/
if(!defined('IN_DISCUZ') || !defined('IN_ADMINCP')) {
	exit('Access Denied');
}
@include_once DISCUZ_ROOT.'./dzz/dzz_version.php';
$isfounder = isfounder();
if(!$isfounder) cpmsg($lang['not_founder'],'','error');
if($operation=='license'){
	include dzztemplate('admin/dzz_install');
}elseif($operation=='install'){
	include DISCUZ_ROOT.'./config/config_global.php';
	include dzztemplate('admin/dzz_install');
		$output_buffering=intval(ini_get('output_buffering'));
		ob_end_flush();//关闭缓存
		echo str_repeat(" ",256); //ie下 需要先发送256个字节
		echo str_repeat(" ",$output_buffering); 
		flush();
		ob_flush();
	showjsmessage($lang['install_create_table']);
	$tablepre = $_config['db'][1]['tablepre'];
	$sql_create = file_get_contents(DISCUZ_ROOT.'./dzz/admin/admincp/install.sql');
	$sql_create = str_replace("\r\n", "\n", $sql_create);
	runquery($sql_create);
	showjsmessage($lang['install_import_data']);
	$sql = file_get_contents(DISCUZ_ROOT.'./dzz/admin/admincp/install_data.sql');
	$sql = str_replace("\r\n", "\n", $sql);
	runquery($sql);
	showjsmessage($lang['install_import_data'].$lang['succeed']);
	touch($lock_install);
	//更新站点id
	if($_G['setting']['dsiteuniqueid']){
		DB::update('dzz_config',array('siteuniqueid'=>$_G['setting']['dsiteuniqueid']),"id='1'");
	}
	//写入系统缓存；
	if($config=DB::fetch_first("select * from ".DB::table('dzz_config')." where id='1'")){
			DB::insert('common_setting', array(
				'skey' => 'dzz_sysconfig',
				'svalue' => addslashes(serialize(dstripslashes($config))),
			), false, true);
			updatecache(array('setting', 'dzz_sysconfig'));
	}
	//添加计划任务;
	$cron=array(
				'available'=>0,
				'type'=>'user',
				'name'=>$lang['cron_title'],
				'filename'=>'cron_dzz_spacecount_daily.php',
				'weekday'=>-1,
				'day'=>-1,
				'hour'=>0,
				'minute'=>0
				);
	if($cronid=DB::result_first("select cronid from ".DB::table('common_cron')." where filename='cron_dzz_spacecount_daily.php'")){
		DB::update('common_cron',daddslashes($cron),"cronid='{$cronid}'");
	}else{
		DB::insert('common_cron',daddslashes($cron),1);
	}
	
	//写入iconview缓存;
	$query=DB::query("select * from ".DB::table('dzz_iconview')." where `avaliable`>0 ORDER BY disp");
	$iconview=array();
	while($value=DB::fetch($query)){
		$iconview[$value['id']]=$value;
	}
	DB::insert('common_setting', array(
			'skey' => 'dzz_iconview',
			'svalue' => addslashes(serialize(dstripslashes($iconview))),
		), false, true);
	updatecache(array('setting', 'dzz_iconview'));
	DB::insert('common_setting', array(
				'skey' => 'dzz_nav',
				'svalue' => addslashes(serialize(array())),
			), false, true);
	updatecache(array('setting', 'dzz_nav'));
	echo '<script type="text/javascript">document.getElementById("laststep").disabled=false;document.getElementById("laststep").value=\''.$lang['install_finish'].'\';setTimeout(function(){setlaststep();},10000);</script>';
}elseif($operation=='finish'){
	include dzztemplate('admin/dzz_install');
	echo "<script type=\"text/javascript\">top.location='".ADMINSCRIPT."';</script>";
}
function showjsmessage($message) {
	
	echo '<script type="text/javascript">showmessage(\''.addslashes($message).' \');</script>'."\r\n";
	flush();
	ob_flush();
}
function createtable($sql) {
	
	$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', 'MEMORY')) ? $type : 'MYISAM';
	return preg_replace("/^\s*(CREATE TABLE\s+.+\s+\(.+?\)).*$/isU", "\\1", $sql).
	(mysql_get_server_info() > '4.1' ? " ENGINE=$type DEFAULT CHARSET=utf8" :  "TYPE=$type");
}
function runquery($sql) {
	global $_G, $tablepre;
	if(!isset($sql) || empty($sql)) return;
	$sql = str_replace("\r", "\n", str_replace(' pre_',' '.$tablepre, $sql));
	$sql = str_replace("\r", "\n", str_replace(' `pre_',' `'.$tablepre, $sql));
	$ret = array();
	$num = 0;
	foreach(explode(";\n", trim($sql)) as $query) {
		$ret[$num] = '';
		$queries = explode("\n", trim($query));
		foreach($queries as $query) {
			$ret[$num] .= (isset($query[0]) && $query[0] == '#') || (isset($query[1]) && isset($query[1]) && $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);
				showjsmessage('CREATE TABLE '.$name.' ... '.$lang['succeed']);
				DB::query(createtable($query));
				
			} else {
				DB::query($query);
			}
		}
	}
	
}
?>