package de.superx.servlet; import java.io.File; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.text.ParseException; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.parsers.FactoryConfigurationError; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import org.apache.commons.fileupload.DiskFileUpload; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUpload; import org.apache.commons.fileupload.FileUploadException; import org.dom4j.DocumentException; import org.xml.sax.SAXException; import de.memtext.db.NichtAngemeldetException; import de.memtext.tree.KeyParentEqualException; import de.memtext.tree.NoMainEntryException; import de.memtext.util.ServletHelper; import de.memtext.util.StringUtils; import de.superx.common.DBServletException; import de.superx.common.InvalidDataTypeException; import de.superx.common.InvalidKeyException; import de.superx.common.SichtException; import de.superx.common.SxUser; import de.superx.common.UngueltigeEingabeException; import de.superx.util.SqlStringUtils; import freemarker.template.TemplateException; public class SuperXUpload extends AbstractSuperXServlet { private static final long serialVersionUID = 2L; private static final String ADMIN_ONLY = de.superx.servlet.SuperXManager.htmlPageHead("Upload")+"

Hier ist ein Login nur für Administratoren möglich.

(Cookies müssen aktiviert sein)" + "

Kennung:

Passwort:
" + "

MandantenID


"; private static String pageBeginning = de.superx.servlet.SuperXManager.htmlPageHead("Upload")+"

SuperX Upload

"; private static String pageEnd = ""; private static String pathstart = ""; private Map mandantenFilter = new HashMap(); private static String tempdir; private class Uploader extends SuperXServletHelper { private String subpath = ""; private StringBuffer result = new StringBuffer(); private Connection conn; private PreparedStatement pst; private List filterList = new LinkedList(); Uploader(HttpServletRequest request, HttpServletResponse response) throws IOException { super(request, response); String filters = (String) mandantenFilter.get(getMandantenID()); if (filters != null) { StringTokenizer st = new StringTokenizer(filters, ","); while (st.hasMoreTokens()) { String afilter = st.nextToken(); filterList.add(afilter); } } result.append(pageBeginning); try { conn = SxPools.getConnection(getMandantenID()); String client_ip = "'" + request.getRemoteAddr() + "'"; String client_dns = "'" + request.getRemoteHost() + "'"; String now = ""; if (SxPools.get(getMandantenID()).getSqlDialect() .equals("Postgres")) { now = ", now()"; } else { now = ", current"; } pst = conn .prepareStatement("insert into protokoll (proto_fkt_id, userinfo_id, " + "ip_adresse, client_name, zeitpunkt,kommentar) values (" + "?, ?," + client_ip + "," + client_dns + now + ",?)"); } catch (Exception e) { throw new IOException(e.getMessage()); } } protected void perform() throws SQLException, DBServletException, TransformerException, KeyParentEqualException, NichtAngemeldetException, IOException, ParseException, ParserConfigurationException, FactoryConfigurationError, SAXException, DocumentException, IllegalArgumentException, SecurityException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, CloneNotSupportedException, TemplateException, InvalidKeyException, SichtException, IOException, ServletException, UngueltigeEingabeException, NoMainEntryException, InvalidDataTypeException { DiskFileUpload fu = new DiskFileUpload(); try { List files = fu.parseRequest(request); String mandantenID = getMandantenID(); subpath = File.separator + mandantenID + File.separator+ "custom"; Iterator iter = files.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { // if (item.getName().equals("pfad")) //NPE // TODO including suppath version subpath = // File.separator + item.getString(); } else { if (item.getSize() == 0) continue; if (isFileAllowed(item.getName())) { uploadFile(item); } else { log(item, new UngueltigeEingabeException( "Hochladen von " + item.getName() + " nicht erlaubt!")); } } } } catch (FileUploadException e) { result.append("

Hochladen nicht erfolgreich: " + e + "

"); } // nur für uneingeschraenkte Version link // String defaultpath = subpath; // if (subpath.startsWith("/") || subpath.startsWith("\\")) // defaultpath = subpath.substring(1); result.append("

zur Upload-Seite

" + " \n" + ""); pst.close(); conn.close(); sendBackHtml(result.toString()); } /** * * @param item * @throws SQLException * - wenn Protokollierung nicht geht */ private void uploadFile(FileItem item) throws SQLException { File dir = new File(pathstart + subpath); try { if (!dir.exists()) throw new IOException("Zielverzeichnis " + dir + " existiert nicht"); File targetFile = new File(pathstart + subpath + File.separator + item.getName()); // System.out.println("target for upload:"+targetFile // ); if (targetFile.exists()) targetFile.delete(); item.write(targetFile); log(item, null); } catch (Exception e) { log(item, e); } } private void log(FileItem item, Exception e) throws SQLException { SxUser user = (SxUser) request.getSession().getAttribute("user"); pst.setInt(2, ((Integer) user.getId()).intValue()); String msg = ""; result.append("

"); String s = item.getName() + " nach superx" + subpath; if (e == null) { msg = "Hochladen von " + s + " erfolgreich"; result.append("" + msg + ""); pst.setInt(1, 11); } else { if (e instanceof UngueltigeEingabeException) { msg = "Hochladen von " + s + " nicht erlaubt!"; result.append("" + msg + ""); pst.setInt(1, 12); } else { msg = "Hochladen von " + s + " nicht erfolgreich:" + e; pst.setInt(1, 13); result.append("" + msg + ""); } } pst.setString(3, msg); pst.execute(); result.append("

"); } private boolean isFileAllowed(String name) { boolean result = false; for (Iterator it = filterList.iterator(); it.hasNext();) { String afilter = (String) it.next(); if (afilter.indexOf("*") == -1) { if (name.equals(afilter)) result = true; } else { afilter = StringUtils.replace(afilter, ".", "\\.") .toLowerCase(); afilter = StringUtils.replace(afilter, "*", ".*"); Pattern p = Pattern.compile(afilter); Matcher m = p.matcher(name.toLowerCase()); if (m.matches()) result = true; } } return result; } } public void init(ServletConfig config) throws ServletException { super.init(config); pathstart = getServletConfig().getServletContext().getRealPath("/"); for (Enumeration en = config.getInitParameterNames(); en .hasMoreElements();) { String mandantenID = (String) en.nextElement(); String mandantenFilterString = config.getInitParameter(mandantenID); mandantenFilter.put(mandantenID, mandantenFilterString); // make sure custom dir exists new File(pathstart + File.separator + mandantenID+"custom" ).mkdirs(); } tempdir = System.getProperty("java.io.tmpdir"); if (!(tempdir.endsWith("/") || tempdir.endsWith("\\"))) tempdir = tempdir + System.getProperty("file.separator"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { checkAnmeldungImRequest(request); if (isAllowed(request, response)) { if (FileUpload.isMultipartContent(request)) { Uploader u = new Uploader(request, response); u.run(true); } else sendFormPage(request, response); } } /** * Fileupload1.22 version boolean isMultipart = * ServletFileUpload.isMultipartContent(request); if (isMultipart) { String * subpath = ""; try { FileItemFactory factory = new DiskFileItemFactory(); * ServletFileUpload upload = new ServletFileUpload(factory); List items = * upload.parseRequest(request); Iterator iter = items.iterator(); * * while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if * (item.isFormField()) { String name = item.getFieldName(); String value = * item.getString(); subpath = File.separator + value; * * } else { * * File targetFile = new File(pathstart +subpath+ File.separator + * item.getName()); if (targetFile.exists()) targetFile.delete(); * item.write(targetFile); */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { AbstractSuperXServlet.setEncoding(request); response.setContentType("text/html; charset=" + SqlStringUtils.getEncoding()); if (isAllowed(request, response)) sendFormPage(request, response); } /** * check if Servlet is allowed in genereal and current user is admin, send * out info if not * * @param request * @param response * @return * @throws IOException */ private boolean isAllowed(HttpServletRequest request, HttpServletResponse response) throws IOException { boolean result = true; SxUser user = (SxUser) request.getSession().getAttribute("user"); if (user == null || !user.isAdmin()) { result = false; ServletUtils.sendBackHtml(response, ADMIN_ONLY); } else { String mandantenID = ServletUtils.getMandantenID(request); if (mandantenID == null || mandantenFilter.get(mandantenID) == null) { ServletUtils .sendBackHtml( response, pageBeginning + "

Die Funktion ist für Ihre MandantenID: " + mandantenID + " nicht aktiviert.

"); result = false; } } return result; } private void sendFormPage(HttpServletRequest request, HttpServletResponse response) throws IOException { String pfad = ServletHelper.getParameter(request, "pfad"); String mandantenID = ServletUtils.getMandantenID(request); if (pfad == null) pfad = ""; // Vorbelegung von value ist aus Sicherheitsgründen nicht möglich String t = // "\n" // + pageBeginning + "

Ihre MandantenID:" + mandantenID + "

" + "

Dateien werden auf dem Webserver gespielt ins Verzeichnis superx/"+ mandantenID+"/custom/" + "
Zur Verlinkung von Grafiken kann z.B. ../"+ mandantenID+"/custom/" + mandantenID + "/logo.gif genutzt werden

" + "

Erlaubte Dateien: " + mandantenFilter.get(mandantenID) + "

Jeder Upload wird einschließlich Dateiname,Username,Zeitpunkt und IP-Nummer protokolliert!

Sie können ein bis vier Dateien gleichzeitig hochladen.
Ggfs. bereits vorhandene Dateien werden überschrieben.

" + "
\n" + "

" // + // "

Pfad unter webapps/superx/ \n" + "

\n" + "
\n" + "
\n" + "

\n" + " \n

" + "
\n" + " \n" + ""; ServletUtils.sendBackHtml(response, t); } public String getServletInfo() { return "SuperXUpload"; } }