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

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
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 kr.co.kihyun.beans.entity.MUser;
import kr.co.kihyun.beans.entity.TotReport;
//import kr.co.kihyun.beans.entity.TotReportProcess;
import kr.co.kihyun.beans.entity.util.MPersistenceManager;
import kr.co.kihyun.beans.entity.util.*;
//import kr.co.kihyun.beans.totsys.report.ReportUpdate;
import kr.co.kihyun.beans.user.HttpSSOLogin;
//import kr.co.kihyun.lang.MInteger;
import kr.co.kihyun.lang.MLong;
import kr.co.kihyun.moumi.MoumiConfig;
import kr.co.kihyun.moumi.report.MReport;
import kr.co.kihyun.text.html.ServletUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

//import kr.co.kihyun.beans.totsys.report.ReportView;
import kr.co.kihyun.beans.totsys.report.ReportViewManager;
import kr.co.kihyun.beans.totsys.report.ReportFormElement;
//import kr.co.kihyun.beans.totsys.doc.table.item.Item;
//import kr.co.kihyun.beans.totsys.doc.table.Table;
import kr.co.kihyun.beans.totsys.doc.table.item.ItemList;
import kr.co.kihyun.text.excel.Excel;
import kr.co.kihyun.text.html.TagFilter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map.Entry;
import java.util.List;
import kr.co.kihyun.util.*;
@WebServlet("/servlet/kr.co.kihyun.beans.totsys.repoper.HttpExcelDown")
public class HttpExcelDown extends HttpServlet 
{
	private static final long serialVersionUID = 1L;
	private static final Logger LOG = LoggerFactory.getLogger(HttpNotUpdate.class);

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

            if (!HttpSSOLogin.isLogin(req)) 
            {
                String connURL = "location='/totsys/login/login.jsp';";
                //v2. 9.크로스사이트 스크립트 (PrintWrier) : Update by KWON,HAN 
//                out.println(ServletUtil.getJavaScript(connURL));
                
                // 수정 : 외부 입력값 필터링
                String filtered_connURL = connURL.replaceAll("<","").replaceAll(">","").replaceAll("&","").replaceAll(",","");
                LOG.debug("v2 9.크로스사이트 스크립트 (PrintWrier) : HttpExcelDown.doPost() filtered_connURL={}, Not Test", filtered_connURL);
                out.println(ServletUtil.getJavaScript(filtered_connURL));               
                //========================================
                
                return;
            }

            Long reportID = MLong.parseLong(req.getParameter("reportID"));
            PersistenceManager pm = new MPersistenceManager(PMF.get().getPersistenceManager());
            Transaction tx = pm.currentTransaction();
            
            try {
                TotReport totReport = pm.getObjectById(TotReport.class, reportID);
                tx.begin(); 
                ReportViewManager reportViewManager = new ReportViewManager(totReport.getTotDoc(), MReport.EXCEL);
                String userId=totReport.getUser(pm).getId();
                reportViewManager.setReportData(totReport.getDept(pm).getId(),userId);

                String party=MoumiConfig.getInitParameter("moumi.partyId");
                String dept=totReport.getDept(pm).getId();
                String docName = totReport.getTotDoc().getName();
                Date date=new Date();
                SimpleDateFormat format=new SimpleDateFormat("yyyyMMddHHmmss");
                String dateStr=format.format(date);
                String excelName=docName+".xls";
                String dirName="/edufile/"+party+"/"+party+"/bms/out/"+dept+"/"+userId+dateStr+"/";
                
                //v2. 4.경로 조작 및 자원 삽입_CWE-22/23/36/99 : 파일명이 아니라 경로를 생성하므로 웹취약점을 해결책을 적용할 수 없음
                File tmpDir=new File(dirName);

                // 43.권한 미설정의 위험성(mkdir)_CWE-379 : Add by YOUNGJUN,CHO
                tmpDir.setExecutable(true, true);
                tmpDir.setReadable(true, true);
                tmpDir.setWritable(true, true);
                
                boolean isMkDir = tmpDir.mkdirs();
                //++++++++++++++++++++++++++++++++++++++++++++++++
                
                // 43.권한 미설정의 위험성(mkdir)_CWE-379 : Update by YOUNGJUN,CHO
                if (isMkDir) {
                    String tmpName,nameList=excelName;
                
                    for(Entry<String, List<Byte>> entry : totReport.getAttachments().entrySet()) {
                        tmpName=entry.getKey();
                        DataOutputStream output1=null;
                    
                    //14.부적절한 자원 해제(FileInputStream/FileOutputStream)_CWE-404 : Update by KWON,HAN 
                        //Byte[] content=totReport.getAttachments().get(tmpName).toArray(new Byte[]{});
                        //output1=new DataOutputStream(new FileOutputStream(dirName+tmpName));
                        //for(int ii=0;ii<content.length;ii++) output1.write(content[ii]);
                        //output1.close();
                        //
                    try {
                        
                        //v2. 4.경로 조작 및 자원 삽입_CWE-22/23/36/99 : Update by KWON,HAN
//                        output1=new DataOutputStream(new FileOutputStream(dirName+tmpName));
//                        Byte[] content=totReport.getAttachments().get(tmpName).toArray(new Byte[]{});
//                        for(int ii=0;ii<content.length;ii++) output1.write(content[ii]);
                        
                        if (tmpName != null && !"".equals(tmpName)) {
                            // 수정 : 외부 입력값 필터링
                            tmpName = tmpName.replaceAll("/","");
                            tmpName = tmpName.replaceAll("\\","");
                            //tmpName = tmpName.replaceAll(".","");
                            //tmpName = tmpName.replaceAll("&","");
                            
                            LOG.debug("v2. 4.경로 조작 및 자원 삽입_CWE-22/23/36/99 : HttpExcelDown.doPost tmpName={} / Not Test", tmpName);
                            output1=new DataOutputStream(new FileOutputStream(dirName+tmpName));
                            Byte[] content=totReport.getAttachments().get(tmpName).toArray(new Byte[]{});
                            if (output1 != null)  {
                                for(int ii=0;ii<content.length;ii++) output1.write(content[ii]);
                            }
                        }
                    } catch (IOException e) { 
                         e.printStackTrace(); 
                    } finally { 
                        output1.close();// 예외 발생 여부와 상관없이 자원 해제  
                    }
                    //===================================================================================
                    
                        nameList+=","+tmpName;
                    }
                    tx.rollback(); 

                    String report = reportViewManager.getReport();			
                    ReportFormElement reportFormElement = new ReportFormElement(totReport.getTotDoc());
                    String Form = reportFormElement.getForm();
                    ItemList itemTypes = reportFormElement.getItemList();
                    int[] tmpItemTypeList = itemTypes.getTypeList();
                    String ttmp=Excel.adjustFmlaToExcel(TagFilter.removeBlankPara(Excel.setCellTypes(Excel.removeFmla(report), tmpItemTypeList)));
                    
                    //v2. 4.경로 조작 및 자원 삽입_CWE-22/23/36/99 : Update by KWON,HAN
//                    File exFile=new File(dirName+excelName);
//                    PrintWriter pw=new PrintWriter(exFile);
//                    pw.print(ttmp);
//                    pw.close();

                    if (excelName != null && !"".equals(excelName)) {
                        // 수정 : 외부 입력값 필터링
                        excelName = excelName.replaceAll("/","");
                        tmpName = excelName.replaceAll("\\","");
                        //excelName = excelName.replaceAll(".","");
                        //excelName = excelName.replaceAll("&","");

                        LOG.debug("v2. 4.경로 조작 및 자원 삽입_CWE-22/23/36/99 : HttpExcelDown.doPost excelName={} / Not Test", excelName);
                        File exFile=new File(dirName+excelName);
                        if (exFile != null)  {
                            PrintWriter pw=new PrintWriter(exFile);
                            pw.print(ttmp);
                            pw.close();
                        }
                    }
                    
                    makeHtml(req,res,dirName,nameList,out,docName,userId,reportID,dept);
                } else {
                    LOG.error("\nFailed to make directory. - dirName : {}", dirName);
                }
                //================================================
                
            //44.적절하지 않은 예외처리(광범위예외클래스)_CWE-754 Add by YOUNGJUN,CHO
            } catch(IOException ioex) {    
                ioex.printStackTrace();
                res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error!: " + ioex.getMessage());
            //++++++++++++++++++++++++++++++++++++++++++++++++
            } catch(Exception ex) {
                ex.printStackTrace();
                res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error!: " + ex.getMessage());
            }
            finally { 
                if(tx.isActive()) tx.rollback(); pm.close(); 
            }
	}

	public void makeHtml(HttpServletRequest req,HttpServletResponse res,String path,String fList,PrintWriter out,String docName,String uid,Long rid,String dept)
	{
            docName=Base64.encodeBase64FromByte(docName.getBytes());
            fList=Base64.encodeBase64FromByte(fList.getBytes());
		res.setContentType("text/html;charset=utf-8");
		out.println("<html>");
		out.println("<head>");
		out.println("</head>");
		out.println("<body>");
		out.println("<form name='payForm' method='post'>");
  	out.println("<input type=hidden name='doctKndCode' value='C21'>");
  	out.println("<input type=hidden name='USER_ID' value='"+uid+"'>");
  	out.println("<input type=hidden name='DEPT_CODE' value='"+dept+"'>");
  	out.println("<input type=hidden name='reportID' value='"+rid+"'>");
  	out.println("<input type=hidden name='filePath' value='"+path+"'>");
  	out.println("<input type=hidden name='fileName' value='"+fList+"'>");
  	out.println("<input type=hidden name='doctName' value='"+docName+"'>");
		out.println("</form>");
		out.println("</body>");
		out.println("</html>");
		out.println("<script>");
		out.println("frm=document.payForm;");
		out.println("frm.target='_self';");
		String url="'http://"+req.getServerName().replace("ats","eis")+"/displayXUI.jsp?mipid=cm.bcm.cfm.rt::bcm_cfmrt00_p00.xfdl';";
		out.println("frm.action="+url);
		out.println("frm.submit();");
		out.println("</script>");
	}
}
