<?php

/**
 *      [Dzz!] (C)2001-2099 dzz.cc
 *      This is NOT a freeware, use is subject to license terms
 *
 *      $Id: update.php 20110821 20:32:12Z angelrain $
 */

define('APPTYPEID', 999);
define('CURSCRIPT', 'dzz');
require '../source/class/class_core.php';
require '../source/function/function_cache.php';
$discuz = & discuz_core::instance();
$discuz->init();
set_time_limit(0);

require DISCUZ_ROOT.'./dzzupdate/update_fun.php';
require DISCUZ_ROOT.'./dzz/dzz_version.php';
$lock_update = DISCUZ_ROOT.'./data/dzzupdate.lock';
if(file_exists($lock_update)){
	 showjsmessage('你的程序已经完成升级！');
	 exit();
}
$output_buffering=intval(ini_get('output_buffering'));
ob_end_flush();//关闭缓存
echo str_repeat(" ",256); //ie下 需要先发送256个字节
echo str_repeat(" ",$output_buffering); 
flush();
ob_flush();
$appid=intval($_GET['appid']);
showjsmessage('正在转换应用图标...,页面将会自动刷新，耐心等待！');
if(!$appid) sleep(1);
$i=0;
$query=DB::query("select appid,appurl,appico from ".DB::table('dzz_apps')." where appid>'{$appid}'  limit 10");
while($value=DB::fetch($query)){
	if($value['appid']>$appid) $appid=$value['appid'];
	$i++;
	if(strpos($value['appico'],'appico')===0) continue;
	if($appico=getappico($value['appurl'])){
		$value['appico']=$appico;
	}else{
		$appico='dzz/images/default/icodefault.png';
		if($appico=imagetolocal($appico,'appico')){
			$value['appico']=$appico;
		}else{
			$value['appico']='dzz/images/default/icodefault.png';
		}
	}
	DB::update('dzz_apps',array('appico'=>$value['appico']),"appid='{$value[appid]}'");
}
if($i){
	echo "<script type=\"text/javascript\">";
	echo "location.href='".$_G['siteurl']."./update.php?appid=".$appid."'";
	echo "</script>";
	exit();
}else{
	showjsmessage('应用图标转换完成...');

	include DISCUZ_ROOT.'./config/config_global.php';
	
	
	showjsmessage('创建新数据表');
	$tablepre = $_config['db'][1]['tablepre'];
	$sql_create = file_get_contents(DISCUZ_ROOT.'./dzzupdate/install.sql');
	$sql_create = str_replace("\r\n", "\n", $sql_create);
	runquery($sql_create);
	showjsmessage('导入默认数据');
	$sql = file_get_contents(DISCUZ_ROOT.'./dzzupdate/install_data.sql');
	$sql = str_replace("\r\n", "\n", $sql);
	runquery($sql);
	showjsmessage('默认数据导入成功！，正在更新系统设置表...');
	
	
	//处理config表数据
	if($_G['setting']['dzz_sysconfig']){
		$config=dstripslashes(unserialize(dstripslashes($_G['setting']['dzz_sysconfig'])));
		$setarr=array(
						'userscreennum'=>$config['screennum']?$config['screennum']:5,
						'loginurl'=>$config['loginurl']?$config['loginurl']:'member.php?mod=logging&action=login',
						'logouturl'=>'member.php?mod=logging&action=logout',
						'logouturl'=>'member.php?mod=logging&action=logout',
						'marketurl' =>$config['marketurl']?$config['marketurl']:'dzz.php?mod=market',
						'systhameurl' =>$config['systhameurl']?str_replace('&op=thame','',$config['systhameurl']):'dzz.php?mod=thame',
						'sysbrowserurl' =>$config['sysbrowserurl']?$config['sysbrowserurl']:'about:blank',
						'defaultdesktop' =>$config['defaultdesktop']?$config['defaultdesktop']:1,
						'sitename' =>$config['sitename']?$config['sitename']:'Dzz Desktop 1.2',
						'keywords' =>$config['keywords']?$config['keywords']:'',
						'tongji' =>$config['tongji']?$config['tongji']:'',
						'copyright' =>$config['copyright']?$config['copyright']:'',
						'dataurl' =>$config['dataurl']?str_replace('market','system',$config['dataurl']):'dzz.php?mod=system&op=json',
						
						'siteuniqueid' =>$_G['setting']['dsiteuniqueid']?$_G['setting']['dsiteuniqueid']:'',
						);	
			DB::update('dzz_config',daddslashes($setarr),"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'));
	}
	showjsmessage('系统设置表更新完成！');
	
	showjsmessage('正在更新应用表结构...！');
	//dzz_apps表
	DB::query("ALTER TABLE ".DB::table('dzz_apps')." ADD `ischeck` tinyint(1) unsigned NOT NULL default '3'",'SILENT');
	DB::query("ALTER TABLE ".DB::table('dzz_apps')." ADD `type` tinyint(1) unsigned NOT NULL default '0'",'SILENT');
	DB::query("ALTER TABLE ".DB::table('dzz_apps')." ADD `lang` tinyint(1) unsigned NOT NULL default '0'",'SILENT');
	DB::query("ALTER TABLE ".DB::table('dzz_apps')." ADD `idtype` varchar(255) NOT NULL",'SILENT');
	DB::query("ALTER TABLE ".DB::table('dzz_apps')." ADD `typeid` int(10) unsigned NOT NULL default '0'",'SILENT');
	DB::query("ALTER TABLE ".DB::table('dzz_apps')." ADD `titlebuttons` varchar(255) NOT NULL default 'home,refresh,detail,min,max,close'",'SILENT');
	DB::query("ALTER TABLE ".DB::table('dzz_apps')." ADD `isshow` tinyint(1) unsigned NOT NULL default '1'",'SILENT');
	DB::query("ALTER TABLE ".DB::table('dzz_apps')." ADD `havetask` tinyint(1) unsigned NOT NULL default '1'",'SILENT');
	
	showjsmessage('应用表结构更新完成');

	showjsmessage('正在更新应用评分数据...');
	DB::query("ALTER TABLE ".DB::table('dzz_score')." ADD `idtype` varchar(255) NOT NULL default 'appid'",'SILENT');
	showjsmessage('更新应用评分数据完成！');
	showjsmessage('正在更新用户桌面数据表结构...');
	//userconfig表
	DB::query("ALTER TABLE ".DB::table('dzz_userconfig')." ADD `iconpositions` text NOT NULL",'SILENT');
	DB::query("ALTER TABLE ".DB::table('dzz_userconfig')." ADD `custom_filemanage` varchar(255) NOT NULL default ''",'SILENT');
	DB::query("ALTER TABLE ".DB::table('dzz_userconfig')." ADD `custom_topbar` varchar(255) NOT NULL default ''",'SILENT');
	DB::query("ALTER TABLE ".DB::table('dzz_userconfig')." CHANGE `custom_bid` `custom_backimg` varchar(255) NOT NULL default ''",'SILENT');
	DB::query("ALTER TABLE ".DB::table('dzz_userconfig')." ADD `spacename` varchar(255) NOT NULL default ''",'SILENT');
	DB::query("ALTER TABLE ".DB::table('dzz_userconfig')." ADD `metakeyword` varchar(255) NOT NULL default ''",'SILENT');
	DB::query("ALTER TABLE ".DB::table('dzz_userconfig')." ADD `metadescription` varchar(255) NOT NULL default ''",'SILENT');
	DB::query("ALTER TABLE ".DB::table('dzz_userconfig')." ADD `friend` tinyint(1) unsigned NOT NULL default '0'",'SILENT');
	DB::query("ALTER TABLE ".DB::table('dzz_userconfig')." ADD `ukey` varchar(16) NOT NULL",'SILENT');
	DB::query("ALTER TABLE ".DB::table('dzz_userconfig')." ADD `viewnum` int(10) unsigned NOT NULL default '0'",'SILENT');
	DB::query("ALTER TABLE ".DB::table('dzz_userconfig')." ADD `usesize` int(10) unsigned NOT NULL default '0'",'SILENT');
	DB::query("ALTER TABLE ".DB::table('dzz_userconfig')." ADD  INDEX (`viewnum`)",'SILENT');
	DB::query("ALTER TABLE ".DB::table('dzz_userconfig')." DROP `navbartop`",'SILENT');
	
	
	showjsmessage('用户桌面数据表结构更新完成！，正在转换用户数据...');
	//处理ueserconfig表数据
	$sysconfig=dstripslashes(unserialize(stripslashes($_G['setting']['dzz_sysconfig'])));
	$query=DB::query("select * from ".DB::table('dzz_userconfig')." where uid>0");
	while($value=DB::fetch($query)){
		if($value['ukey']){
			 $value['screenlist']=$value['setuplist'];
			 $newdocklist=$value['docklist']?explode(',',$value['docklist']):array();
		}else{
			//处理dock条数据；
			$newdocklist=array();
			$docklist=$value['docklist']?explode(',',$value['docklist']):array();
			foreach($docklist as $appid){
				if($icoid=addicofromappid($appid,$value['uid'],$value['username'])){
					$newdocklist[]=$icoid;
				}
			}
		}
		
	    $screenlist_u=array();
		$screenlist=dstripslashes(unserialize(stripslashes($value['screenlist'])));
		foreach($screenlist as $key =>$appids){
				$i=$key+1;
				$screenlist_u[$i]['config']=array(
															'navid'=>$i,
															'navname'=>'桌面'.$i,
															'type'=>'desktop',
															'autolist'=>$sysconfig['autolist'],
															'marginleft'=>$sysconfig['marginleft'],
															'margintop'=>$sysconfig['margintop'],
															'marginright'=>$sysconfig['marginright'],
															'marginbottom'=>$sysconfig['marginbottom'],
															'iconview'=>$sysconfig['iconview'],
															'iconposition'=>$sysconfig['iconposition'],
															'dockshow'=>$sysconfig['dockshow'],
															'topbarshow'=>$sysconfig['topbarshow']
														);
				$screenlist_u[$i]['icos']=array();
				$screenlist_u[$i]['wins']=array();
				$screenlist_u[$i]['widgets']=array();
			if($appids){
				 $appids=explode(',',$appids);
				foreach($appids as $appid){
					if($icoid=addicofromappid($appid,$value['uid'],$value['username'])){
						$screenlist_u[$i]['icos'][]=$icoid;
					}
				}
			}
		}
		$ukey=random(16);
		
		DB::update('dzz_userconfig',daddslashes(array('screenlist'=>serialize(dstripslashes($screenlist_u)),'docklist'=>implode(',',$newdocklist),'setuplist'=>$value['screenlist'],'custom_backimg'=>'','thame'=>2,'ukey'=>$ukey))," uid='{$value[uid]}'");
	}
	showjsmessage('转换用户数据完成，正在更新系统缓存...');
	//添加计划任务;
	$cron=array(
				'available'=>0,
				'type'=>'user',
				'name'=>'每日计算用户空间并将到期的推送到日志库',
				'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'));
	touch($lock_update);
	showjsmessage('恭喜！升级完成！，请手工删除dzzupdate目录，避免安全问题！');
}
?>