<?php
require("session_check.php");
require("proxy/proxy.php");
//语言包引入
$so_softwarelp=new softwarelp;
$er_langpackage=new errorlp;
$version_url="../doc/version.txt";
$whole_version=file_get_contents($version_url);
$version_num=short_check(get_argg('version'));
$serv_url=act_substitue("software","&update_version=".$version_num."&version=".$whole_version);
$update_data=file_get_contents($serv_url);

preg_match_all("/<dir>[\w\/]+<\/dir>/",$update_data,$dir_array);//取得目录列表
preg_match_all("/<file>[\w\/\.]+<\/file>/",$update_data,$file_array);//取得文件列表
preg_match_all("/<del>[\w\/\.]+<\/del>/",$update_data,$del_array);//取得删除列表
preg_match_all("/<update_sql>[\s\S][^<]*<\/update\_sql>/",$update_data,$sql_array);//取得sql列表
$is_success=1;//状态

//升级sql
if(!empty($sql_array[0])){
	$dbo = new dbex;
	dbtarget('w',$dbServs);	
	foreach($sql_array[0] as $sql){
		$queries = explode(";\n", trim($sql));
		foreach($queries as $query){
			$query=str_replace(array("<update_sql>","</update_sql>","isns_"),array("","",$tablePreStr),$query);
			$result=$so_softwarelp->so_success;
			if(!$dbo->exeUpdate($query)){
				$result=$so_softwarelp->so_false;
				$is_success=0;
			}
			echo str_replace("{result}",$result,$so_softwarelp->so_sql_result);
		}
	}
}

//升级目录
foreach($dir_array[0] as $dir){
	$dir=str_replace(array("<dir>","</dir>"),"",$dir);
	if(!file_exists("../".$dir)){
		$result=$so_softwarelp->so_success;
		if(!mkdir("../".$dir)){
			$result=$so_softwarelp->so_false;
			$is_success=0;
		}
		echo str_replace(array("{result}","{dir}"),array($result,$dir),$so_softwarelp->so_dir_result);
	}
}

//升级程序
foreach($file_array[0] as $file){
	$file=str_replace(array("<file>","</file>"),"",$file);
	$download_file=file_get_contents($serv_url."&fileName=".$file);
	$f_ref=fopen("../".$file,"w+");
	$result=$so_softwarelp->so_success;
	if(!fwrite($f_ref,$download_file)){
		$result=$so_softwarelp->so_false;
		$is_success=0;
	}
	echo str_replace(array("{result}","{file}"),array($result,$file),$so_softwarelp->so_download_result);
}

//删除废旧文件
foreach($del_array[0] as $del){
	$del=str_replace(array("<del>","</del>"),"",$del);
	if(file_exists("../".$del)){
		if(is_dir("../".$del)){
			$result=$so_softwarelp->so_false;
			if(@rmdir("../".$del)){
				$result=$so_softwarelp->so_success;
			}
			echo str_replace(array("{result}","{dir}"),array($result,$del),$so_softwarelp->so_del_dir_result);
		}else{
			$result=$so_softwarelp->so_false;
			if(@unlink("../".$del)){
				$result=$so_softwarelp->so_success;
			}
			echo str_replace(array("{result}","{file}"),array($result,$del),$so_softwarelp->so_del_file_result);
		}
	}
}

//更新本地版本号
if($is_success==1){
	$f_ref=fopen($version_url,"w+");
	$num=fwrite($f_ref,$version_num);
	if($num>0){
		echo $so_softwarelp->so_update_success;
	}
}else{
	echo $so_softwarelp->so_update_false;
}
?>