001: /*
002: * FCKeditor - The text editor for internet
003: * Copyright (C) 2003-2005 Frederico Caldeira Knabben
004: *
005: * Licensed under the terms of the GNU Lesser General Public License:
006: * http://www.opensource.org/licenses/lgpl-license.php
007: *
008: * For further information visit:
009: * http://www.fckeditor.net/
010: *
011: * File Name: SimpleUploaderServlet.java
012: * Java File Uploader class.
013: *
014: * Version: 2.3
015: * Modified: 2005-08-11 16:29:00
016: *
017: * File Authors:
018: * Simone Chiaretta (simo@users.sourceforge.net)
019: */
020:
021: package com.fredck.FCKeditor.uploader;
022:
023: import java.io.*;
024: import javax.servlet.*;
025: import javax.servlet.http.*;
026: import java.util.*;
027:
028: import org.apache.commons.fileupload.*;
029:
030: import javax.xml.parsers.*;
031: import org.w3c.dom.*;
032: import javax.xml.transform.*;
033: import javax.xml.transform.dom.DOMSource;
034: import javax.xml.transform.stream.StreamResult;
035:
036: import com.Yasna.forum.util.SkinUtils;
037: import com.Yasna.forum.Authorization;
038:
039: /**
040: * Servlet to upload files.<br>
041: *
042: * This servlet accepts just file uploads, eventually with a parameter specifying file type
043: *
044: * @author Simone Chiaretta (simo@users.sourceforge.net)
045: */
046:
047: public class SimpleUploaderServlet extends HttpServlet {
048:
049: private static String baseDir;
050: private static boolean debug = false;
051: private static boolean enabled = false;
052: private static Hashtable allowedExtensions;
053: private static Hashtable deniedExtensions;
054:
055: /**
056: * Initialize the servlet.<br>
057: * Retrieve from the servlet configuration the "baseDir" which is the root of the file repository:<br>
058: * If not specified the value of "/UserFiles/" will be used.<br>
059: * Also it retrieve all allowed and denied extensions to be handled.
060: *
061: */
062: public void init() throws ServletException {
063:
064: debug = (new Boolean(getInitParameter("debug"))).booleanValue();
065:
066: if (debug)
067: System.out
068: .println("\r\n---- SimpleUploaderServlet initialization started ----");
069:
070: baseDir = getInitParameter("baseDir");
071: enabled = (new Boolean(getInitParameter("enabled")))
072: .booleanValue();
073: if (baseDir == null)
074: baseDir = "/UserFiles/";
075: String realBaseDir = getServletContext().getRealPath(baseDir);
076: File baseFile = new File(realBaseDir);
077: if (!baseFile.exists()) {
078: baseFile.mkdir();
079: }
080:
081: allowedExtensions = new Hashtable(3);
082: deniedExtensions = new Hashtable(3);
083:
084: allowedExtensions
085: .put(
086: "File",
087: stringToArrayList(getInitParameter("AllowedExtensionsFile")));
088: deniedExtensions
089: .put(
090: "File",
091: stringToArrayList(getInitParameter("DeniedExtensionsFile")));
092:
093: allowedExtensions
094: .put(
095: "Image",
096: stringToArrayList(getInitParameter("AllowedExtensionsImage")));
097: deniedExtensions
098: .put(
099: "Image",
100: stringToArrayList(getInitParameter("DeniedExtensionsImage")));
101:
102: allowedExtensions
103: .put(
104: "Flash",
105: stringToArrayList(getInitParameter("AllowedExtensionsFlash")));
106: deniedExtensions
107: .put(
108: "Flash",
109: stringToArrayList(getInitParameter("DeniedExtensionsFlash")));
110:
111: if (debug)
112: System.out
113: .println("---- SimpleUploaderServlet Initialization completed ----\r\n");
114: if (debug)
115: System.out.println("---- Using the directory:"
116: + realBaseDir);
117:
118: }
119:
120: /**
121: * Manage the Upload requests.<br>
122: *
123: * The servlet accepts commands sent in the following format:<br>
124: * simpleUploader?Type=ResourceType<br><br>
125: * It store the file (renaming it in case a file with the same name exists) and then return an HTML file
126: * with a javascript command in it.
127: *
128: */
129: public void doPost(HttpServletRequest request,
130: HttpServletResponse response) throws ServletException,
131: IOException {
132:
133: if (debug)
134: System.out.println("--- BEGIN DOPOST ---");
135: Authorization authToken = SkinUtils.getUserAuthorization(
136: request, response);
137: String userdir = request.getRemoteAddr();
138: if (authToken != null) {
139: userdir = Integer.toString(authToken.getUserID());
140: }
141: if (debug)
142: System.out.println(userdir);
143: String realBaseDir = getServletContext().getRealPath(
144: baseDir + userdir);
145: File baseFile = new File(realBaseDir);
146: if (!baseFile.exists()) {
147: baseFile.mkdir();
148: }
149: if (debug)
150: System.out.println(realBaseDir);
151:
152: response.setContentType("text/html; charset=UTF-8");
153: response.setHeader("Cache-Control", "no-cache");
154: PrintWriter out = response.getWriter();
155:
156: String typeStr = request.getParameter("Type");
157:
158: String currentPath = baseDir + userdir + "/" + typeStr;
159: String currentDirPath = getServletContext().getRealPath(
160: currentPath);
161: currentPath = request.getContextPath() + currentPath;
162:
163: if (debug)
164: System.out.println(currentDirPath);
165:
166: String retVal = "0";
167: String newName = "";
168: String fileUrl = "";
169: String errorMessage = "";
170:
171: if (enabled) {
172: DiskFileUpload upload = new DiskFileUpload();
173: try {
174: List items = upload.parseRequest(request);
175:
176: Map fields = new HashMap();
177:
178: Iterator iter = items.iterator();
179: while (iter.hasNext()) {
180: FileItem item = (FileItem) iter.next();
181: if (item.isFormField())
182: fields.put(item.getFieldName(), item
183: .getString());
184: else
185: fields.put(item.getFieldName(), item);
186: }
187: FileItem uplFile = (FileItem) fields.get("NewFile");
188: String fileNameLong = uplFile.getName();
189: fileNameLong = fileNameLong.replace('\\', '/');
190: String[] pathParts = fileNameLong.split("/");
191: String fileName = pathParts[pathParts.length - 1];
192:
193: String nameWithoutExt = getNameWithoutExtension(fileName);
194: String ext = getExtension(fileName);
195: File pathToSave = new File(currentDirPath, fileName);
196: fileUrl = currentPath + "/" + fileName;
197: if (extIsAllowed(typeStr, ext)) {
198: int counter = 1;
199: while (pathToSave.exists()) {
200: newName = nameWithoutExt + "(" + counter + ")"
201: + "." + ext;
202: fileUrl = currentPath + "/" + newName;
203: retVal = "201";
204: pathToSave = new File(currentDirPath, newName);
205: counter++;
206: }
207: uplFile.write(pathToSave);
208: } else {
209: retVal = "202";
210: errorMessage = "";
211: if (debug)
212: System.out.println("Invalid file type: " + ext);
213: }
214: } catch (Exception ex) {
215: if (debug)
216: ex.printStackTrace();
217: retVal = "203";
218: }
219: } else {
220: retVal = "1";
221: errorMessage = "This file uploader is disabled. Please check the WEB-INF/web.xml file";
222: }
223:
224: out.println("<script type=\"text/javascript\">");
225: out.println("window.parent.OnUploadCompleted(" + retVal + ",'"
226: + fileUrl + "','" + newName + "','" + errorMessage
227: + "');");
228: out.println("</script>");
229: out.flush();
230: out.close();
231:
232: if (debug)
233: System.out.println("--- END DOPOST ---");
234:
235: }
236:
237: /*
238: * This method was fixed after Kris Barnhoorn (kurioskronic) submitted SF bug #991489
239: */
240: private static String getNameWithoutExtension(String fileName) {
241: return fileName.substring(0, fileName.lastIndexOf("."));
242: }
243:
244: /*
245: * This method was fixed after Kris Barnhoorn (kurioskronic) submitted SF bug #991489
246: */
247: private String getExtension(String fileName) {
248: return fileName.substring(fileName.lastIndexOf(".") + 1);
249: }
250:
251: /**
252: * Helper function to convert the configuration string to an ArrayList.
253: */
254:
255: private ArrayList stringToArrayList(String str) {
256:
257: if (debug)
258: System.out.println(str);
259: String[] strArr = str.split("\\|");
260:
261: ArrayList tmp = new ArrayList();
262: if (str.length() > 0) {
263: for (int i = 0; i < strArr.length; ++i) {
264: if (debug)
265: System.out.println(i + " - " + strArr[i]);
266: tmp.add(strArr[i].toLowerCase());
267: }
268: }
269: return tmp;
270: }
271:
272: /**
273: * Helper function to verify if a file extension is allowed or not allowed.
274: */
275:
276: private boolean extIsAllowed(String fileType, String ext) {
277:
278: ext = ext.toLowerCase();
279:
280: ArrayList allowList = (ArrayList) allowedExtensions
281: .get(fileType);
282: ArrayList denyList = (ArrayList) deniedExtensions.get(fileType);
283:
284: if (allowList.size() == 0)
285: if (denyList.contains(ext))
286: return false;
287: else
288: return true;
289:
290: if (denyList.size() == 0)
291: if (allowList.contains(ext))
292: return true;
293: else
294: return false;
295:
296: return false;
297: }
298:
299: }
|