<?
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> >> <b>'.get_mb_name($_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
			FROM
				".$AUTH[auth_m_mf_table]."
			WHERE
				mf_no='" . $_GET['mf_no'] . "'
				AND m_no='" . $AUTH['auth_m_no'] . "'
				AND mb_id='" . $_GET['mb_id'] . "'
			";
		$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($_GET['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='" . $_GET['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='" . $_GET['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']);
		if ($row['mf_content_type'] == 'H')
		{
			$mf['mf_body'] = set_mailbody_html($row['mf_body'], $_GET['mb_id']);
		} else
		{
			$mf['mf_body'] = auto_link(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].'" alt="첨부파일 : '.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($_GET['mb_id'], $_mail_box['mb_name'], $_mail_box['mb_id'], NULL, 0, 1);


// [2006-06-13] 이전, 다음 메일
	$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
		FROM
			".$AUTH[auth_m_mf_table]."
		WHERE
			mf_arrival_date >= '" . $row['mf_arrival_date'] . "'
			AND m_no='" . $AUTH['auth_m_no'] . "'
			AND mb_id='" . $_GET['mb_id'] . "'
			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, mf_no DESC
		";
	$rows = db_get_rows($sql, 0, 1);
	$mf_no_prev = ($rows[0]['mf_no']) ? $rows[0]['mf_no'] : 0;
	$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;
	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
			FROM
				".$AUTH[auth_m_mf_table]."
			WHERE
				mf_arrival_date <= '" . $row['mf_arrival_date'] . "'
				AND mf_arrival_date >= '".$_date."'
				AND m_no='" . $AUTH['auth_m_no'] . "'
				AND mb_id='" . $_GET['mb_id'] . "'
				AND mf_no != '" . $_GET['mf_no'] . "'
				AND mf_no != '" . $mf_no_prev . "'
				$q_stopkey
			ORDER BY
				mf_arrival_date DESC, mf_no
			";
		$rows = db_get_rows($sql, 0, 1);
		if ($rows[0]['mf_no'])
		{
			$mf_no_next = $rows[0]['mf_no'];
			break;
		}	// if()
	}	// for()

	if ($mf_no_next == 0)
	{
		$sql = "
			SELECT
				$q_hint
				mf_no
			FROM
				".$AUTH[auth_m_mf_table]."
			WHERE
				mf_arrival_date <= '" . $row['mf_arrival_date'] . "'
				AND m_no='" . $AUTH['auth_m_no'] . "'
				AND mb_id='" . $_GET['mb_id'] . "'
				AND mf_no != '" . $_GET['mf_no'] . "'
				AND mf_no != '" . $mf_no_prev . "'
				$q_stopkey
			ORDER BY
				mf_arrival_date DESC, mf_no
			";
		$rows = db_get_rows($sql, 0, 1);
		$mf_no_next = ($rows[0]['mf_no']) ? $rows[0]['mf_no'] : 0;
	}	// if()
	$DEBUG['db_next']['exec'] += getmicrotime() - $DEBUG['db_next']['start'];


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


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