AttachmentCommon.java
Upload User: gdxydsw
Upload Date: 2019-01-29
Package Size: 16721k
Code Size: 12k
Category:

Java Develop

Development Platform:

Java

  1. /*
  2.  * Copyright (c) JForum Team
  3.  * All rights reserved.
  4.  * 
  5.  * Redistribution and use in source and binary forms, 
  6.  * with or without modification, are permitted provided 
  7.  * that the following conditions are met:
  8.  * 
  9.  * 1) Redistributions of source code must retain the above 
  10.  * copyright notice, this list of conditions and the 
  11.  * following  disclaimer.
  12.  * 2)  Redistributions in binary form must reproduce the 
  13.  * above copyright notice, this list of conditions and 
  14.  * the following disclaimer in the documentation and/or 
  15.  * other materials provided with the distribution.
  16.  * 3) Neither the name of "Rafael Steil" nor 
  17.  * the names of its contributors may be used to endorse 
  18.  * or promote products derived from this software without 
  19.  * specific prior written permission.
  20.  * 
  21.  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 
  22.  * HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
  23.  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, 
  24.  * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
  25.  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR 
  26.  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 
  27.  * THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE 
  28.  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 
  29.  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES 
  30.  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
  31.  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
  32.  * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 
  33.  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER 
  34.  * IN CONTRACT, STRICT LIABILITY, OR TORT 
  35.  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 
  36.  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF 
  37.  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE
  38.  * 
  39.  * Created on Jan 18, 2005 3:08:48 PM
  40.  * The JForum Project
  41.  * http://www.jforum.net
  42.  */
  43. package net.jforum.view.forum.common;
  44. import java.awt.image.BufferedImage;
  45. import java.io.File;
  46. import java.util.ArrayList;
  47. import java.util.Arrays;
  48. import java.util.Calendar;
  49. import java.util.GregorianCalendar;
  50. import java.util.HashMap;
  51. import java.util.Iterator;
  52. import java.util.List;
  53. import java.util.Map;
  54. import net.jforum.SessionFacade;
  55. import net.jforum.context.RequestContext;
  56. import net.jforum.dao.AttachmentDAO;
  57. import net.jforum.dao.DataAccessDriver;
  58. import net.jforum.entities.Attachment;
  59. import net.jforum.entities.AttachmentExtension;
  60. import net.jforum.entities.AttachmentInfo;
  61. import net.jforum.entities.Group;
  62. import net.jforum.entities.Post;
  63. import net.jforum.entities.QuotaLimit;
  64. import net.jforum.entities.User;
  65. import net.jforum.exceptions.AttachmentException;
  66. import net.jforum.exceptions.AttachmentSizeTooBigException;
  67. import net.jforum.exceptions.BadExtensionException;
  68. import net.jforum.repository.SecurityRepository;
  69. import net.jforum.security.SecurityConstants;
  70. import net.jforum.util.I18n;
  71. import net.jforum.util.MD5;
  72. import net.jforum.util.image.ImageUtils;
  73. import net.jforum.util.legacy.commons.fileupload.FileItem;
  74. import net.jforum.util.preferences.ConfigKeys;
  75. import net.jforum.util.preferences.SystemGlobals;
  76. import org.apache.log4j.Logger;
  77. /**
  78.  * @author Rafael Steil
  79.  * @version $Id: AttachmentCommon.java,v 1.36 2007/09/20 16:07:08 rafaelsteil Exp $
  80.  */
  81. public class AttachmentCommon
  82. {
  83. private static Logger logger = Logger.getLogger(AttachmentCommon.class);
  84. private static final String DENY_ALL = "*";
  85. private RequestContext request;
  86. private AttachmentDAO am;
  87. private boolean canProceed;
  88. private Map filesToSave = new HashMap();
  89. public AttachmentCommon(RequestContext request, int forumId)
  90. {
  91. this.request = request;
  92. this.am = DataAccessDriver.getInstance().newAttachmentDAO();
  93. this.canProceed = SecurityRepository.canAccess(SecurityConstants.PERM_ATTACHMENTS_ENABLED, 
  94. Integer.toString(forumId));
  95. }
  96. public void preProcess()
  97. {
  98. if (!this.canProceed) {
  99. return;
  100. }
  101. String t = this.request.getParameter("total_files");
  102. if (t == null || "".equals(t)) {
  103. return;
  104. }
  105. int total = Integer.parseInt(t);
  106. if (total < 1) {
  107. return;
  108. }
  109. if (total > SystemGlobals.getIntValue(ConfigKeys.ATTACHMENTS_MAX_POST)) {
  110. total = SystemGlobals.getIntValue(ConfigKeys.ATTACHMENTS_MAX_POST);
  111. }
  112. long totalSize = 0;
  113. int userId = SessionFacade.getUserSession().getUserId();
  114. Map extensions = this.am.extensionsForSecurity();
  115. for (int i = 0; i < total; i++) {
  116. FileItem item = (FileItem)this.request.getObjectParameter("file_" + i);
  117. if (item == null) {
  118. continue;
  119. }
  120. if (item.getName().indexOf('00') > -1) {
  121. logger.warn("Possible bad attachment (null char): " + item.getName()
  122. + " - user_id: " + SessionFacade.getUserSession().getUserId());
  123. continue;
  124. }
  125. UploadUtils uploadUtils = new UploadUtils(item);
  126. // Check if the extension is allowed
  127. boolean containsExtension = extensions.containsKey(uploadUtils.getExtension());
  128. boolean denyAll = extensions.containsKey(DENY_ALL);
  129. boolean isAllowed = (!denyAll && !containsExtension)
  130. || (containsExtension && extensions.get(uploadUtils.getExtension()).equals(Boolean.TRUE));
  131. if (!isAllowed) { 
  132. throw new BadExtensionException(I18n.getMessage("Attachments.badExtension", 
  133. new String[] { uploadUtils.getExtension() }));
  134. }
  135. // Check comment length:
  136. String comment = this.request.getParameter("comment_" + i);
  137. if (comment.length() > 254) {
  138. throw new AttachmentException("Comment too long.");
  139. }
  140. Attachment a = new Attachment();
  141. a.setUserId(userId);
  142. AttachmentInfo info = new AttachmentInfo();
  143. info.setFilesize(item.getSize());
  144. info.setComment(comment);
  145. info.setMimetype(item.getContentType());
  146. // Get only the filename, without the path (IE does that)
  147. String realName = this.stripPath(item.getName());
  148. info.setRealFilename(realName);
  149. info.setUploadTimeInMillis(System.currentTimeMillis());
  150. AttachmentExtension ext = this.am.selectExtension(uploadUtils.getExtension().toLowerCase());
  151. if (ext.isUnknown()) {
  152. ext.setExtension(uploadUtils.getExtension());
  153. }
  154. info.setExtension(ext);
  155. String savePath = this.makeStoreFilename(info);
  156. info.setPhysicalFilename(savePath);
  157. a.setInfo(info);
  158. filesToSave.put(uploadUtils, a);
  159. totalSize += item.getSize();
  160. }
  161. // Check upload limits
  162. QuotaLimit ql = this.getQuotaLimit(userId);
  163. if (ql != null) {
  164. if (ql.exceedsQuota(totalSize)) {
  165. throw new AttachmentSizeTooBigException(I18n.getMessage("Attachments.tooBig", 
  166. new Integer[] { new Integer(ql.getSizeInBytes() / 1024), 
  167. new Integer((int)totalSize / 1024) }));
  168. }
  169. }
  170. }
  171. /**
  172.  * @param realName String
  173.  * @return String
  174.  */
  175. public String stripPath(String realName)
  176. {
  177. String separator = "/";
  178. int index = realName.lastIndexOf(separator);
  179. if (index == -1) {
  180. separator = "\";
  181. index = realName.lastIndexOf(separator);
  182. }
  183. if (index > -1) {
  184. realName = realName.substring(index + 1);
  185. }
  186. return realName;
  187. }
  188. public void insertAttachments(Post post)
  189. {
  190. if (!this.canProceed) {
  191. return;
  192. }
  193. post.hasAttachments(this.filesToSave.size() > 0);
  194. for (Iterator iter = this.filesToSave.entrySet().iterator(); iter.hasNext(); ) {
  195. Map.Entry entry = (Map.Entry)iter.next();
  196. Attachment a = (Attachment)entry.getValue();
  197. a.setPostId(post.getId());
  198. String path = SystemGlobals.getValue(ConfigKeys.ATTACHMENTS_STORE_DIR) 
  199. + "/" 
  200. + a.getInfo().getPhysicalFilename();
  201. this.am.addAttachment(a);
  202. ((UploadUtils)entry.getKey()).saveUploadedFile(path);
  203. if (this.shouldCreateThumb(a)) {
  204. this.createSaveThumb(path);
  205. }
  206. }
  207. }
  208. private boolean shouldCreateThumb(Attachment a) {
  209. String extension = a.getInfo().getExtension().getExtension().toLowerCase();
  210. return SystemGlobals.getBoolValue(ConfigKeys.ATTACHMENTS_IMAGES_CREATE_THUMB)
  211. && ("jpg".equals(extension) || "jpeg".equals(extension) 
  212. || "gif".equals(extension) || "png".equals(extension));
  213. }
  214. private void createSaveThumb(String path) {
  215. try {
  216. BufferedImage image = ImageUtils.resizeImage(path, ImageUtils.IMAGE_JPEG, 
  217. SystemGlobals.getIntValue(ConfigKeys.ATTACHMENTS_IMAGES_MAX_THUMB_W),
  218. SystemGlobals.getIntValue(ConfigKeys.ATTACHMENTS_IMAGES_MAX_THUMB_H));
  219. ImageUtils.saveImage(image, path + "_thumb", ImageUtils.IMAGE_JPEG);
  220. }
  221. catch (Exception e) {
  222. logger.error(e.toString(), e);
  223. }
  224. }
  225. public QuotaLimit getQuotaLimit(int userId)
  226. {
  227. QuotaLimit ql = new QuotaLimit();
  228. User u = DataAccessDriver.getInstance().newUserDAO().selectById(userId);
  229. for (Iterator iter = u.getGroupsList().iterator(); iter.hasNext();) {
  230. QuotaLimit l = this.am.selectQuotaLimitByGroup(((Group)iter.next()).getId());
  231. if (l == null) {
  232. continue;
  233. }
  234. if (l.getSizeInBytes() > ql.getSizeInBytes()) {
  235. ql = l;
  236. }
  237. }
  238. if (ql.getSize() == 0) {
  239. return null;
  240. }
  241. return ql;
  242. }
  243. public void editAttachments(int postId, int forumId)
  244. {
  245. // Allow removing the attachments at least
  246. AttachmentDAO am = DataAccessDriver.getInstance().newAttachmentDAO();
  247. // Check for attachments to remove
  248. List deleteList = new ArrayList();
  249. String[] delete = null;
  250. String s = this.request.getParameter("delete_attach");
  251. if (s != null) {
  252. delete = s.split(",");
  253. }
  254. if (delete != null) {
  255. for (int i = 0; i < delete.length; i++) {
  256. if (delete[i] != null && !delete[i].equals("")) {
  257. int id = Integer.parseInt(delete[i]);
  258. Attachment a = am.selectAttachmentById(id);
  259. am.removeAttachment(id, postId);
  260. String filename = SystemGlobals.getValue(ConfigKeys.ATTACHMENTS_STORE_DIR)
  261. + "/" + a.getInfo().getPhysicalFilename();
  262. File f = new File(filename);
  263. if (f.exists()) {
  264. f.delete();
  265. }
  266. // Check if we have a thumb to delete
  267. f = new File(filename + "_thumb");
  268. if (f.exists()) {
  269. f.delete();
  270. }
  271. }
  272. }
  273. deleteList = Arrays.asList(delete);
  274. }
  275. if (!SecurityRepository.canAccess(SecurityConstants.PERM_ATTACHMENTS_ENABLED, 
  276. Integer.toString(forumId))
  277. && !SecurityRepository.canAccess(SecurityConstants.PERM_ATTACHMENTS_DOWNLOAD)) {
  278. return;
  279. }
  280. // Update
  281. String[] attachIds = null;
  282. s = this.request.getParameter("edit_attach_ids");
  283. if (s != null) {
  284. attachIds = s.split(",");
  285. }
  286. if (attachIds != null) {
  287. for (int i = 0; i < attachIds.length; i++) {
  288. if (deleteList.contains(attachIds[i]) 
  289. || attachIds[i] == null || attachIds[i].equals("")) {
  290. continue;
  291. }
  292. int id = Integer.parseInt(attachIds[i]);
  293. Attachment a = am.selectAttachmentById(id);
  294. a.getInfo().setComment(this.request.getParameter("edit_comment_" + id));
  295. am.updateAttachment(a);
  296. }
  297. }
  298. }
  299. private String makeStoreFilename(AttachmentInfo a)
  300. {
  301. Calendar c = new GregorianCalendar();
  302. c.setTimeInMillis(System.currentTimeMillis());
  303. c.get(Calendar.YEAR);
  304. int year = Calendar.getInstance().get(Calendar.YEAR);
  305. int month = Calendar.getInstance().get(Calendar.MONTH) + 1;
  306. int day = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
  307. StringBuffer dir = new StringBuffer(256);
  308. dir.append(year).append('/').append(month).append('/').append(day).append('/');
  309. new File(SystemGlobals.getValue(ConfigKeys.ATTACHMENTS_STORE_DIR) + "/" + dir).mkdirs();
  310. return dir
  311. .append(MD5.crypt(a.getRealFilename() + System.currentTimeMillis()))
  312. .append('_')
  313. .append(SessionFacade.getUserSession().getUserId())
  314. .append('.')
  315. .append(a.getExtension().getExtension())
  316. .append('_')
  317. .toString();
  318. }
  319. public List getAttachments(int postId, int forumId)
  320. {
  321. if (!SecurityRepository.canAccess(SecurityConstants.PERM_ATTACHMENTS_DOWNLOAD)
  322. && !SecurityRepository.canAccess(SecurityConstants.PERM_ATTACHMENTS_ENABLED, 
  323. Integer.toString(forumId))) {
  324. return new ArrayList();
  325. }
  326. return this.am.selectAttachments(postId);
  327. }
  328. public boolean isPhysicalDownloadMode(int extensionGroupId) 
  329. {
  330. return this.am.isPhysicalDownloadMode(extensionGroupId);
  331. }
  332. public void deleteAttachments(int postId, int forumId) 
  333. {
  334. // Attachments
  335. List attachments = DataAccessDriver.getInstance().newAttachmentDAO().selectAttachments(postId);
  336. StringBuffer attachIds = new StringBuffer();
  337. for (Iterator iter = attachments.iterator(); iter.hasNext(); ) {
  338. Attachment a = (Attachment)iter.next();
  339. attachIds.append(a.getId()).append(',');
  340. }
  341. this.request.addOrReplaceParameter("delete_attach", attachIds.toString());
  342. this.editAttachments(postId, forumId);
  343. }
  344. }