/*************************************************************************************************
 * 프로그램명 : HttpReportRegist.java 프로그램설명 : 집계 문서에대한 보고자 보고 또는 보고자 자료 변경에 사용 작성자 : 강원중 작성일 : 2004.01.12 변경일 : 2003.11.30
 **************************************************************************************************/

package kr.co.kihyun.beans.totsys.board;

import java.io.IOException;
import java.io.PrintWriter;

import javax.jdo.PersistenceManager;
import javax.jdo.Transaction;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import kr.co.kihyun.beans.entity.Category;
import kr.co.kihyun.beans.entity.util.*;
import kr.co.kihyun.beans.user.HttpSSOLogin;
import kr.co.kihyun.db.DBManager;
import kr.co.kihyun.io.FileUtil;
import kr.co.kihyun.lang.Encoder;
import kr.co.kihyun.lang.MInteger;
import kr.co.kihyun.lang.MLong;
import kr.co.kihyun.lang.MString;
import kr.co.kihyun.moumi.MoumiConfig;
import kr.co.kihyun.text.html.ServletUtil;
import kr.co.kihyun.text.html.TagFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@WebServlet("/servlet/kr.co.kihyun.beans.totsys.board.HttpBoardModify")
public class HttpBoardModify extends HttpServlet {
	private static final Logger LOG = LoggerFactory
			.getLogger(HttpBoardModify.class);

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		doPost(req, res);
	}

	public void doPost(HttpServletRequest req, HttpServletResponse res)	throws ServletException, IOException {
		res.setContentType("text/html;charset=UTF-8");
		PrintWriter out = res.getWriter();
		HttpSession session = req.getSession(true);

		try {

			/*********** User HttpLogin check ***********/
			if (!HttpSSOLogin.isLogin(req)) {
				String connURL = "location='/totsys/login/login.jsp';";
				out.println(ServletUtil.getJavaScript(connURL));
				return;
			}

			String usID = HttpSSOLogin.getLoginID(req);

			/********** parameter value **********/
			String userID = Encoder.toJava(req.getParameter("userID"));
			String title = Encoder.toJava(req.getParameter("title"));

			// 게시판 글 수정시 제목도 특수기호를 치환하도록 수정. 2014.12.10 by YOUNGJUN,CHO
			title = TagFilter.convertMeta(title);

			String contents = Encoder.toJava(req.getParameter("contents"));
			contents = TagFilter.convertMeta(contents);
			Long boardID = MLong.parseLong(req.getParameter("boardID"), null);
			Long id = MLong.parseLong(req.getParameter("id"), null);
			int fileCount = MInteger.parseInt(req.getParameter("fileCount"));
			String usrFilenames = Encoder.toJava(req.getParameter("usrFilenames"));
			String svrFilenames = Encoder.toJava(req.getParameter("svrFilenames"));
			String checkPopup = req.getParameter("checkPopup");
			String callbackFunc = req.getParameter("callbackFunc");
			String returnURL = "";

			PersistenceManager pm = new MPersistenceManager(PMF.get().getPersistenceManager());
			Transaction tx = pm.currentTransaction();
			try {
				tx.begin();

				kr.co.kihyun.beans.entity.Board mBoard = pm.getObjectById(kr.co.kihyun.beans.entity.Board.class, boardID);

				if (!mBoard.getUser(pm).getId().equals(usID) && HttpSSOLogin.getSysAuth(req) != MoumiConfig.SYSADM) {
					out.println(ServletUtil.alert(MoumiConfig.getMessageBundle().getString("moumi.message.popup.commonWay")));
					returnURL = "document.location.replace('/totsys/sysadm/board/board_list.jsp?boardGroupID=" + mBoard.getCategory().getId() + "')";
				} else {
					mBoard.setTitle(title);
					mBoard.setContents(contents);
					if ("Y".equals(checkPopup)){
						mBoard.setPopupYn("Y");
					}else{
						mBoard.setPopupYn("N");
					}
					pm.makePersistent(mBoard);
					tx.commit();

					FileUtil.putInFiles(svrFilenames, mBoard);
					out.println(ServletUtil.alert(MoumiConfig.getMessageBundle().getString("moumi.message.popup.alter")));

					if (mBoard.getCategory().equals(Category.ID_TOT_DOC_COMMENT)) {
						returnURL = (String) session.getAttribute("modifyTargetURI");
						out.println(ServletUtil.getJavaScript(returnURL));
						out.println(ServletUtil.getJavaScript("window.close();"));
						out.println(ServletUtil.getJavaScript("parent.opener.window.close();"));
					} else {
						if (id == null){
							returnURL = "document.location.replace('/totsys/sysadm/board/board_view.jsp?boardID=" + boardID + "')";
						} else {
							returnURL = "document.location.replace('/totsys/sysadm/board/board_view.jsp?boardID=" + id + "')";
						}

						if (MString.isNull(callbackFunc)) {
							out.println(ServletUtil.getJavaScript(returnURL));
						} else {
							// v2. 9.크로스사이트 스크립트 (PrintWrier) : Update by
							// KWON,HAN
							// out.println(ServletUtil.getJavaScript(callbackFunc));

							// 수정 : 외부 입력값 필터링
							String filtered_callbackFunc = callbackFunc.replaceAll("<", "").replaceAll(">", "").replaceAll("&", "").replaceAll(",", "");
							LOG.debug("v2 9.크로스사이트 스크립트 (PrintWrier) : HttpBoardModify.doPost() filtered_callbackFunc={}, Not Test", filtered_callbackFunc);
							out.println(ServletUtil.getJavaScript(filtered_callbackFunc));
							// ============================================================
						}
					}
				}

				// 44.적절하지 않은 예외처리(광범위예외클래스)_CWE-754 : Update by YOUNGJUN,CHO
			} catch (IOException ioex) {
				ioex.printStackTrace();
				// ================================================

			} catch (Exception ex) {
				out.println(ServletUtil.alert(MoumiConfig.getMessageBundle().getString("moumi.message.popup.alterFail")));
				// v2. 9.크로스사이트 스크립트 (PrintWrier) : Update by KWON,HAN
				// out.println(ServletUtil.getJavaScript("history.go(-1);"));

				// 수정 : 외부 입력값 필터링
				String filtered_callbackFunc = "history.go(-1);";
				filtered_callbackFunc = filtered_callbackFunc.replaceAll("<", "").replaceAll(">", "").replaceAll("&", "").replaceAll(",", "");
				LOG.debug("v2 9.크로스사이트 스크립트 (PrintWrier) : HttpBoardModify.doPost() filtered_callbackFunc={}, Not Test", filtered_callbackFunc);
				out.println(ServletUtil.getJavaScript(filtered_callbackFunc));
				// ============================================================

				ex.printStackTrace();
			} finally {
				if (tx.isActive())
					tx.rollback();
				pm.close();
			}

			// 업데이트시 파일도 업데이트
			FileUtil.getBoardAttachmentsFileNames(boardID, req, true);

		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

}
