1 43 package net.jforum.view.forum.common; 44 45 import java.awt.image.BufferedImage ; 46 import java.io.File ; 47 import java.util.ArrayList ; 48 import java.util.Arrays ; 49 import java.util.Calendar ; 50 import java.util.GregorianCalendar ; 51 import java.util.HashMap ; 52 import java.util.Iterator ; 53 import java.util.List ; 54 import java.util.Map ; 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 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 filesToSave = new HashMap (); 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 108 { 109 if (!this.canProceed) { 110 return; 111 } 112 113 String 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 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 if (extensions.containsKey(uploadUtils.getExtension())) { 150 if (!((Boolean )extensions.get(uploadUtils.getExtension())).booleanValue()) { 151 throw new BadExtensionException(I18n.getMessage("Attachments.badExtension", 152 new String [] { uploadUtils.getExtension() })); 153 } 154 } 155 156 String 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 String 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 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 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 [] { new Integer (ql.getSizeInBytes() / 1024), 197 new Integer ((int)totalSize / 1024) })); 198 } 199 } 200 } 201 202 206 public String stripPath(String realName) 207 { 208 String 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 224 { 225 if (!this.canProceed) { 226 return; 227 } 228 229 post.hasAttachments(this.filesToSave.size() > 0); 230 231 for (Iterator iter = this.filesToSave.entrySet().iterator(); iter.hasNext(); ) { 232 Map.Entry entry = (Map.Entry )iter.next(); 233 Attachment a = (Attachment)entry.getValue(); 234 a.setPostId(post.getId()); 235 236 String 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 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 path) { 258 try { 259 BufferedImage 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 e) { 265 logger.error(e.toString(), e); 266 } 267 } 268 269 public QuotaLimit getQuotaLimit(int userId) throws Exception 270 { 271 QuotaLimit ql = new QuotaLimit(); 272 User u = DataAccessDriver.getInstance().newUserDAO().selectById(userId); 273 274 for (Iterator 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 293 { 294 AttachmentDAO am = DataAccessDriver.getInstance().newAttachmentDAO(); 296 297 List deleteList = new ArrayList (); 299 String [] delete = null; 300 String 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 filename = SystemGlobals.getValue(ConfigKeys.ATTACHMENTS_STORE_DIR) 315 + "/" + a.getInfo().getPhysicalFilename(); 316 317 File f = new File (filename); 318 319 if (f.exists()) { 320 f.delete(); 321 } 322 323 f = new File (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 String [] 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 makeStoreFilename(AttachmentInfo a) 365 { 366 Calendar c = new GregorianCalendar (); 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 dir = "" + year + "/" + month + "/" + day + "/"; 374 new File (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 getAttachments(int postId, int forumId) throws Exception 383 { 384 if (!SecurityRepository.canAccess(SecurityConstants.PERM_ATTACHMENTS_DOWNLOAD) 385 && !SecurityRepository.canAccess(SecurityConstants.PERM_ATTACHMENTS_ENABLED, 386 Integer.toString(forumId))) { 387 return new ArrayList (); 388 } 389 390 return this.am.selectAttachments(postId); 391 } 392 393 public boolean isPhysicalDownloadMode(int extensionGroupId) throws Exception 394 { 395 return this.am.isPhysicalDownloadMode(extensionGroupId); 396 } 397 398 public void deleteAttachments(int postId, int forumId) throws Exception 399 { 400 List attachments = DataAccessDriver.getInstance().newAttachmentDAO().selectAttachments(postId); 402 StringBuffer attachIds = new StringBuffer (); 403 404 for (Iterator 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 |