/*************************************************************************************************
 * 프로그램명 : 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.MUser;
import kr.co.kihyun.beans.entity.TotDoc;
import kr.co.kihyun.beans.entity.util.MPersistenceManager;
import kr.co.kihyun.beans.entity.util.*;
import kr.co.kihyun.beans.user.HttpSSOLogin;
import kr.co.kihyun.io.FileUtil;
import kr.co.kihyun.lang.Encoder;
import kr.co.kihyun.moumi.Moumi;
import kr.co.kihyun.lang.MInteger;
import kr.co.kihyun.lang.MLong;
import kr.co.kihyun.lang.MString;
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.HttpBoardWrite")
public class HttpBoardWrite extends HttpServlet {
        private static final Logger LOG = LoggerFactory.getLogger(HttpBoardWrite.class);
	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	@Override
	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;
			}

			/********** parameter value **********/
			String userID = Encoder.toJava(req.getParameter("userID"));
			String title = Encoder.toJava(req.getParameter("title"));
                        String strPage = Encoder.toJava(req.getParameter("strPage"));
			title = TagFilter.convertMeta(title);
			String contents = Encoder.toJava(req.getParameter("contents"));
			contents = TagFilter.convertMeta(contents);
			String passwd = req.getParameter("passwd");
			String groupID = req.getParameter("boardGroupID");
			Long docID = new Long(MInteger.parseInt(req.getParameter("docID")));
			int tmp1 = MInteger.parseInt(req.getParameter("tmp1"), 0);
			String svrFilenames = Encoder.toJava(req.getParameter("svrFilenames"));
                        String checkPopup=req.getParameter("checkPopup");
                        String callbackFunc = req.getParameter("callbackFunc");

			/********** regist **********/
			MUser mUser = null;
			TotDoc totDoc = null;
			kr.co.kihyun.beans.entity.Board mBoard = null;
			kr.co.kihyun.beans.entity.Board upperBoard = null;

			PersistenceManager pm = new MPersistenceManager(PMF.get().getPersistenceManager());
			Transaction tx = pm.currentTransaction();
			try {
				tx.begin();
				mUser = pm.getObjectById(MUser.class, userID);

				if (docID != 0)
					totDoc = pm.getObjectById(TotDoc.class, docID);
				if (tmp1 != 0)
					upperBoard = pm.getObjectById(kr.co.kihyun.beans.entity.Board.class,
							MLong.parseLong(req.getParameter("boardID")));

				mBoard = new kr.co.kihyun.beans.entity.Board(title);
				mBoard.setUser(mUser);
				mBoard.setPassword(passwd);
				mBoard.setContents(contents);
				mBoard.setCategory(pm.getObjectById(Category.class, groupID));
                                if(checkPopup==null) mBoard.setPopupYn("Y");
                                else mBoard.setPopupYn("N");

				if (totDoc != null)
					mBoard.setTotDoc(totDoc);
				if (upperBoard != null)
					mBoard.setUpperBoard(upperBoard);

				pm.makePersistent(mBoard);
				tx.commit();

				if (tmp1 == 0) {
					FileUtil.putInFiles(svrFilenames, mBoard);
				}
				out.println(ServletUtil.alert(Moumi.getMessageBundle().getString("moumi.message.popup.registComplete")));
			} catch (Exception e) {
				e.printStackTrace();
				out.println(ServletUtil.alert(Moumi.getMessageBundle().getString("moumi.message.popup.registFail")));
			} finally {
				if (tx.isActive())
					tx.rollback();
				pm.close();
			}

			String returnURL = "";
			if (tmp1 == 0) {
				returnURL = (String) session.getAttribute("writeTargetURI");
                                if( MString.isNull(callbackFunc) ) {
                                    out.println(ServletUtil.getJavaScript(returnURL));
                                    out.println(ServletUtil.getJavaScript("window.close();"));
                                }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) : HttpBoardWrite.doPost() filtered_callbackFunc={}, Not Test", filtered_callbackFunc);
                                    out.println(ServletUtil.getJavaScript(filtered_callbackFunc));
                                    //============================================================
                                }
			} else {
				returnURL = "document.location.replace('/totsys/sysadm/board/board_view.jsp?boardGroupID="
						+ groupID + "&boardID=" + (upperBoard == null ? mBoard.getId() : upperBoard.getId())
                                                + "&strPage="+strPage+ "')";
//				returnURL = "document.location.replace('/totsys/sysadm/board/board_view.jsp?boardID="
//						+ (upperBoard == null ? mBoard.getId() : upperBoard.getId()) + "&boardGroupID=" + groupID
//						+ "')";
                                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) : HttpBoardWrite.doPost() filtered_callbackFunc={}, Not Test", filtered_callbackFunc);
                                    out.println(ServletUtil.getJavaScript(filtered_callbackFunc));
                                    //============================================================
                                }
			}
			//업데이트시 파일도 업데이트
			FileUtil.getBoardAttachmentsFileNames(mBoard.getId(), req,true);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}
