<?
require("../../inc/header.inc");
?>
<STYLE TYPE="text/css" MEDIA="screen, print, projection">
<!--
  .inner   {align: right;
  			width: 40px }
-->
</STYLE>
<?
$helpId = isset($helpId)?$helpId:'5.1.6';
$ThisPage="$strMaintenance&nbsp;>&nbsp;$strBackupRestore&nbsp;>&nbsp;"."Download&Upload";
$DEBUG = 0;
$db=$omc_db;
set_time_limit(3600);
$strNoInput = "No file input!";
$needReboot = 0;
function MsgBox($str)
{
	echo "<script language=\"javascript\">";
	echo "alert(\"$str\");";
	echo "history.go(-1)";
	echo "</script>";
}
function getNameByTypeNo($sysTypeNo)
{
	$pubDb = "OMC_PUB";
	$selSql = "select sysTypeName from OMC_PUB.sysConf where sysTypeNo=$sysTypeNo";
	$result = mysqli_query($pubConn,$selSql);
	$row = mysqli_fetch_array($result);
	$name = $row[sysTypeName];
	return $name;
}
function getFileList($dir,&$fileListArr)
{
	if ($handle = opendir($dir)) {
	    while (false !== ($file = readdir($handle))) {
	        if ($file != "." && $file != "..") {
	            $fileListArr[] = $file;
	        }
	    }
	    closedir($handle);
	}
}
function updateParamer($db_name,$table_name,$csvFileName)
{
	$del_sql = "DELETE FROM $table_name";
	if($DEBUG) echo "<br>del_sql = $del_sql";
	$del_result = mysqli_query($pubConn,$del_sql);
	if($DEBUG) echo "<br>del_result=$del_result";
	
	$insert_sql = "LOAD DATA LOCAL INFILE '$csvFileName' 
				INTO TABLE $table_name
				FIELDS TERMINATED BY ',' 
				LINES TERMINATED BY '\n' 
			";
	if(0) echo "<br>insert_sql=$insert_sql";
	$insert_result=mysqli_query($pubConn,$insert_sql);
	if($DEBUG) echo "<br>insert_result=$insert_result";
	if ($insert_result)
		return 1;
	else
		return 0;
}//end updateParamer

function updateSubs($sysId,$dataTypeNo,$impFile)
{
	$nSetComm	= 3;
	$pubDb				= 'OMC_PUB';
	$sysSubsConfTable	= 'OMC_PUB.sysSubsConf';
	$sysInfoTable		= 'OMC_PUB.sysInfo';

	$sysIdArr=explode('_',$sysId);
	$sysTypeNo	=$sysIdArr[0];
	$sysNo		=$sysIdArr[1];
	$subSysNo	=$sysIdArr[2];
	
	if($sysTypeNo==390)
		$getConfSql="SELECT subsDataTable,impObjId,impFileName,ftpDir,ftpLoginName,ftpLoginPwd,
					logFileName,maxSegmentNum,maxIndexNumPerSeg
					FROM $sysSubsConfTable 
					WHERE sysTypeNo='$sysTypeNo' AND dataTypeNo='$dataTypeNo' AND sysNo='$sysNo'
					";
	else
		$getConfSql="SELECT subsDataTable,impObjId,impFileName,ftpDir,ftpLoginName,ftpLoginPwd,
					logFileName,maxSegmentNum,maxIndexNumPerSeg
					FROM $sysSubsConfTable 
					WHERE sysTypeNo='$sysTypeNo' AND dataTypeNo='$dataTypeNo'
					";
	if($DEBUG) echo "<br>getConfSql=$getConfSql";
	$getConfResult=mysqli_query($pubConn,$getConfSql);
	echo mysqli_error($pubConn);
	$getConfRows=mysqli_fetch_array($getConfResult);
	
	$subsDataTable		= $getConfRows[subsDataTable];
	$impObjId			= $getConfRows[impObjId];
	$impFileName		= $getConfRows[impFileName];
	$logFileName		= $getConfRows[logFileName];
	$ftpDir				= $getConfRows[ftpDir];
	$ftpLoginName		= $getConfRows[ftpLoginName];
	$ftpLoginPwd		= $getConfRows[ftpLoginPwd];
	$maxSegmentNum		= $getConfRows[maxSegmentNum];
	$maxIndexNumPerSeg	= $getConfRows[maxIndexNumPerSeg];
	$maxTotalNum		= $maxSegmentNum * $maxIndexNumPerSeg;
	$maxImpFileSize		= 5*1024*1024;
	$maxImpRecordNum	= 5000;
	
	//Get the system name;
	$selSql = "SELECT sysTypeName FROM sysConf WHERE sysTypeNo='$sysTypeNo'";
	if ($DEBUG)	echo "selSql = $selSql<br>";
	$selRes	= @mysqli_query($pubConn, $selSql);
	echo mysqli_error($pubConn);
	$selRow	= @mysqli_fetch_array($selRes);
	$sysName	= $selRow[sysTypeName];

	if($sysTypeNo==390)
		$getSysIdSql = "SELECT sysNo,subSysNo,ip 
				FROM $sysInfoTable
				WHERE sysTypeNo='$sysTypeNo' AND sysNo='$sysNo' AND baseStat > '0'
				ORDER BY sysNo,subSysNo
			";
	else
		$getSysIdSql = "SELECT sysNo,subSysNo,ip 
				FROM $sysInfoTable
				WHERE sysTypeNo='$sysTypeNo' AND baseStat > '0'
				ORDER BY sysNo,subSysNo
			";
	if($DEBUG) echo "<br>getSysIdSql=$getSysIdSql";
	$getSysIdResult= mysqli_query($pubConn,$getSysIdSql);
	echo mysqli_error($pubConn);
	$runningServerNum	= mysqli_num_rows($getSysIdResult);
	if($runningServerNum <= 0){
		echo "<font color=\"#FF0000\" size=\"3\">No system running normally</font>";
		return 0;
	}
	if($DEBUG)	echo "running server number = $runningServerNum<br>";
	//找出已有的记录个数
	$getTotalSql	= "SELECT count(*) FROM $subsDataTable";
	if($DEBUG) echo "<br>getTotalSql=$getTotalSql";	
	$getTotalRes	= mysqli_query($pubConn,$getTotalSql);
	$getTotalRow	= @mysqli_fetch_array($getTotalRes);
	$existNum		= $getTotalRow[0];

	if($DEBUG) echo "<br>existNum=$existNum";
	
	//检查导入的文件大小，记录条数
	$impFileSize = filesize($impFile);
	if($DEBUG) {
		echo "<br>impFile=$impFile";
		echo "<br>impFileSize=$impFileSize";
	}
	if($impFileSize > $maxImpFileSize){
		$impFileSizeM=ceil($impFileSize/1024/1024);
		echo "File size is too large!(Must <= 5M)</font>";
		@unlink ($impFile); 
		return 0;
	}

	if($impFileSize <=0){
		echo "<font color=\"#FF0000\" size=3>subscriber data is null.</font>";
		@unlink ($impFile); 
		return 0;
	}

	$impRecordNum = count(file($impFile));
	if($DEBUG) echo "<br>impRecordNum=$impRecordNum";
	if($impRecordNum > $maxImpRecordNum){
		echo "<font color=\"#FF0000\" size=3>Records are too much!(Must <= $maxImpRecordNum)</font>";
		@unlink ($impFile); 
		return 0;
	}

	if($impRecordNum > $maxTotalNum-$existNum){
		echo "<font color=\"#FF0000\" size=3>User number is too much!</font>";
		@unlink ($impFile); 
		return 0;
	}
	for ($k=0; $k<$runningServerNum; $k++) {
		$getSysIdRow=mysqli_fetch_array($getSysIdResult);
		$sysId=$sysTypeNo.'_'.$getSysIdRow[sysNo].'_'.$getSysIdRow[subSysNo];
		$dstSeverIp = $getSysIdRow[ip];
		if($sysTypeNo==360)
			$sysIdCyc[$k]	= '360_99_99';
		else if($sysTypeNo==390)
			$sysIdCyc[$k]='390_'.$getSysIdRow[sysNo].'_99';
		else
			$sysIdCyc[$k]	= $sysId;
		if($DEBUG) echo "<br>sysId = $sysId";
		if($DEBUG) echo "<br>dstSeverIp = $dstSeverIp";
		
		/* close ftp
		$ftpCon=ftp_connect($dstSeverIp);
		if($ftpCon < 0){
			echo "<font color=\"#FF0000\">Connect Failed!</font>";
			@unlink ($impFile);
			return 0;
		}
		*/
		
		$connection=sftp_connect($dstSeverIp);
		if(!$connection)
		{
			echo "<font color=\"#FF0000\">Connect Failed!</font>";
			@unlink ($impFile);
			return 0;
		}
		
		/* fclose ftp
		if(!ftp_login($ftpCon,$ftpLoginName,$ftpLoginPwd)){
			echo "<font color=\"#FF0000\">Login Failed!</font>";
			@unlink ($impFile); 
			return 0;		
		}
		*/
		
		$key=sftp_login($connection,$ftpLoginName,$ftpLoginPwd);
		if(!$key)
		{
			echo "<font color=\"#FF0000\">Login Failed!</font>";
			@unlink ($impFile); 
			return 0;	
		}

		$remoteFileName=$ftpDir.$impFileName;
		/* close ftp
		if(!ftp_put($ftpCon,$remoteFileName,$impFile,FTP_ASCII)){
			echo "<font color=\"#FF0000\">Put file Failed</font>";
			@unlink ($impFile); 
			return 0;	
		}
		ftp_quit($ftpCon);
		*/
		
		if(!sftp_put($ftpCon,$remoteFileName,$impFile,SFTP_ASCII)){
			echo "<font color=\"#FF0000\">Put file Failed</font>";
			@unlink ($impFile); 
			return 0;	
		}
		
		$logFile="/usr/local/apache/htdocs/ftpFile/$logFileName";
		@unlink ($logFile); 
	}
	@unlink ($impFile); 
	
	//修改设备参数
	if($sysTypeNo==340){
		$k4_flag = 0; //should be 0 or 8.
		$instanceNo	= 0;
		$commState	= $k4_flag.'1';
		$totalNum	= DecHex($impRecordNum);
		$totalNum	= omc_keep_length($totalNum,'0',6);
		if($k4_flag!=8)
			$k4	= '0000000000000000';
		else{
			if(strlen($k4)<16){
				echo "<font color=\"#FF0000\" size=\"4\">K4 is incorrect!</font>";
				return 0;
			}
		}
		$newValue	= $commState.$totalNum.$k4;
	}else{
		$instanceNo	= 0;
		$commState	= '01';
		$totalNum	= DecHex($impRecordNum);
		$totalNum	= omc_keep_length($totalNum,'0',6);
		$finishNum	= '000000';
		$newValue	= $commState.$totalNum.$finishNum;
	}
	if($DEBUG)echo "<br>newValue=$newValue";

	//send set command
	
	for ($k=0; $k< $runningServerNum; $k++) {
		$chgResult	= setSysParamValue($sysIdCyc[$k],$impObjId,$instanceNo,$newValue);
		$commStr	= sysCommSend($sysIdCyc[$k],$nSetComm,$impObjId);	
		
		chkCommStat($sysId,$impObjId,$impRecordNum,$commStr);
	}
}//end updateSubs

function chkCommStat($sysId,$impObjId,$impRecordNum,$commStr)
{
	$nProcFail	=0;
	$nWaitProc	=1;
	$nInProc	=2;
	$nOutProc	=3;
	$sysIdArr=explode('_',$sysId);
	$sysTypeNo	=$sysIdArr[0];
	$sysNo		=$sysIdArr[1];
	$subSysNo	=$sysIdArr[2];
	$maxSeconds = 20;
	while(1) {
		$paramValue = getSysParamValue($sysId,$impObjId,0,'readValue');
		$impCommState = substr($paramValue,0,2);
		$runSeconds += 2;
		if($sysTypeNo==340){
			$allNum=$impRecordNum;
			$doneNum = substr($paramValue,2,6);
			$doneNum = HexDec($doneNum);
		}else{
			$allNum = substr($paramValue,2,6);
			$allNum = HexDec($allNum);
			$doneNum = substr($paramValue,8,6);
			$doneNum = HexDec($doneNum);
		}
		if($doneNum > $oldDoneNum){
			$runSeconds = 0;
		}
		$oldDoneNum = $doneNum;
		sleep(2);
		if($runSeconds > $maxSeconds || $doneNum >= $allNum || $impCommState == '03' || $impCommState == '04') 
		{
			if($impCommState == '04'){
				echo "<FONT color=\"#FF0000\" size=\"3\"><b>Failed!</b></FONT>";
			}elseif($runSeconds > $maxSeconds){
				echo "<FONT color=\"#FF0000\" size=\"3\"><b>Response Time Out!</b></FONT>";
			}else{
				echo "<FONT color=\"#0000FF\" size=\"3\"><b>Finished!</b></FONT>";
			}
			break;
		}
		
		
		$commIdArr	= explode('-',$commStr);
		$commId		= $commIdArr[0];
		
		$commSql	= " SELECT commState FROM parameterComm WHERE commId = '$commId' ";
		$commRes	= mysqli_query($pubConn,$commSql);
		$commRow	= @mysqli_fetch_array($commRes);
		$commStat	= $commRow[commState];
		if($commStat == $nOutProc || !isset($commStat)){
			$commStr = sysCommSend($sysId,0,$impObjId);
		}
	}//end while
}//end chkCommStat
function updateBssDb($bssIpAddr,$localDir)
{
	$remoteDir = "/hd0/iw07_00.010/compile/cfg/";
	$ftpCon=@ftp_connect($bssIpAddr);
	if($ftpCon < 0){
		echo "<font color=\"#FF0000\">BSS's ip is error or connect $bssIpAddr Failed!</font>";
		flush();
		return 0;
	}
	if(!@ftp_login($ftpCon,'','')){
		echo "<font color=\"#FF0000\">BSS's ip is error or login $bssIpAddr Failed!</font>";
		@ftp_close($ftpCon);
		flush();
		return 0;
	}
	if(!@ftp_chdir($ftpCon, $remoteDir)){
		echo "<font color=\"#FF0000\">Change dir error!</font>";
		@ftp_close($ftpCon);
		flush();
		return 0;
	}
	$dir = @dir($localDir);
	while(false !== ($entry=$dir->read())) {
		if(is_file("$localDir$entry") && $entry!='.' && $entry!='..')
			$fileArr[] = $entry;
	}
	for($i=0; $i< sizeof($fileArr); $i++) {
		$file = $fileArr[$i];
		$remoteFile=$remoteDir.$file;
		$localFile=$localDir.$file;
		if (!@ftp_put($ftpCon, $remoteFile, $localFile, FTP_BINARY)) {
			flush();
			echo "<font color=\"#FF0000\">Put file error!</font>";
			@ftp_close($ftpCon);
			return 0;
		}
	}//end for
	
	@ftp_close($ftpCon);
	return 1;		
}//end get BssDb
?>
<body leftmargin=12 topmargin=5>
<?php
echo "<table border=\"0\" width=\"100%\">";
echo "<tr>";
echo "<td width=\"50%\">";
echo "$ThisPage";
echo "</td>";
echo "<td width=\"50%\" align=\"right\" title=\"Help\">";
showHelp($helpId);
echo "</td>";
echo "</tr>";
echo "</table>";
if(isset($inputFile)&&$inputFile!='')
{
	$upload_file		=	$_FILES['inputFile']['tmp_name'];
	$upload_file_name	=	$_FILES['inputFile']['name'];
	$upload_file_size	=	$_FILES['inputFile']['size'];
	$file_size_max = 20*1000*1000;// 20M限制文件上传最大容量(bytes)
	$uploadPath = "/usr/local/apache/htdocs/db_backup/archive/uploaded/";// 上传文件的储存位置
	exec("mkdir $uploadPath -p");
	//exec("chmod -R 777 $uploadPath");
	chmod($uploadPath,0777);
	$accept_overwrite = 1;//是否允许覆盖相同文件
	// 检查文件大小
	if ($upload_file_size > $file_size_max) 
	{
		MsgBox("The file size is too large!");
	}
	
	// 检查读写文件
	if (file_exists($uploadPath . $upload_file_name) && !$accept_overwrite) 
	{
		MsgBox("The file is already existed!");
	}
	
	//复制文件到指定目录
	if (!copy($upload_file,$uploadPath.$upload_file_name)) 
	{
		MsgBox("File copy error!");
	}
	
	//解压缩文件
	chdir($uploadPath);
	exec("tar zxvf $upload_file_name");
	system("rm -f $upload_file_name");
	sleep(2);
}
else
{
	MsgBox($strNoInput);
}
//exit;
//////////////////////////////////////////
if(1)
{//update parameters
	$paramDir = 'params';
	$paramPath = $uploadPath . $paramDir . '/';
	if(is_dir($paramPath)) {//if there is exist paramPath.
		echo "<br><font color=\"#0000FF\"><b>Updating system parameters ... </b></font>";
		flush();
		getFileList($paramPath,$fileListArr);
		
	//	print_r($fileListArr);
	//	exit;
		$allSuccess = 1;
		for($i=0; $i<sizeof($fileListArr); $i++)
		{
			$fileName = $fileListArr[$i];
			$tmpArr = explode('.',$fileName);
			if(sizeof($tmpArr)==3)
			{
				$csvFileName = $paramPath . $fileListArr[$i];
				$db_name = $tmpArr[0];
				$table_name = $tmpArr[1];
				$tmpNameArr = explode('_',$db_name);
				$sysTypeNo=$tmpNameArr[1];
				if($sysTypeNo<300)$sysTypeName="PLAT";
				else if($sysTypeNo==322) $sysTypeName="MSC";
				else $sysTypeName = getNameByTypeNo($sysTypeNo);
				if($oldName !== $sysTypeName){
					echo "<br>&nbsp;&nbsp;&nbsp;&nbsp;<font color=\"#0000FF\">Updating [&nbsp;<span class=\"inner\">$sysTypeName</span>&nbsp;] ... </font>";
					flush();
				}
				$rtn = updateParamer($db_name,$table_name,$csvFileName);
				if($oldName !== $sysTypeName){
					if($rtn==1)
						echo "<font color=\"#0000FF\"><b>-- SUCCESS</b></font>";
					else
						echo "<font color=\"#FF0000\"><b>-- FAIL</b></font>";
					flush();
				}
				$oldName = $sysTypeName;
				$allSuccess &= $rtn;
			}
		}
		
		system("rm -rf $paramDir");
	}//end if
	
}//end update parameters.

if(1)
{//update subscribers' data
	$subsDir = 'subs';
	$subsPath = $uploadPath . $subsDir . '/';
	
	if(is_dir($subsPath)) {//if there is exist subsPath
		echo "<br><br><font color=\"#0000FF\"><b>Updating system subscribers ... </b></font>";
		flush();
		unset($fileListArr);
		getFileList($subsPath,$fileListArr);

		for($i=0; $i<sizeof($fileListArr); $i++)
		{
			$fileName = $fileListArr[$i];
			$tmpArr = explode('.',$fileName);
			if(sizeof($tmpArr)==4)
			{
				$csvFileName = $subsPath . $fileListArr[$i];
				$db_name = $tmpArr[0];
				$table_name = $tmpArr[1];
				$sysId = $tmpArr[2];
				
				$tmpNameArr = explode('_',$db_name);
				$sysTypeName=$tmpNameArr[0];
				
				$filesize = filesize($csvFileName);
				if($filesize > 0) {
					echo "<br>&nbsp;&nbsp;&nbsp;&nbsp;<font color=\"#0000FF\">Updating [&nbsp;<span class=\"inner\">$sysTypeName</span>&nbsp;] ... </font>";
					flush();
					$allSuccess &= updateSubs($sysId,0,$csvFileName);
				}
			}
		}
		system("rm -rf $subsDir");
	}
}//end update subscribers' data

if(1)
{//update bss.
	$bssDir = "bssDir";
	$bssPath = $uploadPath . $bssDir . '/';
	$bssOmcTlbDir = "omcTlb";
	$bssOmcTlbPath = $bssPath . $bssOmcTlbDir . '/';
	$bssDbDir = "dbs";
	$bssDbPath = $bssPath . $bssDbDir . '/';
	if(is_dir($bssPath)){//if there exist this bssDir
		echo "<br><br><font color=\"#0000FF\"><b>Updating BSS ... </b></font>";
		flush();
		//1. update bssomctable.
		{
			unset($fileListArr);
			getFileList($bssOmcTlbPath,$fileListArr);
			for($i=0; $i<sizeof($fileListArr); $i++)
			{
				$fileName = $fileListArr[$i];
				$tmpArr = explode('.',$fileName);
				if(sizeof($tmpArr)==3)
				{
					$csvFileName = $bssOmcTlbPath . $fileListArr[$i];
					$db_name = $tmpArr[0];
					$table_name = $tmpArr[1];
					echo "<br>&nbsp;&nbsp;&nbsp;&nbsp;<font color=\"#0000FF\">Updating BSS' parameters ... </font>";
					$rtn = updateParamer($db_name,$table_name,$csvFileName);
					if($rtn==1)
						echo "<font color=\"#0000FF\"><b>-- SUCCESS</b></font>";
					else
						echo "<font color=\"#FF0000\"><b>-- FAIL</b></font>";
					flush();
					$allSuccess &= $rtn;
				}
			}
		}//end update bssomctable.
		
		//2. update bss db.
		{
			$dir = dir($bssDbPath);
			while(false !== ($entry = $dir->read())) {
				if(is_dir("$bssDbPath/$entry") && $entry != "." && $entry != "..")
					$bssIpArr[] = $entry;
			}
			for($i=0; $i< sizeof($bssIpArr); $i++) {
				$ip = $bssIpArr[$i];
				echo "<br>&nbsp;&nbsp;&nbsp;&nbsp;<font color=\"#0000FF\">Updating BSS' Database [ $ip ] ... </font>";
				flush();
				if(updateBssDb($ip,"$bssDbPath/$ip/"))
					echo "<font color=\"#0000FF\"><b>-- SUCCESS</b></font><br>";
			}
		}//end update bss db.
		if($needReboot)//3. reboot bss.
		{
			chdir("/usr/local/apache/htdocs/wxc2_omc/security/backupRestore");
			for($i=0; $i< sizeof($bssIpArr); $i++) {
				$ip = $bssIpArr[$i];
				echo "<br>&nbsp;&nbsp;&nbsp;&nbsp;<font color=\"#0000FF\">Rebooting BSS [ $ip ] ... </font>";
				flush();
				$tmpCmd ="./bssReboot".' '.$ip;
				system($tmpCmd);
				//$lastLine = system($tmpCmd, $rtn);
				//echo "<br>$tmpCmd<br>$lastLine<br>$rtn";
			}
			//var_dump($bssIpArr);
		}//end reboot bss.
	}
}//end update bss.

//exit;

if($allSuccess) {
	MsgBox("All needed success");
}
else {
	echo "<p align=\"left\"><a href=\"JavaScript:history.go(-1)\"><img align=absBottom border=0 src=\"../../images/left.gif\" width=\"14\" height=\"14\">Back</a>";	
}
?>
