<?php 
/*********************************************************      
  程序说明：         
  功能说明：用户数据的批量导入

  调用关系：调用: header.inc   
  被调用:        

  变量说明：

  作者：huangqingsen    2002-08-27      

  修改注释：      
  NO.1      
  姓名：hewd       
  时间：2003-03-10    
  修改说明：优化流程，规范变量命名    
 *********************************************************/
require("../../inc/header.inc"); 
$sysId=$_POST['sysId'];
$dataTypeNo=$_POST['dataTypeNo'];
function setImpParamValue($sysId,$objIdStr,$instanceNo,$newValue)
{
	global $paramConf_table,$OMC_server;

	$DEBUG=0;

	if($DEBUG) echo"<br>sysId=$sysId";
	$tmpSysIdArr = explode('_',$sysId);
	$sysTypeNo	= $tmpSysIdArr[0];
	$sysNo		= $tmpSysIdArr[1];
	$subSysNo	= $tmpSysIdArr[2];

	$paramDb = 'OBJ_'.$sysTypeNo;

	$objConn = mysqli_connect($OMC_server[0]['host'],$OMC_server[0]['user'],$OMC_server[0]['password'], $paramDb);

	if($DEBUG) echo"<br>paramDb=$paramDb";
	//获取参数定义表的表名，根据oid取出参数定义
	$tmpObjArr = explode('.',$objIdStr);
	$objWhereStr='';
	for($i=0;$i<sizeof($tmpObjArr);$i++){
		$j=$i+1;
		$objWhereStr .= ' level_'.$j."='{$tmpObjArr[$i]}' AND ";
	}
	$objWhereStr = substr($objWhereStr,0,-5); //最后多了一个' AND ',将其去掉


	//根据参数类型，推出参数表的表名
	if($sysTypeNo==390)
	{
		$paramTable = 'param_'.$sysNo;
	}
	else
	{
		$paramTable = 'param_99';
		$subSysNo = '99';
	}
	//subSysNo = '$subSysNo'

	//修改对应的参数值
	$objWhereStr=str_replace("AND",",",$objWhereStr);
	$setParamValueSql="replace $paramTable 
		SET initValue='$newValue',readValue='' 
		,instanceNo = '0000',$objWhereStr ";
	if($DEBUG)echo"<br> $setParamValueSql <br>";
	$setResult=mysqli_query($objConn,$setParamValueSql);
	echo mysqli_error($objConn);
	if($setResult){
		return(1);
	}else{
		return(-1);
	}
}//end of function
$DEBUG = 0;

//echo "<br>impFile=$impFile";
//echo "<br>impFileSize=$impFileSize";
//echo "<br>sysId=$sysId";

$sysId = $_REQUEST['sysId'];
$dataTypeNo = $_REQUEST['dataTypeNo'];
$nGetComm	= 0;
$nSetComm	= 3;
$nSubSysParam		= 0;
$nGlobalSubSysParam = 1;
$nGlobalSysParam	= 2;

$pubDb				= 'OMC_PUB';
$sysSubsConfTable	= 'OMC_PUB.sysSubsConf';
$systemConfTable	= 'OMC_PUB.sysConf';
$sysInfoTable		= 'OMC_PUB.sysInfo';
if($DEBUG)	echo "(1) sysId=$sysId, dataTypeNo = $dataTypeNo<br>";
if(isset($sysId) && isset($dataTypeNo)){
	$sysIdArr=explode('_',$sysId);
	$sysTypeNo	=$sysIdArr[0];
	$sysNo		=$sysIdArr[1];
	$subSysNo	=$sysIdArr[2];
}else{
	echo "Cannot find sysId and dataTypeNo";
	exit(0);
}
if($DEBUG) echo "<br>sysTypeNo=$sysTypeNo";
if($DEBUG) echo "<br>dataTypeNo=$dataTypeNo";
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];
if($sysTypeNo==360||$sysTypeNo==395||$sysTypeNo==370||$sysTypeNo==375||$sysTypeNo==330||$sysTypeNo==325||$sysTypeNo==340||$sysTypeNo==380||$sysTypeNo==378)
	$paramType			= $nGlobalSysParam;
else if($sysTypeNo==390)
	$paramType			= $nGlobalSubSysParam;
	else 
	$paramType			= $nSubSysParam;
	$maxTotalNum		= $maxSegmentNum * $maxIndexNumPerSeg;
if($sysTypeNo == 395)
{
	$maxImpFileSize		= 5*1024*1024*4;
	$maxImpFileSizeM=ceil($maxImpFileSize/1024/1024);
	$maxImpRecordNum	= 20000;
}
else
{
	$maxImpFileSize		= 10*1024*1024;
	$maxImpFileSizeM=ceil($maxImpFileSize/1024/1024);
	$maxImpRecordNum	= 5000;
}

if($DEBUG)echo "<br>subsDataTable=$subsDataTable";
if($DEBUG)echo "<br>impObjId= $impObjId";
if($DEBUG)echo "<br>impFileName=$impFileName ";
if($DEBUG)echo "<br>ftpDir=$ftpDir ";
if($DEBUG)echo "<br>ftpLoginName=$ftpLoginName ";
if($DEBUG)echo "<br>ftpLoginPwd=$ftpLoginPwd";
if($DEBUG)echo "<br>maxSegmentNum=$maxSegmentNum ";
if($DEBUG)echo "<br>maxIndexNumPerSeg=$maxIndexNumPerSeg ";
if($DEBUG)echo "<br>paramType=$paramType ";
if($DEBUG)echo "<br>maxTotalNum=$maxTotalNum ";

//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 ($DEBUG)	echo "sysName = $sysName<br>";

$upfile=$_FILES['impFile']['name'];
$impFile=$_FILES['impFile']['tmp_name'];

//判断是否有文件上载
if(isset($impFile) && $impFile != "none"){
	if($sysTypeNo==390)
	{
		$getSysIdSql = "SELECT sysNo,subSysNo,ip 
			FROM $sysInfoTable
			WHERE sysTypeNo='$sysTypeNo' AND sysNo='$sysNo' AND baseStat > '0'
			ORDER BY sysNo,subSysNo
			";
	}
	else if($sysTypeNo == 378)
	{
		$getSysIdSql = "SELECT sysNo,subSysNo,ip 
			FROM $sysInfoTable
			WHERE sysTypeNo='$sysTypeNo' 
			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);
	//ipalim状态需要查看sysStat里的status值
	if($sysTypeNo == 378)
	{
		$runningServerNum=0;
		$checkstatesql="select detailStat,updateTime from OMC_PUB.sysStat where sysTypeNo=378 ";
		$checkstateres=mysqli_query($pubConn,$checkstatesql);
		while($checkstaterow=mysqli_fetch_array($checkstateres))
		{
			$update_time=$checkstaterow[updateTime];
			$bin_data=$checkstaterow[detailStat];
			$state=substr($bin_data,26*2,2)+0;
			$due_date	= date("Y-m-d H:i:s",mktime(date("H"),date("i"),date("s")-48,date("m"),date("d"),date("Y")));
			$ove_date	= date("Y-m-d H:i:s",mktime(date("H"),date("i"),date("s")+48,date("m"),date("d"),date("Y")));
			if($update_time < $due_date || $update_time > $ove_date)
				continue;
			if($state == 0)
				$runningServerNum++;
		}
	}

	if($runningServerNum <= 0){
		echo "<font color=\"#FF0000\" size=\"3\">Error: No system running normally</font>";
		//by hewd 2003-08-19
		//PPS 没有用户数据的时候，它自己会告警，使状态变为非normal,造成不能导入数据
		exit();

	}
	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<br>";
	}
	if($impFileSize > $maxImpFileSize){
		$impFileSizeM=ceil($impFileSize/1024/1024);
		echo "<br><font color=\"#FF0000\" size=3>Import File Size is $impFileSizeM M";
		echo "<br>File size is too large!(Must <= {$maxImpFileSizeM}M)</font>";
		@unlink ($impFile); 
		exit();
	}

	if($impFileSize <=0){
		echo "<br><font color=\"#FF0000\" size=3>No import File";
		@unlink ($impFile); 
		exit();
	}

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

	if($impRecordNum > $maxTotalNum-$existNum){
		echo "<br><font color=\"#FF0000\" size=3>Exist record number($existNum) + Import record number($impRecordNum) > Max record number ($maxTotalNum)";
		echo "<br>User number is too much!</font>";
		@unlink ($impFile); 
		exit();
	}
	$submitStat = 'DISABLED';
	for ($k=0; $k<$runningServerNum; $k++) {
		$getSysIdRow=mysqli_fetch_array($getSysIdResult);
		$sysId=$sysTypeNo.'_'.$getSysIdRow[sysNo].'_'.$getSysIdRow[subSysNo];
		$dstSeverIp = $getSysIdRow[ip];
		if($sysTypeNo==360||$sysTypeNo==395||$sysTypeNo==370||$sysTypeNo==375||$sysTypeNo==330||$sysTypeNo==325||$sysTypeNo==340||$sysTypeNo==380||$sysTypeNo==378)
			$sysIdCyc[$k]	= $sysTypeNo.'_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";
		 //debug_log("/tmp/deugImport.txt","sysIdCyc=$sysIdCyc[$k]");

		/* close ftp
		$ftpCon=ftp_connect($dstSeverIp);
		if($ftpCon < 0){
			echo "<br><font color=\"#FF0000\">Connect Failed!</font>";
			@unlink ($impFile);
			exit();
		}
		*/
		
		$connection=sftp_connect($dstSeverIp);
		if(!$connection){
			echo "<br><font color=\"#FF0000\">Connect Failed!</font>";
			@unlink ($impFile);
			exit();
		}
		
		/* close ftp
		if(!ftp_login($ftpCon,$ftpLoginName,$ftpLoginPwd)){
			echo "<br><font color=\"#FF0000\">Login Failed!</font>";
			@unlink ($impFile); 
			exit();		
		}
		*/
		
		$key=sftp_login($connection,$ftpLoginName,$ftpLoginPwd);
		if(!$key)
		{
			echo "<br><font color=\"#FF0000\">Login Failed!</font>";
			@unlink ($impFile); 
			exit();		
		}

		$remoteFileName=$ftpDir.$impFileName;
		/* close ftp
		if(!ftp_put($ftpCon,$remoteFileName,$impFile,FTP_ASCII)){
			echo "<br><font color=\"#FF0000\">Put file Failed</font>";
			@unlink ($impFile); 
			exit();	
		}
		*/
		
		if(!sftp_put($key,$remoteFileName,$impFile,SFTP_ASCII))
		{
			echo "<br><font color=\"#FF0000\">Put file Failed</font>";
			@unlink ($impFile); 
			exit();	
		}
		/* close ftp
		ftp_quit($ftpCon);
		*/
		$logFile="/usr/local/apache/htdocs/ftpFile/$logFileName";
		@unlink ($logFile); 
	}
	@unlink ($impFile); 
	
	//修改设备参数
	if($sysTypeNo==340){
		$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 "<br><font color=\"#FF0000\" size=\"4\">K4 is incorrect!</font>";
				exit();
			}
		}
		$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";
	//exit();
	switch($paramType){
		case '1':
			$sysId=$sysTypeNo.'_'.$getSysIdRow[sysNo].'_99';
			break;
		case '2':
			$sysId=$sysTypeNo.'_99_99';
			break;
		default:
			break;
	}
	if($DEBUG)	echo "<br>(2) sysId=$sysId";
	//send set command

	if($sysTypeNo==360||$sysTypeNo==395||$sysTypeNo==370||$sysTypeNo==375||$sysTypeNo==330||$sysTypeNo==325||$sysTypeNo==340||$sysTypeNo==380||$sysTypeNo==390||$sysTypeNo==378){
        //if($sysTypeNo==360)
        //	$chgResult  = setSysParamValue($sysIdCyc[0],$impObjId,$instanceNo,$newValue);
        //else
        	$chgResult  = setImpParamValue($sysIdCyc[0],$impObjId,$instanceNo,$newValue);
        $commStr    = sysCommSend($sysIdCyc[0],$nSetComm,$impObjId);
    }else{	
		for ($k=0; $k<$runningServerNum; $k++) {
			//if($DEBUG)	
				//echo "<br>{$sysIdCyc[$k]},$nSetComm,$impObjId<br>";
			$chgResult	= setSysParamValue($sysIdCyc[$k],$impObjId,$instanceNo,$newValue);
			$commStr	= sysCommSend($sysIdCyc[$k],$nSetComm,$impObjId);			
			if($DEBUG){
				echo "setSysParamValue($sysId,$impObjId,$instanceNo,$newValue)<br>";
				echo "sysCommSend($sysId,$nSetComm,$impObjId)";
			}
		}
	}
			
	//让下面的命令扫描页面开始启动
	echo "<script language=\"javascript\">";
	echo "window.parent.frames.main.location.href='./subscriberImportDown.php?showFlag=1&sysId=$sysIdCyc[0]&dataTypeNo=$dataTypeNo&dstSeverIp=$dstSeverIp&impRecordNum=$impRecordNum&commStr=$commStr&impFile=$impFile';";
	echo "</script>";
	sleep(2);
}elseif(isset($impFile)){
	echo "<br><font color=\"#FF0000\" size=\"3\"><b>Upload file failed, File isn't exist or file is empty!</b></font>";
}
?>
<body  leftmargin="15" rightmargin="10" onload="javascript:adjust_frame('down');" onresize="javascript:adjust_frame('down');" style="overflow:hidden;overflow-x:hidden;overflow-y:hidden;">
<?php
adjust_head_frame("down");
adjust_title_head_frame("down");
adjust_title_tail_frame("down");
adjust_content_head_frame("down");	
echo "<br>";
?>
<form method="POST" action="<?php echo "$PHP_SELF";?>" name="subsData" enctype="multipart/form-data">
<table  border="1" width="100%" cellpadding="2" cellspacing="0"  bordercolor="#666666" bordercolordark="#FFFFFF" > 

<?php
	//<!-- *************    Display title   *************  -->
	if ( (395 == $sysTypeNo || 360 == $sysTypeNo) && (1 == $dataTypeNo) ) {
		$title = "$sysName recharge card data import";
	} else {
		$title = "$sysName subscriber data import";
	}
	echo "<tr bgcolor=\"#E6E6E6\">";
	echo "<td width=100% colspan=2 align=center>";
	echo "<font size=3><b>$title</b></font>";
	echo "</td>";
	echo "</tr>";
?>

<tr>
<td colspan=2>
<font color="#0000FF" size=2>Note:Import File's size <= <?php echo $maxImpFileSizeM;?>M, records <= <?php echo $maxImpRecordNum;?></font>
</td>
</tr>
<tr>
<td>Select File:</td>
<td>
<input type="file" name="impFile">
<input type="hidden" name="MAX_FILE_SIZE" value="20971520"><!-- MAX_FILE_SIZE = 20M -->
</td>
</tr>
<?php
	if($sysTypeNo==340){
		echo "<tr>";
		echo "<td>K4 Flag</td>";
		echo "<td>";
		echo "<select size=\"1\" name=\"k4_flag\">";
			echo "<option value=\"0\">Disable</option>";       
			echo "<option value=\"8\" selected>Enable</option>";
		echo "</select>";
		echo "</td>";
		echo "</tr>";
		echo "<tr>";
		echo "<td>K4</td>";
		echo "<td><input type=\"text\" name=\"k4\" maxlength=\"16\" size=\"17\" value=\"$k4\" class=\"text\"></td>";
		echo "</tr>";
	}
?>	
<tr>
<td colspan=2>
<?php
if($DEBUG) echo "<br>submitStat=$submitStat";

if($submitStat == 'DISABLED'){
	echo "<input type=\"submit\" DISABLED value=\"$strSubmit\">";
}else{
	echo "<input type=\"submit\"  value=\"$strSubmit\">";
}

echo "<input Name=\"dataTypeNo\" type=\"hidden\" value=\"$dataTypeNo\">";
echo "<input Name=\"sysId\" type=\"hidden\" value=\"$sysId\">";
?>
</td>
</tr>
</table>
</form>
<?php
adjust_content_tail("down");
?>
</body>
</html>
