<?php
/********************************************************************
 程序说明：   
    功能说明：发送完参数命令后，通过定时扫描数据库，显示命令的操作的状态过程，每隔两秒自动刷新
    
    输入变量：(由发送命令页面传来)$commIdStr,$okURL,$failURL
	
	输出并输入变量：$usedTime,$waitTime,$isFinish,$okURL,$failURL,$commIdStr

 作者：
********************************************************************/
require("../../inc/header.inc");
$DEBUG = 0;
global $pubConn;
$commIdStr=$_REQUEST['commIdStr'];
$okURL=$_REQUEST['okURL'];
$failURL=$_REQUEST['failURL'];

//commType 's value 
$nReadComm		= 1;
$nChangeComm	= 2;
$nCreateComm	= 3;
$nDeleteComm	= 4;
$nLoadIndexComm	= 5;
$nReplaceIndexComm=6;
//commState's value
$nProcFail		= 0;
$nWaitProc		= 1;
$nInProc		= 2;
$nOutProc		= 3;

$failURL	= rawurldecode($failURL);
$okURL		= rawurldecode($okURL);
$pubDb		= 'OMC_PUB';
$commTable	= 'subscriberComm';
$sysConfTable ='sysConf';

$commNum=$_REQUEST['commNum'];
$commType=$_REQUEST['commType'];
$lastTimeFinishNumStr=$_REQUEST['lastTimeFinishNumStr'];

if($commNum <= 0){
	$commArr = explode('-',$commIdStr);
	$commNum = sizeof($commArr);
}
$maxOverTime = $commNum * 5 + 10; //根据子系统个数和对每个子系统操作的最大延时（5秒）来决定
$maxWaitTime = $commNum * 2;
$maxStopTime = $commNum * 5 + 10;
$maxOfCommId = 50000; //设定命令表的最大值


$isFinish = $_REQUEST['isFinish'];
$waitTime = $_REQUEST['waitTime'];
$stopTime = $_REQUEST['stopTime'];
$usedTime =  $_REQUEST['usedTime'];
$isBatchCreate = $_REQUEST['isBatchCreate'];
$batchDelete = $_REQUEST['batchDelete'];
$dataTypeNo = $_REQUEST['dataTypeNo'];
if($DEBUG) echo "<br>if(isFinish != 0 || (waitTime >= maxWaitTime) ||(stopTime > maxStopTime))<br>";
if($DEBUG) echo "<br>if($isFinish != 0 || ($waitTime >= $maxWaitTime) ||($stopTime > $maxStopTime))<br>";

//命令处理完毕
//---------------- 
if(($isFinish != 0) || ($waitTime >= $maxWaitTime) || ($stopTime > $maxStopTime)){ 
	if($commId >= $maxOfCommId){ //初始化命令表
		//先删除表
		$dropSql = "DROP TABLE $commTable ";
		mysqli_query($pubConn,$dropSql);
		//再建一个结构相同的新表
		$createSql="CREATE TABLE subscriberComm (
			   commId smallint(5) unsigned NOT NULL auto_increment,
			   commType tinyint(1) DEFAULT '0' NOT NULL,
			   dataTypeNo tinyint(4) DEFAULT '0' NOT NULL,
			   sysTypeNo smallint(5) unsigned DEFAULT '0' NOT NULL,
			   sysNo smallint(5) unsigned DEFAULT '0' NOT NULL,
			   subSysNo smallint(5) unsigned DEFAULT '0' NOT NULL,
			   indexValueList varchar(255) NOT NULL,
			   fieldNameList tinytext NOT NULL,
			   paramType tinyint(4) DEFAULT '0' NOT NULL,
			   commState tinyint(3) unsigned DEFAULT '0' NOT NULL,
			   totalNum smallint(5) unsigned DEFAULT '0' NOT NULL,
			   finishNum smallint(5) unsigned DEFAULT '0' NOT NULL,
			   sendTime datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
			   bgnTime datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
			   endTime datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
			   remark varchar(200) binary NOT NULL,
			   PRIMARY KEY (commId),
			   KEY sysTypeNo (sysTypeNo),
			   KEY sysNo (sysNo),
			   KEY subSysNo (subSysNo),
			   KEY bufferKey (indexValueList)
			)
			";
		mysqli_query($pubConn,$createSql);
	}else{
		//删除命令表的相关命令
		$commArr = explode('-',$commIdStr);
		for($i=0;$i<sizeof($commArr);$i++){
			if(strlen($commArr[$i]) <=0){ 
				continue;
			}
			$deleteSql = "DELETE FROM $commTable WHERE commId='$commArr[$i]'";
			if($DEBUG) echo "<br>deleteSql = $deleteSql";
			mysqli_query($pubConn,$deleteSql);
			echo mysqli_error($pubConn);
		}
	}
	
	// 重定向返回指定页
	if($isFinish != 0){
		if($isFinish > 0){
			echo "<b><font size=3 color=blue>Finished!!</font></b>";
			if($commType == $nLoadIndexComm){
				sleep(8);//等8秒，这样数据库插入才能完全完成
			}
			if($DEBUG) echo "<br>okURL=$okURL";
			if($DEBUG) exit();
			echo " <meta http-equiv=\"refresh\" content=\"2; url=$okURL\"> ";
		}elseif($isFinish == -1){
			echo "<b><font size=3 color=black>Failed in some system!!</font></b>";
			if($DEBUG) exit();
			echo " <meta http-equiv=\"refresh\" content=\"2; url=$okURL\"> ";
		}else{
			echo "<b><font size=3 color=red>Failed!!</font></b>";
			if($DEBUG) exit();
			echo " <meta http-equiv=\"refresh\" content=\"2; url=$failURL\"> ";
		}
	}elseif($usedTime >= $maxOverTime && $stopTime == 1){
		echo "<b><font size=3 color=red>Stoped!!</font></b>";
		if($DEBUG) exit();
		echo " <meta http-equiv=\"refresh\" content=\"2; url=$failURL\"> ";
	}else{ //$usedTime >= $maxOverTime
	  	echo "<b><font size=3 color=red>Timeout!!</font></b>";
		if($DEBUG) exit();
		echo " <meta http-equiv=\"refresh\" content=\"2; url=$failURL\"> ";
	}
	exit();	
}//end of if($isFinish....)

//显示命令执行状态
//----------------------------- 
$showTime = $usedTime*2;
echo "<font size=2>Time:$showTime s</font>";
$okNum	 = 0;
$failNum = 0;
$commNum = 0;
$commArr = explode('-',$commIdStr);
$thisTImeFinishNumstr='';
$lastTimeFinishNumArr = explode('-',$lastTimeFinishNumStr);
for($i=0;$i<sizeof($commArr);$i++){
	if(strlen($commArr[$i]) <=0){ continue;}
	$commNum++;
	$commSql = "SELECT * FROM $commTable WHERE commId= $commArr[$i]";
	if($DEBUG) echo "<br>get command = $commSql";
	$commResult = mysqli_query($pubConn,$commSql);
	if(mysqli_num_rows($commResult) <= 0){
		echo "<br>Can not find this command's info in datebase";
		exit();
	}
	$commRows	= @mysqli_fetch_array($commResult);
	$sysTypeNo	= $commRows[sysTypeNo];
	$sysNo		= $commRows[sysNo];
	$subSysNo	= $commRows[subSysNo];
	$commType	= $commRows[commType];
	$paramType	= $commRows[paramType];
	$objId		= $commRows[objId];
	$commState	= $commRows[commState];
	$indexValueList = $commRows[indexValueList];
	$fieldNameList	= $commRows[fieldNameList];
	$remark = $commRows[remark];
	if ($DEBUG)echo "commState=$commState, commRemakr=$remark<br>";

	//获取该系统类型的snmp头和类型名称
	if(!isset($sysTypeName)){
		$sysConfSql = "SELECT snmpHead,sysTypeName FROM $sysConfTable WHERE sysTypeNo='$sysTypeNo'";
		if($DEBUG) echo "<br>get conf = $sysConfSql";
		$sysConfResult = mysqli_query($pubConn,$sysConfSql);
		echo mysqli_error($pubConn);
		$sysConfRows   = @mysqli_fetch_array($sysConfResult);
		$sysTypeName = $sysConfRows[sysTypeName];
		$snmpHead	 = $sysConfRows[snmpHead];
	}
	$sysName = $sysTypeName.'_'.$sysNo.'_'.$subSysNo;
	//echo "<br><font size=2> $sysName 's</font>";
	$objIdStr=$snmpHead.'.'.$objId;
	//echo "<font size=2 color=blue>$objIdStr</font>";

	switch($commType){
		case $nReadComm:
			$showInfo="Read $indexValueList from $sysName";	
			break;
		case $nChangeComm:
			$showInfo="Change $indexValueList's field[$fieldNameList] in $sysName";	
			break;
		case $nCreateComm:
			$showInfo="Create $indexValueList to $sysName";	
			break;
		case $nDeleteComm:
			$showInfo="Delete $sysName's  $indexValueList";	
			break;
		case $nLoadIndexComm:
			$showInfo="Load $sysName's subscriber Data ";
			break;
		case $nReplaceIndexComm:
			$showInfo="Replace Index $indexValueList -> $remark in $sysName";
			break;
		default:
			echo "<font size=2> Unknown Command Type</font>";
			exit();
	}
	
	echo "<font size=2> $showInfo</font>";
	
	switch($commState){
		case 0: //process failed
			$failNum++;
			echo "<br><b><font size=2 color=red> $commRows[remark] </font></b>";
			insertLog("$showInfo Failed:$remark");
			sleep(1);
			break;
		case 1: //wait process
			$waitTime++;
			break;
		case 2: //in process
			$waitTime = 0;
			//只要有一个命令的完成数在增长，就认为该组命令在运行，否则认为命令处理超时
			if($DEBUG) echo "====> {$commRows[finishNum]} > {$lastTimeFinishNumArr[$i]}";
			if($commRows[finishNum] > $lastTimeFinishNumArr[$i]){
				$stopTime = 0;
			}else{
				$stopTime++;
			}
			omcProgressBar($commRows[totalNum],$commRows[finishNum]);
			$thisTimeFinishNumStr .=$commRows[finishNum].'-';
			break;
		case 3: //process finished
			$okNum++;
			omcProgressBar(100,100);
			insertLog("$showInfo OK");
			break;
		default:
			echo "<font size=3>Unknown Command State</font>";
			exit();
	}
	echo "<br><br>";
}//end of for($i=0;$i<sizeof($commArr);$i++)

if($DEBUG) echo"<br>$commNum =?= $finishNum";
if($commNum == $okNum){
	$isFinish = 1;
}elseif($failNum > 0 && $okNum > 0){
	$isFinish = -1;
}elseif($commNum == $failNum){
	$isFinish = -2;
}else{
	$isFinish = 0;
}

//当删除用户时，只要不是"回应超时"，都删除OMC数据库的用户
if($commType == $nDeleteComm && $commState != $nWaitProc && $commState != $nInProc){
	if($DEBUG) echo"<br>commType == DeleteComm ($commType == $nDeleteComm)";
	if($DEBUG) echo"<br>remark={$commRows[remark]}";
	if($DEBUG) sleep(5);
	if( $commRows[remark] != "response timeout"){
		if(!strstr($commRows[remark],"Can not delete an in used subscriber, please disable first"))
			$isFinish = 1;
	}
}
if($DEBUG) echo"<br>lastTimeFinishNumStr=$lastTimeFinishNumStr";
if($DEBUG) echo"<br>thisTimeFinishNumStr=$thisTimeFinishNumStr";
$lastTimeFinishNumStr = $thisTimeFinishNumStr;
//刷新返回
//--------------
$usedTime++; //总时间
$failURL= rawurlencode($failURL);
$okURL  = rawurlencode($okURL);
//保留变量值,传到下次刷新
$keepStr= "usedTime=$usedTime&waitTime=$waitTime&isFinish=$isFinish&stopTime=$stopTime&failURL=$failURL&okURL=$okURL&commIdStr=$commIdStr&commNum=$commNum&lastTimeFinishNumStr=$lastTimeFinishNumStr&commType=$commType";
if($DEBUG) echo "<br>keepStr=$keepStr";
/*
if ( 1!=$searchInServer ) {
	require("commDown.php");
}
*/
sleep(5);
$PHP_SELF = $_SERVER['PHP_SELF'];

?>
<script type="text/javascript">
	window.location.href="<?php echo "$PHP_SELF?$keepStr"; ?>";
</script>
