#!/usr/bin/php
<?
chdir(dirname(__FILE__));
require_once('../nmail/include/global.php');
require_once("include/mail_lib.php");
require_once('include/admin_lib.php');
require_once("include/file.php");

// 웹상에서의 실행방지.
if ($_SERVER['DOCUMENT_ROOT'] || $_SERVER['SERVER_SOFTWARE'])
{
	die("Access Denied");
}	// if()

$_time = time();

// [2009-05-06] root권한으로만 실행되도록 함.
	if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN')
	{
		ob_start();
		system('whoami');
		$whoami = trim(ob_get_contents());
		ob_end_clean();
		if ($whoami != '' && $whoami != 'root')
		{
			die("[에러]root 계정에서 실행하셔야 합니다.  패치가 적용되지 않았습니다.\n");
		}	// if()
	}	// if()


echo "[Nmail PHP]변경된 내용의 패치를 적용중입니다.  완료 메세지가 나올때까지 중단하지 마십시오.\n\n";
echo "  안내) 작업도중 이미 패치된 부분은 자동으로 넘어가므로, 중복실행하더라도 에러가 생기지는 않습니다.\n\n";


// [2009-05-07] Windows UTF-8 버젼에서는 한글출력을 위해 update_db.php 파일이 euc-kr로 되어 있음.  그러나 DB나 파일에 저장되는 부분은 UTF-8로 변환필요.
function win_utf8_conv($str)
{
	if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' && strtoupper($G_SYS[CHARSET]) == 'UTF-8')
		$str = iconv_fix('CP949', $str, 'UTF-8');
	return $str;
}	// function()


// set
set_time_limit(0);

// [2008-10-21] 업데이트시 한번만 실행하는 루틴의 임시파일 저장 디렉토리
$updated_dir = dirname(__FILE__).DIRECTORY_SEPARATOR.'updated';
if (!is_dir($updated_dir))
	mkdir($updated_dir);


// [2008-02-22]대용량첨부/웹하드 업로드 디렉토리 생성.
	if (!is_dir($UPLOAD_ROOT_NEW))
	{
		mkdir($UPLOAD_ROOT_NEW, 0777);
		chmod($UPLOAD_ROOT_NEW, 0777);		// mkdir 에서 0777로 지정해도 0755 로 생성되는 문제있음.
	}	// if()

// [2008-03-26] 기존 업로드 디렉토리를 옮겨옴.
	if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN')
	{
		$cmd_mv = 'move';
		$cmd_rm = 'rmdir/q/s';
		$crlf = "\r\n";
	} else
	{
		$cmd_mv = 'mv';
		$cmd_rm = 'rm -rf';
		$crlf = "\n";

		// [2008-03-31] 윈도우 전용 bat 파일 삭제
		if (file_exists('update_db.bat'))
			unlink('update_db.bat');
		if (file_exists('mysql_repair.bat'))
			unlink('mysql_repair.bat');
		if (file_exists('mail_box_dbsync_all.bat'))
			unlink('mail_box_dbsync_all.bat');
		if (file_exists('mail_box_dbsync_all_auto.bat'))
			unlink('mail_box_dbsync_all_auto.bat');

		// [2008-05-27] 사용하지 않는 파일 삭제
		if (file_exists('perm_change_bigfile.sh'))
			unlink('perm_change_bigfile.sh');
		if (file_exists('perm_change_mailroot.sh'))
			unlink('perm_change_mailroot.sh');

		// [2008-05-27] 메일 로그 뷰어 추가
		$file = 'perm_change.sh';
		$file_endstr = 'echo "Complete!!!"';
		$data = file_get_contents($file);
		if (strpos($data, '# Mail logs') === false)
		{
			$add = "\n";
			$add .= "# Mail logs\n";
			$add .= "chmod 711 /var/MailRoot/logs/\n";
			$add .= "\n";
			$add .= "# Upload data\n";
			$add .= "chmod -R 777 ../upload/\n";
			$add .= "\n";

			$data = str_replace("\r\n", "\n", $data);		// unix 형식으로 변환

			$_sp = strpos($data, $file_endstr);
			if ($_sp === false)
			{
				$data .= $add;
			} else		// Complete 문자열이 있을 때 해당 문자열 윗쪽에 추가함.
			{
				$data = str_replace($file_endstr, $add.$file_endstr, $data);
			}	// if()
			if (strlen($data) > 10)
			{
				file_write($file, $data);
				chmod('/var/MailRoot/logs/', 0711);
				echo " [OK]2.5.0 부터 ".$file." 스크립트에 아래 명령이 추가되었습니다.\n";
				echo trim($add)."\n\n";
			}	// if()
		}	// if()

		// [2009-02-09] 편지지 업로드 디렉토리 추가
		$file = 'perm_change.sh';
		$file_endstr = 'echo "Complete!!!"';
		$data = file_get_contents($file);
		if (strpos($data, '# Letter data') === false)
		{
			$add = "\n";
			$add .= "# Letter data\n";
			$add .= "cd ../\n";
			$add .= "chmod -R 777 nmail/letter/\n";
			$add .= "\n";

			$data = str_replace("\r\n", "\n", $data);		// unix 형식으로 변환

			$_sp = strpos($data, $file_endstr);
			if ($_sp === false)
			{
				$data .= $add;
			} else		// Complete 문자열이 있을 때 해당 문자열 윗쪽에 추가함.
			{
				$data = str_replace($file_endstr, $add.$file_endstr, $data);
			}	// if()
			if (strlen($data) > 10)
			{
				file_write($file, $data);
				if (!is_dir($G_SYS['PAGE_ROOT'].'/letter'))
					mkdir($G_SYS['PAGE_ROOT'].'/letter', 0777);
				chmod($G_SYS['PAGE_ROOT'].'/letter', 0777);		// mkdir 에서 0777로 지정해도 0755 로 생성되는 문제있음.
				echo " [OK]2.5.0 부터 ".$file." 스크립트에 아래 명령이 추가되었습니다.\n";
				echo trim($add)."\n\n";
			}	// if()
		}	// if()

		// [2008-05-27] 백업 스크립트에서 업로드 디렉토리 변경 부분 반영
		$file = '../_backup/backup.sh';
		// [2013-07-15] 백업 스크립트가 없는 경우에는 생략.
		if (file_exists($file))
		{
			$data = file_get_contents($file);
			if (strpos($data, '# Upload data') === false)
			{
				$add = "\n";
				$add .= "# Upload data\n";
				$add .= "tar zcvf \$BACKUP_DIR/\$FN.upload.tar.gz upload/ --exclude=\"upload/session/*\"\n";
				$add .= "\n";

				$data = str_replace("\r\n", "\n", $data);		// unix 형식으로 변환

				$data = str_replace('tar zcvf $BACKUP_DIR/$FN.board.tar.gz nmail/data/board/', '#tar zcvf $BACKUP_DIR/$FN.board.tar.gz nmail/data/board/', $data);		// 기존 board 폴더 백업 생략.

				$file_endstr = 'echo "Backup Complete!!!"';
				$_sp = strpos($data, $file_endstr);
				if ($_sp === false)
				{
					$data .= $add;
				} else		// Complete 문자열이 있을 때 해당 문자열 윗쪽에 추가함.
				{
					$data = str_replace($file_endstr, $add.$file_endstr, $data);
				}	// if()

				if (strlen($data) > 10)
				{
					file_write($file, $data);
					echo " [OK]2.5.0 부터 ".$file." 스크립트에 아래 명령이 추가되었습니다.\n";
					echo trim($add)."\n\n";
				}	// if()
			}	// if()

			// [2013-07-12] 백업 스크립트에서 파일목록을 보여주지 않도록 변경.
			$file = '../_backup/backup.sh';
			$data = file_get_contents($file);
			if (strpos($data, "\ntar zcvf") !== false)
			{
				$data_modify = str_replace("\ntar zcvf", "\ntar zcf", $data);
				if (strlen($data_modify) != strlen($data))
				{
					file_write($file, $data_modify);
					echo " [OK]2.6.1 부터 ".$file." 스크립트에서 파일이 많을 경우를 고려하여, 압축시 파일목록을 보여주지 않도록 변경되었습니다.\n";
					echo "    tar zcvf => tar zcf\n\n";
				}	// if()
			}	// if()
		}	// if()

		// [2008-05-27] 디비테이블최적화 스크립트를 매일 새벽에 실행되도록 등록해둠
		$file_php = dirname($G_SYS[PAGE_ROOT]).'/tools/mysql_optimize.php';
		$file_cron = '/etc/cron.daily/nmail_mysql_optimize.cron';
		if (!file_exists($file_cron) &&is_dir(dirname($file_cron)) && file_exists($file_php))
		{
			symlink($file_php, $file_cron);
			echo " [OK]2.5.0 부터 디비테이블 최적화 스크립트가 크론데몬에 자동 등록되었습니다.\n";
			echo "    ".$file_cron."\n\n";
		}	// if()
	}	// if()

	if ($UPLOAD_ROOT_OLD != '' && $UPLOAD_ROOT != '')
	{
		if (is_dir($UPLOAD_ROOT_OLD . "/session") && !is_dir($UPLOAD_ROOT . "/session"))
			system($cmd_mv.' '.$UPLOAD_ROOT_OLD . "/session".' '.$UPLOAD_ROOT . "/session");

		if (is_dir($UPLOAD_ROOT_OLD . "/config") && !is_dir($UPLOAD_ROOT . "/config"))
			system($cmd_mv.' '.$UPLOAD_ROOT_OLD . "/config".' '.$UPLOAD_ROOT . "/config");

		if (is_dir($UPLOAD_ROOT_OLD . "/member") && !is_dir($UPLOAD_ROOT . "/member"))
			system($cmd_mv.' '.$UPLOAD_ROOT_OLD . "/member".' '.$UPLOAD_ROOT . "/member");

		if (is_dir($UPLOAD_ROOT_OLD . "/board") && !is_dir($UPLOAD_ROOT . "/board"))
			system($cmd_mv.' '.$UPLOAD_ROOT_OLD . "/board".' '.$UPLOAD_ROOT . "/board");

		if (is_dir($UPLOAD_ROOT_OLD . "/mailtemp"))
		{
			system($cmd_rm.' '.realpath($UPLOAD_ROOT_OLD . "/mailtemp"));
			echo " [OK]2.4.0 부터 업로드 디렉토리가 변경되었습니다.\n";
			echo "    ".$UPLOAD_ROOT_OLD." -> ".$UPLOAD_ROOT."\n\n";
		}	// if()
	}	// if()


// [2009-04-02] 리턴메일로그, 스팸차단로그를 '메일로그 - SMTP' 와 연동
// [2009-05-07] 기존에 경로가 바뀌므로 파일을 교체하지 않고 수정하도록 변경.(Linux/Solaris/Windows 호환)
	$filter_tab_argv = '"@@FILE"	"@@FROM"	"@@RRCPT"	"@@REMOTEADDR"	"@@USERAUTH"	"@@RCPT"	"@@RFROM"	"@@MSGREF"';
	if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN')
	{
		$filters_dir = 'filters_win';
		$filter_in = dirname($G_SYS[PAGE_ROOT]).'/tools/filter.bat';
		$filter_out = dirname($G_SYS[PAGE_ROOT]).'/tools/filter_out.bat';
	} else if (strtoupper(substr(PHP_OS, 0, 3)) === 'SUN')
	{
		$filters_dir = 'filters_sol';
		$filter_in = dirname($G_SYS[PAGE_ROOT]).'/nmail/filter.sh.php';
		$filter_out = dirname($G_SYS[PAGE_ROOT]).'/nmail/filter_out.sh.php';
	} else
	{
		$filters_dir = 'filters';
		$filter_in = dirname($G_SYS[PAGE_ROOT]).'/nmail/filter.sh.php';
		$filter_out = dirname($G_SYS[PAGE_ROOT]).'/nmail/filter_out.sh.php';
	}	// if()

	$file = dirname($G_SYS[MAIL_ROOT]).'/filters/nmail.tab';
	$file_new = dirname(__FILE__).'/mailserver/'.$filters_dir.'/nmail.tab';
	if (!file_exists($file) || strpos(file_get_contents($file), '@@MSGREF') === false)
	{
		$data = '"'.$filter_in.'"	'.$filter_tab_argv;
		file_write($file, $data, 0777);
		#echo " [OK]2.5.0 부터 ".$file." 파일이 갱신되었습니다.\n";
	}	// if()

	$file = dirname($G_SYS[MAIL_ROOT]).'/filters/nmail_out.tab';
	$file_new = dirname(__FILE__).'/mailserver/'.$filters_dir.'/nmail_out.tab';
	if (!file_exists($file) || strpos(file_get_contents($file), '@@MSGREF') === false)
	{
		$data = '"'.$filter_out.'"	'.$filter_tab_argv;
		file_write($file, $data, 0777);
		#echo " [OK]2.5.0 부터 ".$file." 파일이 갱신되었습니다.\n";
	}	// if()


// [2009-04-03] DNS 직접 지정 - /etc/resolv.conf 에 등록된 DNS를 자동 입력하도록 함.
	if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN' && file_exists('/etc/resolv.conf'))
	{
		$resolv = file('/etc/resolv.conf');
		$dns = array();
		for ($i=0; $i<sizeof($resolv); $i++)
		{
			preg_match('/^nameserver[ \t]+((([0-9]{1,3}){1}\.){3}([0-9]{1,3}){1})?/i', $resolv[$i], $mc);
			if ($mc[1] != '')
			{
				$dns[] = $mc[1];
			}	// if()
		}	// for()

		if (sizeof($dns) > 0)
		{
			$dns[] = '164.124.101.2';
			$dns[] = '168.126.63.2';
			$dns[] = '203.248.252.2';
			$dns = array_values(array_unique($dns));

			$file = $UPLOAD_ROOT.'/config/nmail_server.php';
			if (file_exists($file))
			{
				$data = file_get_contents($file);
				if (strpos($data, 'S_DNS_DIRECT') === false)
				{
					$exp = $dns;
					$_s_dns_direct = '';
					$_s_dns_direct_cfg = '';
					for($i=0; $i<sizeof($exp); $i++)
					{
						$chk_id = trim($exp[$i]);
						if ($chk_id != '')
						{
							if ($_s_dns_direct != '')
								$_s_dns_direct .= ",";
							$_s_dns_direct .= "'".$chk_id."'";

							if ($_s_dns_direct_cfg != '')
								$_s_dns_direct_cfg .= ",";
							$_s_dns_direct_cfg .= $chk_id.":tcp";
						}
					}	// for()
					$data = str_replace('?>', win_utf8_conv("\$G_SYS[S_DNS_DIRECT] = array(".$_s_dns_direct.");		// DNS 직접 지정\n?>"), $data);
					file_write($file, $data, 0777);

					// mailserver
					if ($_s_dns_direct_cfg != '')
					{
						$cfgs = nm_cfgfileget('server.tab');
						$cfgs = nm_cfg_val_set($cfgs, 'SmartDNSHost', $_s_dns_direct_cfg);
						//nm_cfgfileset('server.tab', $cfgs);
						$tmp = '';
						foreach($cfgs as $var) {
							if (trim($var[0]) != '')
								$tmp .= '"'.implode("\"\t\"", $var) . "\"\n";
						}
						if (trim($tmp) != '')
							file_write(dirname($G_SYS[MAIL_ROOT]).'/server.tab', $tmp);
					}	// if()

					echo " [OK]2.5.0 부터 [메일서버관리 >> 서버 설정]에서 'DNS 직접 지정'항목이 추가되었습니다.\n";
					echo "     /etc/resolv.conf 에 등록된 DNS가 자동으로 추가되었습니다.\n";
					echo implode(', ', $dns)."\n\n";
				}	// if()
			}	// if()
		}	// if()
	}	// if()


// [2009-04-04] 서비스가 중단되었거나, 권장하지 않는 RBL 자동삭제
$s_spam_rbl_clean = $updated_dir.DIRECTORY_SEPARATOR.'s_spam_rbl_clean';
if (!file_exists($s_spam_rbl_clean))
{
	if (in_array('list.dsbl.org', $G_SYS[S_SPAM_RBL]) || in_array('cblless.anti-spam.org.cn', $G_SYS[S_SPAM_RBL]))
	{
		$exp = $G_SYS[S_SPAM_RBL];
		$_s_spam_rbl = '';
		$_s_spam_rbl_cfg = '';
		for($i=0; $i<sizeof($exp); $i++)
		{
			$chk_id = trim($exp[$i]);
			if ($chk_id != '' && $chk_id != 'list.dsbl.org' && $chk_id != 'cblless.anti-spam.org.cn')
			{
				if ($_s_spam_rbl != '')
					$_s_spam_rbl .= ",";
				$_s_spam_rbl .= "'".$chk_id."'";
				$_s_spam_rbl_cfg .= ",".$chk_id.".:0";
			}
		}	// for()

		$file = $UPLOAD_ROOT.'/config/nmail_server.php';
		$data = file_get_contents($file);
		$data = str_replace("\$G_SYS[S_SPAM_RBL]", "//\$G_SYS[S_SPAM_RBL]", $data);
		$data = str_replace('?>', win_utf8_conv("\$G_SYS[S_SPAM_RBL] = array(".$_s_spam_rbl.");		// 해외 RBL 목록\n?>"), $data);
		file_write($file, $data, 0777);

		// mailserver
		switch ($G_SYS[S_SPAM_LEVEL])
		{
			case 'SAFETY':
				$CustMapsList = '';
				break;

			case 'BASIC':
				$CustMapsList = 'kisarbl.passkorea.net.:0';
				break;

			case 'POWER':
				$CustMapsList = 'kisarbl.passkorea.net.:0'.$_s_spam_rbl_cfg;
				break;

			default:
				$CustMapsList = '';
				break;
		}	// switch()
		$cfgs = nm_cfgfileget('server.tab');
		$cfgs = nm_cfg_val_set($cfgs, 'CustMapsList', $CustMapsList);
		//nm_cfgfileset('server.tab', $cfgs);
		$tmp = '';
		foreach($cfgs as $var) {
			if (trim($var[0]) != '')
				$tmp .= '"'.implode("\"\t\"", $var) . "\"\n";
		}
		if (trim($tmp) != '')
			file_write(dirname($G_SYS[MAIL_ROOT]).'/server.tab', $tmp);
	}	// if()

	touch($s_spam_rbl_clean);
	echo " [OK]2.5.0 부터 아래 '해외 RBL 목록'이 자동 삭제됩니다.\n";
	echo "     list.dsbl.org - 서비스중단\n";
	echo "     cblless.anti-spam.org.cn - 국내업체가 블랙IP로 등록된 경우가 많음\n\n";
}	// if()


// [2009-06-23] 구버젼 로그인 이미지 자동교체
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN')
{
	$skindir = dirname($G_SYS[PAGE_ROOT]).'/nmail/skin/main';
} else if (strtoupper(substr(PHP_OS, 0, 3)) === 'SUN')
{
	$skindir = dirname($G_SYS[PAGE_ROOT]).'/nmail/skin/main';
} else
{
	$skindir = dirname($G_SYS[PAGE_ROOT]).'/nmail/skin/main';
}	// if()
if ($dh = opendir($skindir)) {
	while (($file = readdir($dh)) !== false) {
		if ($file!="." && $file!=".." && is_dir($skindir.'/'.$file))
		{
			$_img = $skindir.'/'.$file.'/img/bg_login.jpg';
			if (file_exists($skindir.'/'.$file.'/img/bg_login.jpg'))
			{
				$_stat = stat($_img);
				if ($_stat['size'] == 66033)
				{
					copy(dirname(__FILE__).DIRECTORY_SEPARATOR.'updated'.DIRECTORY_SEPARATOR.'bg_login.jpg', $_img);
					echo " [OK]2.5.0 부터 구버젼의 기본 로그인 배경 이미지가 교체되었습니다.\n";
					echo "   ".$_img."\n";
				}	// if()
			}	// if()
		}	// if()
	}
	closedir($dh);
}


// [2009-06-26] filtertemp 에 남아있는 찌꺼기 삭제
$filtertemp_clear = $updated_dir.DIRECTORY_SEPARATOR.'filtertemp_clear';
if (!file_exists($filtertemp_clear))
{
	if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN')
	{
		system('del /q '.str_replace('/', '\\', dirname($G_SYS[PAGE_ROOT]).'/filtertemp/*'));
	} else
	{
		system('find '.dirname($G_SYS[PAGE_ROOT]).'/filtertemp/ -size 0 -exec rm -f {} \;');
	}	// if()
	echo " [OK]2.5.1 filtertemp 디렉토리안의 찌거기 파일들을 삭제하였습니다.\n";
	echo trim($add)."\n\n";
	touch($filtertemp_clear);
}	// if()



// [2010-05-17] SMTP submission port & SMTP AUTH (587)
// [2013-07-15] Windows까지 지원.
$mailserver_smtp_587 = $updated_dir.DIRECTORY_SEPARATOR.'mailserver_smtp_587_2';
if (!file_exists($mailserver_smtp_587))
{
	// mailserver
	$cfgs = nm_cfgfileget('server.tab');

	if (nm_cfg_val_get($cfgs, 'SmtpConfig-0.0.0.0,587') != 'mail-auth')
	{
		$cfgs = nm_cfg_val_set($cfgs, 'SmtpConfig-0.0.0.0,587', 'mail-auth');
		//nm_cfgfileset('server.tab', $cfgs);
		$tmp = '';
		foreach($cfgs as $var) {
			if (trim($var[0]) != '')
				$tmp .= '"'.implode("\"\t\"", $var) . "\"\n";
		}
		if (trim($tmp) != '')
			file_write(dirname($G_SYS[MAIL_ROOT]).'/server.tab', $tmp);
	}	// if()

	// xmail, install_config.reg
	If (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN')
	{
		$_file = dirname($G_SYS[PAGE_ROOT]).'/tools/install_config.reg';
		if (file_exists($_file))
		{
			$_data = file_get_contents($_file);
			
			preg_match('/[\n]+"MAIL_ROOT"\="([^"]+)"/i', $_data, $mc2);

			preg_match('/[\n]+"MAIL_CMD_LINE"\="([^"]+)"/i', $_data, $mc);

			if ($mc[1] != '')
			{
				$_cmd = $mc[1];

				// [2013-07-15] 예외 처리
				$_cmd = str_replace('-St 90 ', '-St 300 ', $_cmd);
				$_cmd = preg_replace('/\-Sp ([0-9]+)/', '-SI 0.0.0.0:\\1', $_cmd);

				//$_add_search = array(' -St', ' -Pt', ' -Se', ' -QT', ' -SI 0.0.0.0:25', ' -SI 0.0.0.0:587');
				$_add_search = array(' -St', ' -Pt', ' -Se', ' -QT', ' -SI 0.0.0.0:', ' -SI 0.0.0.0:587');
				$_add_str = array(' -St 300', ' -Pt 300', ' -Se 3600', ' -QT 900', ' -SI 0.0.0.0:25', ' -SI 0.0.0.0:587');
				for ($i=0; $i<sizeof($_add_search); $i++)
				{
					if (strpos($_cmd, $_add_search[$i]) === false)
						$_cmd .= $_add_str[$i];
				}	// for()

				if ($_cmd != $mc[1])
				{
					//$tmp = str_replace($mc[0], str_replace("\nXMAIL_CMD_LINE=\"", "\n#XMAIL_CMD_LINE=\"", $mc[0]).$crlf.'XMAIL_CMD_LINE="'.$_cmd.'"', $_data);

					// [2013-07-15] 64bit 설정도 추가
					$tmp = 'Windows Registry Editor Version 5.00'.$crlf;
					$tmp .= $crlf;
					$tmp .= '[HKEY_LOCAL_MACHINE\SOFTWARE\GNU]'.$crlf;
					$tmp .= $crlf;
					$tmp .= '[HKEY_LOCAL_MACHINE\SOFTWARE\GNU\XMail]'.$crlf;
					$tmp .= '"MAIL_ROOT"="'.$mc2[1].'"'.$crlf;
					$tmp .= '"MAIL_CMD_LINE"="'.$_cmd.'"'.$crlf;
					$tmp .= $crlf;
					$tmp .= '[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\GNU]'.$crlf;
					$tmp .= $crlf;
					$tmp .= '[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\GNU\XMail]'.$crlf;
					$tmp .= '"MAIL_ROOT"="'.$mc2[1].'"'.$crlf;
					$tmp .= '"MAIL_CMD_LINE"="'.$_cmd.'"'.$crlf;

					file_write($_file, $tmp);
					echo " [OK]2.6.1 부터 SMTP 서비스가 587 포트에서도 추가 동작됩니다.\n\n";

					# 레지스트리 등록
					echo "    변경된 레지스트리를 추가해야 합니다.\n    확인창이 나오면 [예]를 눌러 주십시오.\n";
					system(dirname($G_SYS[PAGE_ROOT]).'/tools/install_config.reg');
				}	// if()
			}	// if()
		}	// if()
	} else
	{
		$_file = '/etc/init.d/xmail';
		if (file_exists($_file))
		{
			$_data = file_get_contents($_file);
			preg_match('/[\n]+XMAIL_CMD_LINE\="([^"]+)"/i', $_data, $mc);
			if ($mc[1] != '')
			{
				$_cmd = $mc[1];

				// [2013-07-15] 예외 처리
				$_cmd = str_replace('-St 90 ', '-St 300 ', $_cmd);
				$_cmd = preg_replace('/\-Sp ([0-9]+)/', '-SI 0.0.0.0:\\1', $_cmd);

				//$_add_search = array(' -St', ' -Pt', ' -Se', ' -QT', ' -SI 0.0.0.0:25', ' -SI 0.0.0.0:587');
				$_add_search = array(' -St', ' -Pt', ' -Se', ' -QT', ' -SI 0.0.0.0:', ' -SI 0.0.0.0:587');
				$_add_str = array(' -St 300', ' -Pt 300', ' -Se 3600', ' -QT 900', ' -SI 0.0.0.0:25', ' -SI 0.0.0.0:587');
				for ($i=0; $i<sizeof($_add_search); $i++)
				{
					if (strpos($_cmd, $_add_search[$i]) === false)
						$_cmd .= $_add_str[$i];
				}	// for()

				if ($_cmd != $mc[1])
				{
					$tmp = str_replace($mc[0], str_replace("\nXMAIL_CMD_LINE=\"", "\n#XMAIL_CMD_LINE=\"", $mc[0]).$crlf.'XMAIL_CMD_LINE="'.$_cmd.'"', $_data);
					file_write($_file, $tmp);
					echo " [OK]2.6.1 부터 SMTP 서비스가 587 포트에서도 추가 동작됩니다.\n\n";
				}	// if()
			}	// if()
		}	// if()
	}	// if()

	touch($mailserver_smtp_587);
}	// if()

// [2013-07-15] tools/mailserver/xmail 파일이 갱신되면, 자동으로 MailRoot/_script/xmail 파일로 덮어씌움.
$_file_src = dirname($G_SYS[PAGE_ROOT]).'/tools/mailserver/xmail';
$_file_tgt = dirname($G_SYS[PAGE_ROOT]).'/MailRoot/_script/xmail';
if (file_exists($_file_src) && is_dir(dirname($_file_tgt)))
{
	if (file_get_contents($_file_src) != file_get_contents($_file_tgt))
		copy($_file_src, $_file_tgt);	
}	// if()

################################################################################

$_start = getmicrotime();

$patch_query = array();

$patch_query[drop] = "
ALTER TABLE nmail_domain DROP d_quota_mbr_use ;
";

$patch_query[create] = "
CREATE TABLE nmail_spam_reject (
  m_no int(10) unsigned NOT NULL default '0',
  sr_email varchar(255) NOT NULL default '',
  sr_regdate datetime NOT NULL default '0000-00-00 00:00:00',
  PRIMARY KEY  (m_no, sr_email),
  INDEX (sr_regdate)
);

CREATE TABLE nmail_auto_filter
(
  as_no bigint(20) unsigned NOT NULL auto_increment,
  m_no int(10) unsigned NOT NULL default '0',
  as_name varchar(255),
  as_condition varchar(255),
  as_condition_text text,
  as_exec varchar(255),
  as_exec_text text,
  as_econdition varchar(255),
  as_econdition_text text,
  as_is_use enum('Y','N') default 'Y',
  as_sort tinyint unsigned NOT NULL default '0',
  PRIMARY KEY  (as_no),
  KEY as_m_no (m_no)
);

CREATE TABLE nmail_spam_allow (
  m_no int(10) unsigned NOT NULL default '0',
  sa_email varchar(255) NOT NULL default '',
  sa_regdate datetime NOT NULL default '0000-00-00 00:00:00',
  PRIMARY KEY  (m_no,sa_email),
  KEY sa_regdate (sa_regdate)
) ;

CREATE TABLE nmail_spam_config (
  m_no int(10) unsigned NOT NULL default '0',
  sc_addr_allow enum('Y','N') NOT NULL default 'Y',
  sc_fake_del enum('Y','N') NOT NULL default 'Y',
  sc_foreign_spam enum('Y','N') NOT NULL default 'N',
  sc_write_allow_add enum('Y','N') NOT NULL default 'Y',
  sc_from_subj_null_dell enum('Y','N') NOT NULL default 'N',
  sc_moddate datetime NOT NULL default '0000-00-00 00:00:00',
  PRIMARY KEY  (m_no)
) ;

CREATE TABLE nmail_member_group (
  mg_no int(10) unsigned NOT NULL auto_increment,
  d_no int(10) unsigned NOT NULL default '0',
  mg_name varchar(50) default NULL,
  mg_quota_default int(10) unsigned NOT NULL default '0',
  PRIMARY KEY  (mg_no),
  KEY mg_d_no (d_no)
);

CREATE TABLE nmail_auto_reply_loop_check (
  m_no int(10) unsigned NOT NULL default '0',
  ar_lc_email varchar(255) NOT NULL default '',
  ar_lc_regdate datetime NOT NULL default '0000-00-00 00:00:00',
  PRIMARY KEY  (m_no,ar_lc_email),
  KEY ar_lc_regdate (ar_lc_regdate)
) ;

CREATE TABLE nmail_white_ip (
  ip_ipaddr varchar(15) NOT NULL default '',
  ip_netmask varchar(15) NOT NULL default '',
  ip_regdate datetime NOT NULL default '0000-00-00 00:00:00',
  PRIMARY KEY  (ip_ipaddr,ip_netmask),
  KEY ip_regdate (ip_regdate)
) ;
CREATE TABLE nmail_black_ip (
  ip_ipaddr varchar(15) NOT NULL default '',
  ip_netmask varchar(15) NOT NULL default '',
  ip_regdate datetime NOT NULL default '0000-00-00 00:00:00',
  PRIMARY KEY  (ip_ipaddr,ip_netmask),
  KEY ip_regdate (ip_regdate)
) ;
CREATE TABLE nmail_relay_ip (
  ip_ipaddr varchar(15) NOT NULL default '',
  ip_netmask varchar(15) NOT NULL default '',
  ip_regdate datetime NOT NULL default '0000-00-00 00:00:00',
  PRIMARY KEY  (ip_ipaddr,ip_netmask),
  KEY ip_regdate (ip_regdate)
) ;
CREATE TABLE nmail_mailing_list (
  m_no int(10) unsigned NOT NULL default '0',
  ml_email varchar(255) NOT NULL default '',
  ml_perms char(2) NOT NULL default 'RW',
  ml_regdate datetime NOT NULL default '0000-00-00 00:00:00',
  PRIMARY KEY  (m_no,ml_email),
  KEY ml_regdate (ml_regdate)
) ;
CREATE TABLE nmail_member_size (
m_no int(10) unsigned NOT NULL default '0',
ms_mail BIGINT UNSIGNED NOT NULL DEFAULT '0',
ms_bigfile BIGINT UNSIGNED NOT NULL DEFAULT '0',
ms_webhard BIGINT UNSIGNED NOT NULL DEFAULT '0',
PRIMARY KEY  (m_no)
) ;
CREATE TABLE nmail_webhard_folder (
wfd_key INT UNSIGNED NOT NULL AUTO_INCREMENT ,
m_no INT UNSIGNED,
ws_key INT UNSIGNED,
wfd_parent INT UNSIGNED DEFAULT '0' NOT NULL ,
wfd_depth TINYINT UNSIGNED NOT NULL ,
wfd_name VARCHAR( 255 ) NOT NULL ,
wfd_issystem ENUM( 'Y', 'N' ) DEFAULT 'N' NOT NULL ,
wfd_memo TEXT,
wfd_regdate DATETIME NOT NULL default '0000-00-00 00:00:00',
PRIMARY KEY ( wfd_key ) ,
KEY wdf_m_no (m_no, wfd_parent),
KEY wdf_ws_key (ws_key)
);
CREATE TABLE nmail_webhard_file (
wf_key BIGINT UNSIGNED NOT NULL AUTO_INCREMENT ,
m_no INT UNSIGNED DEFAULT '0' NOT NULL ,
wfd_key INT UNSIGNED NOT NULL,
wf_name VARCHAR( 255 ) NOT NULL ,
wf_size INT UNSIGNED DEFAULT '0' NOT NULL ,
wf_type VARCHAR( 10 ) ,
wf_memo TEXT,
wf_regdate DATETIME NOT NULL default '0000-00-00 00:00:00',
PRIMARY KEY ( wf_key ) ,
KEY wf_wfd_key (wfd_key),
KEY wf_m_no (m_no)
);
CREATE TABLE nmail_webhard_share (
ws_key BIGINT UNSIGNED NOT NULL AUTO_INCREMENT ,
d_no INT UNSIGNED DEFAULT '0' NOT NULL ,
ws_name VARCHAR( 255 ) NOT NULL ,
ws_quota INT UNSIGNED DEFAULT '0' NOT NULL ,
ws_quota_use BIGINT UNSIGNED DEFAULT '0' NOT NULL ,
ws_mg_no TEXT,
ws_admin_id TEXT,
ws_perm VARCHAR( 7 ),
ws_memo TEXT,
ws_isuse ENUM( 'Y', 'N' ) DEFAULT 'Y' NOT NULL ,
ws_regdate DATETIME NOT NULL default '0000-00-00 00:00:00',
PRIMARY KEY ( ws_key ) ,
KEY ws_d_no (d_no)
);
CREATE TABLE nmail_bigfile (
bf_key BIGINT UNSIGNED NOT NULL AUTO_INCREMENT ,
m_no INT UNSIGNED NOT NULL,
wf_key BIGINT UNSIGNED,
wfd_key INT UNSIGNED,
mf_no bigint(20) unsigned,
bf_to TEXT,
bf_subject VARCHAR( 255 ),
bf_type ENUM( 'B', 'W' ) DEFAULT 'B' NOT NULL ,
bf_name VARCHAR( 255 ) NOT NULL ,
bf_size INT UNSIGNED DEFAULT '0' NOT NULL ,
bf_down INT UNSIGNED DEFAULT '0' ,
bf_expire ENUM( 'Y', 'N' ) NOT NULL DEFAULT 'N' ,
bf_regdate DATETIME NOT NULL default '0000-00-00 00:00:00',
PRIMARY KEY ( bf_key ) ,
KEY bf_m_no (m_no)
);
CREATE TABLE nmail_log_smtp (
s_date date default NULL,
s_time time default NULL,
s_ip varchar(255) default NULL,
s_sender_user varchar(255) default NULL,
s_sender_dom varchar(255) default NULL,
s_rcpt_user varchar(255) default NULL,
s_rcpt_dom varchar(255) default NULL,
s_msgid varchar(255) default NULL,
s_status varchar(100) default NULL,
s_authuser varchar(255) default NULL,
s_msgsize bigint(20) unsigned default '0',
s_smail_type varchar(20) default NULL,
s_smail_rcpt_user varchar(255) default NULL,
s_smail_rcpt_dom varchar(255) default NULL,
s_smail_mx varchar(255) default NULL,
s_smail_date date default NULL,
s_smail_time time default NULL,
KEY ls_s_date (s_date,s_msgid(4))
);
CREATE TABLE nmail_log_pop3 (
p_date date default NULL,
p_time time default NULL,
p_ip varchar(255) default NULL,
p_user varchar(255) default NULL,
p_dom varchar(255) default NULL,
KEY lp_p_date (p_date)
);
CREATE TABLE nmail_member_group_rel (
mg_no int(10) unsigned NOT NULL default '0',
m_no int(10) unsigned NOT NULL default '0',
PRIMARY KEY  (mg_no, m_no)
);
CREATE TABLE nmail_member_class (
mc_no INT UNSIGNED NOT NULL AUTO_INCREMENT ,
d_no int(10) unsigned NOT NULL default '0',
mc_name VARCHAR(50) NOT NULL,
mc_sort TINYINT UNSIGNED NOT NULL DEFAULT '1',
PRIMARY KEY  (mc_no),
KEY mc_d_no (d_no)
);
CREATE TABLE nmail_letter_group (
lg_no INT UNSIGNED NOT NULL AUTO_INCREMENT ,
lg_name VARCHAR(50) NOT NULL,
lg_sort TINYINT UNSIGNED NOT NULL DEFAULT '1',
PRIMARY KEY  (lg_no)
);
CREATE TABLE nmail_letter (
l_no BIGINT UNSIGNED NOT NULL AUTO_INCREMENT ,
lg_no INT UNSIGNED NOT NULL,
l_name VARCHAR( 255 ) NOT NULL,
l_preview VARCHAR( 255 ),
l_top VARCHAR( 255 ),
l_top_w SMALLINT UNSIGNED NULL,
l_top_h SMALLINT UNSIGNED NULL,
l_middle VARCHAR( 255 ),
l_bottom VARCHAR( 255 ),
l_bottom_w SMALLINT UNSIGNED NULL,
l_bottom_h SMALLINT UNSIGNED NULL,
l_bgcolor VARCHAR( 20 ),
l_color VARCHAR( 20 ),
l_sort TINYINT UNSIGNED NOT NULL DEFAULT '1',
l_isuse ENUM( 'Y', 'N' ) NOT NULL DEFAULT 'Y' ,
l_memo TEXT,
l_regdate DATETIME NOT NULL default '0000-00-00 00:00:00',
l_send_cnt INT UNSIGNED DEFAULT '0' ,
l_lastsenddate DATETIME default '0000-00-00 00:00:00',
PRIMARY KEY ( l_no ) ,
KEY l_lg_no (lg_no)
);
CREATE TABLE nmail_log_return (
mr_no bigint(20) unsigned NOT NULL auto_increment,
mr_mail_from varchar(255) default NULL,
mr_rcpt_to varchar(255) default NULL,
mr_smtp_error_type tinyint(4) unsigned default NULL,
mr_smtp_error varchar(255) default NULL,
mr_smtp_error_str varchar(255) default NULL,
mr_smtp_server varchar(255) default NULL,
mr_msgid varchar(255) default NULL,
mr_hdr_subject varchar(255) default NULL,
mr_hdr_date datetime NOT NULL default '0000-00-00 00:00:00',
mr_date datetime NOT NULL default '0000-00-00 00:00:00',
mr_body text,
PRIMARY KEY  (mr_no),
KEY mr_hdr_date (mr_hdr_date),
KEY mr_msgid (mr_msgid)
);
CREATE TABLE nmail_log_filter (
f_no bigint(20) unsigned NOT NULL auto_increment,
m_no bigint(20) unsigned NOT NULL,
f_code varchar(10) NOT NULL,
f_action char(1) NOT NULL,
f_msgid varchar(255) default NULL,
f_memo varchar(255) default NULL,
f_mail_from varchar(255) default NULL,
f_rcpt_to varchar(255) default NULL,
f_hdr_from varchar(255) default NULL,
f_hdr_subject varchar(255) default NULL,
f_date datetime NOT NULL default '0000-00-00 00:00:00',
f_ip varchar(15) default NULL,
PRIMARY KEY  (f_no),
KEY lf_date (f_date),
KEY lf_msgid (f_msgid)
);
CREATE TABLE nmail_board_read_log (
  br_no bigint(20) unsigned NOT NULL auto_increment,
  ba_no smallint(5) unsigned NOT NULL default '0',
  b_no bigint(20) unsigned NOT NULL default '0',
  m_no int(10) unsigned NOT NULL default '0',
  br_regdate datetime NOT NULL default '0000-00-00 00:00:00',
  br_reghost varchar(15) NOT NULL default '',
  PRIMARY KEY  (br_no),
  KEY br_b_no (b_no)
);
CREATE TABLE nmail_board_draft (
  bd_no bigint(20) unsigned NOT NULL auto_increment,
  m_no int(10) unsigned NOT NULL default '0',
  b_subject varchar(255) NOT NULL default '',
  b_memo mediumtext NOT NULL,
  bd_regdate datetime NOT NULL default '0000-00-00 00:00:00',
  bd_reghost varchar(15) NOT NULL default '',
  PRIMARY KEY  (bd_no),
  KEY bd_m_no (m_no)
);
CREATE TABLE nmail_board_menu (
  bm_no smallint(5) unsigned NOT NULL auto_increment,
  d_no int(10) unsigned NOT NULL default '0',
  bm_name varchar(255) NOT NULL,
  bm_sort tinyint(3) unsigned NOT NULL default '1',
  PRIMARY KEY  (bm_no),
  KEY bm_d_no (d_no)
);
CREATE TABLE nmail_quota_alert (
  qa_no bigint(20) unsigned NOT NULL auto_increment,
  m_no int(10) unsigned NOT NULL default '0',
  qa_cursize bigint(20) unsigned NOT NULL default '0',
  qa_maxsize bigint(20) unsigned NOT NULL default '0',
  qa_date datetime NOT NULL default '0000-00-00 00:00:00',
  qa_type char(1) NOT NULL default 'L',
  PRIMARY KEY  (qa_no),
  KEY qa_m_no_date (m_no, qa_date)
);
CREATE TABLE nmail_domain_alias (
  da_no int(10) unsigned NOT NULL auto_increment,
  d_no int(10) unsigned NOT NULL default '0',
  da_name varchar(255) NOT NULL default '',
  da_regdate DATETIME NOT NULL default '0000-00-00 00:00:00',
  PRIMARY KEY  (da_no),
  UNIQUE KEY da_name (d_no,da_name)
);
CREATE TABLE nmail_log_login (
d_no int(10) unsigned NOT NULL,
m_no int(10) unsigned NOT NULL,
m_id VARCHAR( 50 ) NOT NULL,
l_date date NOT NULL,
l_time time NOT NULL,
l_ip varchar(15) NOT NULL,
l_status enum('OK','FI','FP','LID','LIP') NOT NULL,
KEY l_l_date_time (l_date, l_time),
KEY l_l_date_ip (l_date, l_ip),
KEY l_l_date_m_no (l_date, m_no),
KEY l_l_date_d_no (l_date, d_no)
);
CREATE TABLE nmail_log_member (
d_no int(10) unsigned NOT NULL,
m_no int(10) unsigned NOT NULL,
m_id VARCHAR( 50 ) NOT NULL,
l_date date NOT NULL,
l_time time NOT NULL,
l_ip varchar(15) NOT NULL,
l_admin_id VARCHAR( 255 ) NOT NULL,
l_status enum('ADD','DEL','MODP') NOT NULL,
KEY l_m_date_time (l_date, l_time),
KEY l_m_date_ip (l_date, l_ip),
KEY l_m_date_m_no (l_date, m_no),
KEY l_m_date_d_no (l_date, d_no)
);
";

$patch_query[add] = "
ALTER TABLE nmail_member ADD m_forwarding_type ENUM( 'N', 'Y', 'C' ) DEFAULT 'N' NOT NULL AFTER m_forwarding ;
ALTER TABLE nmail_member_field ADD d_no INT UNSIGNED DEFAULT '0' NOT NULL AFTER mbf_no ;
ALTER TABLE nmail_domain ADD d_quota_mbr_count INT UNSIGNED DEFAULT '100' NOT NULL AFTER d_quota_mbr_default ;
ALTER TABLE nmail_domain ADD d_memo TEXT;
ALTER TABLE nmail_domain ADD d_regdate DATETIME NOT NULL ;

ALTER TABLE nmail_mail_receive_check
ADD mrcext_m_id VARCHAR( 50 ) default NULL,
ADD mrcext_d_name VARCHAR( 255 ) default NULL,
ADD mrcext_key VARCHAR( 10 ) default NULL,
ADD mrcext_ip VARCHAR( 15 ) default NULL;

ALTER TABLE nmail_member ADD mg_no INT UNSIGNED AFTER d_no ;
ALTER TABLE nmail_member ADD m_autoreply_isuse ENUM( 'Y', 'N' ) DEFAULT 'N' NOT NULL;
ALTER TABLE nmail_member ADD m_autoreply_subject VARCHAR( 255 );
ALTER TABLE nmail_member ADD m_autoreply_body TEXT;

ALTER TABLE nmail_domain ADD d_saveday TINYINT UNSIGNED DEFAULT '0'  AFTER d_quota_mbr_count ;
ALTER TABLE nmail_mail_box ADD mb_saveday TINYINT UNSIGNED DEFAULT '0' ;

ALTER TABLE nmail_member ADD m_suspend_start DATE;
ALTER TABLE nmail_member ADD m_suspend_end DATE;
ALTER TABLE nmail_member ADD m_use_start DATE;
ALTER TABLE nmail_member ADD m_use_end DATE;

ALTER TABLE nmail_domain ADD d_skin_main VARCHAR( 20 ) NOT NULL DEFAULT 'basic' AFTER d_saveday;
ALTER TABLE nmail_domain ADD d_skin_webmail VARCHAR( 20 ) NOT NULL DEFAULT 'basic' AFTER d_skin_main;
ALTER TABLE nmail_domain ADD d_skin_member VARCHAR( 20 ) NOT NULL DEFAULT 'basic' AFTER d_skin_webmail;
ALTER TABLE nmail_domain ADD d_skin_board VARCHAR( 20 ) NOT NULL DEFAULT 'basic' AFTER d_skin_member;

ALTER TABLE nmail_domain ADD d_shareaddr_isuse ENUM( 'Y', 'N' ) NOT NULL DEFAULT 'Y' AFTER d_skin_board ;
ALTER TABLE nmail_domain ADD d_shareaddr_reg ENUM( 'U', 'A' ) NOT NULL DEFAULT 'U' AFTER d_shareaddr_isuse ;
ALTER TABLE nmail_domain ADD d_sharediary_isuse ENUM( 'Y', 'N' ) NOT NULL DEFAULT 'Y' AFTER d_shareaddr_isuse ;
ALTER TABLE nmail_domain ADD d_sharediary_reg ENUM( 'U', 'A' ) NOT NULL DEFAULT 'U' AFTER d_sharediary_isuse ;

ALTER TABLE nmail_addr_group ADD d_no INT UNSIGNED NULL ;
ALTER TABLE nmail_addr ADD ad_no_share BIGINT unsigned;

ALTER TABLE nmail_diary ADD d_no INT UNSIGNED NULL ;
ALTER TABLE nmail_diary ADD di_no_share BIGINT UNSIGNED NULL ;

ALTER TABLE nmail_domain ADD d_quota_board INT UNSIGNED NOT NULL DEFAULT '2097152' AFTER d_quota_mbr_count ;
ALTER TABLE nmail_board ADD b_file_size INT UNSIGNED NOT NULL DEFAULT '0' AFTER b_file ;

ALTER TABLE nmail_member ADD m_cfg_new_mail_box VARCHAR( 255 ) NULL DEFAULT 'inbox|spam';
ALTER TABLE nmail_member ADD m_cfg_new_cnt TINYINT UNSIGNED NULL DEFAULT '7';
ALTER TABLE nmail_member ADD m_cfg_week_diray_cnt TINYINT UNSIGNED NULL DEFAULT '5';
ALTER TABLE nmail_member ADD m_cfg_from_name VARCHAR( 255 ) NULL ;
ALTER TABLE nmail_member ADD m_cfg_mail_list_cnt TINYINT UNSIGNED NULL DEFAULT '20';

ALTER TABLE nmail_domain ADD d_site_name VARCHAR( 255 ) NULL AFTER d_shareaddr_reg ;
ALTER TABLE nmail_domain ADD d_site_owner VARCHAR( 255 ) NULL AFTER d_site_name ;
ALTER TABLE nmail_domain ADD d_site_title VARCHAR( 255 )  NULL AFTER d_site_owner ;
ALTER TABLE nmail_domain ADD d_site_license TEXT NULL AFTER d_site_title ;

ALTER TABLE nmail_domain ADD d_svc_smtp enum('Y', 'N') DEFAULT 'Y' NOT NULL AFTER d_saveday ;
ALTER TABLE nmail_domain ADD d_svc_pop3 enum('Y', 'N') DEFAULT 'Y' NOT NULL AFTER d_svc_smtp ;
ALTER TABLE nmail_domain ADD d_svc_forward enum('Y', 'N') DEFAULT 'Y' NOT NULL AFTER d_svc_pop3 ;
ALTER TABLE nmail_member ADD m_svc_smtp enum('Y', 'N') DEFAULT 'Y' NOT NULL;
ALTER TABLE nmail_member ADD m_svc_pop3 enum('Y', 'N') DEFAULT 'Y' NOT NULL;

ALTER TABLE nmail_mail_receive_check ADD mrc_status CHAR( 1 ) NULL AFTER mrc_readdate;

ALTER TABLE nmail_member ADD m_usertype CHAR( 1 ) NULL ;

ALTER TABLE nmail_domain
ADD  d_bigfile_isuse enum('Y','N') NOT NULL default 'Y' AFTER d_svc_forward ,
ADD  d_bigfile_quota int(10) unsigned NOT NULL default '1048576' AFTER d_bigfile_isuse ,
ADD  d_bigfile_quota_default int(10) unsigned NOT NULL default '10240' AFTER d_bigfile_quota ,
ADD  d_webhard_isuse enum('Y','N') NOT NULL default 'N' AFTER d_bigfile_quota_default ,
ADD  d_webhard_quota int(10) unsigned NOT NULL default '0' AFTER d_webhard_isuse ,
ADD  d_webhard_quota_default int(10) unsigned NOT NULL default '102400' AFTER d_webhard_quota ;

ALTER TABLE nmail_member ADD m_bigfile_quota INT UNSIGNED NOT NULL DEFAULT '10240' AFTER m_quota ,
ADD m_webhard_quota INT UNSIGNED NOT NULL DEFAULT '0' AFTER m_bigfile_quota ;

ALTER TABLE nmail_domain ADD d_skin_webhard VARCHAR( 20 ) NOT NULL DEFAULT 'basic' AFTER d_skin_board ;

ALTER TABLE nmail_board_admin ADD ba_mg_no TEXT NULL AFTER ba_mbronly_reply ,
ADD ba_use_id TEXT NULL AFTER ba_mg_no ;

ALTER TABLE nmail_domain ADD d_site_logo1 VARCHAR( 255 ) NULL AFTER d_site_license ,
ADD d_site_logo2 VARCHAR( 255 ) NULL AFTER d_site_logo1 ;
ALTER TABLE nmail_domain ADD d_site_logo1_w SMALLINT UNSIGNED NULL AFTER d_site_logo1 ,
ADD d_site_logo1_h SMALLINT UNSIGNED NULL AFTER d_site_logo1_w ;
ALTER TABLE nmail_domain ADD d_site_logo2_w SMALLINT UNSIGNED NULL AFTER d_site_logo2 ,
ADD d_site_logo2_h SMALLINT UNSIGNED NULL AFTER d_site_logo2_w ;

ALTER TABLE nmail_board ADD b_files TEXT NULL AFTER b_file ;

ALTER TABLE nmail_member_group ADD mg_parent INT UNSIGNED NOT NULL DEFAULT '0' AFTER d_no ,
ADD mg_depth TINYINT UNSIGNED NOT NULL DEFAULT '1' AFTER mg_parent ,
ADD mg_sort TINYINT UNSIGNED NOT NULL DEFAULT '1' AFTER mg_depth ;
ALTER TABLE nmail_member ADD mc_no INT UNSIGNED NULL AFTER mg_no ;

ALTER TABLE nmail_domain ADD d_mbrgrp_isuse ENUM( 'Y', 'N' ) NOT NULL DEFAULT 'N' AFTER d_skin_webhard ;

ALTER TABLE nmail_webhard_share ADD ws_guest_id TEXT NULL AFTER ws_mg_no ;

ALTER TABLE nmail_member ADD m_cfg_from_addr VARCHAR( 255 ) NULL AFTER m_cfg_from_name ;

ALTER TABLE nmail_board_admin ADD ba_isuse_rewrite CHAR( 1 ) NOT NULL DEFAULT 'N' AFTER ba_isuse_reply ;
ALTER TABLE nmail_board_admin ADD ba_isuse_read_log CHAR( 1 ) NOT NULL DEFAULT 'N' AFTER ba_isuse_rewrite ;

ALTER TABLE nmail_board_admin ADD ba_perm_rewrite tinyint(3) unsigned NOT NULL default '3' AFTER ba_perm_reply;
ALTER TABLE nmail_board_admin ADD ba_perm_read_log tinyint(3) unsigned NOT NULL default '3' AFTER ba_perm_rewrite;

ALTER TABLE nmail_board_admin ADD bm_no SMALLINT UNSIGNED AFTER d_no ;
ALTER TABLE nmail_board_admin ADD ba_sort tinyint(3) unsigned NOT NULL default '1' AFTER bm_no ;

ALTER TABLE nmail_domain ADD d_mbrgrp_list TEXT AFTER d_mbrgrp_isuse;
ALTER TABLE nmail_domain ADD d_mbrgrp_view TEXT AFTER d_mbrgrp_list;

ALTER TABLE nmail_mail_receive_check ADD mrc_reserve_status char(1);

ALTER TABLE nmail_addr_group ADD adg_parent BIGINT UNSIGNED NOT NULL DEFAULT '0' AFTER adg_name;
ALTER TABLE nmail_addr_group ADD adg_depth TINYINT UNSIGNED NOT NULL DEFAULT '1' AFTER adg_parent;
ALTER TABLE nmail_addr_group ADD adg_sort TINYINT UNSIGNED NOT NULL DEFAULT '1' AFTER adg_depth;

ALTER TABLE nmail_domain_alias ADD da_mail_from_select ENUM( 'Y', 'N' ) NOT NULL DEFAULT 'N' AFTER da_name;

ALTER TABLE nmail_domain_alias ADD da_memo TEXT NULL AFTER da_mail_from_select ;
";

// index drop & add, update, delete, alter table change
$patch_query[normal] = "
ALTER TABLE nmail_member_field DROP INDEX mbf_name , ADD UNIQUE mbf_name ( d_no , mbf_name ) ;
UPDATE nmail_member_field SET mbf_issystem='N' WHERE mbf_name IN ('m_jumin', 'm_lostpwd_q', 'm_lostpwd_a');
ALTER TABLE nmail_domain CHANGE d_quota d_quota INT( 10 ) UNSIGNED DEFAULT '2097152' NOT NULL;
ALTER TABLE nmail_domain CHANGE d_quota_mbr_default d_quota_mbr_default INT( 10 ) UNSIGNED DEFAULT '20480' NOT NULL;
ALTER TABLE nmail_member_field CHANGE mbf_no mbf_no INT UNSIGNED NOT NULL AUTO_INCREMENT;
UPDATE nmail_diary SET di_content='기념일' WHERE m_no='0' AND di_subject='식목일' AND di_startdate='1900-04-05' AND di_content='공휴일';
UPDATE nmail_diary SET di_startdate='1900-05-15', di_enddate='1900-05-15' WHERE m_no='0' AND di_subject='스승의 날' AND di_startdate='1900-05-08' AND di_content='기념일';
UPDATE nmail_mail_receive_check SET mrc_status='N' WHERE mrc_readdate IS NULL AND mrc_status IS NULL;
UPDATE nmail_mail_receive_check SET mrc_status='R' WHERE mrc_readdate IS NOT NULL AND mrc_status IS NULL;
ALTER TABLE nmail_diary_lunar CHANGE lunar_date lunar_date VARCHAR( 10 ) NOT NULL DEFAULT '0000-00-00';
ALTER TABLE nmail_log_smtp DROP INDEX ls_s_date , ADD INDEX ls_s_date ( s_date , s_msgid ( 7 ) );
ALTER TABLE nmail_log_smtp CHANGE s_msgid s_msgid VARCHAR( 20 ) NULL DEFAULT NULL ;
UPDATE nmail_diary SET di_content='기념일' WHERE m_no='0' AND di_subject='제헌절' AND di_startdate='1900-07-17' AND di_content='공휴일';
ALTER TABLE nmail_board CHANGE b_memo b_memo MEDIUMTEXT NOT NULL;
UPDATE nmail_domain SET d_mbrgrp_list='m_mobile|m_office_tel', d_mbrgrp_view='m_mobile|m_office_tel' WHERE d_mbrgrp_list IS NULL;
UPDATE nmail_member SET m_etc2='0' WHERE m_usertype='M' AND m_etc2='';
";

$patch_query[index_add] = "
ALTER TABLE nmail_member ADD INDEX mg_no ( mg_no ) ;
ALTER TABLE nmail_member ADD INDEX m_quota ( d_no , m_quota );
ALTER TABLE nmail_addr ADD INDEX ad_email ( adg_no , ad_email ) ;
ALTER TABLE nmail_mail_receive_check ADD INDEX m_no ( m_no ) ;
ALTER TABLE nmail_addr_group ADD INDEX m_no ( m_no ) ;
ALTER TABLE nmail_addr_group ADD INDEX d_no ( d_no ) ;
ALTER TABLE nmail_diary ADD INDEX d_no ( d_no ) ;
ALTER TABLE nmail_board ADD INDEX ba_no ( ba_no ) ;
ALTER TABLE nmail_board_comment ADD INDEX b_no ( b_no ) ;
ALTER TABLE nmail_board_admin ADD INDEX d_no ( d_no ) ;
ALTER TABLE nmail_board ADD INDEX b_ref_list ( ba_no , b_ref , b_re_step ) ;
ALTER TABLE nmail_mail_receive_check ADD INDEX mrc_reserve_status ( mrc_reserve_status );
ALTER TABLE nmail_mail_receive_check ADD INDEX mrc_m_no_senddate ( m_no, mrc_senddate );
ALTER TABLE nmail_log_pop3 ADD INDEX lp_date_time ( p_date , p_time );
";

$patch_query[index_drop] = "
ALTER TABLE nmail_mail_receive_check DROP INDEX mrc_no_2 ;
ALTER TABLE nmail_mail_receive_check DROP INDEX mrc_no ;
ALTER TABLE nmail_addr_group DROP INDEX adg_no ;
ALTER TABLE nmail_board_category DROP INDEX ba_no ;
ALTER TABLE nmail_log_pop3 DROP INDEX lp_p_date;
";




################################################################################

function table_exists($table)
{
	global $db;

	$q = "SHOW TABLES LIKE '$table'";
	$chk_objName = db_get_one($q);
	$table_exists = ($chk_objName) ? true : false;

	return $table_exists;
}	// function()


function field_exists($table, $name)
{
	global $db;

	$ti = $db->tableInfo($table);
	$field_exists = 0;
	for ($i=0; $i<sizeof($ti); $i++)
	{
		if ($ti[$i]['name'] == $name)
		{
			$field_exists = 1;
			break;
		}	// if()
	}	// for()
	return $field_exists;
}	// function()

function index_exists($table, $name)
{
	global $db;

	$q = "SHOW INDEX FROM $table";
	$idxs = db_get_rows($q);

	$field_exists = 0;
	for ($i=0; $i<sizeof($idxs); $i++)
	{
		if ($idxs[$i]['key_name'] == $name)
		{
			$field_exists = 1;
			break;
		}	// if()
	}	// for()

	return $field_exists;
}	// function()

function get_query_name($query, $str)
{
	$pt = '/'.$str.'[ `\r\n\t]+([a-z0-9_\-]+)/i';
	preg_match($pt, $query, $mc);

	if (!$mc[1])
		die("[Error]패치 작업중 다음 쿼리를 분석하는 과정에서 알 수 없는 원인으로 실패하였습니다.=>\n".$query);

	return $mc[1];
}	// function()


function db_index_diff($table, $idxs, $key_name, $colmun_name_chk)
{
	$cols = array();
	for ($i=0; $i<sizeof($idxs['key_name']); $i++)
	{
		if ($idxs['key_name'][$i] == $key_name)
		{
			$cols[] = $idxs['column_name'][$i];
		}	// if()
	}	// for()
	#vd($cols);

	if ($key_name == 'PRIMARY')
	{
		$idx_str = 'PRIMARY KEY';
	} else
	{
		$idx_str = 'INDEX '.$key_name;
	}	// if()

	if (sizeof($cols) > 0)
	{
		$diff = array_diff($colmun_name_chk, $cols);
		$diff2 = array_diff($cols, $colmun_name_chk);
		if (sizeof($diff) > 0 || sizeof($diff2) > 0)
		{
			#echo "인덱스 구성이 다르므로 삭제후 생성.";
			$q = "ALTER TABLE ".$table." DROP ".$idx_str.", ADD ".$idx_str." ( ".implode(',', $colmun_name_chk)." )";
			db_query_debug($q);
		}	// if()
	} else
	{
		#echo "인덱스가 없으므로 바로 생성.";
		$q = "ALTER TABLE ".$table." ADD ".$idx_str." ( ".implode(',', $colmun_name_chk)." )";
		db_query_debug($q);
	}	// if()
}	// function()


function db_query_debug($q)
{
	global $_start;
	if ($_SERVER['argv'][1] == 'DEBUG')
	{
		echo "    - Execute Query : " . trim($q)." (" . round((getmicrotime() - $_start),4) . "sec)\n";
		flush();
		db_query($q);
	} else if ($_SERVER['argv'][1] == 'TEST')
	{
		echo "    - View Query : " . trim($q)." (" . round((getmicrotime() - $_start),4) . "sec)\n";
		flush();
	} else
	{
		db_query($q);
	}	// if()
}	// function()


function scanf($msg, $values=array(), $length=64, $isupper=true, $allownull=false, $defalut_value=true)
{
	echo $msg;
	// [2006-09-06] AnNyung 1.2 에서 php stdin 사용시 문제가 발견됨.
	// [2006-11-13] Windows PHP 5.2.0 에서 입력안되던 문제 수정.
	// [2006-11-14] RWAPM 에서 STDIN 이 지원되지 않는 문제 발견.
	// [2007-01-29] 일부 Linux 에서 엔터를 2byte로 인식해서 scanf()가 반복되는 문제 해결.
	// [2013-07-18] 일부 Windows 에서 첫번째 입력시 Y 나 N을 입력한 경우, 두번째 항목은 자동으로 기본 선택이 되던 문제 해결.
	if (defined('STDIN'))
	{
		//$data = trim(fgets(STDIN,$length+1));
		$data = trim(fread(STDIN,$length+1));
	} else
	{
		$stdin = (file_exists("/dev/stdin")) ? "/dev/stdin" : "php://stdin";
		$fp = fopen($stdin,"r");
		//$data = trim(fgets($fp,$length+1));
		$data = trim(fread($fp,$length+1));
		fclose($fp);
	}	// if()
	if ($isupper)
		$data = strtoupper($data);

	if ($defalut_value && $values && $data == '')
	{
		$data = $values[0];
	}	// if()

	if (!$allownull && ($data == '' || ($values && sizeof($values) > 1 && !in_array($data, $values))))
	{
		$data = scanf($msg, $values, $length, $isupper, $allownull, $defalut_value);
	}	// if()

	return $data;
}	// function()


function title($msg)
{
	global $__TITLE_NO;
	global $crlf;
	if (!$__TITLE_NO)
	{
		$__TITLE_NO = 1;
	} else
	{
		$__TITLE_NO++;
	}	// if()
	echo $crlf;
	echo "==============================================================================".$crlf;
	echo "= [".$__TITLE_NO."] ".$msg.$crlf;
	echo "==============================================================================".$crlf;
}	// function()


################################################################################


nm_update_exec();

if ($G_SYS[DB] != 'oracle')
{

	$patch_query_key = array();
	$patch_query_key = array_keys($patch_query);


	for ($p=0; $p<sizeof($patch_query); $p++)
	{
		$ar_query = array();
		$ar_query = explode(";", $patch_query[$patch_query_key[$p]]);
		for ($i=0; $i<sizeof($ar_query)-1; $i++)		// 마지막 세미콜론(;)뒤의 문장은 주석뿐이거나 공백이므로 생략함.
		{
			$ar_query[$i] = trim($ar_query[$i]);
			if ($ar_query[$i] == '')
				continue;

			$isExecute = 1;

			if ($patch_query_key[$p] == 'normal')
			{
				$_table = '';
			} else
			{
				$_table = get_query_name($ar_query[$i], "TABLE");
			}	// if()

			switch($patch_query_key[$p])
			{
				case "drop":
					$_field = get_query_name($ar_query[$i], "DROP");
					if (!field_exists($_table, $_field))
					{
						$isExecute = 0;
					}	// if()
					break;

				case "create":
					if (table_exists($_table))
					{
						$isExecute = 0;
					}	// if()
					break;

				case "add":
					$_field = get_query_name($ar_query[$i], "ADD");
					if (field_exists($_table, $_field))
					{
						$isExecute = 0;
					}	// if()
					break;

				case "index_add":
					$_field = get_query_name($ar_query[$i], "ADD INDEX");
					if (index_exists($_table, $_field))
					{
						$isExecute = 0;
					}	// if()
					break;

				case "index_drop":
					$_field = get_query_name($ar_query[$i], "DROP INDEX");
					if (!index_exists($_table, $_field))
					{
						$isExecute = 0;
					}	// if()
					break;

				default:		// normal
					// 중복실행해도 되는부분
					// [2009-06-25] 업데이트 속도 개선을 위해 1회만 실행하도록 변경.
					$patch_query_normal = $updated_dir.DIRECTORY_SEPARATOR.'patch_query_normal';
					$_data = '';
					if (file_exists($patch_query_normal))
					{
						$_data = file_get_contents($patch_query_normal);
					}	// if()
					if (strpos($_data, $ar_query[$i]) !== false)
					{
						$isExecute = 0;
					} else
					{
						file_write($patch_query_normal, $_data.$crlf.$ar_query[$i].';');
					}	// if()
					break;
			}	// switch()

			if ($isExecute == 1)
			{
				db_query_debug($ar_query[$i]);
			}	// if()
		}	// for();
	}	// for()

	################################################################################
	# nmail_mail_file_?_????
	################################################################################

	$q = "SHOW TABLES LIKE 'nmail_mail_file_%'";
	$db->setFetchMode(DB_FETCHMODE_ORDERED);
	$mft = db_get_rows($q);
	$db->setFetchMode(DB_FETCHMODE_ASSOC);


	for ($i=0; $i<sizeof($mft); $i++)
	{
		#echo "\n".$mft[$i][0];

		// column
		if (!field_exists($mft[$i][0], 'mf_spam_point'))
		{
			$q = "ALTER TABLE ".$mft[$i][0]." ADD mf_spam_point FLOAT( 2 ) DEFAULT '0' NOT NULL";
			db_query_debug($q);
		}	// if()
		if (!field_exists($mft[$i][0], 'mf_is_userauth'))
		{
			$q = "ALTER TABLE ".$mft[$i][0]." ADD mf_is_userauth enum('Y', 'N')";
			db_query_debug($q);
		}	// if()
		if (!field_exists($mft[$i][0], 'mfext1'))
		{
			$q = "ALTER TABLE ".$mft[$i][0]." ADD mfext1 CHAR(1)";
			db_query_debug($q);
		}	// if()
		if (!field_exists($mft[$i][0], 'mfext2'))
		{
			$q = "ALTER TABLE ".$mft[$i][0]." ADD mfext2 VARCHAR( 20 )";
			db_query_debug($q);
		}	// if()
		if (!field_exists($mft[$i][0], 'mfext3'))
		{
			$q = "ALTER TABLE ".$mft[$i][0]." ADD mfext3 VARCHAR( 255 )";
			db_query_debug($q);
		}	// if()

		// index
		$q = "SHOW INDEX FROM ".$mft[$i][0];
		$idxs = db_get_rows($q, true);
		#vd($idxs['key_name']); vd($idxs['column_name']);
		db_index_diff($mft[$i][0], $idxs, 'PRIMARY', array('mf_no'));
		db_index_diff($mft[$i][0], $idxs, 'mf_no', array('m_no', 'mb_id', 'mf_no'));
		db_index_diff($mft[$i][0], $idxs, 'mf_filename', array('mf_filename'));
		db_index_diff($mft[$i][0], $idxs, 'mno_mbid', array('m_no', 'mb_id', 'mf_is_read', 'mf_filesize'));
		db_index_diff($mft[$i][0], $idxs, 'mf_arrival_date', array('m_no', 'mb_id', 'mf_arrival_date'));

		// [2006-11-01] 이전 버젼의 버그등으로 인해 mf_filename 등 아무런 값이 없는 메일은 삭제하도록 함.
			$q = "SELECT COUNT(*) FROM ".$mft[$i][0]." WHERE  mf_filename = '' AND mf_from = '' AND mf_to = '' AND mf_body = '' AND mf_attach_names = ''";
			$mf_error_cnt = db_get_one($q);
			if ($mf_error_cnt > 0)
			{
				$q = "DELETE FROM ".$mft[$i][0]." WHERE  mf_filename = '' AND mf_from = '' AND mf_to = '' AND mf_body = '' AND mf_attach_names = ''";
				db_query_debug($q);
			}	// if()
	}	// for()


	// [2006-07-20] 자료실 첨부파일 사이즈를 디비에 기록.
		$q = "
			SELECT
				ba_no, b_no, b_file
			FROM
				".$TB['BOARD']."
			WHERE
				b_file != ''
				AND b_file_size = 0
			";
		$bf = db_get_rows($q);
		for ($i=0; $i<sizeof($bf); $i++)
		{
			$file = $UPLOAD_ROOT . "/" . $UPLOAD_DIR[BOARD] . "/" . $bf[$i]['ba_no'] . "/" . file_name_fix($bf[$i]['b_file'], $bf[$i]['b_no']);
			$fs = @filesize($file);
			if ($fs > 0)
			{
				$q = "UPDATE ".$TB['BOARD']." SET b_file_size='".$fs."' WHERE b_no='".$bf[$i]['b_no']."'";
				db_query($q);
			}	// if()
		}	// for()

}	// if()		// oracle


// [2008-08-26] 조직도 모듈 추가 - MEMBER 테이블의 mg_no 를 기준으로 MEMBER_GROUP_REL 테이블 갱신함.
$q = "SELECT m_no, mg_no FROM ".$TB['MEMBER']." WHERE mg_no > 0";
$rows = db_get_rows($q);
$rows_cnt = sizeof($rows);
for ($i=0; $i<$rows_cnt; $i++)
{
	$q = "SELECT COUNT(*) FROM ".$TB['MEMBER_GROUP_REL']." WHERE mg_no='".$rows[$i]['mg_no']."' AND m_no='".$rows[$i]['m_no']."'";
	$mgr_cnt = db_get_one($q);
	if ($mgr_cnt == 0)
	{
		$q = "INSERT INTO ".$TB['MEMBER_GROUP_REL']." (mg_no, m_no) VALUES ('".$rows[$i]['mg_no']."', '".$rows[$i]['m_no']."')";
		db_query($q);
	}	// if()
}	// for()


// [2008-08-26] main 스킨 폴더아래에 iframe 레이아웃 파일이 없을 때 basic2.5에서 자동 복사
$skin_main_dir = $G_SYS['PAGE_ROOT'].DIRECTORY_SEPARATOR.'skin'.DIRECTORY_SEPARATOR.'main'.DIRECTORY_SEPARATOR;
if (file_exists($skin_main_dir.'basic2.5'.DIRECTORY_SEPARATOR.'layout_iframe.inc.html'))
{
	chdir($G_SYS['PAGE_ROOT']);
	$dirs = nskinopendir('main');
	for ($i=0; $i<sizeof($dirs); $i++)
	{
		if ($dirs[$i] != 'basic2.5' && !file_exists($skin_main_dir.$dirs[$i].DIRECTORY_SEPARATOR.'layout_iframe.inc.html'))
		{
			copy($skin_main_dir.'basic2.5'.DIRECTORY_SEPARATOR.'layout_iframe.inc.html', $skin_main_dir.$dirs[$i].DIRECTORY_SEPARATOR.'layout_iframe.inc.html');
		}	// if()
	}	// for()
}	// if()


// [2008-09-24] [일정관리]MySQL 5 버젼에서 음력데이타가 잘못 저장된 오류 수정.
$q = "SELECT COUNT(*) FROM ".$TB['DIARY_LUNAR']." WHERE lunar_date='0000-00-00'";
$diary_lunar_error = db_get_one($q);
if ($diary_lunar_error > 0)
{
	// 잘못된 데이타 삭제
	$q = "DELETE FROM ".$TB['DIARY_LUNAR']." WHERE lunar_date='0000-00-00'";
	db_query($q);

	// 올바른 데이타 추가
	$q = array();
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1900-02-29', '1900-03-29', 0, '辛丑')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1900-02-30', '1900-03-30', 0, '壬寅')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1901-02-29', '1901-04-17', 0, '乙丑')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1901-02-30', '1901-04-18', 0, '丙寅')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1902-02-29', '1902-04-07', 0, '庚申')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1903-02-29', '1903-03-27', 0, '甲寅')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1903-02-30', '1903-03-28', 0, '乙卯')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1904-02-30', '1904-04-15', 0, '己卯')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1905-02-29', '1905-04-03', 0, '壬申')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1905-02-30', '1905-04-04', 0, '癸酉')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1906-02-29', '1906-03-23', 0, '丙寅')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1906-02-30', '1906-03-24', 0, '丁卯')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1907-02-29', '1907-04-11', 0, '庚寅')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1907-02-30', '1907-04-12', 0, '辛卯')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1909-02-29', '1909-03-20', 0, '己卯')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1909-02-30', '1909-03-21', 0, '庚辰')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1909-02-29', '1909-04-19', 1, '己酉')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1910-02-29', '1910-04-08', 0, '癸卯')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1910-02-30', '1910-04-09', 0, '甲辰')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1911-02-29', '1911-03-29', 0, '戊戌')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1913-02-29', '1913-04-05', 0, '丙辰')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1913-02-30', '1913-04-06', 0, '丁巳')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1914-02-29', '1914-03-25', 0, '庚戌')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1914-02-30', '1914-03-26', 0, '辛亥')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1915-02-29', '1915-04-13', 0, '甲戌')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1916-02-30', '1916-04-02', 0, '己巳')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1917-02-29', '1917-03-22', 0, '癸亥')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1917-02-29', '1917-04-20', 1, '壬辰')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1918-02-29', '1918-04-10', 0, '丁亥')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1919-02-29', '1919-03-30', 0, '辛巳')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1919-02-30', '1919-03-31', 0, '壬午')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1920-02-30', '1920-04-18', 0, '丙午')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1921-02-29', '1921-04-07', 0, '庚子')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1922-02-29', '1922-03-27', 0, '甲午')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1923-02-29', '1923-04-14', 0, '丁巳')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1923-02-30', '1923-04-15', 0, '戊午')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1925-02-29', '1925-03-23', 0, '丙午')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1926-02-29', '1926-04-11', 0, '庚午')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1927-02-29', '1927-04-01', 0, '乙丑')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1928-02-30', '1928-03-21', 0, '庚申')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1929-02-29', '1929-04-08', 0, '癸未')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1929-02-30', '1929-04-09', 0, '甲申')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1930-02-29', '1930-03-28', 0, '丁丑')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1930-02-30', '1930-03-29', 0, '戊寅')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1931-02-29', '1931-04-16', 0, '辛丑')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1931-02-30', '1931-04-17', 0, '壬寅')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1932-02-30', '1932-04-05', 0, '丙申')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1933-02-29', '1933-03-24', 0, '己丑')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1933-02-30', '1933-03-25', 0, '庚寅')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1934-02-29', '1934-04-12', 0, '癸丑')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1934-02-30', '1934-04-13', 0, '甲寅')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1935-02-29', '1935-04-02', 0, '戊申')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1937-02-29', '1937-04-10', 0, '丁卯')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1938-02-29', '1938-03-30', 0, '辛酉')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1938-02-30', '1938-03-31', 0, '壬戌')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1939-02-29', '1939-04-18', 0, '乙酉')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1939-02-30', '1939-04-19', 0, '丙戌')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1940-02-30', '1940-04-07', 0, '庚辰')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1941-02-29', '1941-03-26', 0, '癸酉')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1941-02-30', '1941-03-27', 0, '甲戌')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1942-02-29', '1942-04-14', 0, '丁酉')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1943-02-29', '1943-04-03', 0, '辛卯')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1943-02-30', '1943-04-04', 0, '壬辰')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1945-02-29', '1945-04-11', 0, '庚戌')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1946-02-29', '1946-04-01', 0, '乙巳')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1947-02-29', '1947-03-21', 0, '己亥')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1947-02-30', '1947-03-22', 0, '庚子')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1947-02-29', '1947-04-20', 1, '己巳')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1949-02-29', '1949-03-28', 0, '丁巳')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1949-02-30', '1949-03-29', 0, '戊午')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1950-02-29', '1950-04-16', 0, '辛巳')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1951-02-29', '1951-04-05', 0, '乙亥')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1952-02-30', '1952-03-25', 0, '庚午')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1953-02-29', '1953-04-12', 0, '癸巳')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1953-02-30', '1953-04-13', 0, '甲午')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1954-02-29', '1954-04-02', 0, '戊子')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1955-02-29', '1955-03-23', 0, '癸未')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1956-02-30', '1956-04-10', 0, '丁未')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1957-02-29', '1957-03-30', 0, '辛丑')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1958-02-29', '1958-04-17', 0, '甲子')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1958-02-30', '1958-04-18', 0, '乙丑')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1959-02-29', '1959-04-06', 0, '戊午')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1959-02-30', '1959-04-07', 0, '己未')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1961-02-29', '1961-04-14', 0, '丁丑')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1962-02-29', '1962-04-03', 0, '辛未')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1962-02-30', '1962-04-04', 0, '壬申')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1963-02-29', '1963-03-24', 0, '丙寅')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1965-02-29', '1965-03-31', 0, '甲申')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1965-02-30', '1965-04-01', 0, '乙酉')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1966-02-29', '1966-03-20', 0, '戊寅')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1966-02-30', '1966-03-21', 0, '己卯')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1967-02-29', '1967-04-08', 0, '壬寅')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1967-02-30', '1967-04-09', 0, '癸卯')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1968-02-30', '1968-03-28', 0, '丁酉')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1969-02-29', '1969-04-15', 0, '庚申')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1969-02-30', '1969-04-16', 0, '辛酉')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1970-02-29', '1970-04-05', 0, '乙卯')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1971-02-29', '1971-03-25', 0, '己酉')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1971-02-30', '1971-03-26', 0, '庚戌')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1972-02-30', '1972-04-13', 0, '甲戌')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1973-02-29', '1973-04-02', 0, '戊辰')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1974-02-29', '1974-03-22', 0, '壬戌')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1974-02-30', '1974-03-23', 0, '癸亥')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1975-02-29', '1975-04-10', 0, '丙戌')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1975-02-30', '1975-04-11', 0, '丁亥')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1976-02-30', '1976-03-30', 0, '辛巳')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1977-02-29', '1977-04-17', 0, '甲辰')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1978-02-29', '1978-04-06', 0, '戊戌')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1978-02-30', '1978-04-07', 0, '己亥')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1979-02-29', '1979-03-27', 0, '癸巳')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1981-02-29', '1981-04-03', 0, '辛亥')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1981-02-30', '1981-04-04', 0, '壬子')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1982-02-29', '1982-03-24', 0, '丙午')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1983-02-29', '1983-04-12', 0, '庚午')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1985-02-29', '1985-04-18', 0, '丁亥')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1985-02-30', '1985-04-19', 0, '戊子')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1986-02-29', '1986-04-07', 0, '辛巳')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1986-02-30', '1986-04-08', 0, '壬午')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1987-02-29', '1987-03-28', 0, '丙子')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1989-02-29', '1989-04-05', 0, '乙未')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1990-02-29', '1990-03-25', 0, '己丑')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1990-02-30', '1990-03-26', 0, '庚寅')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1991-02-29', '1991-04-13', 0, '癸丑')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1991-02-30', '1991-04-14', 0, '甲寅')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1992-02-30', '1992-04-02', 0, '戊申')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1993-02-29', '1993-03-21', 0, '辛丑')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1993-02-30', '1993-03-22', 0, '壬寅')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1994-02-29', '1994-04-09', 0, '乙丑')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1994-02-30', '1994-04-10', 0, '丙寅')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1995-02-29', '1995-03-29', 0, '己未')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1995-02-30', '1995-03-30', 0, '庚申')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1996-02-30', '1996-04-17', 0, '甲申')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1997-02-29', '1997-04-06', 0, '戊寅')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1998-02-29', '1998-03-27', 0, '癸酉')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('1999-02-29', '1999-04-15', 0, '丁酉')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2000-02-30', '2000-04-04', 0, '壬辰')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2001-02-29', '2001-03-23', 0, '乙酉')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2001-02-30', '2001-03-24', 0, '丙戌')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2002-02-29', '2002-04-11', 0, '己酉')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2002-02-30', '2002-04-12', 0, '庚戌')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2003-02-29', '2003-03-31', 0, '癸卯')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2003-02-30', '2003-04-01', 0, '甲辰')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2004-02-30', '2004-03-20', 0, '戊戌')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2005-02-29', '2005-04-07', 0, '辛酉')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2005-02-30', '2005-04-08', 0, '壬戌')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2006-02-29', '2006-03-28', 0, '丙辰')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2007-02-29', '2007-04-16', 0, '庚辰')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2009-02-29', '2009-03-25', 0, '己巳')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2009-02-30', '2009-03-26', 0, '庚午')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2010-02-29', '2010-04-13', 0, '癸巳')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2011-02-29', '2011-04-02', 0, '丁亥')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2013-02-29', '2013-04-09', 0, '乙巳')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2014-02-29', '2014-03-29', 0, '己亥')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2014-02-30', '2014-03-30', 0, '庚子')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2015-02-29', '2015-04-17', 0, '癸亥')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2015-02-30', '2015-04-18', 0, '甲子')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2017-02-29', '2017-03-27', 0, '癸丑')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2018-02-29', '2018-04-14', 0, '丙子')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2018-02-30', '2018-04-15', 0, '丁丑')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2019-02-29', '2019-04-04', 0, '辛未')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2021-02-29', '2021-04-10', 0, '戊子')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2021-02-30', '2021-04-11', 0, '己丑')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2022-02-29', '2022-03-31', 0, '癸未')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2023-02-29', '2023-03-20', 0, '丁丑')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2023-02-30', '2023-03-21', 0, '戊寅')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2023-02-29', '2023-04-19', 1, '丁未')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2024-02-30', '2024-04-08', 0, '壬寅')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2025-02-29', '2025-03-28', 0, '丙申')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2026-02-29', '2026-04-16', 0, '庚申')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2027-02-29', '2027-04-05', 0, '甲寅')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2027-02-30', '2027-04-06', 0, '乙卯')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2028-02-30', '2028-03-25', 0, '己酉')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2029-02-29', '2029-04-12', 0, '壬申')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2029-02-30', '2029-04-13', 0, '癸酉')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2030-02-29', '2030-04-01', 0, '丙寅')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2030-02-30', '2030-04-02', 0, '丁卯')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2031-02-29', '2031-03-22', 0, '辛酉')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2033-02-29', '2033-03-29', 0, '己卯')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2033-02-30', '2033-03-30', 0, '庚辰')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2034-02-29', '2034-04-17', 0, '癸卯')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2034-02-30', '2034-04-18', 0, '甲辰')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2035-02-29', '2035-04-07', 0, '戊戌')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2036-02-30', '2036-03-27', 0, '癸巳')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2037-02-29', '2037-04-14', 0, '丙辰')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2037-02-30', '2037-04-15', 0, '丁巳')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2038-02-29', '2038-04-03', 0, '庚戌')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2038-02-30', '2038-04-04', 0, '辛亥')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2039-02-29', '2039-03-23', 0, '甲辰')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2039-02-30', '2039-03-24', 0, '乙巳')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2041-02-29', '2041-03-31', 0, '癸亥')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2042-02-29', '2042-03-20', 0, '丁巳')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2042-02-30', '2042-03-21', 0, '戊午')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2042-02-29', '2042-04-19', 1, '丁亥')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2043-02-29', '2043-04-08', 0, '辛巳')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2043-02-30', '2043-04-09', 0, '壬午')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2045-02-29', '2045-04-16', 0, '庚子')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2046-02-29', '2046-04-05', 0, '甲午')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2047-02-29', '2047-03-25', 0, '戊子')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2048-02-30', '2048-04-12', 0, '壬子')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2049-02-29', '2049-04-01', 0, '丙午')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2050-02-29', '2050-03-22', 0, '辛丑')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2051-02-29', '2051-04-10', 0, '乙丑')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2052-02-30', '2052-03-30', 0, '庚申')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2053-02-29', '2053-04-17', 0, '癸未')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2053-02-30', '2053-04-18', 0, '甲申')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2054-02-29', '2054-04-06', 0, '丁丑')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2054-02-30', '2054-04-07', 0, '戊寅')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2055-02-29', '2055-03-26', 0, '辛未')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2055-02-30', '2055-03-27', 0, '壬申')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2056-02-30', '2056-04-14', 0, '丙申')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2057-02-29', '2057-04-02', 0, '己丑')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2057-02-30', '2057-04-03', 0, '庚寅')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2058-02-29', '2058-03-23', 0, '甲申')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2059-02-29', '2059-04-11', 0, '戊申')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2061-02-29', '2061-03-20', 0, '丁酉')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2061-02-30', '2061-03-21', 0, '戊戌')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2062-02-29', '2062-04-08', 0, '辛酉')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2062-02-30', '2062-04-09', 0, '壬戌')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2063-02-29', '2063-03-28', 0, '乙卯')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2063-02-30', '2063-03-29', 0, '丙辰')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2064-02-30', '2064-04-16', 0, '庚辰')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2065-02-29', '2065-04-04', 0, '癸酉')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2065-02-30', '2065-04-05', 0, '甲戌')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2066-02-29', '2066-03-24', 0, '丁卯')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2066-02-30', '2066-03-25', 0, '戊辰')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2067-02-29', '2067-04-12', 0, '辛卯')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2067-02-30', '2067-04-13', 0, '壬辰')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2069-02-29', '2069-03-22', 0, '辛巳')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2070-02-29', '2070-04-10', 0, '乙巳')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2071-02-29', '2071-03-30', 0, '己亥')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2071-02-30', '2071-03-31', 0, '庚子')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2073-02-29', '2073-04-06', 0, '丁巳')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2074-02-29', '2074-03-26', 0, '辛亥')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2075-02-29', '2075-04-14', 0, '乙亥')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2076-02-30', '2076-04-03', 0, '庚午')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2077-02-29', '2077-03-23', 0, '甲子')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2078-02-29', '2078-04-11', 0, '戊子')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2079-02-29', '2079-03-31', 0, '壬午')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2079-02-30', '2079-04-01', 0, '癸未')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2081-02-29', '2081-04-08', 0, '辛丑')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2082-02-29', '2082-03-27', 0, '甲午')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2082-02-30', '2082-03-28', 0, '乙未')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2083-02-29', '2083-04-15', 0, '戊午')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2083-02-30', '2083-04-16', 0, '己未')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2085-02-29', '2085-03-24', 0, '丁未')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2085-02-30', '2085-03-25', 0, '戊申')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2086-02-29', '2086-04-12', 0, '辛未')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2086-02-30', '2086-04-13', 0, '壬申')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2087-02-29', '2087-04-02', 0, '丙寅')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2088-02-30', '2088-03-22', 0, '辛酉')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2089-02-29', '2089-04-09', 0, '甲申')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2089-02-30', '2089-04-10', 0, '乙酉')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2090-02-29', '2090-03-29', 0, '戊寅')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2090-02-30', '2090-03-30', 0, '己卯')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2091-02-29', '2091-04-17', 0, '壬寅')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2091-02-30', '2091-04-18', 0, '癸卯')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2092-02-30', '2092-04-06', 0, '丁酉')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2093-02-29', '2093-03-25', 0, '庚寅')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2093-02-30', '2093-03-26', 0, '辛卯')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2094-02-29', '2094-04-14', 0, '乙卯')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2095-02-29', '2095-04-03', 0, '己酉')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2095-02-30', '2095-04-04', 0, '庚戌')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2097-02-29', '2097-04-11', 0, '戊辰')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2098-02-29', '2098-03-31', 0, '壬戌')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2098-02-30', '2098-04-01', 0, '癸亥')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2099-02-29', '2099-03-20', 0, '丙辰')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2099-02-30', '2099-03-21', 0, '丁巳')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2100-02-29', '2100-04-08', 0, '庚辰')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2100-02-30', '2100-04-09', 0, '辛巳')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2101-02-29', '2101-03-28', 0, '甲戌')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2101-02-30', '2101-03-29', 0, '乙亥')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2102-02-29', '2102-04-16', 0, '戊戌')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2103-02-29', '2103-04-06', 0, '癸巳')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2104-02-30', '2104-03-26', 0, '戊子')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2105-02-29', '2105-04-13', 0, '辛亥')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2105-02-30', '2105-04-14', 0, '壬子')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2106-02-29', '2106-04-03', 0, '丙午')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2107-02-29', '2107-03-23', 0, '庚子')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2107-02-30', '2107-03-24', 0, '辛丑')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2109-02-29', '2109-03-30', 0, '戊午')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2110-02-29', '2110-04-17', 0, '辛巳')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2110-02-30', '2110-04-18', 0, '壬午')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2111-02-29', '2111-04-07', 0, '丙子')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2112-02-30', '2112-03-27', 0, '辛未')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2113-02-29', '2113-04-15', 0, '乙未')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2114-02-29', '2114-04-04', 0, '己丑')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2114-02-30', '2114-04-05', 0, '庚寅')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2115-02-29', '2115-03-25', 0, '甲申')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2116-02-30', '2116-04-12', 0, '戊申')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2117-02-29', '2117-03-31', 0, '辛丑')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2117-02-30', '2117-04-01', 0, '壬寅')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2118-02-29', '2118-03-20', 0, '乙未')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2118-02-30', '2118-03-21', 0, '丙申')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2119-02-29', '2119-04-08', 0, '己未')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2119-02-30', '2119-04-09', 0, '庚申')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2121-02-29', '2121-04-16', 0, '戊寅')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2122-02-29', '2122-04-06', 0, '癸酉')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2123-02-29', '2123-03-26', 0, '丁卯')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2123-02-30', '2123-03-27', 0, '戊辰')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2124-02-30', '2124-04-14', 0, '壬辰')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2125-02-29', '2125-04-02', 0, '乙酉')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2125-02-30', '2125-04-03', 0, '丙戌')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2126-02-29', '2126-03-22', 0, '己卯')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2126-02-30', '2126-03-23', 0, '庚辰')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2127-02-29', '2127-04-10', 0, '癸卯')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2127-02-30', '2127-04-11', 0, '甲辰')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2128-02-30', '2128-03-30', 0, '戊戌')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2129-02-29', '2129-04-17', 0, '辛酉')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2129-02-30', '2129-04-18', 0, '壬戌')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2130-02-29', '2130-04-07', 0, '丙辰')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2131-02-29', '2131-03-28', 0, '辛亥')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2133-02-29', '2133-04-04', 0, '己巳')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2134-02-29', '2134-03-24', 0, '癸亥')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2134-02-30', '2134-03-25', 0, '甲子')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2135-02-29', '2135-04-12', 0, '丁亥')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2137-02-29', '2137-03-20', 0, '乙亥')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2137-02-30', '2137-03-21', 0, '丙子')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2137-02-29', '2137-04-19', 1, '乙巳')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2138-02-29', '2138-04-08', 0, '己亥')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2138-02-30', '2138-04-09', 0, '庚子')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2139-02-29', '2139-03-29', 0, '甲午')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2141-02-29', '2141-04-05', 0, '壬子')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2141-02-30', '2141-04-06', 0, '癸丑')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2142-02-29', '2142-03-26', 0, '丁未')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2143-02-29', '2143-04-13', 0, '庚午')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2143-02-30', '2143-04-14', 0, '辛未')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2144-02-30', '2144-04-02', 0, '乙丑')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2145-02-29', '2145-03-22', 0, '己未')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2146-02-29', '2146-04-10', 0, '癸未')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2147-02-29', '2147-03-30', 0, '丁丑')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2147-02-30', '2147-03-31', 0, '戊寅')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2148-02-30', '2148-04-18', 0, '壬寅')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2149-02-29', '2149-04-07', 0, '丙申')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2150-02-29', '2150-03-27', 0, '庚寅')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2150-02-30', '2150-03-28', 0, '辛卯')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2151-02-29', '2151-04-15', 0, '甲寅')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2151-02-30', '2151-04-16', 0, '乙卯')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2152-02-30', '2152-04-04', 0, '己酉')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2153-02-29', '2153-03-23', 0, '壬寅')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2153-02-30', '2153-03-24', 0, '癸卯')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2154-02-29', '2154-04-11', 0, '丙寅')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2154-02-30', '2154-04-12', 0, '丁卯')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2155-02-29', '2155-03-31', 0, '庚申')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2155-02-30', '2155-04-01', 0, '辛酉')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2157-02-29', '2157-04-08', 0, '己卯')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2157-02-30', '2157-04-09', 0, '庚辰')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2158-02-29', '2158-03-29', 0, '甲戌')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2159-02-29', '2159-04-17', 0, '戊戌')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2160-02-30', '2160-04-06', 0, '癸巳')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2161-02-29', '2161-03-25', 0, '丙戌')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2161-02-30', '2161-03-26', 0, '丁亥')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2162-02-29', '2162-04-13', 0, '庚戌')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2162-02-30', '2162-04-14', 0, '辛亥')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2163-02-29', '2163-04-02', 0, '甲辰')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2163-02-30', '2163-04-03', 0, '乙巳')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2164-02-30', '2164-03-22', 0, '己亥')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2165-02-29', '2165-04-09', 0, '壬戌')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2165-02-30', '2165-04-10', 0, '癸亥')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2166-02-29', '2166-03-30', 0, '丁巳')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2166-02-30', '2166-03-31', 0, '戊午')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2167-02-29', '2167-04-18', 0, '辛巳')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2167-02-30', '2167-04-19', 0, '壬午')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2169-02-29', '2169-03-27', 0, '庚午')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2169-02-30', '2169-03-28', 0, '辛未')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2170-02-29', '2170-04-15', 0, '甲午')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2171-02-29', '2171-04-04', 0, '戊子')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2173-02-29', '2173-04-11', 0, '丙午')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2174-02-29', '2174-03-31', 0, '庚子')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2174-02-30', '2174-04-01', 0, '辛丑')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2175-02-29', '2175-03-21', 0, '乙未')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2175-02-30', '2175-03-22', 0, '丙申')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2176-02-30', '2176-04-09', 0, '庚申')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2177-02-29', '2177-03-29', 0, '甲寅')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2178-02-29', '2178-04-16', 0, '丁丑')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2178-02-30', '2178-04-17', 0, '戊寅')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2179-02-29', '2179-04-05', 0, '辛未')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2179-02-30', '2179-04-06', 0, '壬申')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2180-02-30', '2180-03-25', 0, '丙寅')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2181-02-29', '2181-04-12', 0, '己丑')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2181-02-30', '2181-04-13', 0, '庚寅')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2182-02-29', '2182-04-02', 0, '甲申')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2183-02-29', '2183-03-22', 0, '戊寅')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2183-02-30', '2183-03-23', 0, '己卯')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2185-02-29', '2185-03-30', 0, '丁酉')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2185-02-30', '2185-03-31', 0, '戊戌')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2186-02-29', '2186-04-18', 0, '辛酉')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2186-02-30', '2186-04-19', 0, '壬戌')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2187-02-29', '2187-04-07', 0, '乙卯')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2187-02-30', '2187-04-08', 0, '丙辰')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2188-02-30', '2188-03-27', 0, '庚戌')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2189-02-29', '2189-04-14', 0, '癸酉')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2189-02-30', '2189-04-15', 0, '甲戌')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2190-02-29', '2190-04-03', 0, '丁卯')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2190-02-30', '2190-04-04', 0, '戊辰')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2191-02-29', '2191-03-24', 0, '壬戌')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2193-02-29', '2193-03-31', 0, '庚辰')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2193-02-30', '2193-04-01', 0, '辛巳')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2194-02-29', '2194-03-21', 0, '乙亥')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2194-02-30', '2194-03-22', 0, '丙子')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2195-02-29', '2195-04-09', 0, '己亥')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2196-02-30', '2196-03-29', 0, '甲午')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2197-02-29', '2197-04-16', 0, '丁巳')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2198-02-29', '2198-04-05', 0, '辛亥')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2199-02-29', '2199-03-25', 0, '乙巳')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2199-02-30', '2199-03-26', 0, '丙午')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2200-02-29', '2200-04-13', 0, '己巳')";
	$q[] = "INSERT INTO nmail_diary_lunar VALUES('2200-02-30', '2200-04-14', 0, '庚午')";
	$q_cnt = sizeof($q);
	for ($i=0; $i<$q_cnt; $i++)
	{
		db_query(win_utf8_conv($q[$i]));
	}	// for()
}	// if()

// [2008-10-21] 수정화면에서 메일용량을 변경할 경우 실제 서버에 반영안되는 문제수정.
$mbr_quota_update = $updated_dir.DIRECTORY_SEPARATOR.'mbr_quota_update';
if (!file_exists($mbr_quota_update))
{
	$q = "
		SELECT
			m.m_id, m.m_quota, d.d_name
		FROM
			".$TB['MEMBER']." m,
			".$TB['DOMAIN']." d
		WHERE
			m.d_no=d.d_no
			AND m.m_usertype IS NULL
		";
	$rows = db_get_rows($q);
	for ($i=0; $i<sizeof($rows); $i++)
	{
		$G_SYS['MAIL_DOMAIN'] = $rows[$i]['d_name'];
		mbr_quota_mod($rows[$i]['m_id'], $rows[$i]['m_quota']);
	}	// for()
	touch($mbr_quota_update);

	echo " [OK]메일계정의 메일용량이 제대로 수정되지 않았던 문제가 일괄 수정되었습니다.\n\n";
}	// if()


// [2009-03-27] White IP 에서는 RBL 체크 생략
// 설정파일과 디비간의 차이가 있을 경우 동기화를 시켜줌.
// 동기화조건 : 디비에 없는 설정파일의 내용을 디비에 추가한 다음, 디비를 기준으로 설정파일을 새로 생성함.
nm_iptab_dbsync($TB['WHITE_IP'], 'smtp.ipprop.tab');
nm_iptab_dbsync($TB['BLACK_IP'], 'spammers.tab');
nm_iptab_dbsync($TB['RELAY_IP'], 'smtprelay.tab');


// [2011-01-04] 게시판 메뉴관리 추가
$admin_board_menu_add = $updated_dir.DIRECTORY_SEPARATOR.'admin_board_menu_add';
if (!file_exists($admin_board_menu_add))
{
	$q = "
		SELECT
			d_no
		FROM
			".$TB['DOMAIN']."
		";
	$rows = db_get_rows($q);
	for ($i=0; $i<sizeof($rows); $i++)
	{
		$q = "SELECT COUNT(*) FROM ".$TB['BOARD_MENU']." WHERE d_no='".$rows[$i]['d_no']."'";
		$board_menu_cnt = db_get_one($q);
		if ($board_menu_cnt < 1)
		{
			// [2011-03-29] 게시판이 하나라도 있는 경우에만 메뉴관리 추가
			$q = "SELECT COUNT(*) FROM ".$TB['BOARD_ADMIN']." WHERE d_no='".$rows[$i]['d_no']."'";
			$board_admin_cnt = db_get_one($q);

			if ($board_admin_cnt > 0)
			{
				$q = "
					INSERT INTO
						" . $TB['BOARD_MENU'] . "
						(bm_no, d_no, bm_name, bm_sort)
					VALUES
						(".db_sqc_next($TB['BOARD_MENU']).", '" . $rows[$i]['d_no'] . "', '게시판', '0')
					";
				db_query($q);

				$curr_bm_no = db_sqc_curr($TB['BOARD_MENU']);

				$q = "UPDATE ".$TB['BOARD_ADMIN']." SET bm_no='".$curr_bm_no."' WHERE d_no='".$rows[$i]['d_no']."' AND bm_no IS NULL";
				db_query($q);
			}	// if()
		}	// if()
	}	// for()
	touch($admin_board_menu_add);
}	// if()

// [2012-10-17] 앨리어스 주소 관리
$admin_alias_add = $updated_dir.DIRECTORY_SEPARATOR.'admin_alias_add';
if (!file_exists($admin_alias_add))
{
	$tab = nm_cfgfileget('aliases.tab');

	if (is_array($tab))
	{
		for ($i=0; $i<sizeof($tab); $i++)
		{
			$q = "SELECT d_no FROM ".$TB['DOMAIN']." WHERE d_name='".$tab[$i][0]."'";
			$_d_no = db_get_one($q);

			$q = "SELECT COUNT(*) FROM ".$TB['MEMBER']." WHERE m_id='" . $tab[$i][1] . "' AND d_no='".$_d_no."' AND m_usertype='A'";
			$_alias_cnt = db_get_one($q);

			if ($_alias_cnt == 0)
			{
				$_m_id = trim($tab[$i][1]);		// alias
				$_m_name = trim($tab[$i][2]);		// real
				$m_usertype = 'A';		// Alias User
				$m_mail_file_group = get_mail_file_group_now($_d_no);
				$q = "INSERT INTO ".$TB['MEMBER']." (m_no, d_no, m_id, m_pwd, m_level, m_name, m_is_use, m_mail_file_group, m_quota, m_bigfile_quota, m_webhard_quota, m_forwarding_type, m_regdate, m_reghost, m_login_cnt, m_autoreply_isuse, m_svc_smtp, m_svc_pop3, m_usertype, m_memo)";
				$q .= " VALUES (".db_sqc_next($TB['MEMBER']).", '".$_d_no."', '".$_m_id."', '', 0, '".$_m_name."', 'Y', '".$m_mail_file_group."', 0, 0, 0, 'N', '".date("Y-m-d H:i:s")."', '".$_SERVER['REMOTE_ADDR']."', 0, 'N', 'N', 'N', '".$m_usertype."', '')";
				db_query($q);
			}	// if()
		}	// for()
	}	// if()

	touch($admin_alias_add);
}	// if()

// [2013-06-05] 앨리어스 주소 관리 - 업데이트 보완
$q = "SELECT m_no, m_id, m_name FROM ".$TB['MEMBER']." WHERE m_usertype = 'A' AND (m_id LIKE '%\\n%' OR m_name LIKE '%\\n%')";
$rows = db_get_rows($q);
for ($i=0; $i<sizeof($rows); $i++)
{
	$q = "UPDATE ".$TB['MEMBER']." SET m_id='".trim($rows[$i]['m_id'])."', m_name='".trim($rows[$i]['m_name'])."' WHERE m_no='".$rows[$i]['m_no']."'";
	db_query($q);
}	// for()

// [2012-11-05] 앨리어스 도메인 관리
$sdomain_alias_add = $updated_dir.DIRECTORY_SEPARATOR.'sdomain_alias_add';
if (!file_exists($sdomain_alias_add))
{
	$tab = nm_cfgfileget('aliasdomain.tab');

	if (is_array($tab))
	{
		for ($i=0; $i<sizeof($tab); $i++)
		{
			$_da_name = $tab[$i][0];		// alias
			$_d_name = $tab[$i][1];		// real

			$q = "SELECT * FROM ".$TB['DOMAIN_ALIAS']." WHERE da_name='".$_da_name."'";
			$_da = db_get_row($q);

			if (!$_da)
			{
				$q = "SELECT d_no FROM ".$TB['DOMAIN']." WHERE d_name='".$_d_name."'";
				$_d_no = db_get_one($q);

				if ($_d_no > 0)
				{
					$q = "
						INSERT INTO
							" .	$TB['DOMAIN_ALIAS']	. "
							( da_no , d_no , da_name, da_mail_from_select, da_regdate )
						VALUES
							( ".db_sqc_next($TB['DOMAIN_ALIAS']).", '" . $_d_no . "', '" .	$_da_name . "', 'N', '"	. date("Y-m-d H:i:s") .	"' )
						";
					db_query($q);
				}	// if()
			}	// if()
		}	// for()
	}	// if()

	touch($sdomain_alias_add);
}	// if()

// [2012-11-13] IE 10 호환성 패치, 스킨 자동 적용
$ie10_skin_auto_update = $updated_dir.DIRECTORY_SEPARATOR.'ie10_skin_auto_update';
if (!file_exists($ie10_skin_auto_update))
{
	$skin_files = array('layout.inc.html', 'layout_iframe.inc.html', 'layout_window_open.inc.html', 'login.html');
	$backup_dir = $updated_dir.DIRECTORY_SEPARATOR.'backup_skin_main_'.date('Ymd_His', $_time);
	if (!is_dir($backup_dir))
		mkdir($backup_dir);

	$skin_file_add_content = '<?= $G_SYS[\'NM_HTML_HEAD_FIRST\'] ?>';

	$skin_main = $G_SYS[PAGE_ROOT].'/skin/main/';
	$modify_files = array();
	if (is_dir($skin_main))
	{
		$handle=opendir($skin_main);
		while ($node = readdir($handle))
		{
		   if ($node!="." && $node!=".." && is_dir($skin_main.$node))
		   {
			   // test - 특정 스킨만
			   //if ($node == 'basic2.5_up_test')
			   if (1)
			   {
				   $_is_ok = true;
				   foreach ($skin_files as $key=>$val)
				   {
					   if (!file_exists($skin_main.$node.DIRECTORY_SEPARATOR.$val))
					   {
						   $_is_ok = false;
						   break;
					   }	// if()
				   }	// foreach()
				   if ($_is_ok)
				   {
					   if (!is_dir($backup_dir.DIRECTORY_SEPARATOR.$node))
						   mkdir($backup_dir.DIRECTORY_SEPARATOR.$node);
					   foreach ($skin_files as $key=>$val)
					   {
						   // backup
						   $skinfile = $skin_main.$node.DIRECTORY_SEPARATOR.$val;
						   copy($skinfile, $backup_dir.DIRECTORY_SEPARATOR.$node.DIRECTORY_SEPARATOR.$val);

						   // modify
							$fd = fopen($skinfile, "r");
							$contents = fread($fd, filesize($skinfile));
							$fstat = fstat($fd);
							$modtime = $fstat['mtime'];
							fclose($fd);

							$sp = strpos($contents, $skin_file_add_content);
							if ($sp === false)
							{
								$contents2 = str_replace("<head>", "<head>\n\t".$skin_file_add_content, $contents);
								if (strcmp($contents, $contents2))
								{
									$fh = fopen($skinfile, 'w');
									fwrite($fh, $contents2);
									fclose($fh);
									// [2013-06-07] touch($skinfile, $modtime);
									$modify_files[] = $skinfile;
								}	// if()
							}	// if()
					   }	// foreach()
				   }	// if()
			   }	// if()
		   }
		}
		closedir($handle);
	} else
	{
		die("[Error/ie10_skin_auto_update]웹메일 스킨 디렉토리가 존재하지 않습니다.=> ".$skin_main);
	}	// if()

	if ($modify_files)
	{
		echo " [OK]IE 10 호환성 패치를 위해 아래 스킨파일들에 프로그램 코드가 추가되었습니다.\n    - 추가된 프로그램 코드 : ".$skin_file_add_content."\n    - 원본 소스 백업 디렉토리 : ".$backup_dir."\n\n";
		foreach ($modify_files as $key=>$val)
		{
			echo "      ".$val."\n";
		}	// foreach()
	}	// if()

	touch($ie10_skin_auto_update);
}	// if()


// [2013-05-22] IE 10 호환성 패치 2, 스킨 자동 적용
$ie10_skin_auto_update2 = $updated_dir.DIRECTORY_SEPARATOR.'ie10_skin_auto_update2';
if (!file_exists($ie10_skin_auto_update2))
{
	$skin_files = array('page_loading_view.inc.html');
	$backup_dir = $updated_dir.DIRECTORY_SEPARATOR.'backup_skin_webmail_'.date('Ymd_His', $_time);
	if (!is_dir($backup_dir))
		mkdir($backup_dir);

	$skin_file_add_content = '<?= $G_SYS[\'NM_HTML_HEAD_FIRST\'] ?>';

	$skin_main = $G_SYS[PAGE_ROOT].'/skin/webmail/';
	$modify_files = array();
	if (is_dir($skin_main))
	{
		$handle=opendir($skin_main);
		while ($node = readdir($handle))
		{
		   if ($node!="." && $node!=".." && is_dir($skin_main.$node))
		   {
			   // test - 특정 스킨만
			   //if ($node == 'basic2.5_up_test')
			   if (1)
			   {
				   $_is_ok = true;
				   foreach ($skin_files as $key=>$val)
				   {
					   if (!file_exists($skin_main.$node.DIRECTORY_SEPARATOR.$val))
					   {
						   $_is_ok = false;
						   break;
					   }	// if()
				   }	// foreach()
				   if ($_is_ok)
				   {
					   if (!is_dir($backup_dir.DIRECTORY_SEPARATOR.$node))
						   mkdir($backup_dir.DIRECTORY_SEPARATOR.$node);
					   foreach ($skin_files as $key=>$val)
					   {
						   // backup
						   $skinfile = $skin_main.$node.DIRECTORY_SEPARATOR.$val;
						   copy($skinfile, $backup_dir.DIRECTORY_SEPARATOR.$node.DIRECTORY_SEPARATOR.$val);

						   // modify
							$fd = fopen($skinfile, "r");
							$contents = fread($fd, filesize($skinfile));
							$fstat = fstat($fd);
							$modtime = $fstat['mtime'];
							fclose($fd);

							$sp = strpos($contents, $skin_file_add_content);
							if ($sp === false)
							{
								$contents2 = str_replace("<head>", "<head>\n\t".$skin_file_add_content, $contents);
								if (strcmp($contents, $contents2))
								{
									$fh = fopen($skinfile, 'w');
									fwrite($fh, $contents2);
									fclose($fh);
									// [2013-06-07] touch($skinfile, $modtime);
									$modify_files[] = $skinfile;
								}	// if()
							}	// if()
					   }	// foreach()
				   }	// if()
			   }	// if()
		   }
		}
		closedir($handle);
	} else
	{
		die("[Error/ie10_skin_auto_update2]웹메일 스킨 디렉토리가 존재하지 않습니다.=> ".$skin_main);
	}	// if()

	if ($modify_files)
	{
		echo " [OK]IE 10 호환성 패치를 위해 아래 스킨파일들에 프로그램 코드가 추가되었습니다.\n    - 추가된 프로그램 코드 : ".$skin_file_add_content."\n    - 원본 소스 백업 디렉토리 : ".$backup_dir."\n\n";
		foreach ($modify_files as $key=>$val)
		{
			echo "      ".$val."\n";
		}	// foreach()
	}	// if()

	touch($ie10_skin_auto_update2);
}	// if()


// [2012-11-14] 일부 스킨의 css 변경, 스킨 자동 적용
$skin_style_auto_update2 = $updated_dir.DIRECTORY_SEPARATOR.'skin_style_auto_update2';
if (!file_exists($skin_style_auto_update2))
{
	$skin_files = array('style.css');
	$backup_dir = $updated_dir.DIRECTORY_SEPARATOR.'backup_skin_main_css_'.date('Ymd_His', $_time);
	if (!is_dir($backup_dir))
		mkdir($backup_dir);

	$skin_file_add_content = '.main_table_head2';

	$skin_main = $G_SYS[PAGE_ROOT].'/skin/main/';
	$modify_files = array();
	if (is_dir($skin_main))
	{
		$handle=opendir($skin_main);
		while ($node = readdir($handle))
		{
		   if ($node!="." && $node!=".." && is_dir($skin_main.$node))
		   {
			   // test - 특정 스킨만
			   //if ($node == 'basic2.5_up_test')
			   if (1)
			   {
				   $_is_ok = true;
				   foreach ($skin_files as $key=>$val)
				   {
					   if (!file_exists($skin_main.$node.DIRECTORY_SEPARATOR.$val))
					   {
						   $_is_ok = false;
						   break;
					   }	// if()
				   }	// foreach()
				   if ($_is_ok)
				   {
					   if (!is_dir($backup_dir.DIRECTORY_SEPARATOR.$node))
						   mkdir($backup_dir.DIRECTORY_SEPARATOR.$node);
					   foreach ($skin_files as $key=>$val)
					   {
						   // backup
						   $skinfile = $skin_main.$node.DIRECTORY_SEPARATOR.$val;
						   copy($skinfile, $backup_dir.DIRECTORY_SEPARATOR.$node.DIRECTORY_SEPARATOR.$val);

						   // modify
							$fd = fopen($skinfile, "r");
							$contents = fread($fd, filesize($skinfile));
							$fstat = fstat($fd);
							$modtime = $fstat['mtime'];
							fclose($fd);

							$sp = strpos($contents, $skin_file_add_content);
							if ($sp === false)
							{
								$contents2 = $contents."\n";
								$contents2 .= "\n";
								$contents2 .= "/* [2012-10-29] */\n";
								$contents2 .= ".main_table_head2 { background-color:#9197C2; color: #FFFFFF; font-weight: bold; text-align: center; }\n";
								$contents2 .= ".main_table_head2 td { background-color:#9197C2; color: #FFFFFF; font-weight: bold; text-align: center; }\n";
								$contents2 .= ".main_table_head2 a { background-color:#9197C2; color: #FFFFFF; font-weight: bold; text-align: center; }\n";
								$contents2 .= ".main_table_head2 a:link { background-color:#9197C2; color: #FFFFFF; font-weight: bold; text-align: center; }\n";
								$contents2 .= ".main_table_head2 a:visited { background-color:#9197C2; color: #FFFFFF; font-weight: bold; text-align: center; }\n";
								$contents2 .= ".main_table_list_tail_bar { background-color:#D7D4E8; }\n";
								$contents2 .= ".diary_month_table_outer { background-color:#867BA1; }\n";
								if (strcmp($contents, $contents2))
								{
									$fh = fopen($skinfile, 'w');
									fwrite($fh, $contents2);
									fclose($fh);
									// [2013-06-07] touch($skinfile, $modtime);
									$modify_files[] = $skinfile;
								}	// if()
							}	// if()
					   }	// foreach()
				   }	// if()
			   }	// if()
		   }
		}
		closedir($handle);
	} else
	{
		die("[Error/skin_style_auto_update2]웹메일 스킨 디렉토리가 존재하지 않습니다.=> ".$skin_main);
	}	// if()

	if ($modify_files)
	{
		echo " [OK]웹메일 스킨의 css class 추가를 위해 아래 style.css 파일에 class 가 추가되었습니다.\n    - 추가된 class : main_table_head2, main_table_list_tail_bar, diary_month_table_outer\n    - 원본 소스 백업 디렉토리 : ".$backup_dir."\n\n";
		foreach ($modify_files as $key=>$val)
		{
			echo "      ".$val."\n";
		}	// foreach()
	}	// if()

	touch($skin_style_auto_update2);
}	// if()


// [2013-06-05]크롬/파이어폭스 호환 패치
$chrome_skin_auto_update = $updated_dir.DIRECTORY_SEPARATOR.'chrome_skin_auto_update';
if (!file_exists($chrome_skin_auto_update))
{
	$skin_files = array('notice.html');
	$backup_dir = $updated_dir.DIRECTORY_SEPARATOR.'backup_skin_member_'.date('Ymd_His', $_time);
	if (!is_dir($backup_dir))
		mkdir($backup_dir);

	$skin_file_add_content = '<?= $nmpath ?>/member.php?mode=JOIN';

	$skin_main = $G_SYS[PAGE_ROOT].'/skin/member/';
	$modify_files = array();
	if (is_dir($skin_main))
	{
		$handle=opendir($skin_main);
		while ($node = readdir($handle))
		{
		   if ($node!="." && $node!=".." && is_dir($skin_main.$node))
		   {
			   // test - 특정 스킨만
			   //if ($node == 'basic2.5_up_test')
			   if (1)
			   {
				   $_is_ok = true;
				   foreach ($skin_files as $key=>$val)
				   {
					   if (!file_exists($skin_main.$node.DIRECTORY_SEPARATOR.$val))
					   {
						   $_is_ok = false;
						   break;
					   }	// if()
				   }	// foreach()
				   if ($_is_ok)
				   {
					   if (!is_dir($backup_dir.DIRECTORY_SEPARATOR.$node))
						   mkdir($backup_dir.DIRECTORY_SEPARATOR.$node);
					   foreach ($skin_files as $key=>$val)
					   {
						   // backup
						   $skinfile = $skin_main.$node.DIRECTORY_SEPARATOR.$val;
						   copy($skinfile, $backup_dir.DIRECTORY_SEPARATOR.$node.DIRECTORY_SEPARATOR.$val);

						   // modify
							$fd = fopen($skinfile, "r");
							$contents = fread($fd, filesize($skinfile));
							$fstat = fstat($fd);
							$modtime = $fstat['mtime'];
							fclose($fd);

							$sp = strpos($contents, $skin_file_add_content);
							if ($sp === false)
							{
								$contents2 = str_replace("JavaScript:self.location='member.php?mode=JOIN';", $skin_file_add_content, $contents);
								if (strcmp($contents, $contents2))
								{
									$fh = fopen($skinfile, 'w');
									fwrite($fh, $contents2);
									fclose($fh);
									// [2013-06-07] touch($skinfile, $modtime);
									$modify_files[] = $skinfile;
								}	// if()
							}	// if()
					   }	// foreach()
				   }	// if()
			   }	// if()
		   }
		}
		closedir($handle);
	} else
	{
		die("[Error/chrome_skin_auto_update]웹메일 스킨 디렉토리가 존재하지 않습니다.=> ".$skin_main);
	}	// if()

	if ($modify_files)
	{
		echo " [OK]크롬/파이어폭스 호환성 패치를 위해 아래 스킨파일들에 프로그램 코드가 추가되었습니다.\n    - 추가된 프로그램 코드 : ".$skin_file_add_content."\n    - 원본 소스 백업 디렉토리 : ".$backup_dir."\n\n";
		foreach ($modify_files as $key=>$val)
		{
			echo "      ".$val."\n";
		}	// foreach()
	}	// if()

	touch($chrome_skin_auto_update);
}	// if()


// [2013-07-08] robots.txt 자동 추가
$robots_add = $updated_dir.DIRECTORY_SEPARATOR.'robots_add';
if (!file_exists($robots_add))
{
	if (!file_exists(dirname($G_SYS[PAGE_ROOT]).'/nmail/robots.txt'))
		copy(dirname($G_SYS[PAGE_ROOT]).'/tools/updated/robots.txt', dirname($G_SYS[PAGE_ROOT]).'/nmail/robots.txt');
	touch($robots_add);
}	// if()


// [2013-07-09] custom
if (file_exists(dirname($G_SYS[PAGE_ROOT]).'/tools/__custom_update_db.php'))
{
	include(dirname($G_SYS[PAGE_ROOT]).'/tools/__custom_update_db.php');
}	// if()


################################################################################
# 사용자 질의후 처리
################################################################################

$member_group_isuse = $updated_dir.DIRECTORY_SEPARATOR.'member_group_isuse';
if (!file_exists($member_group_isuse))
{
	// [2008-08-26]
	title("조직도 기능 사용여부 선택");
	echo($crlf."  기능안내)".$crlf."    새롭게 추가된 조직도 기능은 편지쓰기와 주소록 메뉴에서".$crlf."    조직이 설정된 회원 리스트를 사용자들이 확인하고 사용할 수 있게 됩니다.".$crlf."  주의)".$crlf."    회원 리스트가 일반 사용자에게 보여지므로 회사처럼 특정 사용자로 제한된 환경에서만 사용해야 합니다.".$crlf."  참고) ".$crlf."    사용할 경우 모든 도메인에  일괄 적용됩니다.".$crlf."    필요시 [도메인관리 >> 도메인설정]이나 [메일서버관리 >> 도메인관리]에서 도메인별로 변경이 가능합니다.".$crlf);
	$scan = scanf($crlf."  조직도 기능을 사용하시겠습니까? [Y/n] : ", array('Y', 'N'), 2);
	if ($scan == 'Y')
	{
		$q = "UPDATE ".$TB['DOMAIN']." SET d_mbrgrp_isuse='Y'";
		db_query($q);

		echo $crlf;
		title("회원 가입항목 변경");
		echo($crlf."  기능안내)".$crlf."    [주소록 >> 조직도]에서 보여지는 '휴대폰, 전화' 필드를 관리자나 사용자가 입력할 수 있도록 합니다.".$crlf."  참고) ".$crlf."    변경할 경우 모든 도메인에  일괄 적용됩니다.".$crlf."    필요시 [관리자메뉴 >> 회원관리 >> 가입항목관리]에서 '핸드폰(PCS), 직장 전화번호'".$crlf."    필드의 사용여부를 도메인별로 변경이 가능합니다.".$crlf);
		$scan = scanf($crlf."  회원 가입항목에서 '휴대폰, 전화'필드를 '사용함'으로 변경하시겠습니까? [Y/n] : ", array('Y', 'N'), 2);
		if ($scan == 'Y')
		{
			$q = "UPDATE ".$TB['MEMBER_FIELD']." SET mbf_isuse='Y' WHERE mbf_name IN ('m_mobile', 'm_office_tel')";
			db_query($q);
		}	// if()
	}	// if()

	/*
	echo $crlf;
	title("최신스킨으로 변경");
	echo($crlf."  기능안내)".$crlf."    새롭게 개편된 메뉴구성과 조직도 기능을 사용하려면 최신스킨으로 변경해야 합니다.".$crlf."  주의)".$crlf."    프로그램 소스나 스킨을 직접 수정하신 경우에는 변경시 문제가 발생할 수 있으므로 따로 확인해보신후 변경하셔야 합니다.".$crlf."  참고) ".$crlf."    변경할 경우 모든 도메인에  일괄 적용됩니다.".$crlf."    필요시 [도메인관리 >> 도메인설정]이나 [메일서버관리 >> 도메인관리]에서 도메인별로 변경이 가능합니다.".$crlf);
	$scan = scanf($crlf."  최신스킨(basic2.5)으로 변경하시겠습니까? [y/N] : ", array('N', 'Y'), 2);
	if ($scan == 'Y')
	{
		$q = "UPDATE ".$TB['DOMAIN']." SET d_skin_main='basic2.5', d_skin_webmail='basic', d_skin_member='basic', d_skin_board='basic'";
		db_query($q);
	}	// if()
	*/
	touch($member_group_isuse);
}	// if()

// [2009-04-30] 웹에디터 선택
$webeditor_ischange = $updated_dir.DIRECTORY_SEPARATOR.'webeditor_ischange';
if (!file_exists($webeditor_ischange))
{
	title("새로운 웹에디터 교체여부 선택");
	echo($crlf."  기능안내)".$crlf."    편지쓰기시 본문내에 이미지 첨부(업로드)가 지원되는 새로운 웹에디터(TinyMCE)로 교체할 수 있습니다.".$crlf."  주의)".$crlf."    직접 소스를 수정하여 웹에디터를 교체하신 경우에는 아니오(n)를 누르셔야 합니다.".$crlf);
	$scan = scanf($crlf."  최신 웹에디터로 교체하시겠습니까? [Y/n] : ", array('Y', 'N'), 2);
	if ($scan == 'Y')
	{
		$file = '../nmail/include/global_var.php';
		$data = file_get_contents($file);
		$data = str_replace(array("\$G_SYS['WEBEDITOR'] = 'OPEN';", "\$G_SYS['WEBEDITOR'] = 'FCK';", "\$G_SYS['WEBEDITOR'] = 'GM';"), "\$G_SYS['WEBEDITOR'] = 'TINYMCE';", $data);
		file_write($file, $data);
	}	// if()
	touch($webeditor_ischange);
}	// if()


// [2009-05-06] 편지함 백업/복구 사용여부
$mail_box_backup_isuse = $updated_dir.DIRECTORY_SEPARATOR.'mail_box_backup_isuse';
if (!file_exists($mail_box_backup_isuse))
{
	title("편지함 백업/복구 사용여부 선택");
	echo($crlf."  기능안내)".$crlf."    사용자들이 직접 편지함내의 메일들을 백업받고, 복구할 수 있는 기능을 추가되었습니다.".$crlf."  주의)".$crlf."    서버에서 메일파일들의 압축 및 압축해제가 이루어지므로 서버부하가 늘어나는 것을 고려하셔야 합니다.".$crlf."  기능참고)".$crlf."    필요시 [메일서버관리 >> 서버 설정]에서 변경이 가능합니다.".$crlf);
	$scan = scanf($crlf."  편지함 백업/복구 기능을 사용하시겠습니까? [Y/n] : ", array('Y', 'N'), 2);

	$file = $UPLOAD_ROOT.'/config/nmail_server.php';
	if (file_exists($file))
	{
		$data = file_get_contents($file);
		if ($scan == 'Y')
		{
			// [2008-09-24] 편지함 백업/복구시 사용되는 압축 프로그램 Linux/Windows 구분
			if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN')
			{
				$unzip_bin = dirname($G_SYS[PAGE_ROOT]).'/tools/7-zip/7za.exe';
				if (!file_exists($unzip_bin))
				{
					echo $crlf."  에러)".$crlf."    서버에서 압축프로그램을 찾을 수 없습니다. => ".$unzip_bin.$crlf;
					scanf($crlf."-- 엔터를 누르면 계속 진행됩니다. --", array(), 5, false, true);
				}	// if()
			} else
			{
				$zip_bin = '/usr/bin/zip';
				if (!file_exists($zip_bin))
				{
					echo $crlf."  에러)".$crlf."    서버에서 압축프로그램을 찾을 수 없습니다. => ".$zip_bin.$crlf;
					echo "    서버 OS의 배포판에서 제공하는 zip 패키지를 설치하셔야 합니다.".$crlf;
					scanf($crlf."-- 엔터를 누르면 계속 진행됩니다. --", array(), 5, false, true);
				}	// if()

				$unzip_bin = '/usr/bin/unzip';
				if (!file_exists($unzip_bin))
				{
					echo $crlf."  에러)".$crlf."    서버에서 압축프로그램을 찾을 수 없습니다. => ".$unzip_bin.$crlf;
					echo "    서버 OS의 배포판에서 제공하는 unzip 패키지를 설치하셔야 합니다.".$crlf;
					scanf($crlf."-- 엔터를 누르면 계속 진행됩니다. --", array(), 5, false, true);
				}	// if()
			}	// if()

			$data = str_replace('?>', win_utf8_conv("\$G_SYS[MAIL_BOX_BACKUP_USE] = 1;		// 편지함 백업/복구 사용여부.\n?>"), $data);
		} else
		{
			$data = str_replace('?>', win_utf8_conv("\$G_SYS[MAIL_BOX_BACKUP_USE] = 0;		// 편지함 백업/복구 사용여부.\n?>"), $data);
		}	// if()
		file_write($file, $data, 0777);
	}	// if()
	touch($mail_box_backup_isuse);
}	// if()


// [2013-07-08] White IP 추가
$white_ip_add = $updated_dir.DIRECTORY_SEPARATOR.'white_ip_add';
if (!file_exists($white_ip_add))
{
	$sql = "SELECT COUNT(*)  FROM " . $TB['WHITE_IP'] . " WHERE ip_ipaddr='127.0.0.1' AND ip_netmask='255.255.255.255'";
	$ip_cnt = db_get_one($sql);

	if ($ip_cnt == 0)
	{
		echo $crlf;
		title("White IP 에 웹메일 발송 IP 등록");
		echo($crlf."  White IP 에 웹메일 발송 IP 인 127.0.0.1 을 등록하면, 웹메일에서 보낸 메일은 스팸검사를 거치지 않게 됩니다.".$crlf."    필요시 [메일서버관리 - White IP 관리]에서 추가/삭제가 가능합니다.".$crlf);
		$scan = scanf($crlf."  White IP 에 127.0.0.1 을 등록하시겠습니까? [Y/n] : ", array('Y', 'N'), 2);
		if ($scan == 'Y')
		{
			$sql = "
				INSERT INTO
					" . $TB['WHITE_IP'] . "
					(ip_ipaddr, ip_netmask, ip_regdate)
				VALUES
					('127.0.0.1', '255.255.255.255', '" . date('Y-m-d H:i:s') . "')
				";
			db_query($sql);

			// 디비를 기준으로 설정파일 갱신.
			nm_iptab_update_by_db($TB['WHITE_IP'], 'smtp.ipprop.tab');
		}	// if()
	}	// if()

	touch($white_ip_add);
}	// if()


$skin_main_basic26 = $updated_dir.DIRECTORY_SEPARATOR.'skin_main_basic2.6.1';
if (!file_exists($skin_main_basic26))
{
	echo $crlf;
	title("최신스킨으로 변경");
	echo($crlf."  기능안내)".$crlf."    새롭게 개편된 [게시판 메뉴관리]와 [조직도 상세정보]를 사용하려면 최신스킨으로 변경해야 합니다.".$crlf."  주의)".$crlf."    프로그램 소스나 스킨을 직접 수정하신 경우에는 변경시 문제가 발생할 수 있으므로 따로 확인해보신후 변경하셔야 합니다.".$crlf."  참고) ".$crlf."    변경할 경우 모든 도메인에  일괄 적용됩니다.".$crlf."    필요시 [도메인관리 >> 도메인설정]이나 [메일서버관리 >> 도메인관리]에서 도메인별로 변경이 가능합니다.".$crlf);
	$scan = scanf($crlf."  최신스킨(basic2.6.1)으로 변경하시겠습니까? [y/N] : ", array('N', 'Y'), 2);
	if ($scan == 'Y')
	{
		$q = "UPDATE ".$TB['DOMAIN']." SET d_skin_main='basic2.6.1', d_skin_webmail='basic', d_skin_member='basic', d_skin_board='basic'";
		db_query($q);
	}	// if()
	touch($skin_main_basic26);
}	// if()


if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN')
{
	echo $crlf;
	title("웹메일 디렉토리 퍼미션 재조정");
	$scan = scanf($crlf."  perm_change.sh 스크립트를 실행하시겠습니까? [Y/n] : ", array('Y', 'N'), 2);
	if ($scan == 'Y')
	{
		chdir(dirname(__FILE__));
		system('./perm_change.sh');
	}	// if()
}	// if()



################################################################################

if ($G_SYS[DB] == 'oracle')
{
	die("[경고]Oracle 버젼을 사용시에는 자동 패치과정중 '테이블 추가/변경'작업이 적용되지 않습니다.\n  이 부분은 개발사에 문의하여 수작업으로 갱신해야 합니다.\n");
} else
{
	echo "\n패치 작업이 완료되었습니다. (" . round((getmicrotime() - $_start),4) . "sec)\n";
}	// if()


#require_once('include/global_end.php');
?>