KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > jforum > view > forum > common > AttachmentCommon


1 /*
2  * Copyright (c) Rafael Steil
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
45 import java.awt.image.BufferedImage JavaDoc;
46 import java.io.File JavaDoc;
47 import java.util.ArrayList JavaDoc;
48 import java.util.Arrays JavaDoc;
49 import java.util.Calendar JavaDoc;
50 import java.util.GregorianCalendar JavaDoc;
51 import java.util.HashMap JavaDoc;
52 import java.util.Iterator JavaDoc;
53 import java.util.List JavaDoc;
54 import java.util.Map JavaDoc;
55
56 import net.jforum.ActionServletRequest;
57 import net.jforum.SessionFacade;
58 import net.jforum.dao.AttachmentDAO;
59 import net.jforum.dao.DataAccessDriver;
60 import net.jforum.entities.Attachment;
61 import net.jforum.entities.AttachmentExtension;
62 import net.jforum.entities.AttachmentInfo;
63 import net.jforum.entities.Group;
64 import net.jforum.entities.Post;
65 import net.jforum.entities.QuotaLimit;
66 import net.jforum.entities.User;
67 import net.jforum.exceptions.AttachmentException;
68 import net.jforum.exceptions.AttachmentSizeTooBigException;
69 import net.jforum.exceptions.BadExtensionException;
70 import net.jforum.repository.SecurityRepository;
71 import net.jforum.security.SecurityConstants;
72 import net.jforum.util.I18n;
73 import net.jforum.util.MD5;
74 import net.jforum.util.image.ImageUtils;
75 import net.jforum.util.legacy.commons.fileupload.FileItem;
76 import net.jforum.util.preferences.ConfigKeys;
77 import net.jforum.util.preferences.SystemGlobals;
78
79 import org.apache.log4j.Logger;
80
81 /**
82  * @author Rafael Steil
83  * @version $Id: AttachmentCommon.java,v 1.26 2006/01/16 15:00:44 rafaelsteil Exp $
84  */

85 public class AttachmentCommon
86 {
87     private static Logger logger = Logger.getLogger(AttachmentCommon.class);
88     
89     private ActionServletRequest request;
90     private AttachmentDAO am;
91     private boolean canProceed;
92     private Map JavaDoc filesToSave = new HashMap JavaDoc();
93     
94     public AttachmentCommon(ActionServletRequest request, int forumId)
95     {
96         this.request = request;
97         this.am = DataAccessDriver.getInstance().newAttachmentDAO();
98         
99         this.canProceed = SecurityRepository.canAccess(SecurityConstants.PERM_ATTACHMENTS_ENABLED,
100                 Integer.toString(forumId));
101         
102         if (!this.canProceed) {
103             return;
104         }
105     }
106     
107     public void preProcess() throws Exception JavaDoc
108     {
109         if (!this.canProceed) {
110             return;
111         }
112         
113         String JavaDoc t = this.request.getParameter("total_files");
114         
115         if (t == null || "".equals(t)) {
116             return;
117         }
118         
119         int total = Integer.parseInt(t);
120         
121         if (total < 1) {
122             return;
123         }
124         
125         if (total > SystemGlobals.getIntValue(ConfigKeys.ATTACHMENTS_MAX_POST)) {
126             total = SystemGlobals.getIntValue(ConfigKeys.ATTACHMENTS_MAX_POST);
127         }
128
129         long totalSize = 0;
130         int userId = SessionFacade.getUserSession().getUserId();
131         Map JavaDoc extensions = this.am.extensionsForSecurity();
132         
133         for (int i = 0; i < total; i++) {
134             FileItem item = (FileItem)this.request.getObjectParameter("file_" + i);
135             
136             if (item == null) {
137                 continue;
138             }
139
140             if (item.getName().indexOf('\000') > -1) {
141                 logger.warn("Possible bad attachment (null char): " + item.getName()
142                     + " - user_id: " + SessionFacade.getUserSession().getUserId());
143                 continue;
144             }
145             
146             UploadUtils uploadUtils = new UploadUtils(item);
147             
148             // Check if the extension is allowed
149
if (extensions.containsKey(uploadUtils.getExtension())) {
150                 if (!((Boolean JavaDoc)extensions.get(uploadUtils.getExtension())).booleanValue()) {
151                     throw new BadExtensionException(I18n.getMessage("Attachments.badExtension",
152                         new String JavaDoc[] { uploadUtils.getExtension() }));
153                 }
154             }
155
156             // Check comment length:
157
String JavaDoc comment = this.request.getParameter("comment_" + i);
158             if (comment.length() > 254) {
159                 throw new AttachmentException("Comment too long.");
160             }
161             
162             Attachment a = new Attachment();
163             a.setUserId(userId);
164             
165             AttachmentInfo info = new AttachmentInfo();
166             info.setFilesize(item.getSize());
167             info.setComment(comment);
168             info.setMimetype(item.getContentType());
169             
170             // Get only the filename, without the path (IE does that)
171
String JavaDoc realName = this.stripPath(item.getName());
172             
173             info.setRealFilename(realName);
174             info.setUploadTimeInMillis(System.currentTimeMillis());
175             
176             AttachmentExtension ext = this.am.selectExtension(uploadUtils.getExtension().toLowerCase());
177             if (ext.isUnknown()) {
178                 ext.setExtension(uploadUtils.getExtension());
179             }
180             
181             info.setExtension(ext);
182             String JavaDoc savePath = this.makeStoreFilename(info);
183             info.setPhysicalFilename(savePath);
184             
185             a.setInfo(info);
186             filesToSave.put(uploadUtils, a);
187             
188             totalSize += item.getSize();
189         }
190         
191         // Check upload limits
192
QuotaLimit ql = this.getQuotaLimit(userId);
193         if (ql != null) {
194             if (ql.exceedsQuota(totalSize)) {
195                 throw new AttachmentSizeTooBigException(I18n.getMessage("Attachments.tooBig",
196                     new Integer JavaDoc[] { new Integer JavaDoc(ql.getSizeInBytes() / 1024),
197                         new Integer JavaDoc((int)totalSize / 1024) }));
198             }
199         }
200     }
201
202     /**
203      * @param realName
204      * @return
205      */

206     public String JavaDoc stripPath(String JavaDoc realName)
207     {
208         String JavaDoc separator = "/";
209         int index = realName.lastIndexOf(separator);
210         
211         if (index == -1) {
212             separator = "\\";
213             index = realName.lastIndexOf(separator);
214         }
215         
216         if (index > -1) {
217             realName = realName.substring(index + 1);
218         }
219         
220         return realName;
221     }
222     
223     public void insertAttachments(Post post) throws Exception JavaDoc
224     {
225         if (!this.canProceed) {
226             return;
227         }
228         
229         post.hasAttachments(this.filesToSave.size() > 0);
230         
231         for (Iterator JavaDoc iter = this.filesToSave.entrySet().iterator(); iter.hasNext(); ) {
232             Map.Entry JavaDoc entry = (Map.Entry JavaDoc)iter.next();
233             Attachment a = (Attachment)entry.getValue();
234             a.setPostId(post.getId());
235             
236             String JavaDoc path = SystemGlobals.getValue(ConfigKeys.ATTACHMENTS_STORE_DIR)
237                 + "/"
238                 + a.getInfo().getPhysicalFilename();
239             
240             this.am.addAttachment(a);
241             ((UploadUtils)entry.getKey()).saveUploadedFile(path);
242             
243             if (this.shouldCreateThumb(a)) {
244                 this.createSaveThumb(path);
245             }
246         }
247     }
248     
249     private boolean shouldCreateThumb(Attachment a) {
250         String JavaDoc extension = a.getInfo().getExtension().getExtension();
251         
252         return SystemGlobals.getBoolValue(ConfigKeys.ATTACHMENTS_IMAGES_CREATE_THUMB)
253             && ("jpg".equals(extension) || "jpeg".equals(extension)
254                 || "gif".equals(extension) || "png".equals(extension));
255     }
256     
257     private void createSaveThumb(String JavaDoc path) {
258         try {
259             BufferedImage JavaDoc image = ImageUtils.resizeImage(path, ImageUtils.IMAGE_JPEG,
260                 SystemGlobals.getIntValue(ConfigKeys.ATTACHMENTS_IMAGES_MAX_THUMB_W),
261                 SystemGlobals.getIntValue(ConfigKeys.ATTACHMENTS_IMAGES_MAX_THUMB_H));
262             ImageUtils.saveImage(image, path + "_thumb", ImageUtils.IMAGE_JPEG);
263         }
264         catch (Exception JavaDoc e) {
265             logger.error(e.toString(), e);
266         }
267     }
268     
269     public QuotaLimit getQuotaLimit(int userId) throws Exception JavaDoc
270     {
271         QuotaLimit ql = new QuotaLimit();
272         User u = DataAccessDriver.getInstance().newUserDAO().selectById(userId);
273         
274         for (Iterator JavaDoc iter = u.getGroupsList().iterator(); iter.hasNext();) {
275             QuotaLimit l = this.am.selectQuotaLimitByGroup(((Group)iter.next()).getId());
276             if (l == null) {
277                 continue;
278             }
279             
280             if (l.getSizeInBytes() > ql.getSizeInBytes()) {
281                 ql = l;
282             }
283         }
284         
285         if (ql.getSize() == 0) {
286             return null;
287         }
288         
289         return ql;
290     }
291     
292     public void editAttachments(int postId, int forumId) throws Exception JavaDoc
293     {
294         // Allow removing the attachments at least
295
AttachmentDAO am = DataAccessDriver.getInstance().newAttachmentDAO();
296         
297         // Check for attachments to remove
298
List JavaDoc deleteList = new ArrayList JavaDoc();
299         String JavaDoc[] delete = null;
300         String JavaDoc s = this.request.getParameter("delete_attach");
301         
302         if (s != null) {
303             delete = s.split(",");
304         }
305         
306         if (delete != null) {
307             for (int i = 0; i < delete.length; i++) {
308                 if (delete[i] != null && !delete[i].equals("")) {
309                     int id = Integer.parseInt(delete[i]);
310                     Attachment a = am.selectAttachmentById(id);
311                     
312                     am.removeAttachment(id, postId);
313                     
314                     String JavaDoc filename = SystemGlobals.getValue(ConfigKeys.ATTACHMENTS_STORE_DIR)
315                         + "/" + a.getInfo().getPhysicalFilename();
316                     
317                     File JavaDoc f = new File JavaDoc(filename);
318                     
319                     if (f.exists()) {
320                         f.delete();
321                     }
322                     
323                     // Check if we have a thumb to delete
324
f = new File JavaDoc(filename + "_thumb");
325                     
326                     if (f.exists()) {
327                         f.delete();
328                     }
329                 }
330             }
331             
332             deleteList = Arrays.asList(delete);
333         }
334         
335         if (!SecurityRepository.canAccess(SecurityConstants.PERM_ATTACHMENTS_ENABLED,
336                 Integer.toString(forumId))
337                 && !SecurityRepository.canAccess(SecurityConstants.PERM_ATTACHMENTS_DOWNLOAD)) {
338             return;
339         }
340         
341         // Update
342
String JavaDoc[] attachIds = null;
343         s = this.request.getParameter("edit_attach_ids");
344         if (s != null) {
345             attachIds = s.split(",");
346         }
347         
348         if (attachIds != null) {
349             for (int i = 0; i < attachIds.length; i++) {
350                 if (deleteList.contains(attachIds[i])
351                         || attachIds[i] == null || attachIds[i].equals("")) {
352                     continue;
353                 }
354                 
355                 int id = Integer.parseInt(attachIds[i]);
356                 Attachment a = am.selectAttachmentById(id);
357                 a.getInfo().setComment(this.request.getParameter("edit_comment_" + id));
358
359                 am.updateAttachment(a);
360             }
361         }
362     }
363     
364     private String JavaDoc makeStoreFilename(AttachmentInfo a)
365     {
366         Calendar JavaDoc c = new GregorianCalendar JavaDoc();
367         c.setTimeInMillis(System.currentTimeMillis());
368         c.get(Calendar.YEAR);
369         int year = Calendar.getInstance().get(Calendar.YEAR);
370         int month = Calendar.getInstance().get(Calendar.MONTH) + 1;
371         int day = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
372         
373         String JavaDoc dir = "" + year + "/" + month + "/" + day + "/";
374         new File JavaDoc(SystemGlobals.getValue(ConfigKeys.ATTACHMENTS_STORE_DIR) + "/" + dir).mkdirs();
375         
376         return dir
377             + MD5.crypt(a.getRealFilename() + a.getUploadTime())
378             + "_" + SessionFacade.getUserSession().getUserId()
379             + "." + a.getExtension().getExtension();
380     }
381     
382     public List JavaDoc getAttachments(int postId, int forumId) throws Exception JavaDoc
383     {
384         if (!SecurityRepository.canAccess(SecurityConstants.PERM_ATTACHMENTS_DOWNLOAD)
385                 && !SecurityRepository.canAccess(SecurityConstants.PERM_ATTACHMENTS_ENABLED,
386                         Integer.toString(forumId))) {
387             return new ArrayList JavaDoc();
388         }
389         
390         return this.am.selectAttachments(postId);
391     }
392     
393     public boolean isPhysicalDownloadMode(int extensionGroupId) throws Exception JavaDoc
394     {
395         return this.am.isPhysicalDownloadMode(extensionGroupId);
396     }
397
398     public void deleteAttachments(int postId, int forumId) throws Exception JavaDoc
399     {
400         // Attachments
401
List JavaDoc attachments = DataAccessDriver.getInstance().newAttachmentDAO().selectAttachments(postId);
402         StringBuffer JavaDoc attachIds = new StringBuffer JavaDoc();
403         
404         for (Iterator JavaDoc iter = attachments.iterator(); iter.hasNext(); ) {
405             Attachment a = (Attachment)iter.next();
406             attachIds.append(a.getId()).append(',');
407         }
408         
409         this.request.addParameter("delete_attach", attachIds.toString());
410         this.editAttachments(postId, forumId);
411     }
412 }
413
Popular Tags