<?
require_once('include/global.php');
require_once("include/mail_lib.php");
require_once('conf.inc.php');


// check
	if (!$_GET['mb_id'] && !$_GET['mf_no'] )
		msg('올바른 URL로 접근하여 주십시오');


// set
	$CFG['TITLE'] = '<b>편지읽기</b>';
	$CFG['TITLE'] .= ' >> <b>'.get_mb_name_title($_GET['mb_id']).'</b>';

	if ($_GET['back_url'])
	{
		cut_qs('back_url');
	} else
	{
		$_GET['back_url'] = 'mail_list.php?'.get_qs('mf_no');
	}	// if()


// data
	// db - select
	$DEBUG['db_select']['start'] = getmicrotime();
		$sql = "
			SELECT
				mf_no, mf_from, mf_reply_to, mf_sender, mf_to, mf_cc, mf_bcc, mf_importance, mf_subject, mf_body, mf_content_type, mf_charset, mf_arrival_date, mf_send_date, mf_filename, mf_filesize, mf_attach_names, mf_is_read, mf_is_read_date, mf_is_reply, mf_is_reply_date, mf_is_forward, mf_is_forward_date,  mf_send_ip , mf_spam_point , mf_is_userauth, mfext1
			  , mb_id, ms.id AS is_starred
			FROM
				".$AUTH[auth_m_mf_table]."
				LEFT JOIN " . $TB['MAIL_STAR'] . " ms ON mf_no = ms_mf_no AND m_no = ms_m_no 
			WHERE
				mf_no='" . $_GET['mf_no'] . "'
				AND m_no='" . $AUTH['auth_m_no'] . "'
			";
		$row = db_get_row($sql);
		if (!$row)
		{
			msg("존재하지 않는 메일입니다.\\n\\n이미 삭제되었거나 다른 편지함으로 옮겨졌을 수 있습니다.", 0);
			movepage($_GET['back_url']);
		}	// if()
	$DEBUG['db_select']['exec'] += getmicrotime() - $DEBUG['db_select']['start'];

	// 해당 파일이 존재하지 않을 경우 아웃룩에서 삭제된것으로 간주해서 동기화 시작.
	$mf_dir = get_mail_dir().'/'.get_mb_dir($row['mb_id']).'/';

	// [2025-11-25] 편지함 HTML 제한 설정 가져오기
	$html_limit = db_get_one("SELECT html_limit FROM " . $TB['MAIL_BOX']. " WHERE m_no='" . $AUTH['auth_m_no'] . "' AND mb_id='" . $row['mb_id'] . "'");

	// [2005-12-03] 메일폴더에 쓰기권한이 없을때는 퍼미션문제이므로 동기화하지 않음.
	if (!is_writable($mf_dir))
	{
		// [2006-10-23] 에러 문구 보완
		#error("사용자 메일 디렉토리에 퍼미션 오류가 있습니다.\n=> " . $mf_dir, 'FILE', false);
		#error("사용자 메일 디렉토리에 퍼미션 오류가 있습니다.\n=> " . $mf_dir . "\n
		#문제의 원인은 다음처럼 발생시기에 따라 다릅니다.
		// [2012-10-05] 에러 문구 보완
		if (!is_dir($mf_dir))
		{
			error("사용자 메일 디렉토리가 존재하지 않습니다.\n=> " . $mf_dir, 'FILE', false);
		} else
		{
			error("사용자 메일 디렉토리에 쓰기권한이 없습니다.\n=> " . $mf_dir, 'FILE', false);
		}	// if()
	} else if ($row['mf_filename'] && !file_exists($mf_dir.$row['mf_filename']))
	{
		$sql = "
			DELETE
			FROM
				".$AUTH[auth_m_mf_table]."
			WHERE
				mf_no='" . $_GET['mf_no'] . "'
				AND m_no='" . $AUTH['auth_m_no'] . "'
				AND mb_id='" . $row['mb_id'] . "'
			";
		db_query($sql);
		msg("존재하지 않는 메일입니다.\\n\\n아웃룩등의 메일클라이언트에서 POP3 서비스를 통해 메일을 가져갈때\\n\\n[서버에 메시지 복사본 저장]옵션을 체크하지 않아 삭제되었을 가능성이 높습니다.", 0);
		movepage($_GET['back_url']);
	}	// if()

	// db - mail index rebuild
		if ($_GET['mf_rebuild'])
		{
			mail_db_rebuild($AUTH['auth_m_mf_table'], $mf_dir.$row['mf_filename'], $_GET['mf_no'], $AUTH['auth_m_no']);
			movepage($_SERVER['PHP_SELF'].'?'.get_qs('mf_rebuild'));
		}	// if()

	// db - 메일읽음표시
		if ($row['mf_is_read'] == 'N')
		{
			$now = date('Y-m-d H:i:s');
			$sql = "
				UPDATE
					".$AUTH[auth_m_mf_table]."
				SET
					mf_is_read = 'Y',
					mf_is_read_date = '".$now."'
				WHERE
					mf_no='" . $_GET['mf_no'] . "'
					AND m_no='" . $AUTH['auth_m_no'] . "'
					AND mb_id='" . $row['mb_id'] . "'
				";
			db_query($sql);
		}	// if()

	// process data
		$mf = array();
		$mf = $row;

		$mf['mf_subject'] = (trim($row['mf_subject']) == NULL) ? "__제목없음__" : htmlspecialchars_fix($row['mf_subject']);
		// [2005-07-12] 보낸날짜가 없을때는 도착날짜를 사용함.
		#$mf['mf_send_date'] = ($row['mf_send_date'] != '0000-00-00 00:00:00') ? $row['mf_send_date'] : $row['mf_send_date_str'];
		$mf['mf_send_date'] = ($row['mf_send_date'] != '0000-00-00 00:00:00') ? $row['mf_send_date'] : $row['mf_arrival_date'];
		$_from = mime_address_parse($row['mf_from']);
		// [2007-07-11] UTF-8 버젼에서 한글이 제대로 전달되도록 처리.
		//$mf['mf_from_name'] = htmlspecialchars_fix(addslashes($_from['display']));
		$mf['mf_from_name'] = urlencode(urlencode(base64_encode(htmlspecialchars_fix(addslashes($_from['display'])))));
		$mf['mf_from_email'] = htmlspecialchars_fix(addslashes($_from['address']));
		$mf['mf_from'] = address_view($row['mf_from']);
		$mf['mf_to'] = address_view($row['mf_to']);
		$_to = mime_address_parse($row['mf_to']);
		// [2007-07-11] UTF-8 버젼에서 한글이 제대로 전달되도록 처리.
		//$mf['mf_to_name'] = htmlspecialchars_fix(addslashes($_to['display']));
		$mf['mf_to_name'] = urlencode(urlencode(base64_encode(htmlspecialchars_fix(addslashes($_to['display'])))));
		$mf['mf_to_email'] = htmlspecialchars_fix(addslashes($_to['address']));
		$mf['mf_cc'] = address_view($row['mf_cc']);
		$mf['mf_bcc'] = address_view($row['mf_bcc']);
		$mf['mf_reply-to'] = address_view($row['mf_reply_to']);
		$mf['mf_sender'] = address_view($row['mf_sender']);
		$mf['is_attachment'] = ($row['mf_attach_names'] != NULL) ? true : false;
		$mf['mf_attach_names'] = attach_names_toarray($row['mf_attach_names']);
		$mf['is_starred'] = ($row['is_starred'] != NULL ) ? 'Y' : 'N';

		if ($row['mf_content_type'] == 'H')
		{
			// [2025-11-05] 개인 정보 보호 기능
			if ($html_limit === 'Y' && ! (isset($_GET['hv']) || isset($_GET['ov']))) {
				$GLOBALS['__NMAIL_HTML_CLEAN'] = true;
				$mf['mf_body'] = nl2br(purifier_content_text($mf['mf_body']));      // 스팸편지함, 지운편지함에서는 HTML 제외후 표시
			} else {
				$GLOBALS['__NMAIL_HTML_CLEAN'] = false;
				$mf['mf_body'] = set_mailbody_html($row['mf_body'], $row['mb_id']);
			}
		} else
		{
			// [2025-11-13] text 본문에 링크가 포함된 경우만 자동 링크 검토
			if (preg_match("/(http|https|ftp|mms)(:\/\/[^ \n\r\t<>]+)/i", $mf['mf_body'])) {
				if ($html_limit === 'Y' && ! (isset($_GET['hv']) || isset($_GET['ov']))) {
					$GLOBALS['__NMAIL_AUTO_LINK_ENABLED'] = true;
					// 스팸편지함, 지운편지함에서는 TEXT 자동 링크 비활성화
					$mf['mf_body'] = nl2br(htmlspecialchars_fix($row['mf_body']));
				} else {
					$GLOBALS['__NMAIL_AUTO_LINK_ENABLED'] = false;
					$mf['mf_body'] = auto_link(nl2br(htmlspecialchars_fix($row['mf_body'])));
				}
			} else {
				$mf['mf_body'] = nl2br(htmlspecialchars_fix($row['mf_body']));
			}
		}	// if()

	// [2006-09-29]첨부파일이 이미지일 경우 본문 아래에 바로 보여주도록 함.
		for ($i=0; $i<sizeof($mf['mf_attach_names']['name']); $i++)
		{
			if (preg_match('/\.(jpg|jpeg|gif|png)$/i', $mf['mf_attach_names']['name'][$i]))
			{
				$mf['mf_body'] .= '<div style="padding:10px 0px 10px 10px"><img id=mf_attach_img_'.$i.' src="'.$nmpath.'/mail_attach_down.php?'.get_qs().'&mf_an_struct='.$mf['mf_attach_names']['struct'][$i].'&disposition=inline" title="첨부파일 : '.htmlspecialchars_fix($mf['mf_attach_names']['name'][$i].' ('.$mf['mf_attach_names']['size_human'][$i].')').'" style="position: absolute; visibility: hidden" onLoad="JavaScript:onload_mf_attach_img_'.$i.'();"></div>
					<script>
						function onload_mf_attach_img_'.$i.'()
						{
							var obj_mf_attach_img_'.$i.' = new Image();
							obj_mf_attach_img_'.$i.'.src = document.all.mf_attach_img_'.$i.'.src;
							var imgMaxWidth = document.body.clientWidth - 330;
							if (obj_mf_attach_img_'.$i.' && obj_mf_attach_img_'.$i.'.width > imgMaxWidth)
								document.all.mf_attach_img_'.$i.'.width = imgMaxWidth;
							document.all.mf_attach_img_'.$i.'.style.position = "static";
							document.all.mf_attach_img_'.$i.'.style.visibility = "visible";
						}	// function()
					</script>';
			}	// if()
		}	// for()

	// 메일박스
		$mail_box = get_mail_box();
		$_mail_box = db_rows_fieldtokey($mail_box);
		$select_mail_box = select_list_value($row['mb_id'], $_mail_box['mb_name'], $_mail_box['mb_id'], NULL, 0, 1);

	// [2025-11-24] 편지함 트리 지원
		$cg                = get_mail_box_tree_class();
		$cg_dataall        = $cg->getRowsByParent(0, 255, 1, "AND " . get_mail_box_where());
		$cg_dataall_option = $cg->getSelectOption($cg_dataall);
		$select_mail_box_parent        = select_list_value(
			$row['mb_id'], $cg_dataall_option['val'], $cg_dataall_option['key'], null, 0, 1
		);


// [2006-06-13] 이전, 다음 메일
	// [2025-08-05] 메일 검색 쿼리
	list($q_where, $bindings, $v_s_word, $vs, $mb_child_count) = mail_list_search_query();

	$DEBUG['db_prev']['start'] = getmicrotime();
	// [2006-09-14] Oracle Hint
	$q_hint = '';
	$q_stopkey = '';
	if ($G_SYS[DB] == 'oracle')
	{
		$q_stopkey = " AND ROWNUM <= 1 ";
		$q_hint = "/*+ ORDERED index_desc (".$AUTH['auth_m_mf_table']." MF_".$AUTH['auth_d_no']."_".$AUTH['auth_m_mail_file_group']."_MF_ARRIVAL_DATE) */";
	}	// if()
	$sql = "
		SELECT
			$q_hint
			mf_no,
		    mb_id,
		    mf_from,
		    mf_to,
		    mf_importance,
		    mf_subject,
		    mf_arrival_date,
		    mf_is_read,
		    mf_is_reply,
		    mf_is_forward
		FROM
			".$AUTH[auth_m_mf_table]."
			LEFT JOIN " . $TB['MAIL_STAR'] . " ms ON mf_no = ms_mf_no AND m_no = ms_m_no 
		WHERE
			m_no='" . $AUTH['auth_m_no'] . "'
			" . $q_where . "
			AND mf_no <> '" . $_GET['mf_no'] . "'
			AND (
				mf_arrival_date > '" . $row['mf_arrival_date'] . "'
				OR 
					( mf_arrival_date = '" . $row['mf_arrival_date'] . "'
						AND mf_no > '" . $_GET['mf_no'] . "'
					)
				)
			$q_stopkey
		ORDER BY
			mf_arrival_date ASC, mf_no ASC
		";
	$rows = db_get_rows($sql, 0, 1, false, $bindings);

	$_sc = '#000000';
	$mf_no_prev = ($rows[0]['mf_no']) ? $rows[0]['mf_no'] : 0;
	$mb_id_prev = ($rows[0]['mb_id']) ? $rows[0]['mb_id'] : '';
	$mf_from_prev = address_view($rows[0]['mf_from'], false, $_sc, false);
	$mf_from_title_prev = htmlspecialchars_fix($rows[0]['mf_from']);
	$mf_to_prev = address_view($rows[0]['mf_to'], false, $_sc, false);
	$mf_to_title_prev = htmlspecialchars_fix($rows[0]['mf_to']);
	$mf_importance_prev = $rows[0]['mf_importance'];
	$mf_subject_prev = (trim($rows[0]['mf_subject']) == NULL) ? '__제목없음__' : htmlspecialchars_fix($rows[0]['mf_subject']);
	$mf_mf_arrival_date_prev = ($rows[0]['mf_arrival_date'] != null) ? date('y-m-d H:i', strtotime($rows[0]['mf_arrival_date'])) : '';
	$mf_is_read_prev = $rows[0]['mf_is_read'];
    $mf_is_reply_prev = $rows[0]['mf_is_reply'];
    $mf_is_forward_prev = $rows[0]['mf_is_forward'];

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

	$DEBUG['db_next']['start'] = getmicrotime();
	// [2006-09-14] Oracle Hint
	$q_hint = '';
	$q_stopkey = '';
	if ($G_SYS[DB] == 'oracle')
	{
		$q_stopkey = " AND ROWNUM <= 1 ";
		$q_hint = "/*+ ORDERED index_asc (".$AUTH['auth_m_mf_table']." MF_".$AUTH['auth_d_no']."_".$AUTH['auth_m_mail_file_group']."_MF_ARRIVAL_DATE) */";
	}	// if()

	// [2009-04-20] 다음글 가져오기 성능 튜닝
	$_time = time();
	$mf_no_next = 0;
	$mb_id_next = '';
	$mf_from_next = '';
	$mf_from_title_next = '';
	$mf_to_next = '';
	$mf_to_title_next = '';
	$mf_importance_next = '';
	$mf_subject_next = '';
	$mf_mf_arrival_date_next = '';
	$mf_is_read_next = '';
	$mf_is_reply_next = '';
	$mf_is_forward_next = '';
	for ($i=1; $i<=4; $i++)
	{
		$_date = date('Y-m-d H:i:s', ($_time-(86400*round(pow(2.5,$i)))));

		$sql = "
			SELECT
				$q_hint
				mf_no,
			    mb_id,
			    mf_from,
			    mf_to,
			    mf_importance,
			    mf_subject,
			    mf_arrival_date,
			    mf_is_read,
			    mf_is_reply,
			    mf_is_forward
			FROM
				".$AUTH[auth_m_mf_table]."
				LEFT JOIN " . $TB['MAIL_STAR'] . " ms ON mf_no = ms_mf_no AND m_no = ms_m_no 
			WHERE
				(
				mf_arrival_date < '" . $row['mf_arrival_date'] . "'
				OR 
					( mf_arrival_date = '" . $row['mf_arrival_date'] . "'
						AND mf_no < '" . $_GET['mf_no'] . "'
					)
				)
				AND m_no='" . $AUTH['auth_m_no'] . "'
				" . $q_where . "
				AND mf_no <> '" . $_GET['mf_no'] . "'
				AND mf_no <> '" . $mf_no_prev . "'
				$q_stopkey
			ORDER BY
				mf_arrival_date DESC, mf_no DESC
			";
		$rows = db_get_rows($sql, 0, 1, false, $bindings);
		if ($rows[0]['mf_no'])
		{
			$mf_no_next = $rows[0]['mf_no'];
			$mb_id_next = ($rows[0]['mb_id']) ? $rows[0]['mb_id'] : '';
			$mf_from_next = address_view($rows[0]['mf_from'], false, $_sc, false);
			$mf_from_title_next = htmlspecialchars_fix($rows[0]['mf_from']);
			$mf_to_next = address_view($rows[0]['mf_to'], false, $_sc, false);
			$mf_to_title_next = htmlspecialchars_fix($rows[0]['mf_to']);
			$mf_importance_next = ($rows[0]['mf_importance']) ? $rows[0]['mf_importance'] : '';
			$mf_subject_next = (trim($rows[0]['mf_subject']) == NULL) ? '__제목없음__' : htmlspecialchars_fix($rows[0]['mf_subject']);
			$mf_mf_arrival_date_next = ($rows[0]['mf_arrival_date'] != null) ? date('y-m-d H:i', strtotime($rows[0]['mf_arrival_date'])) : '';
			$mf_is_read_next = $rows[0]['mf_is_read'];
			$mf_is_reply_next = $rows[0]['mf_is_reply'];
			$mf_is_forward_next = $rows[0]['mf_is_forward'];
			break;
		}	// if()
	}	// for()

	if ($mf_no_next == 0)
	{
		$sql = "
			SELECT
				$q_hint
				mf_no,
			    mb_id,
			    mf_from,
			    mf_to,
			    mf_importance,
			    mf_subject,
			    mf_arrival_date,
			    mf_is_read,
			    mf_is_reply,
			    mf_is_forward
			FROM
				".$AUTH[auth_m_mf_table]."
				LEFT JOIN " . $TB['MAIL_STAR'] . " ms ON mf_no = ms_mf_no AND m_no = ms_m_no 
			WHERE
				mf_arrival_date <= '" . $row['mf_arrival_date'] . "'
				AND m_no='" . $AUTH['auth_m_no'] . "'
				" . $q_where . "
				AND mf_no <> '" . $_GET['mf_no'] . "'
				AND mf_no <> '" . $mf_no_prev . "'
				$q_stopkey
			ORDER BY
				mf_arrival_date DESC, mf_no DESC
			";
		$rows = db_get_rows($sql, 0, 1, false, $bindings);
		$mf_no_next = ($rows[0]['mf_no']) ? $rows[0]['mf_no'] : 0;
		$mb_id = ($rows[0]['mb_id']) ? $rows[0]['mb_id'] : '';
		$mf_from_next = address_view($rows[0]['mf_from'], false, $_sc, false);
		$mf_from_title_next = htmlspecialchars_fix($rows[0]['mf_from']);
		$mf_to_next = address_view($rows[0]['mf_to'], false, $_sc, false);
		$mf_to_title_next = htmlspecialchars_fix($rows[0]['mf_to']);
		$mf_importance_next = ($rows[0]['mf_importance']) ? $rows[0]['mf_importance'] : '';
		$mf_subject_next = (trim($rows[0]['mf_subject']) == NULL) ? '__제목없음__' : htmlspecialchars_fix($rows[0]['mf_subject']);
		$mf_mf_arrival_date_next = ($rows[0]['mf_arrival_date'] != null) ? date('y-m-d H:i', strtotime($rows[0]['mf_arrival_date'])) : '';
	}	// if()
	$DEBUG['db_next']['exec'] += getmicrotime() - $DEBUG['db_next']['start'];

	// [2022-09-25] 브라우저 타이틀에 메일 제목 보여주기
	$G_SYS[SITE_TITLE] = $mf['mf_subject'] . ' - ' . $G_SYS[SITE_TITLE];

// skin view
	// [2011-03-02] 읽기 창 보여주기
	if ($_GET['iframe'])
	{
		$G_SYS['NM_HTML_IFRAME_HEAD'] .= '<base target="_parent">';
		nskinset('webmail', 'mail_read.html', 'iframe');
	} elseif ($_GET['window_open']) {
		nskinset('webmail', 'mail_read.html', 'window_open');
	} else {
		nskinset('webmail', 'mail_read.html');
	}	// if()
	include($NSKIN['view_layout']);


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