<?
require_once('include/global.php');
require_once('include/admin_lib.php');
require_once('include/pager.php');
require_once('include/file.php');
require_once('sadmin_conf.inc.php');


// set
	$CFG['TITLE'] = '<b>메일서버관리</b> >> <b>메일 로그 - SMTP</b>';

nskinset('sadmin', 'admin_mail_log.html');		// 컨텐츠
page_loading_view("메일 로그를 분석중입니다.");


// log analyze : smtp -> lmail -> smail
set_time_limit(3600);

// [2010-10-12] 첫페이지에서만 분석함.
if ($_GET['pageID'] <= 1)
	mail_log_analyze(date('Ymd'));


// set
$CFG['log_smtp_type'] = array(
					'L' => '수신',
					'S' => '송신',
					'R' => '재전송',
					'D' => '서버차단',
					'P' => '필터차단',
					'X' => '발송실패',
					'E' => '처리중',
					);

$CFG['log_smtp_type_smail'] = array(
					'L' => 'LOCAL',
					'S' => 'SMTP',
					'R' => 'REDIR',
					'E' => '',
					);


// data

	// search
		$q_where = "";
		if ($_GET['s_word'])
		{
			if ($_GET['s_word'] == '(Local)')
			{
				$q_where .= " AND s_ip = '' ";
			} else 
			{
				// 메일주소 형태일 경우 별도 검색
				$_ex = explode('@', trim($_GET['s_word']));
				if (trim($_ex[0]) != '' && trim($_ex[1]) != '')
				{
					$q_where .= " AND (
													(s_sender_user = '" . $_ex[0] . "' AND s_sender_dom = '" . $_ex[1] . "')
													OR (s_rcpt_user = '" . $_ex[0] . "' AND s_rcpt_dom = '" . $_ex[1] . "')
													OR (s_smail_rcpt_user = '" . $_ex[0] . "' AND s_smail_rcpt_dom = '" . $_ex[1] . "')
													OR s_authuser = '" . $_GET['s_word'] . "'
												) ";
				} else
				{
					$_GET['s_word'] = str_replace('@', '', $_GET['s_word']);
					set_q_search($_GET['s_word']);
					$q_where .= " AND (
													s_date LIKE '%" . $_GET['s_word'] . "%'
													OR s_time LIKE '%" . $_GET['s_word'] . "%'
													OR s_ip LIKE '%" . $_GET['s_word'] . "%'
													OR s_sender_user LIKE '%" . $_GET['s_word'] . "%'
													OR s_sender_dom LIKE '%" . $_GET['s_word'] . "%'
													OR s_rcpt_user LIKE '%" . $_GET['s_word'] . "%'
													OR s_rcpt_dom LIKE '%" . $_GET['s_word'] . "%'
													OR s_msgid LIKE '%" . $_GET['s_word'] . "%'
													OR s_status LIKE '%" . $_GET['s_word'] . "%'
													OR s_authuser LIKE '%" . $_GET['s_word'] . "%'
													OR s_smail_type LIKE '%" . $_GET['s_word'] . "%'
													OR s_smail_rcpt_user LIKE '%" . $_GET['s_word'] . "%'
													OR s_smail_rcpt_dom LIKE '%" . $_GET['s_word'] . "%'
													OR s_smail_mx LIKE '%" . $_GET['s_word'] . "%'
													OR s_smail_date LIKE '%" . $_GET['s_word'] . "%'
													OR s_smail_time LIKE '%" . $_GET['s_word'] . "%'
												) ";
				}	// if()
			}	// if()

			$v_s_word = htmlspecialchars_fix(stripslashes($_GET['s_word']));
		}	// if()

		// 검색조건이 없을 때 기본적으로 오늘 로그만 보여주도록 함.
		if ($_GET['sdp'] != 'A' && !$_GET['sd1'] && !$_GET['sd2'])
		{
			$_GET['sdp'] = '0';
			$_GET['sd1'] = date('Y-m-d');
			$_GET['sd2'] = $_GET['sd1'];
		}	// if()

		if ($_GET['sd1'] && strtotime($_GET['sd1']))
		{
			$_ex = explode('-', $_GET['sd1']);
			$_GET['sd1'] = sprintf('%04d', $_ex[0]).'-'.sprintf('%02d', $_ex[1]).'-'.sprintf('%02d', $_ex[2]);
			if ($_GET['sd2'] && strtotime($_GET['sd2']))
			{
				$_ex = explode('-', $_GET['sd2']);
				$_GET['sd2'] = sprintf('%04d', $_ex[0]).'-'.sprintf('%02d', $_ex[1]).'-'.sprintf('%02d', $_ex[2]);
				$q_where .= " AND s_date >= '".$_GET['sd1']."' AND s_date <= '".$_GET['sd2']."' ";
			}	// if()
		}	// if()

		if ($_GET['s_log_type'] != '')
		{
			if ($_GET['s_log_type'] == 'E')
			{
				$q_where .= " AND s_smail_type IS NULL AND s_status IN ('RCPT=OK', 'RECV=OK', '') ";
			} else if ($_GET['s_log_type'] == 'D')
			{
				// [2009-05-14]
				if ($G_SYS[DB] == 'oracle')
				{
					$q_where .= " AND s_smail_type IS NULL AND s_status NOT IN ('RCPT=OK', 'RECV=OK') ";
				} else 
				{
					$q_where .= " AND s_smail_type IS NULL AND s_status NOT IN ('RCPT=OK', 'RECV=OK', '') ";
				}	// if()
			} else if ($_GET['s_log_type'] == 'X')
			{
				$q_where .= " AND s_smail_type = 'RETURN' AND s_status = 'RECV=OK' ";
			} else if ($_GET['s_log_type'] == 'P')
			{
				$q_where .= " AND s_smail_type = 'SPAM' AND s_status = 'RECV=OK' ";
			} else
			{
				$q_where .= " AND s_smail_type = '".$CFG['log_smtp_type_smail'][$_GET['s_log_type']]."' ";
			}	// if()
		}	// if()

	// sort
		$CFG['ADMIN_MEMBER_FIELD'] = array(
				's_date' => '날짜',
				's_sender_user' => '보낸주소',
				's_rcpt_user' => '받는주소',

				's_smail_type' => '처리형태',
				//'s_smail_rcpt_user' => '처리주소',
				//'s_smail_mx' => '처리서버',
				//'s_smail_date' => '처리시간',

				//'s_status' => '전송상태',
				's_msgsize' => '크기',
				's_msgid' => 'MSG ID',
				's_ip' => 'IP',
				's_authuser' => 'SMTP 인증',
				);
		$order_set = get_order(array_keys($CFG['ADMIN_MEMBER_FIELD']), 's_date DESC, s_time ', $_GET['s_key'], $_GET['s_key2']);
		$order_img = get_order_img(array_keys($CFG['ADMIN_MEMBER_FIELD']), $_GET['s_key'], $_GET['s_key2'], false, 'common_skin');		// array

	// db - pager
		$DEBUG['db_cnt']['start'] = getmicrotime();
		$pager_params['totalItems'] = db_get_one("
			SELECT
				COUNT(*)
			FROM
				" . $TB['LOG_SMTP'] . "
			WHERE
				1=1
				" . $q_where
			);
		$pager_params['perPage'] = 100;

		$DEBUG['db_cnt']['exec'] += getmicrotime() - $DEBUG['db_cnt']['start'];

		$pager = &new Pager_Sliding($pager_params);
		$pager_links = $pager->getLinks();
		$pager_limit = get_pager_limit($pager->getCurrentPageID(), $pager_params['perPage']);

	// db - select

		// s_date 로 정렬시 날짜,시간 필드를 동시에 정렬하도록 함.
		if ($order_set['query'] == 's_date ASC')
		{
			$order_set['query'] = 's_date ASC, s_time ASC';
		} else if ($order_set['query'] == 's_date DESC')
		{
			$order_set['query'] = 's_date DESC, s_time DESC';
		}	// if()

		if ($order_set['query'] == 's_smail_type ASC')
		{
			$order_set['query'] = 's_smail_type ASC, s_status ASC';
		} else if ($order_set['query'] == 's_smail_type DESC')
		{
			$order_set['query'] = 's_smail_type DESC, s_status DESC';
		}	// if()

		$DEBUG['db_select']['start'] = getmicrotime();
		$sql = "
			SELECT
				*
			FROM
				" . $TB['LOG_SMTP'] . "
			WHERE
				1=1
				" . $q_where . "
			ORDER BY
				" . $order_set['query'] . "
			";
		$rows = db_get_rows($sql, $pager_limit['from'], $pager_limit['count']);
		$DEBUG['db_select']['exec'] += getmicrotime() - $DEBUG['db_select']['start'];




	// process data
		$DEBUG['db_fetch_all']['start'] = getmicrotime();
		for ($i=0; $i<sizeof($rows); $i++)
		{
			$rows[$i]['s_date'] = $rows[$i]['s_date'].' '.$rows[$i]['s_time'];
			$rows[$i]['s_smail_date'] = $rows[$i]['s_smail_date'].' '.$rows[$i]['s_smail_time'];
			if ($rows[$i]['s_sender_user'] != '')
				$rows[$i]['s_sender_user'] = $rows[$i]['s_sender_user'].'@'.$rows[$i]['s_sender_dom'];
			if ($rows[$i]['s_rcpt_user'] != '')
				$rows[$i]['s_rcpt_user'] = $rows[$i]['s_rcpt_user'].'@'.$rows[$i]['s_rcpt_dom'];
			if ($rows[$i]['s_smail_rcpt_dom'] != '')
				$rows[$i]['s_smail_rcpt_user'] = $rows[$i]['s_smail_rcpt_user'].'@'.$rows[$i]['s_smail_rcpt_dom'];

			// 받는주소와 실제 받는주소가 같은 경우엔 식별이 편리하도록 보여주지 않음.
			if ($rows[$i]['s_smail_rcpt_dom'] != '' && $rows[$i]['s_rcpt_user'] != $rows[$i]['s_smail_rcpt_user'])
				$rows[$i]['s_rcpt_user'] .= '<br><font color=blue>-> '.$rows[$i]['s_smail_rcpt_user'].'</font>';

			// SMTP MX
			if ($rows[$i]['s_smail_mx'] != '')
				$rows[$i]['s_rcpt_user'] .= '<br><font color=blue>MX : '.get_host_skip_last_porint($rows[$i]['s_smail_mx']).'</font>';

			if ($rows[$i]['s_msgsize'] == 0)
			{
				$rows[$i]['s_msgsize'] = '-';
			} else
			{
				//$rows[$i]['s_msgsize'] = '<div align=right class=nm_number>'.filesize_human($rows[$i]['s_msgsize']).'</div>';
				$rows[$i]['s_msgsize'] = filesize_human($rows[$i]['s_msgsize']);
			}	// if()

			if ($rows[$i]['s_ip'] == '')
				$rows[$i]['s_ip'] = '(Local)';


			// 로그 형태 알아내기
			$_s_log_type = get_log_smtp_type($rows[$i]['s_status'], $rows[$i]['s_smail_type']);
			if ($_s_log_type == 'X')
			{
				$rows[$i]['s_smail_type'] = '<font color=red title="'.$rows[$i]['s_status'].'">발송실패</font><br><div style="text-align:left; font-size:8pt">'.get_log_return_info($rows[$i]['s_msgid'], $rows[$i]['s_date']).'</div>';
			} else if ($_s_log_type == 'P')
			{
				$rows[$i]['filter'] = get_log_filter_info($rows[$i]['s_msgid'], $rows[$i]['s_date']);
				$rows[$i]['s_smail_type'] = '<font color=red title="'.$rows[$i]['s_status'].'">필터차단 ('.$rows[$i]['filter']['msg'].')</font>';
				if ($rows[$i]['filter']['memo'] != '')
					$rows[$i]['s_smail_type'] .= '<br><div style="text-align:left; font-size:8pt">'.$rows[$i]['filter']['memo'].'</div>';
			} else if ($_s_log_type == 'D')
			{
				// [2012-09-27] 스팸단어관리
				$rows[$i]['filter'] = get_log_filter_info($rows[$i]['s_msgid'], $rows[$i]['s_date']);
				$rows[$i]['s_smail_type'] = '<font color=red title="'.$rows[$i]['s_status'].'">서버차단 ('.get_log_smtp_status($rows[$i]['s_status'], $rows[$i]['s_msgid'], $rows[$i]['s_date']).')</font>';
			} else if ($_s_log_type == 'E')
			{
				$_msg = $CFG['log_smtp_type'][$_s_log_type];
				switch ($rows[$i]['s_status'])
				{
					case 'RCPT=OK':
						$_msg .= ' (전송대기)';
						break;
				
					case 'RECV=OK':
						$_msg .= ' (전송완료)';
						break;
				}	// switch()
				$rows[$i]['s_smail_type'] = '<font color=red title="'.$rows[$i]['s_status'].'">'.$_msg.'</font>';
			} else if ($_s_log_type == 'L')
			{
				// [2012-09-27] 스팸단어관리
				$rows[$i]['s_smail_type'] = $CFG['log_smtp_type'][$_s_log_type];
				$rows[$i]['filter'] = get_log_filter_info($rows[$i]['s_msgid'], $rows[$i]['s_date']);
				if ($rows[$i]['filter']['msg'] != '')
					$rows[$i]['s_smail_type'] .= ' ('.$rows[$i]['filter']['msg'].')';
			} else
			{
				$rows[$i]['s_smail_type'] = $CFG['log_smtp_type'][$_s_log_type];
			}	// if()
		}	// for()
		$rows = db_rows_fieldtokey($rows);
		$rows_cnt = getarraycount($rows['s_date']);

		$DEBUG['db_fetch_all']['exec'] += getmicrotime() - $DEBUG['db_fetch_all']['start'];

	// 메일 로그 뷰어수
		$admin_mailing_all_cnt = number_format($pager_params['totalItems']);

// skin view
	//nskinset('sadmin', 'admin_mail_log.html');		// 컨텐츠
	page_loading_view_hidden();
	include($NSKIN['view_layout']);


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