<?
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');		// 컨텐츠

if ( ! $_GET['excel_down'])
{
	page_loading_view("메일 로그를 분석중입니다.");
}

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

// [2013-10-07] 로그 분석이 진행중이더라도, 새창에서는 접근 가능하도록 함.
session_write_close();

// [2010-10-12] 첫페이지에서만 분석함.
if ($_GET['pageID'] <= 1)
	$last_analyze_time = 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' => '',
					);

$CFG['s_status'] = array(
	'EIPMAP'     => 'RBL 차단',
	'EIPSPAM'    => '스팸 IP',
	'EFILTER'    => '필터 차단',
	'AF_DEL'     => '메일자동분류 삭제',
	'AF_MOVE'    => '메일자동분류 이동',
	'S_POINT'    => '스팸포인트 초과 스팸분류',
	'S_FROMFAKE' => '보낸주소 위조메일 스팸분류',
	'EFAIL'      => 'SMTP 인증오류',
	'ERELAY'     => '발송권한 오류',
	'EDSBL'      => '비활성화 계정',
	'EAVAIL'     => '없는 주소',
	'EFULL'      => '편지함 용량초과',
	'EBIG'       => '메일 최대크기 초과',
	'ESSL'       => 'SSL 통신 오류',
);

// data
		// [2025-08-21] 개별 검색 추가
		$CFG['SEARCH_LIST_FIELD'] = array(
			's_sender_user' => '보낸주소(아이디)',
			's_sender_dom' => '보낸주소(도메인)',
			's_rcpt_user' => '받는주소(아이디)',
			's_rcpt_dom' => '받는주소(도메인)',
			's_msgid' => 'MSG ID',
			's_ip' => 'IP',
			's_authuser' => 'SMTP 인증',
		);

		$select_search_field = select_list_value($_GET['s_field'], array_values($CFG['SEARCH_LIST_FIELD']), array_keys($CFG['SEARCH_LIST_FIELD']), '전체', 0, 1);

	// search
		$q_where = "";

		if ($_GET['d_name'])
			$q_where .= " AND s_rcpt_dom='".$_GET['d_name']."' ";

		if ($_GET['s_word'])
		{
			if ($_GET['s_word'] == '(Local)')
			{
				$q_where .= " AND s_ip = '' ";
			} else {
				// [2025-08-21] 개별 검색 추가
				if ($_GET['s_field']) {
					set_q_search($_GET['s_word']);

					switch ($_GET['s_field']) {
						case 's_sender_user':
							$q_where .= " AND s_sender_user LIKE '%".$_GET['s_word']."%' ";
							break;
						case 's_sender_dom':
							$q_where .= " AND s_sender_dom LIKE '%".$_GET['s_word']."%' ";
							break;
						case 's_rcpt_user':
							$q_where .= " AND s_rcpt_user LIKE '%".$_GET['s_word']."%' ";
							break;
						case 's_rcpt_dom':
							$q_where .= " AND s_rcpt_dom LIKE '%".$_GET['s_word']."%' ";
							break;
						case 's_msgid':
							$q_where .= " AND s_msgid LIKE '%".$_GET['s_word']."%' ";
							break;
						case 's_ip':
							$q_where .= " AND s_ip LIKE '%".$_GET['s_word']."%' ";
							break;
						case 's_authuser':
							$q_where .= " AND s_authuser LIKE '%".$_GET['s_word']."%' ";
							break;
					}
				} 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']);
						// [2015-11-03] Illegal mix of collations for operation 'like' 개선
						// datatime,date,time 타입 컬럼 한글키워드로 검색시 에러
						$q_where .= " AND (
													   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_date LIKE '%" . $_GET['s_word'] . "%'
													OR s_time LIKE '%" . $_GET['s_word'] . "%'
													OR s_smail_date LIKE '%" . $_GET['s_word'] . "%'
													OR s_smail_time LIKE '%" . $_GET['s_word'] . "%'
												) ";
					}    // if()
				}    // 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'];
			$_GET['sd1'] = date('Y-m-d 00:00:00');
			$_GET['sd2'] = date('Y-m-d 23:59:59');
		}	// if()

		if ($_GET['sd1'] && strtotime($_GET['sd1']))
		{
			$date_parts = explode(' ', $_GET['sd1']);

			$_ex = explode('-', $date_parts[0]);
			if (isset($date_parts[1])) {
				$_ex2 = explode(':', $date_parts[1]);
			} else {
				$_ex2 = explode(':', '00:00:00');
			}
			$sd1_date = sprintf('%04d', $_ex[0]).'-'.sprintf('%02d', $_ex[1]).'-'.sprintf('%02d', $_ex[2]);
			$sd1_time = sprintf('%02d', $_ex2[0]) . ':' . sprintf('%02d', $_ex2[1]) . ':' . sprintf('%02d', $_ex2[2]);
			$_GET['sd1'] = $sd1_date . ' ' . $sd1_time;
			if ($_GET['sd2'] && strtotime($_GET['sd2']))
			{
				$date_parts = explode(' ', $_GET['sd2']);
				$_ex = explode('-', $date_parts[0]);
				if (isset($date_parts[1])) {
					$_ex2 = explode(':', $date_parts[1]);
				} else {
					$_ex2 = explode(':', '23:59:59');
				}
				$sd2_date = sprintf('%04d', $_ex[0]).'-'.sprintf('%02d', $_ex[1]).'-'.sprintf('%02d', $_ex[2]);
				$sd2_time = sprintf('%02d', $_ex2[0]) . ':' . sprintf('%02d', $_ex2[1]) . ':' . sprintf('%02d', $_ex2[2]);
				$_GET['sd2'] = $sd2_date . ' ' . $sd2_time;
				$q_where .= " AND s_date >= '".$sd1_date."' AND s_date <= '".$sd2_date."' ";
				$q_where .= " AND s_time >= '" . $sd1_time."' AND s_time <= '" . $sd2_time."' ";
			}	// 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', '') OR s_status LIKE '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') AND s_status NOT LIKE 'RECV=OK%') ";
				} else
				{
					$q_where .= " AND s_smail_type IS NULL AND (s_status NOT IN ('RCPT=OK', 'RECV=OK', '') AND s_status NOT LIKE 'RECV=OK%') ";
				}	// if()
			} else if ($_GET['s_log_type'] == 'X')
			{
				$q_where .= " AND s_smail_type = 'RETURN' AND (s_status = 'RECV=OK' OR s_status LIKE 'RECV=OK%') ";
			} else if ($_GET['s_log_type'] == 'P')
			{
				$q_where .= " AND s_smail_type = 'SPAM' AND (s_status = 'RECV=OK' OR s_status LIKE 'RECV=OK%') ";
			} else if ($_GET['s_log_type'] == 'S')		// [2013-11-18] smtp fwd (FWD) 추가
			{
				$q_where .= " AND s_smail_type IN ('SMTP', 'FWD') ";
			} else
			{
				$q_where .= " AND s_smail_type = '".$CFG['log_smtp_type_smail'][$_GET['s_log_type']]."' ";
			}	// if()
		}	// if()

		// [2025-11-21] 처리형태(s_status) 검색 추가
		if ($_GET['s_status']) {
			switch ($_GET['s_status']) {
				case 'EIPMAP':
					$q_where .= " AND s_status LIKE 'SNDRIP=EIPMAP%' ";
					break;
				case 'EFILTER':
					$q_where .= " AND (s_status='PREDATA=EFILTER' OR s_status='POSTDATA=EFILTER' OR s_status='DATA=EFILTER') ";
					break;
				case 'EAVAIL':
					$q_where .= " AND s_status='RCPT=EAVAIL' ";
					break;
				case 'EFULL':
					$q_where .= " AND s_status='RCPT=EFULL' ";
					break;
				case 'EDSBL':
					$q_where .= " AND s_status='RCPT=EDSBL' ";
					break;
				case 'ERELAY':
					$q_where .= " AND s_status='RCPT=ERELAY' ";
					break;
				case 'EIPSPAM':
					$q_where .= " AND s_status='SNDRIP=EIPSPAM' ";
					break;
				case 'EBIG':
					$q_where .= " AND s_status='SIZE=EBIG' ";
					break;
				case 'ESSL':
					$q_where .= " AND s_status='SMTP=ESSL' ";
					break;
				case 'S_POINT':
					$q_where .= " AND s_status LIKE '%S_POINT%' ";
					break;
				case 'S_FROMFAKE':
					$q_where .= " AND s_status LIKE '%S_FROMFAKE%' ";
					break;
				case 'AF_DEL':
					$q_where .= " AND s_status LIKE '%AF_DEL%' ";
					break;
				case 'AF_MOVE':
					$q_where .= " AND s_status LIKE '%AF_MOVE%' ";
					break;

			}   // switch()
		}   // if()

		// [2025-11-28] 처리 형태에서 'SMTP 인증오류' 추가
		if ($_GET['s_status'] === 'EFAIL') {
			$q_where .= " AND s_status IN ('AUTH=EFAIL:TYPE=PLAIN', 'AUTH=EFAIL:TYPE=LOGIN', 'AUTH=EFAIL:TYPE=CRAM-MD5', 'AUTH=EFAIL:TYPE=EXTRN') ";
		} else {
			// [2023-01-19] SMTP 인증오류 제외 옵션 (기본 제외됨)
			if (! isset($_GET['s_skip_auth_fail']) || $_GET['s_skip_auth_fail'] === '1')
			{
				$q_where .= " AND s_status NOT IN ('AUTH=EFAIL:TYPE=PLAIN', 'AUTH=EFAIL:TYPE=LOGIN', 'AUTH=EFAIL:TYPE=CRAM-MD5', 'AUTH=EFAIL:TYPE=EXTRN') ";
			}
		}

	// sort
		$CFG['ADMIN_MEMBER_FIELD'] = array(
			's_date'            => '날짜',
			's_sender_user'     => '보낸주소(Return-Path)',
			'f_hdr_from'        => '보낸주소(From)',
			's_rcpt_user'       => '받는주소',
			's_smail_rcpt_user' => '실제받는주소',      // SMAIL 처리 주소
			's_smail_mx'        => '처리서버',     // MX, FWD 서버
			'f_hdr_subject'     => '차단/스팸분류된 제목',
			's_smail_type'      => '처리형태',
			//'s_smail_date' => '처리시간',
			//'s_status' => '전송상태',
			's_msgsize'         => '크기',
			's_msgid'           => 'MSG ID',
			's_ip'              => 'IP',
			's_authuser'        => 'SMTP 인증',
		);
		if ( ! $_GET['excel_down'])
		{
			unset(
				$CFG['ADMIN_MEMBER_FIELD']['f_hdr_from'],
				$CFG['ADMIN_MEMBER_FIELD']['s_smail_rcpt_user'],
				$CFG['ADMIN_MEMBER_FIELD']['s_smail_mx']
			);
		}

		$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
			);

		if ($_GET['excel_down'])
		{
			set_time_limit(3600);
			ini_set('memory_limit', '2047M');

			$pager_params['perPage'] = 999999;
		} else
		{
			$pager_params['perPage'] = 100;
		}

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

		// [2016-01-11] PHP 5버전대에서 Ampersand가 DEPRECATED처리되어 &삭제
		#$pager = &new Pager_Sliding($pager_params);
		// [2016-01-11] Ampersand가 DEPRECATED관련하여 PEAR Pager라이브러리 업그레이드 소스적용
		#$pager = new Pager_Sliding($pager_params);
		$pager = Pager::factory($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'];

	// 도메인
		$q = "SELECT * FROM ".$TB['DOMAIN']." WHERE d_is_use='Y' ORDER BY d_name";
		$mbr_domain = db_get_rows($q, true);
		$mbr_domain_select = select_list_value($_GET['d_name'], $mbr_domain['d_name'], $mbr_domain['d_name'], '전체 도메인', 0, 1);

	// 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'];

			$rows[$i]['filter'] = get_log_filter_info($rows[$i]['s_msgid'], $rows[$i]['s_date'], $rows[$i]['s_smail_rcpt_user']);

			// [2025-11-14] 보낸주소(From)
			if (! $_GET['excel_down'] && $rows[$i]['filter'] !== false && $rows[$i]['filter']['f_hdr_from'] !== null) {
				$_from = mime_address_parse($rows[$i]['filter']['f_hdr_from']);
				if ($rows[$i]['s_sender_user'] !== $_from['address']) {
					$rows[$i]['s_sender_user'] .= '<br><div class="log-extra-info">-> From: ' . $_from['address'] . '</div>';
				}
			} elseif ($_GET['excel_down'] && $rows[$i]['filter'] !== false && $rows[$i]['filter']['f_hdr_from'] !== null) {
				$_from = mime_address_parse($rows[$i]['filter']['f_hdr_from']);
				$rows[$i]['f_hdr_from'] = $_from['address'];
			}

			// [2025-11-21] 차단/스팸분류된 메일 제목 추가
			if ($rows[$i]['filter'] !== false && ! in_array($rows[$i]['filter']['code'], array('U_ALLOW', 'U_A_ADDR', 'U_A_EADDR', 'S_WHITEIP', 'AF_MOVE', 'AF_READ'))) {
				$rows[$i]['f_hdr_subject'] = $rows[$i]['filter']['f_hdr_subject'];
			}

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

			// SMTP MX
			if ( ! $_GET['excel_down'] && $rows[$i]['s_smail_mx'] != '')
			{
				// [2013-11-18] smtp fwd (FWD) 추가
				if ($rows[$i]['s_smail_type'] == 'FWD')
				{
					$rows[$i]['s_rcpt_user'] .= '<br><div class="log-extra-info">FWD : '.get_host_skip_last_porint($rows[$i]['s_smail_mx']).'</div>';
				} else
				{
					$rows[$i]['s_rcpt_user'] .= '<br><div class="log-extra-info">MX : '.get_host_skip_last_porint($rows[$i]['s_smail_mx']).'</div>';
				}	// if()
			}	// if()

			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')
			{
				// [2013-10-29] 로그분석시 처리형태가 같은 msgid 내의 다른 발송건에 대해 보여지던 오류 수정.
				//$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>';
				// [2014-05-13] 포워딩된 경우를 감안하여, s_smail_rcpt_user 로 가져오도록 변경.
				//$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'], $rows[$i]['s_rcpt_user']).'</div>';
				// [2016-02-11] 포워딩된 경우를 감안하여, s_smail_rcpt_user 로 가져오도록 변경.(2)
				//$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'], $rows[$i]['s_smail_rcpt_user']).'</div>';
				list($return_msg, $return_row) = get_log_return_info($rows[$i]['s_msgid'], $rows[$i]['s_date'], ($rows[$i]['s_smail_rcpt_user'] != '' ? $rows[$i]['s_smail_rcpt_user'] : $rows[$i]['s_rcpt_user']));
				$rows[$i]['s_smail_type'] = '<div class="log-type-danger log-type-send-fail" title="'.$rows[$i]['s_status'].'">발송실패</div><div class="log-type-detail">'.$return_msg.'</div>';

				if ($return_row) {
					$rows[$i]['f_hdr_subject'] = $return_row['mr_hdr_subject'];
				}
			} 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'] = '<div class="log-type-danger" title="'.$rows[$i]['s_status'].'">필터차단 ('.$rows[$i]['filter']['msg'].')</div>';
				if ($rows[$i]['filter']['memo'] != '')
					$rows[$i]['s_smail_type'] .= '<div class="log-type-detail">'.$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']);
				$title = $rows[$i]['s_status'];

				// [2025-11-21] SSL 통신 오류
				if ($rows[$i]['s_status'] === 'SMTP=ESSL') {
					$title .= ' 메일서버에서 지원하지 않는 SSL 암호화 통신을 시도하였거나, 상대방 메일서버의 SSL 설정 오류';
				}

				// [2025-11-21] 스팸 IP일 경우 등록된 스팸 IP 조회
				if ($rows[$i]['s_status'] === 'SNDRIP=EIPSPAM') {
					$black_ip = db_get_row("SELECT * FROM ". $TB['BLACK_IP'] . " WHERE ip_ipaddr = ?", array($rows[$i]['s_ip']));
					if ($black_ip !== false) {
						$title .= ' 등록일 : ' . $black_ip['ip_regdate'] . ' 메모 : ' . e($black_ip['ip_memo']);
					}
				}

				if ($rows[$i]['s_status'] === 'POSTDATA=EFILTER') {
					// [2025-11-21] 스팸 단어일 경우 등록된 스팸 단어 조회
					if ($rows[$i]['filter']['code'] === 'SA_S_W_S' || $rows[$i]['filter']['code'] === 'SA_S_W_B') {
						$spam_word = db_get_row("SELECT * FROM " . $TB['SADMIN_SPAM_WORD'] . " WHERE ssw_word = ?", array($rows[$i]['filter']['memo']));

						if ($spam_word !== false) {
							$title .= ' 등록일 : ' . $spam_word['ssw_regdate'] . ' 메모 : ' . e($spam_word['ssw_memo']);
						}
					}

					// [2025-11-21] 스팸 주소일 경우 등록된 스팸 주소 조회
					if ($rows[$i]['filter']['code'] === 'SA_S_ADDR') {
						$spam_addr = db_get_row("SELECT * FROM " . $TB['SADMIN_SPAM_ADDR'] . " WHERE ssa_email = ?", array($rows[$i]['filter']['memo']));

						if ($spam_addr !== false) {
							$title .= ' 등록일 : ' . $spam_addr['ssa_regdate'] . ' 메모 : ' . e($spam_addr['ssa_memo']);
						}
					}
				}
				$rows[$i]['s_smail_type'] = '<div class="log-type-danger" title="'.$title.'">서버차단</div><div class="log-type-detail">('.get_log_smtp_status($rows[$i]['s_status'], $rows[$i]['s_msgid'], $rows[$i]['s_date']).')</div>';
			} else if ($_s_log_type == 'E')
			{
				$_msg = $CFG['log_smtp_type'][$_s_log_type];

				// [2025-11-25] 필터 코드(f_code)를 s_status에 더해서 자르기 위해 추가
				if (strpos($rows[$i]['s_status'], " ") !== false) {
					$_ex = explode(' ', $rows[$i]['s_status']);
					$_s_status = $_ex[0];
				} else {
					$_s_status = $rows[$i]['s_status'];
				}

				switch ($_s_status)
				{
					case 'RCPT=OK':
						$_msg .= ' (전송대기)';
						break;

					case 'RECV=OK':
						$_msg .= ' (전송완료)';
						break;
				}	// switch()
				$rows[$i]['s_smail_type'] = '<div class="log-type-danger" title="'.$rows[$i]['s_status'].'">'.$_msg.'</div>';
			} else if ($_s_log_type == 'L')     // 수신
			{
				// [2012-09-27] 스팸단어관리
				$rows[$i]['s_smail_type'] = '<div class="log-type-normal" title="'.$rows[$i]['s_status'].'">' . $CFG['log_smtp_type'][$_s_log_type] . '</div>';
//				$rows[$i]['filter'] = get_log_filter_info($rows[$i]['s_msgid'], $rows[$i]['s_date']);
				if ($rows[$i]['filter']['msg'] != '') {
					// [2026-01-08] 메일 자동분류 편지함 이동시, 이동된 편지함 표시
					if (strpos($rows[$i]['s_status'], 'AF_MOVE') !== false) {
						list(, $_mb_id) = explode('|', $rows[$i]['filter']['memo']);
						if (is_numeric($_mb_id)) {
							$_mb_id = '개인' . $_mb_id;
						}
						$rows[$i]['filter']['msg'] .= '/' . $_mb_id;
					}
					$rows[$i]['s_smail_type'] .= '<div class="log-type-detail" title="' . e($rows[$i]['filter']['memo'])
						. '">(' . $rows[$i]['filter']['msg'] . ')</div>';
				}
			} 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
	if ($_GET['excel_down'])
	{
		$excel_down_name = 'NmailLogSmtp_' . $_GET['sd1'] . '_' . $_GET['sd2'] . '.xls';
		header("Content-type: application/vnd.ms-excel; charset=utf-8");
		header("Content-Disposition: attachment; filename=$excel_down_name");
		header("Expires: 0");
		header("Cache-Control: must-revalidate, post-check=0,pre-check=0");
		header("Pragma: public");

		include('sadmin/admin_mail_log_excel.html');

		exit;
	}

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


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