<?php
/*********************************************************      
 程序说明：         
    功能说明：将数据库中的数据以csv文件的格式导出。
              
    调用关系：调用: header.inc,connectdb_prepaid.inc     
              被调用:        
 
    变量说明： var $key_menu_id 
               get from load_csv_list.php,and use $key_menu_id can get $server_name,$db_name,$table_name from database;

    作者：    
      
修改注释：      
NO.1      
姓名：            
时间：      
修改说明：      
*********************************************************/

@set_time_limit(600);
if (!session_id()) session_start();

if (isset($_SESSION["userInfo"])){
	if (!isset($userInfo)) $userInfo = $_SESSION["userInfo"];
	$userName=$userInfo['ID'];
	//echo "userName=$userName";
}
require("../../inc/lib.inc");
$key_menu_id = $_REQUEST['key_menu_id'];
$sel_name = $_REQUEST['sel_name'];
$file_clean=1;
$download_all=$_REQUEST['download_all'];
if($download_all==1)//download all parameters
{
	$start_flag = "start of ";
	$end_flag = "end of ";
	$path='/usr/local/apache/htdocs/db_backup/paramConf/';
	$date_num=date("YmdHis", mktime(date("H"),date("i"),date("s"),date("m"),date("d"),date("Y")));
	$keyMenuIdArr=explode(",",$str_keyMenuId);
	for($k_no=0; $k_no<sizeof($keyMenuIdArr); $k_no++)
	{
		//update last download time 
		$update_sql="UPDATE $syscsvconf_table SET last_download = CURRENT_TIMESTAMP WHERE key_menu_id='{$keyMenuIdArr[$k_no]}'";
		mysqli_query($pubConn,$update_sql);
		
		//get load out information
		$info_sql="SELECT * FROM $syscsvconf_table  WHERE key_menu_id='{$keyMenuIdArr[$k_no]}'";
		$result=mysqli_query($pubConn,$info_sql);
		$info_rows=mysqli_fetch_array($result);
		$server_name	= $info_rows[server_name];
		$db_name		= $info_rows[db_name];
		$table_name		= $info_rows[table_name];
		$where_find		= $info_rows[where_find];
		$menu_name_2	= $info_rows[menu_name_2];
		$menu_name		= $info_rows[menu_name];


		$csvFileNameArr[$k_no] = $menu_name_2 . '-' . $date_num;
		if(0)echo "<br>csvFileNameArr[$k_no] $csvFileNameArr[$k_no]";
		$file_full_name = $path . "{$csvFileNameArr[$k_no]}.csv";
		$objDb=$db_name;
		$objDbConn = mysqli_connect($OMC_server[0]['host'],$OMC_server[0]['user'],$OMC_server[0]['password'],$objDb);	
		if (is_file($file_full_name))
			unlink($file_full_name);
		$csvFileUpdateSql="	SELECT * 
				INTO OUTFILE '{$file_full_name}' 
				FIELDS TERMINATED BY ',' 
				LINES TERMINATED BY '\n' 
				FROM $table_name 
			";		
		$csvFileUpdateResult = mysqli_query($objDbConn ,$csvFileUpdateSql);
		echo mysqli_error($objDbConn);		
	}
	
	$allone_filename = "all-" . $sel_name . "-" . $date_num . ".csv";
	$allone_fullName = $path . $allone_filename;
	if(is_file($allone_fullName))
	{
		unlink($allone_fullName);
	}
	$fd=fopen($allone_fullName, "wa");
	for($i=0; $i< sizeof($csvFileNameArr); $i++)
	{
		$tmpfile = $path . "{$csvFileNameArr[$i]}.csv";
		$nameline = $csvFileNameArr[$i];
		$nameline_start = $start_flag . $nameline . ".csv and keyMenuId=".$keyMenuIdArr[$i]."\n";
		fputs($fd,$nameline_start);
		$tmpfd=fopen($tmpfile, "r");
		while(!feof($tmpfd))
		{
			$line=fgets($tmpfd,4096);
			fputs($fd,$line);
		}
		$nameline_end = $end_flag . $nameline . "\n";
		fputs($fd,$nameline_end);
		fclose($tmpfd);
		unlink($tmpfile);
	}
	fclose($fd);
	
	header("Content-type: application/csv");
	header("Content-Disposition: attachment; filename=$allone_filename");
	$file_path = $path . $allone_filename;
	readfile($file_path);
	
	if($file_clean && is_file($file_path))
		unlink($file_path);
	
	$where = "description=\"sel_name is $sel_name\"";
	$update_sql="UPDATE $syscsvconf_table SET last_download = CURRENT_TIMESTAMP WHERE $where";
	mysqli_query($pubConn,$update_sql);

	//echo " <body onblur=\"opener=null;window.close();\" scroll=\"no\"> ";
	//echo " <meta http-equiv=\"refresh\" content=\"0;url=../../../db_backup/$allone_filename\"> ";
}
else//download respectively
{
	//update last download time 
	$update_sql="UPDATE $syscsvconf_table SET last_download = CURRENT_TIMESTAMP WHERE key_menu_id='$key_menu_id'";
	mysqli_query($pubConn,$update_sql);
	
	//get load out information
	$info_sql="SELECT * FROM $syscsvconf_table  WHERE key_menu_id='$key_menu_id'";
	$result=mysqli_query($pubConn,$info_sql);
	$info_rows=mysqli_fetch_array($result);
	$server_name	= $info_rows[server_name];
	$db_name		= $info_rows[db_name];
	$table_name		= $info_rows[table_name];
	$where_find		= $info_rows[where_find];
	$menu_name_2	= $info_rows[menu_name_2];
	$menu_name		= $info_rows[menu_name];

	if(($table_name=='sysOperLog')||($table_name=='sysAlarmLog'))
	{
		$tmpMenuArr=explode('_',$menu_name_2);
		$day=date("md",mktime(0,0,0,date("m"),date("d")-($tmpMenuArr[1]),date("Y")));
		$date_num=date("YmdHis", mktime(date("H"),date("i"),date("s"),date("m"),date("d"),date("Y")));
		$file_name=$tmpMenuArr[0].$day.'-'.$date_num;
		$bgn_time=date("Y-m-d H:i:s", mktime(0,0,0,date("m"),date("d")-$tmpMenuArr[1],date("Y")));
		$end_time=date("Y-m-d H:i:s", mktime(0,0,0,date("m"),date("d")-$tmpMenuArr[1]+1,date("Y")));
		if($table_name=='sysAlarmLog')
			$where_find=" WHERE alarmTime>='$bgn_time' AND alarmTime<='$end_time'";
		else
			$where_find=" WHERE datetime>='$bgn_time' AND datetime<='$end_time'";
	
	}
	else
	{
		//echo "$where<br>";
		$date_num=date("YmdHis", mktime(date("H"),date("i"),date("s"),date("m"),date("d"),date("Y")));
		if($sel_name == "network")
		{
			$file_name = "param-";
			$file_name=$file_name.$menu_name_2.'-'.$date_num;
		}
		else
		{
			$file_name=$menu_name_2.'-'.$date_num;
		}
	}
	$ext = "csv";
	/*
	header("Content-disposition: filename=$file_name.$ext");
	header("Content-type: application/octetstream");
	header("Pragma: no-cache");
	header("Expires: 0");
	*/
		
	// doing some DOS-CRLF magic...
	$client=getenv("HTTP_USER_AGENT");
	//if(ereg('[^(]*\((.*)\)[^)]*',$client,$regs)){
	if(preg_match("/[^(]*\((.*)\)[^)]*/",$client,$regs)){
		$os = $regs[1];
		
		// this looks better under WinX
	//	if (eregi("Win",$os)) 
	if (preg_match("/Win/i",$os))
	$crlf="\r\n";
	}
	
	//---------insert log-------
	//$log_name	   = "Download-- '$db_name' '$table_name'";
	//$selectedLanguage=$userInfo[language];
	//if($selectedLanguage == 'eng')
		$log_name	   = "Download--"."'$menu_name_2'";
	//else
	//	$log_name	   = "Download--"."'$menu_name'";
	insertLog("$log_name");
	//--------
	 
	function my_csvhandler($sql_insert) {   
	    global $crlf, $asfile;        //$crlf=="\n"
	    if(empty($asfile))
	        echo htmlspecialchars("$sql_insert$crlf");
	    else
	        echo "$sql_insert $crlf";
	 }
	
	//get_table_csv($link[0],$db_name, $table_name, $where_find, "my_csvhandler")
	if(0)
	{
		echo "<br>db_name:$db_name.$table_name";
		//echo "	SELECT * INTO OUTFILE '$csvFileName' FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' FROM $table_name ";
	//	exit;
	}
	if ( 1|| ($table_name == 'paramConf') 
		||($table_name == 'subsParamConf_0')
		||($table_name == 'subsParamConf_1')
		||($table_name == 'logAttrDef_0')
		||($table_name == 'logAttrDef_1'))
	{
		$file_name = $menu_name_2.'-'.$date_num.'.csv';
		$csvFileName = '/usr/local/apache/htdocs/db_backup/paramConf/'.$file_name;
		if (is_file($csvFileName))
			unlink("$csvFileName");
		$csvFileUpdateSql="	SELECT * 
				INTO OUTFILE '$csvFileName' 
				FIELDS TERMINATED BY ',' 
				LINES TERMINATED BY '\n' 
				FROM $table_name 
			";
		//	echo $csvFileUpdateSql;
			$objDbConn = mysqli_connect($OMC_server[0]['host'],$OMC_server[0]['user'],$OMC_server[0]['password'],$db_name);	

		if(stristr($table_name,"sysAlarmLog"))
		{
			$csvFileUpdateSql="SELECT sysConf.sysTypeName,
																$table_name.sysNo,
																$table_name.subSysNo,
																sysAlarmLevelDesc.desc_2,
																sysAlarmConf.alarmDesc_2,
																$table_name.alarmTime,
																$table_name.clearTime,
																$table_name.clearBy 
												INTO OUTFILE '$csvFileName' FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' 
												FROM 
												((($table_name INNER JOIN sysConf ON sysConf.sysTypeNo=$table_name.sysTypeNo) INNER JOIN sysAlarmConf ON $table_name.compCode=sysAlarmConf.compCode AND $table_name.alarmCode=sysAlarmConf.alarmCode AND $table_name.sysTypeNo=sysAlarmConf.sysTypeNo) INNER JOIN sysAlarmLevelDesc ON sysAlarmConf.alarmLevel=sysAlarmLevelDesc.level)
												";
			
			
		}
		
		//echo "table_name = $table_name<br>";
		//echo "<br>$csvFileUpdateSql";
		$csvFileUpdateResult = mysqli_query($objDbConn ,$csvFileUpdateSql);
		echo mysqli_error($objDbConn);
		
		//echo " <body onblur=\"opener=null;window.close();\" scroll=\"no\"> ";
		//echo " <meta http-equiv=\"refresh\" content=\"0;url=../../../db_backup/paramConf/$file_name\"> ";
		header("Content-type: application/csv");
		header("Content-Disposition: attachment; filename=$file_name");
		
		//use for download csv in https
		header('Expires: 0'); 
		header('Pragma: public'); 
		header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); 
		header('Cache-Control: public'); 

		readfile($csvFileName);
		//if($file_clean)
		//	unlink($csvFileName);
		//echo " <meta http-equiv=\"refresh\" content=\"0;url=./load_csv_list.php?sel_name=$sel_name\"> ";
	}
	else
	{
		header("Content-disposition: filename=$file_name.$ext");
		header("Content-type: application/octetstream");
		header("Pragma: no-cache");
		header("Expires: 0");
		get_table_csv($link[0],$db_name, $table_name, $where_find, "my_csvhandler");
	}
}
?>