<?
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>메일 로그 - POP3</b>';

nskinset('sadmin', 'admin_mail_log_pop3.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' => '차단',
					'E' => '처리중 or 실패',
					);

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

$CFG['log_pop3_login'] = array(
	'LOGIN' => '성공',
	'ELOGIN' => '실패'
);
// data

	// search
		$q_where = "";

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

		if ($_GET['s_word'])
		{
			if ($_GET['s_word'] == '(Local)')
			{
				$q_where .= " AND p_ip = '' ";
			} else
			{
				set_q_search($_GET['s_word']);
				// [2015-11-03] Illegal mix of collations for operation 'like' 개선
				// datatime,date,time 타입 컬럼 한글키워드로 검색시 에러
				$q_where .= " AND (
												p_date LIKE '%" . $_GET['s_word'] . "%'
												OR p_time LIKE '%" . $_GET['s_word'] . "%'
												OR p_ip LIKE '%" . $_GET['s_word'] . "%'
												OR p_user LIKE '%" . $_GET['s_word'] . "%'
												OR p_dom LIKE '%" . $_GET['s_word'] . "%'
											) ";
			}	// 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 p_date >= '".$_GET['sd1']."' AND p_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')
			{
				$q_where .= " AND s_smail_type IS NULL AND s_status NOT IN ('RCPT=OK', '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(
				'p_date' => '날짜',
				'p_dom' => '도메인',
				'p_user' => '아이디',
				'p_ip' => 'IP',
				'p_count' => '메일 개수',
				'p_size' => '메일 용량',
				'p_login' => '인증',
				);
		$order_set = get_order(array_keys($CFG['ADMIN_MEMBER_FIELD']), 'p_date DESC, p_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_POP3'] . "
			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

		// p_date 로 정렬시 날짜,시간 필드를 동시에 정렬하도록 함.
		if ($order_set['query'] == 'p_date ASC')
		{
			$order_set['query'] = 'p_date ASC, p_time ASC';
		} else if ($order_set['query'] == 'p_date DESC')
		{
			$order_set['query'] = 'p_date DESC, p_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_POP3'] . "
			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]['p_date'] = $rows[$i]['p_date'].' '.$rows[$i]['p_time'];
		}	// for()
		$rows = db_rows_fieldtokey($rows);
		$rows_cnt = getarraycount($rows['p_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 = 'NmailLogPop3_' . $_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_pop3_excel.html');

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


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