<?php 
/*********************************************************      
 程序说明：         
    功能说明：费率启动
              
    调用关系：调用: header.inc   
              被调用:        
 
    变量说明：

    作者：
      
修改注释：      
NO.1      
姓名：Cui Ticun       
时间：2004-4-26    
修改说明：Support OMC7.0    
*********************************************************/
require("../../inc/header.inc"); 
?>
<body leftmargin="15" rightmargin="10" onload="javascript:adjust();" onresize="javascript:adjust();" style="overflow:hidden;overflow-x:hidden;overflow-y:hidden;">

<?php
adjust_head();
adjust_title_head();

$DEBUG=0;
$helpId = "2.49"; 

//==========================================================
//变量定义
//==========================================================
$nGetComm	= 0;
$nSetComm	= 3;
$nSubSysParam		= 0;
$nPubSubSysParam	= 1;
$nPubSysParam		= 2;

$ppsDb				='PPS_DB';
$pubDb				='OMC_PUB';
$sysInfoTable		= 'OMC_PUB.sysInfo';
$tableName			='tariffPlanComm';
$sysTypeNo			=360;

global $OMC_server;
$objConn = mysqli_connect($OMC_server[0]['host'],$OMC_server[0]['user'],$OMC_server[0]['password'], 'OBJ_'.$sysTypeNo);
$dbConn = mysqli_connect($OMC_server[0]['host'],$OMC_server[0]['user'],$OMC_server[0]['password'], $ppsDb);

$plan_year=$_REQUEST['plan_year'];
$plan_month=$_REQUEST['plan_month'];
$plan_day=$_REQUEST['plan_day'];
$plan_hour=$_REQUEST['plan_hour'];
$plan_minute=$_REQUEST['plan_minute'];
$plan_second=$_REQUEST['plan_second'];
$plan_remark=$_REQUEST['plan_remark'];
$set_plan_time=$_REQUEST['set_plan_time'];

$sysTypeName		='PPS';

$ftpInfo=getMSSFtpAccount();
//print_r($ftpInfo);
$ftpLoginName		= $ftpInfo[UserName];
$ftpLoginPwd		= $ftpInfo[Password];
$paramType			= $nPubSysParam;

//$commDefArr[0][oid]			= "2.1.3.4";
$commDefArr[0][oid]			= "2.5.4";
$commDefArr[0][paramType]	= $nPubSysParam;
$commDefArr[0][value]		= "00000000000000";

//$commDefArr[1][oid]			= "2.1.3.3";
$commDefArr[1][oid]			= "2.5.3";
$commDefArr[1][paramType]	= $nPubSysParam;
$commDefArr[1][value]		= 1;

$dataDefArr[0][tableName]	='pre_rent';
$dataDefArr[0][orderBy]		='id';
$dataDefArr[0][localFile]	='/usr/local/apache/htdocs/ftpFile/pre_rent.csv';
$dataDefArr[0][remoteFile]	='/tmp/pre_rent.csv';

$dataDefArr[1][tableName]	='pre_bill_sms';
$dataDefArr[1][orderBy]		='id';
$dataDefArr[1][localFile]	='/usr/local/apache/htdocs/ftpFile/pre_bill_sms.csv';
$dataDefArr[1][remoteFile]	='/tmp/pre_bill_sms.csv';

$dataDefArr[2][tableName]	='pre_bill_discount';
$dataDefArr[2][orderBy]		='hours';
$dataDefArr[2][localFile]	='/usr/local/apache/htdocs/ftpFile/pre_bill_discount.csv';
$dataDefArr[2][remoteFile]	='/tmp/pre_bill_discount.csv';

$dataDefArr[3][tableName]	='pre_bill_holiday';
$dataDefArr[3][orderBy]		='month,day';
$dataDefArr[3][localFile]	='/usr/local/apache/htdocs/ftpFile/pre_bill_holiday.csv';
$dataDefArr[3][remoteFile]	='/tmp/pre_bill_holiday.csv';

$dataDefArr[4][tableName]	='pre_comm_tariff';
$dataDefArr[4][orderBy]		='tariff_id';
$dataDefArr[4][localFile]	='/usr/local/apache/htdocs/ftpFile/pre_comm_tariff.csv';
$dataDefArr[4][remoteFile]	='/tmp/pre_comm_tariff.csv';

$dataDefArr[5][tableName]	='pre_mo_tariff';
$dataDefArr[5][orderBy]		='bill_id';
$dataDefArr[5][localFile]	='/usr/local/apache/htdocs/ftpFile/pre_mo_tariff.csv';
$dataDefArr[5][remoteFile]	='/tmp/pre_mo_tariff.csv';

$dataDefArr[6][tableName]	='pre_mt_tariff';
$dataDefArr[6][orderBy]		='bill_id';
$dataDefArr[6][localFile]	='/usr/local/apache/htdocs/ftpFile/pre_mt_tariff.csv';
$dataDefArr[6][remoteFile]	='/tmp/pre_mt_tariff.csv';

$dataDefArr[7][tableName]	='pre_gprs_tariff';
$dataDefArr[7][orderBy]		='tariff_id,record_id';
$dataDefArr[7][localFile]	='/usr/local/apache/htdocs/ftpFile/pre_gprs_tariff.csv';
$dataDefArr[7][remoteFile]	='/tmp/pre_gprs_tariff.csv';

$dataDefArr[8][tableName]	='pre_vas_mms_email_tariff';
$dataDefArr[8][orderBy]		='tariff_id,email_id';
$dataDefArr[8][localFile]	='/usr/local/apache/htdocs/ftpFile/pre_vas_mms_email_tariff.csv';
$dataDefArr[8][remoteFile]	='/tmp/pre_vas_mms_email_tariff.csv';

$dataDefArr[9][tableName]	='pre_vas_mms_retrieve_tariff';
$dataDefArr[9][orderBy]		='tariff_id,mms_retrieve_id';
$dataDefArr[9][localFile]	='/usr/local/apache/htdocs/ftpFile/pre_vas_mms_retrieve_tariff.csv';
$dataDefArr[9][remoteFile]	='/tmp/pre_vas_mms_retrieve_tariff.csv';

$dataDefArr[10][tableName]	='pre_vas_mms_send_tariff';
$dataDefArr[10][orderBy]		='tariff_id,mms_send_id';
$dataDefArr[10][localFile]	='/usr/local/apache/htdocs/ftpFile/pre_vas_mms_send_tariff.csv';
$dataDefArr[10][remoteFile]	='/tmp/pre_vas_mms_send_tariff.csv';

$strThisPage=$strTitleAdvanced.$strTitleSpace.$strTariffPlan.$strTitleSpace."Startup";

function getImpParamValue($sysId,$objIdStr,$instanceNo,$valueName)
{
	global $paramConf_table,$objConn;
	$DEBUG=0;

	$tmpSysIdArr = explode('_',$sysId);
	$sysTypeNo	= $tmpSysIdArr[0];
	$sysNo		= $tmpSysIdArr[1];
	$subSysNo	= $tmpSysIdArr[2];

	$paramDb = 'OBJ_'.$sysTypeNo;
	//获取参数定义表的表名，根据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' AND instanceNo = '$instanceNo' AND 

	//修改对应的参数值
	$getParamValueSql="SELECT $valueName FROM $paramTable 
			WHERE $objWhereStr and instanceNo <> ''
			";
	if($DEBUG) echo"<br> $getParamValueSql <br>";
	$getResult=mysqli_query($objConn,$getParamValueSql);
	echo mysqli_error($objConn);
	if(mysqli_num_rows($getResult) > 0){
		$paramRows = mysqli_fetch_array($getResult);

		$paramValue = $paramRows[0];
		return($paramValue);
	}else{
		return(-1);
	}
}

function setImpParamValue($sysId,$objIdStr,$instanceNo,$newValue)
{
	global $paramConf_table,$objConn;
	$DEBUG=0;

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

	$paramDb = 'OBJ_'.$sysTypeNo;
	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 ',将其去掉
	

	//根据参数类型，推出参数表的表名
	$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

function putImpFile($ftpCon)
{
	global $dataDefArr;
	for($j=0;$j<sizeof($dataDefArr);$j++){
		$localFile	=$dataDefArr[$j][localFile];
		$remoteFile	=$dataDefArr[$j][remoteFile];
		/* close ftp
		if(!ftp_put($ftpCon,$remoteFile,$localFile,FTP_ASCII)){
		*/
		if(!sftp_put($ftpCon,$remoteFile,$localFile,SFTP_ASCII)){
			echo "<br><font color=\"#FF0000\">Put file Failed</font>";
			return(-1);
		}else{
			echo "<br><font color=\"#0000FF\">Put {$dataDefArr[$j][remoteFile]} OK</font>";
		}
	}
	return(1);
}

function delImpFile()
{
	global $dataDefArr;
	for($j=0;$j<sizeof($dataDefArr);$j++){
		$localFile	=$dataDefArr[$j][localFile];
		@unlink ($localFile); 
	}
}

//==========================================================
//输入变量
//==========================================================
if ($DEBUG) echo "<br>plandate= $plan_year-$plan_month-$plan_day $plan_hour:$plan_minute:$plan_second";
if ($DEBUG) echo "<br>plan_remark=$plan_remark";
$commDefArr[0][value]	= $plan_year.$plan_month.$plan_day.$plan_hour.$plan_minute.$plan_second;
if ($DEBUG) echo "<br>commDefArr[1][value]={$commDefArr[1][value]}";

//==========================================================
//数据处理
//==========================================================

if($_SERVER['REQUEST_METHOD'] == "POST"){
	echo "<br><br><br><br><br>";
	$planStatTime= mktime($plan_hour, $plan_minute, $plan_second, $plan_month, $plan_day, $plan_year);
	if ($DEBUG) echo "<br>planStatTime=$planStatTime";
	$nowTime = time();
	if ($DEBUG) echo "<br>nowTime=$nowTime";
	if($planStatTime >= ($nowTime + 10)){
		//导出各项计划费率文件
		for($i=0;$i<sizeof($dataDefArr);$i++){
			//先删除
			@unlink($dataDefArr[$i][localFile]);
			sleep(1);
			//后导出
			$selSql=" SELECT * INTO OUTFILE '{$dataDefArr[$i][localFile]}'
						FIELDS 
							TERMINATED BY ',' 
						LINES 
							TERMINATED BY '\n'
						FROM 
							{$dataDefArr[$i][tableName]}
						ORDER BY {$dataDefArr[$i][orderBy]} ";
			if($DEBUG)echo "<br>selSql=$selSql";
			$selRes=mysqli_query($dbConn,$selSql);
			echo mysqli_error($dbConn);
		}
	}else{
		echo "<font size=3><br>Plan start time must later 10 second than now!</font>";
		echo "<p><br><a href=\"./planManage.php\"><img align=absBottom border=0 src=\"../../images/left.gif\" width=\"14\" height=\"14\">Back</a>";
		exit();
	}

	//查找正在运行的，状态为正常的PPS系统,来导入费率参数
	$getSysIdSql = "SELECT sysNo,subSysNo,ip 
				FROM $sysInfoTable
				WHERE sysTypeNo='$sysTypeNo'
				ORDER BY sysNo,subSysNo
			";
	if($DEBUG) echo "<br>getSysIdSql=$getSysIdSql";
	$getSysIdResult= mysqli_query($pubConn,$getSysIdSql);
	echo mysqli_error($pubConn);
	$ppsNum=mysqli_num_rows($getSysIdResult);
	if($ppsNum <= 0){
		echo "Error:Can not find any PPS's IP in system list,Please ADD it!";
		delImpFile();
		exit();
	}
	//顺次上载文件
	$impOkFlag=0;
	for($i=0;$i<$ppsNum;$i++){
		$getSysIdRow=mysqli_fetch_array($getSysIdResult);
		$sysName='PPS_'.$getSysIdRow[sysNo].'_'.$getSysIdRow[subSysNo];
		$dstSeverIp = $getSysIdRow[ip];
		if($DEBUG) echo "<br>sysId = $sysId";
		if($DEBUG) echo "<br>dstSeverIp = $dstSeverIp";

		echo "<br> Try to ftp tariff files to $sysName($dstSeverIp) ......";
		flush();

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

	//设置参数
	echo "<br> Try to send command to $sysTypeName ......";
	flush();


	//修改设备参数
	for($i=0;$i<sizeof($commDefArr);$i++){
		sleep(2);
		$instanceNo	= 0;
		$commState	= '01';
		$objId		= $commDefArr[$i][oid];
		$newValue	= $commDefArr[$i][value];
		$paramType	= $nPubSysParam;
		
		switch($paramType){
			case $nPubSubSysParam:
				$sysId=$sysTypeNo.'_'.$getSysIdRow[sysNo].'_99';
				break;
			case $nPubSysParam:
				$sysId=$sysTypeNo.'_99_99';
				break;
			default:
				break;
		}

		if($DEBUG) echo "<br>setImpParamValue($sysId,$objId,$instanceNo,$newValue)";
		//$chgResult	= setSysParamValue($sysId,$objId,$instanceNo,$newValue);
		$chgResult	= setImpParamValue($sysId,$objId,$instanceNo,$newValue);
		
		if($chgResult != -1){
			//send set command
			if($DEBUG) echo "<br>sysCommSend($sysId,$nSetComm,$objId)";
			$commStr	= sysCommSend($sysId,$nSetComm,$objId);
			sleep(2);
		}
		//根据读回的参数，判断费率是否导入成功
		if($i == 1){
			$waitTime	= 0;
			$maxWaitTime= 5;
			do{
				//获取导入费率命令执行状态
				$commStr	= sysCommSend($sysId,$nGetComm,$objId);
				$commResult = getImpParamValue($sysId,$objId,$instanceNo,'readValue');
				//echo "<br>get value=$commResult in $waitTime";
				flush();
				switch($commResult){
					case '1': //wait process
						echo "<br>Import ok, wait process";
						break;
					case '2': //in process
						echo "<br>In process";
						break;
					case '3': //process OK
						$waitTime = $maxWaitTime;
						echo "<br>Process OK";
						break;
					case '4': //process Failed
						$waitTime = $maxWaitTime;
						echo "<br>Process Failed";
						break;
					default:
						break;
				}
				if($commResult == 3 || $commResult == 5)
					break;
				$waitTime++;
				sleep(2);
			}while($waitTime < $maxWaitTime);
		}//end of if($i == 1)
		
		echo "OK!";
		flush();
	}//end of for($i=0;$i<sizeof($commDefArr);$i++)
	
	//由于参数处理底层程序对系统公用参数的连续设置有问题，
	//故把参数设置放到最后，一次设下去。
	if($chgResult != -1){
		//send set command
		if($DEBUG) echo "<br>sysCommSend($sysId,$nSetComm,'2.5.4')";
		$commStr	= sysCommSend($sysId,$nSetComm,'2.5.4');
		sleep(2);
		if($DEBUG) echo "<br>sysCommSend($sysId,$nSetComm,'2.5.3')";
		$commStr	= sysCommSend($sysId,$nSetComm,'2.5.3');
		sleep(2);
	}

	//插入到命令纪录表
	$sql="	REPLACE $tableName
			SET 
			comm_status			=	'1',
			take_affect_time	=	'$planStatTime',
			operator			=	'$userInfo[ID]',
			host_ip				=	'$userInfo[IP]',
			request_time		=	CURRENT_TIMESTAMP,
			finish_time			=	DEFAULT,
			remark				=	'$plan_remark',
			key_comm_id			=	'01'
			 ";
	if ($DEBUG) echo "<br>sql=$sql";
	$res=@mysqli_query($dbConn,$sql);
	echo mysqli_error($dbConn);

	echo "<br> <a href=\"$PHP_SELF\">&nbsp; << Return</a>";
	exit();
}

$this_year=date("Y", mktime());
$this_month=date("m", mktime()+24*60*60);
$this_day=date("d", mktime());

$next_year=$this_year+1;
$next_month=$this_month+1;
$next_day=date("d", mktime()+24*60*60);

//==========================================================
//数据显示
//==========================================================
?>

<?php 
	echo "<table id=\"table_up\" border=\"0\" width=\"100%\">";
	echo "<tr>";
	echo "<td width=\"50%\" align=\"left\">";
	echo "$strThisPage";
	echo "</td>";
	echo "<td width=\"50%\" align=\"right\" title=\"Help\">";
	showHelp($helpId);
	echo "</td>";
	echo "</tr>";
	echo "</table>";
adjust_title_tail();
adjust_content_head();
echo "<br>";
?>
<form method="POST" action="<?php echo "$PHP_SELF";?>" name="tariff_plan">
<table border="0">

<tr>
<td rowspan="2">
<?php echo"$strStartTime";?>&nbsp;&nbsp;
</td>
<td>Year</td>
<td></td>
<td>Month</td>
<td></td>
<td>Date</td>
<td width="10">&nbsp;</td>
<td>Hour</td>
<td></td>
<td>Minute</td>
<td></td>
<td>Second</td>
</tr>

<tr>
<td>
<select name="plan_year" size="1">
<option value="<?php echo "$this_year";?>" selected><?php echo "$this_year";?> </option> 
<option value="<?php echo "$next_year";?>"  ><?php echo "$next_year";?> </option>
</select>
</td>
<td>-</td>
<td>
<select name="plan_month" size="1">
<?php
for($i=1;$i<13;$i++){
	$i=(strlen($i) < 2)?'0'.$i:$i;
	$selected=($this_month == $i)?'selected':'';
	echo "<option value=\"$i\" $selected>$i </option> \n";
}
?>
</select>
</td>
<td>-</td>
<td>
<select name="plan_day" size="1">
<?php
for($i=1;$i<32;$i++){
	$i=(strlen($i) < 2)?'0'.$i:$i;
	$selected=($next_day == $i)?'selected':'';
	echo "<option value=\"$i\" $selected>$i </option> \n";
}
?>
</select>
</td>
<td width="10">&nbsp;</td>
<td>
<select name="plan_hour" size="1">
<?php
for($i=0; $i<24; $i++){
	$i=(strlen($i) < 2)?'0'.$i:$i;
	$selected=($i == '00')?'selected':'';
	echo "<option value=\"$i\" $selected>$i </option> \n";
}
?>
</select>
</td>
<td>:</td>
<td>
<select name="plan_minute" size="1">
<?php
for($i=0;$i<60;$i++){
	$i=(strlen($i) < 2)?'0'.$i:$i;
	$selected=('00' == $i)?'selected':'';
	echo "<option value=\"$i\" $selected>$i </option> \n";
}
?>
</select>
</td>
<td>:</td>
<td>
<select name="plan_second" size="1">
<?php
for($i=0;$i<60;$i++){
	$i=(strlen($i) < 2)?'0'.$i:$i;
	$selected=('00' == $i)?'selected':'';
	echo "<option value=\"$i\" $selected>$i </option> \n";
}
?>
</select>
</td>
</tr>

<tr>
<td><?php echo "$strRemark";?></td>
<td colspan="12"><input type="text" name="plan_remark" size="52" class="text"></td>
</tr>

<tr>
<td><input type="submit" name="set_plan_time" value="<?php echo $strSubmit; ?>" class="button"></td>
<td>&nbsp;&nbsp;&nbsp;&nbsp;</td>
</tr>
</table>
</form>

<?php
//key_comm_id comm_status take_affect_time  operator  host_ip  request_time  finish_time  remark
$sel_sql="SELECT * FROM $tableName ORDER BY request_time DESC";
//echo $sel_sql;
$result=mysqli_query($dbConn,$sel_sql);
$result_rows=mysqli_fetch_array($result);
$rows_num=@mysqli_num_rows($result);
echo mysqli_error($dbConn);
if(!$rows_num){
	exit();
	echo "$strNoTariffPlan";
}
echo "<table border=\"1\" width=\"100%\" cellpadding=\"2\" cellspacing=\"0\"  bordercolor=\"#666666\" bordercolordark=\"#FFFFFF\" bgcolor=\"#FFFFFF\">";
echo "<tr bgcolor=\"#E6E6E6\">";
echo "<td align=\"center\">$strStartTime</td>"; 
echo "<td align=\"center\">$strSender</td>"; 
echo "<td align=\"center\">$strSourceIP</td>"; 
echo "<td align=\"center\">$strAppealTime</td>"; 
echo "<td align=\"center\" width=\"40%\">$strRemark</td>";
echo "</tr>";
echo "<tr>";
do{
	$take_affect_time = date("Y-m-d H:i:s",$result_rows[take_affect_time]);
	echo "<td align=\"center\">$take_affect_time</td>"; 
	echo "<td align=\"center\">$result_rows[operator]</td>"; 
	echo "<td align=\"center\">$result_rows[host_ip]</td>"; 
	echo "<td align=\"center\">$result_rows[request_time]</td>"; 
	echo "<td colspan=\"5\">$result_rows[remark] &nbsp;</td>"; 
	echo "</tr>";
}while($result_rows=mysqli_fetch_array($result));
echo "</table>";
adjust_content_tail();
?>

</body>
</html>
