KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > mvnforum > user > PostWebHandler


1 /*
2  * $Header: /cvsroot/mvnforum/mvnforum/src/com/mvnforum/user/PostWebHandler.java,v 1.78 2006/04/14 17:05:27 minhnn Exp $
3  * $Author: minhnn $
4  * $Revision: 1.78 $
5  * $Date: 2006/04/14 17:05:27 $
6  *
7  * ====================================================================
8  *
9  * Copyright (C) 2002-2006 by MyVietnam.net
10  *
11  * All copyright notices regarding mvnForum MUST remain
12  * intact in the scripts and in the outputted HTML.
13  * The "powered by" text/logo with a link back to
14  * http://www.mvnForum.com and http://www.MyVietnam.net in
15  * the footer of the pages MUST remain visible when the pages
16  * are viewed on the internet or intranet.
17  *
18  * This program is free software; you can redistribute it and/or modify
19  * it under the terms of the GNU General Public License as published by
20  * the Free Software Foundation; either version 2 of the License, or
21  * any later version.
22  *
23  * This program is distributed in the hope that it will be useful,
24  * but WITHOUT ANY WARRANTY; without even the implied warranty of
25  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
26  * GNU General Public License for more details.
27  *
28  * You should have received a copy of the GNU General Public License
29  * along with this program; if not, write to the Free Software
30  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
31  *
32  * Support can be obtained from support forums at:
33  * http://www.mvnForum.com/mvnforum/index
34  *
35  * Correspondence and Marketing Questions can be sent to:
36  * info at MyVietnam net
37  *
38  * @author: Minh Nguyen
39  * @author: Mai Nguyen
40  */

41 package com.mvnforum.user;
42
43 import java.io.IOException JavaDoc;
44 import java.sql.Timestamp JavaDoc;
45 import java.util.*;
46
47 import com.mvnforum.*;
48 import com.mvnforum.auth.*;
49 import com.mvnforum.common.StatisticsUtil;
50 import com.mvnforum.db.*;
51 import com.mvnforum.search.post.*;
52 import net.myvietnam.mvncore.exception.*;
53 import net.myvietnam.mvncore.filter.DisableHtmlTagFilter;
54 import net.myvietnam.mvncore.interceptor.InterceptorService;
55 import net.myvietnam.mvncore.security.FloodControl;
56 import net.myvietnam.mvncore.util.*;
57 import net.myvietnam.mvncore.web.GenericRequest;
58 import net.myvietnam.mvncore.web.GenericResponse;
59 import org.apache.commons.logging.Log;
60 import org.apache.commons.logging.LogFactory;
61
62 public class PostWebHandler {
63
64     private static Log log = LogFactory.getLog(PostWebHandler.class);
65
66     private OnlineUserManager onlineUserManager = OnlineUserManager.getInstance();
67
68     public PostWebHandler() {
69     }
70
71     /**
72      * This method is for addpost page
73      */

74     public void prepareAdd(GenericRequest request, GenericResponse response)
75         throws ObjectNotFoundException, DatabaseException, BadInputException, AuthenticationException, AssertionException {
76
77         Locale locale = I18nUtil.getLocaleInRequest(request);
78
79         if (MVNForumConfig.getEnableNewPost() == false) {
80             String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.AssertionException.cannot_create_new_post.new_post_is_disabled");
81             throw new AssertionException(localizedMessage);
82             //throw new AssertionException("Cannot create new post because NEW_POST feature is disabled by administrator.");
83
}
84
85         OnlineUser onlineUser = onlineUserManager.getOnlineUser(request);
86         MVNForumPermission permission = onlineUser.getPermission();
87
88         if (MVNForumConfig.isGuestUserInDatabase() == false) {
89             permission.ensureIsAuthenticated();
90         }
91
92         // we set this action attribute first because the return below can make method return prematurely
93
request.setAttribute("action", "addnew");
94
95         int parentPostID = 0;
96         try {
97             // neu co parent thi` khong co forum !!!
98
parentPostID = GenericParamUtil.getParameterInt(request, "parent");
99         } catch (Exception JavaDoc ex) {
100             // do nothing
101
// NOTE: we cannot return here since user can have a parameter parent = 0
102
}
103
104         if (parentPostID == 0) {// new thread
105
int forumID = GenericParamUtil.getParameterInt(request, "forum");
106
107             ForumBean forumBean = null;
108             try {
109                 forumBean = ForumCache.getInstance().getBean(forumID);
110             } catch (ObjectNotFoundException e) {
111                 String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.ObjectNotFoundException.forumid_not_exists", new Object JavaDoc[] {new Integer JavaDoc(forumID)});
112                 throw new ObjectNotFoundException(localizedMessage);
113             }
114             forumBean.ensureNotDisabledForum();
115             forumBean.ensureNotClosedForum();
116             forumBean.ensureNotLockedForum();
117
118             permission.ensureCanAddThread(forumID);
119         } else {// reply to a post
120
// this is a parent post
121
PostBean postBean = null;
122             try {
123                 postBean = DAOFactory.getPostDAO().getPost(parentPostID);// can throw DatabaseException
124
} catch (ObjectNotFoundException ex) {
125                 String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.ObjectNotFoundException.postid_not_exists", new Object JavaDoc[] {new Integer JavaDoc(parentPostID)});
126                 throw new ObjectNotFoundException(localizedMessage);
127             }
128
129             // check permission
130
int forumID = postBean.getForumID();
131
132             ForumBean forumBean = null;
133             try {
134                 forumBean = ForumCache.getInstance().getBean(forumID);
135             } catch (ObjectNotFoundException e) {
136                 String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.ObjectNotFoundException.forumid_not_exists", new Object JavaDoc[] {new Integer JavaDoc(forumID)});
137                 throw new ObjectNotFoundException(localizedMessage);
138             }
139             forumBean.ensureNotDisabledForum();
140             forumBean.ensureNotClosedForum();
141             forumBean.ensureNotLockedForum();
142
143             permission.ensureCanAddPost(forumID);
144
145             // now we prepare to list lastest post in the thread
146
int threadID = postBean.getThreadID();
147
148             // now check if thread is closed or locked, if it is, then cannot reply to a post
149
ThreadBean threadBean = null;
150             try {
151                 threadBean = DAOFactory.getThreadDAO().getThread(threadID);
152             } catch ( ObjectNotFoundException ex ) {
153                 String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.ObjectNotFoundException.threadid_not_exists", new Object JavaDoc[] {new Integer JavaDoc(threadID)});
154                 throw new ObjectNotFoundException(localizedMessage);
155             }
156
157             threadBean.ensureStatusCanReply();
158
159             Collection postBeans = DAOFactory.getPostDAO().getLastEnablePosts_inThread_limit(threadID, MVNForumConfig.ROWS_IN_LAST_REPLIES);
160             request.setAttribute("ParentPostBean", postBean);
161             request.setAttribute("PostBeans", postBeans);
162         }
163
164         boolean isPreviewing = GenericParamUtil.getParameterBoolean(request, "preview");
165         if (isPreviewing) {
166             MyUtil.saveVNTyperMode(request, response);
167
168             // Check if user enter some text or not
169
GenericParamUtil.getParameter(request, "PostTopic", true);
170             GenericParamUtil.getParameter(request, "message", true);// use message instead of MessageBody
171
MemberBean memberBean = MemberCache.getInstance().getMember_forPublic(onlineUser.getMemberID());
172             request.setAttribute("MemberBean", memberBean);
173         }
174     }
175
176     public void processAdd(GenericRequest request, GenericResponse response)
177         throws ObjectNotFoundException, AssertionException, DatabaseException, CreateException,
178         BadInputException, ForeignKeyNotFoundException, AuthenticationException, FloodException, InterceptorException {
179
180         Locale locale = I18nUtil.getLocaleInRequest(request);
181         if (MVNForumConfig.getEnableNewPost() == false) {
182             String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.AssertionException.cannot_create_new_post.new_post_is_disabled");
183             throw new AssertionException(localizedMessage);
184             //throw new AssertionException("Cannot create new post because NEW_POST feature is disabled by administrator.");
185
}
186
187         String JavaDoc currentIP = request.getRemoteAddr();
188         try {
189             FloodControl.ensureNotReachMaximum(MVNForumGlobal.FLOOD_ID_NEW_POST, currentIP);
190         } catch (FloodException fe) {
191             //throw new FloodException("You have reached the maximum number of the post adding actions for this page. Please try this page later. This is to prevent forum from being flooded.");
192
Integer JavaDoc maxPosts = new Integer JavaDoc(FloodControl.getActionsPerHour(MVNForumGlobal.FLOOD_ID_NEW_POST));
193             String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.FloodException.add_post_too_many_times", new Object JavaDoc[] {maxPosts});
194             throw new FloodException(localizedMessage);
195         }
196         OnlineUser onlineUser = onlineUserManager.getOnlineUser(request);
197         MVNForumPermission permission = onlineUser.getPermission();
198
199         MyUtil.saveVNTyperMode(request, response);
200
201         int memberID = onlineUser.getMemberID();
202         String JavaDoc memberName = onlineUser.getMemberName();
203
204         Timestamp JavaDoc now = DateUtil.getCurrentGMTTimestamp();
205
206         int parentPostID = GenericParamUtil.getParameterInt(request, "parent");
207
208         boolean attachMore = GenericParamUtil.getParameterBoolean(request, "AttachMore");
209         boolean addFavoriteThread = GenericParamUtil.getParameterBoolean(request, "AddFavoriteParentThread");
210         boolean addWatchThread = GenericParamUtil.getParameterBoolean(request, "AddWatchParentThread");
211
212         String JavaDoc postTopic = GenericParamUtil.getParameter(request, "PostTopic", true);
213         postTopic = DisableHtmlTagFilter.filter(postTopic);// always disable HTML
214
postTopic = InterceptorService.getInstance().validateContent(postTopic);
215
216         String JavaDoc postBody = GenericParamUtil.getParameter(request, "message", true); // use message instead of MessageBody
217
postBody = DisableHtmlTagFilter.filter(postBody);// always disable HTML
218
postBody = InterceptorService.getInstance().validateContent(postBody);
219
220         String JavaDoc postIcon = GenericParamUtil.getParameter(request, "PostIcon");
221         postIcon = DisableHtmlTagFilter.filter(postIcon);// always disable HTML
222

223         int forumID = 0;
224         int threadID= 0;
225         boolean isPendingThread = false;
226         boolean isForumModerator = false;
227         if (parentPostID == 0) {// new thread
228

229             forumID = GenericParamUtil.getParameterInt(request, "forum");
230             ForumBean forumBean = null;
231             try {
232                 forumBean = ForumCache.getInstance().getBean(forumID);
233             } catch (ObjectNotFoundException e) {
234                 String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.ObjectNotFoundException.forumid_not_exists", new Object JavaDoc[] {new Integer JavaDoc(forumID)});
235                 throw new ObjectNotFoundException(localizedMessage);
236             }
237             forumBean.ensureNotDisabledForum();
238             forumBean.ensureNotClosedForum();
239             forumBean.ensureNotLockedForum();
240
241             // check permission
242
isForumModerator = permission.canModerateThread(forumID);
243             permission.ensureCanAddThread(forumID);
244
245             String JavaDoc lastPostMemberName = memberName;
246
247             int threadType = GenericParamUtil.getParameterUnsignedInt(request, "ThreadType", ThreadBean.THREAD_TYPE_DEFAULT);
248             if ( threadType > ThreadBean.THREAD_TYPE_GLOBAL_ANNOUNCEMENT /* 3 */) {
249                 //threadType = 0;
250
throw new BadInputException("Not support this thread type");
251             }
252
253             if (threadType == ThreadBean.THREAD_TYPE_GLOBAL_ANNOUNCEMENT) {
254                 permission.ensureCanAdminSystem();
255                 //forumID = -1; // this thread not belongs to any forum
256
} else if (threadType != ThreadBean.THREAD_TYPE_DEFAULT ) {
257                 permission.ensureCanModerateThread(forumID);
258             }
259
260             int threadOption = 0; //@todo review and support it later
261
int threadStatus = ThreadBean.THREAD_STATUS_DEFAULT;
262
263             // Ensure that moderator dont have to moderate the thread to enable it
264
if (forumBean.shouldModerateThread() && !isForumModerator) {
265                 threadStatus = ThreadBean.THREAD_STATUS_DISABLED;
266                 isPendingThread = true;
267             }
268
269             int threadHasPoll = 0;//@todo review and support it later
270
int threadDuration = 0;//@todo review and support it later
271
int threadAttachCount = 0;
272             threadID = DAOFactory.getThreadDAO().createThread(forumID, memberName, lastPostMemberName,
273                                    postTopic, postBody, 0/*threadVoteCount*/,
274                                    0/*threadVoteTotalStars*/, now/*threadCreationDate*/, now/*threadLastPostDate*/,
275                                    threadType, threadOption, threadStatus,
276                                    threadHasPoll, 0/*threadViewCount*/, 0/*threadReplyCount*/,
277                                    postIcon, threadDuration, threadAttachCount);
278         } else {// reply to a post
279
PostBean parentPostBean = null;
280             try {
281                 parentPostBean = DAOFactory.getPostDAO().getPost(parentPostID);// can throw DatabaseException
282
} catch (ObjectNotFoundException ex) {
283                 String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.ObjectNotFoundException.postid_not_exists", new Object JavaDoc[] {new Integer JavaDoc(parentPostID)});
284                 throw new ObjectNotFoundException(localizedMessage);
285             }
286             forumID = parentPostBean.getForumID();
287             threadID = parentPostBean.getThreadID();
288
289             ForumBean forumBean = null;
290             try {
291                 forumBean = ForumCache.getInstance().getBean(forumID);
292             } catch (ObjectNotFoundException e) {
293                 String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.ObjectNotFoundException.forumid_not_exists", new Object JavaDoc[] {new Integer JavaDoc(forumID)});
294                 throw new ObjectNotFoundException(localizedMessage);
295             }
296             forumBean.ensureNotDisabledForum();
297             forumBean.ensureNotClosedForum();
298             forumBean.ensureNotLockedForum();
299
300             // check permission
301
isForumModerator = permission.canModerateThread(forumID);
302             permission.ensureCanAddPost(forumID);
303
304             // now check if thread is closed or locked, if it is, then cannot reply to a post
305
ThreadBean threadBean = null;
306             try {
307                 threadBean = DAOFactory.getThreadDAO().getThread(threadID);
308             } catch (ObjectNotFoundException ex ) {
309                 String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.ObjectNotFoundException.threadid_not_exists", new Object JavaDoc[] {new Integer JavaDoc(threadID)});
310                 throw new ObjectNotFoundException(localizedMessage);
311             }
312             threadBean.ensureStatusCanReply();
313         }
314
315         //Timestamp postLastEditDate = now;
316
String JavaDoc postCreationIP = currentIP;
317         String JavaDoc postLastEditIP = "";// should we init it to postCreationIP ???
318
int postFormatOption = 0;
319         int postOption = 0;
320         int postStatus = PostBean.POST_STATUS_DEFAULT;
321
322         try {
323             // Ensure that moderator dont have to moderate the thread to enable it
324
if (ForumCache.getInstance().getBean(forumID).shouldModeratePost() && !isForumModerator) {
325                 // we will not disble post that is a thread (parentPostID == 0)
326
if (parentPostID != 0) {// replied post
327
postStatus = PostBean.POST_STATUS_DISABLED;
328                 }
329             }
330         } catch (ObjectNotFoundException e) {
331             String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.ObjectNotFoundException.forumid_not_exists", new Object JavaDoc[] {new Integer JavaDoc(forumID)});
332             throw new ObjectNotFoundException(localizedMessage);
333         }
334
335         int postAttachCount = 0;
336
337         int postID = DAOFactory.getPostDAO().createPost(parentPostID, forumID, threadID,
338                              memberID, memberName, ""/*lastEditMemberName*/,
339                              postTopic, postBody, now/*postCreationDate*/,
340                              now/*postLastEditDate*/, postCreationIP, postLastEditIP,
341                              0/*postEditCount*/, postFormatOption, postOption,
342                              postStatus, postIcon, postAttachCount);
343
344         StatisticsUtil.updateMemberStatistics(memberID);
345         StatisticsUtil.updateForumStatistics(forumID);
346         StatisticsUtil.updateThreadStatistics(threadID);
347
348         /** @todo Update PostEditLog table here */
349
350         //add favorite thread if user checked it
351
if (addFavoriteThread) {
352             permission.ensureIsAuthenticated();
353             //@todo: add checking of MVNForumConfig.getEnableFavoriteThread()
354
// check to make sure that this user doesnt exceed his favorite max
355
int currentFavoriteCount = DAOFactory.getFavoriteThreadDAO().getNumberOfFavoriteThreads_inMember(memberID);
356             int maxFavorites = MVNForumConfig.getMaxFavoriteThread();
357             if (currentFavoriteCount < maxFavorites) {
358                 Timestamp JavaDoc favoriteCreationDate = now;
359                 int favoriteType = 0; //@todo implement it later
360
int favoriteOption = 0; //@todo implement it later
361
int favoriteStatus = 0; //@todo implement it later
362

363                 // now check permission the this user have the readPost permission
364
permission.ensureCanReadPost(forumID);
365
366                 // has the permission now, then insert to database
367
try {
368                     DAOFactory.getFavoriteThreadDAO().create(memberID, threadID, forumID,
369                         favoriteCreationDate, favoriteType, favoriteOption,
370                         favoriteStatus);
371                 } catch (DuplicateKeyException ex) {
372                     // already add favorite thread, just ignore
373
}
374             }
375         }
376
377         //add watch if user checked it
378
if (addWatchThread) {
379             permission.ensureIsAuthenticated();
380             permission.ensureIsActivated();
381             if (MVNForumConfig.getEnableWatch() == false) {
382                 // should never happen, because if it happen, then the whole process is broken
383
String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.AssertionException.cannot_add_watch.watch_is_disabled");
384                 throw new AssertionException(localizedMessage);
385                 //throw new AssertionException("Cannot add Watch because Watch feature is disabled by administrator.");
386
}
387
388             int watchType = 0;//GenericParamUtil.getParameterInt(request, "WatchType");
389
int watchOption = 0;//GenericParamUtil.getParameterInt(request, "WatchOption");
390
int watchStatus = 0;//GenericParamUtil.getParameterInt(request, "WatchStatus");
391
Timestamp JavaDoc watchCreationDate = now;
392             Timestamp JavaDoc watchLastSentDate = now;
393             Timestamp JavaDoc watchEndDate = now;// @todo: check it !!!
394

395             try {
396                 DAOFactory.getWatchDAO().create(memberID, 0/*watchCategoryID*/, 0/*watchForumID*/,
397                                            threadID, watchType, watchOption,
398                                            watchStatus, watchCreationDate, watchLastSentDate,
399                                            watchEndDate);
400             } catch (DuplicateKeyException ex) {
401                 // User try to create a duplicate watch, just ignore
402
}
403         }
404
405
406         // Now clear the cache
407
PostCache.getInstance().clear();
408         ThreadCache.getInstance().clear();
409
410         // now, update the Search Index
411
//@todo check the performance here
412
PostBean justAddedPostBean = null;
413         try {
414             justAddedPostBean = DAOFactory.getPostDAO().getPost(postID);
415         } catch(ObjectNotFoundException ex) {
416             String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.ObjectNotFoundException.postid_not_exists", new Object JavaDoc[] {new Integer JavaDoc(postID)});
417             throw new ObjectNotFoundException(localizedMessage);
418         }
419
420         PostIndexer.scheduleAddPostTask(justAddedPostBean);
421
422         request.setAttribute("PostBean", justAddedPostBean);
423         request.setAttribute("ForumID", String.valueOf(forumID));
424         request.setAttribute("ThreadID", String.valueOf(threadID));
425         request.setAttribute("PostID", String.valueOf(postID));
426         request.setAttribute("AttachMore", new Boolean JavaDoc(attachMore));
427         request.setAttribute("AddFavoriteParentThread", new Boolean JavaDoc(addFavoriteThread));
428         request.setAttribute("AddWatchParentThread", new Boolean JavaDoc(addWatchThread));
429         request.setAttribute("IsPendingThread", new Boolean JavaDoc(isPendingThread));
430         /**@todo: review, this variable is still reserved*/
431         //request.setAttribute("ParentPostID", String.valueOf(parentPostID));
432

433         FloodControl.increaseCount(MVNForumGlobal.FLOOD_ID_NEW_POST, currentIP);
434     }
435
436     public void preparePrintPost(GenericRequest request)
437         throws ObjectNotFoundException, DatabaseException, BadInputException,
438         AuthenticationException, AssertionException {
439
440         OnlineUser onlineUser = onlineUserManager.getOnlineUser(request);
441         MVNForumPermission permission = onlineUser.getPermission();
442
443         int postID = GenericParamUtil.getParameterInt(request, "post");
444         Locale locale = I18nUtil.getLocaleInRequest(request);
445
446         PostBean postBean = null;
447         try {
448             postBean = DAOFactory.getPostDAO().getPost(postID);
449         } catch(ObjectNotFoundException ex) {
450             String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.ObjectNotFoundException.postid_not_exists", new Object JavaDoc[] {new Integer JavaDoc(postID)});
451             throw new ObjectNotFoundException(localizedMessage);
452         }
453         int threadID = postBean.getThreadID();
454         int forumID = postBean.getForumID();
455
456         try {
457             ForumCache.getInstance().getBean(forumID).ensureNotDisabledForum();
458         } catch (ObjectNotFoundException e) {
459             String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.ObjectNotFoundException.forumid_not_exists", new Object JavaDoc[] {new Integer JavaDoc(forumID)});
460             throw new ObjectNotFoundException(localizedMessage);
461         }
462
463         permission.ensureCanReadPost(forumID);
464
465         // to show the thread topic
466
ThreadBean threadBean = null;
467         try {
468             threadBean = DAOFactory.getThreadDAO().getThread(threadID);
469         } catch ( ObjectNotFoundException ex ) {
470             String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.ObjectNotFoundException.threadid_not_exists", new Object JavaDoc[] {new Integer JavaDoc(threadID)});
471             throw new ObjectNotFoundException(localizedMessage);
472         }
473
474         MemberBean memberBean = null;
475         if (postBean.getMemberID() > 0) {
476             memberBean = DAOFactory.getMemberDAO().getMember_forPublic(postBean.getMemberID());
477         }
478         postBean.setMemberBean(memberBean);
479
480         int postAttachCount = postBean.getPostAttachCount();
481         if ( (postAttachCount > 0) && MVNForumConfig.getEnableAttachment()) {
482             Collection attachBeans = DAOFactory.getAttachmentDAO().getAttachments_inPost(postID);
483             int actualAttachCount = attachBeans.size();
484
485             // now check if the attachCount in talbe Post equals to the actual attachCount in table Attachment
486
if (postAttachCount != actualAttachCount) {
487                 if (actualAttachCount != DAOFactory.getAttachmentDAO().getNumberOfAttachments_inPost(postID)) {
488                     String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.AssertionException.serious_error.cannot_process_attachment_count");
489                     throw new AssertionException(localizedMessage);
490                     //throw new AssertionException("AssertionException: Serious error: cannot process Attachment Count in table Attachment");
491
}
492                 log.warn("The attachment count in table Post and Attachment are not synchronized. In table Post = " + postAttachCount + " and in table Attachment = " + actualAttachCount + ". Synchronize to " + actualAttachCount);
493                 DAOFactory.getPostDAO().updateAttachCount(postID, actualAttachCount);
494             }
495             if (actualAttachCount > 0) {
496                 postBean.setAttachmentBeans(attachBeans);
497             }
498         }
499
500         request.setAttribute("PostBean", postBean);
501         request.setAttribute("ThreadBean", threadBean);
502     }
503
504     /**
505      * then, it will be forward to addpost.jsp
506      * NOTE: This method MUST NOT use parameter MessageParent (need some process to figure out)
507      */

508     public void prepareEdit(GenericRequest request)
509         throws ObjectNotFoundException, DatabaseException, BadInputException, AuthenticationException, AssertionException {
510
511         OnlineUser onlineUser = onlineUserManager.getOnlineUser(request);
512         MVNForumPermission permission = onlineUser.getPermission();
513
514         // a guest CANNOT edit a post, because it need Authenticated Permission
515
permission.ensureIsAuthenticated();
516         Locale locale = I18nUtil.getLocaleInRequest(request);
517
518         int postID = GenericParamUtil.getParameterInt(request, "post");
519         PostBean postBean = null;
520         try {
521             postBean = DAOFactory.getPostDAO().getPost(postID);
522         } catch(ObjectNotFoundException ex) {
523             String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.ObjectNotFoundException.postid_not_exists", new Object JavaDoc[] {new Integer JavaDoc(postID)});
524             throw new ObjectNotFoundException(localizedMessage);
525         }
526         int forumID = postBean.getForumID();
527
528         ForumBean forumBean = null;
529         try {
530             forumBean = ForumCache.getInstance().getBean(forumID);
531         } catch (ObjectNotFoundException e) {
532             String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.ObjectNotFoundException.forumid_not_exists", new Object JavaDoc[] {new Integer JavaDoc(forumID)});
533             throw new ObjectNotFoundException(localizedMessage);
534         }
535         forumBean.ensureNotDisabledForum();
536         forumBean.ensureNotLockedForum();
537
538         // now check if thread is closed or locked, if it is, then cannot reply to a post
539
int threadID = postBean.getThreadID();
540         ThreadBean threadBean = null;
541         try {
542             threadBean = DAOFactory.getThreadDAO().getThread(threadID);
543         } catch ( ObjectNotFoundException ex ) {
544             String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.ObjectNotFoundException.threadid_not_exists", new Object JavaDoc[] {new Integer JavaDoc(threadID)});
545             throw new ObjectNotFoundException(localizedMessage);
546         }
547         threadBean.ensureStatusCanEdit();
548
549         int logonMemberID = onlineUser.getMemberID();
550         int authorID = postBean.getMemberID();
551
552         // check constraint
553
if (permission.canEditPost(forumID)) {
554             // have permission, just do nothing, that is dont check the max day contraint
555
} else if (logonMemberID == authorID) {// same author
556
// make sure user have permission to edit his own post
557
permission.ensureCanEditOwnPost(forumID);
558
559             // check date here, usually must not older than 7 days
560
Timestamp JavaDoc now = DateUtil.getCurrentGMTTimestamp();
561             Timestamp JavaDoc postDate = postBean.getPostCreationDate();
562             int maxDays = MVNForumConfig.getMaxEditDays();
563             if ( (now.getTime() - postDate.getTime()) > (DateUtil.DAY * maxDays) ) {
564                 /** @todo choose a better Exception here */
565                 String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.BadInputException.cannot_edit.post_is_too_old", new Object JavaDoc[] {new Integer JavaDoc(maxDays)});
566                 throw new BadInputException(localizedMessage);
567                 //throw new BadInputException("You cannot edit a post which is older than " + maxDays + " days.");
568
}
569
570             // check status of this post
571
if (postBean.getPostStatus() == PostBean.POST_STATUS_DISABLED) {
572                 String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.BadInputException.cannot_edit_your_post.which_is_disabled");
573                 throw new BadInputException(localizedMessage);
574                 //throw new BadInputException("Cannot edit message which is disable.");
575
}
576         } else {//not an author, so this user must have Edit Permission
577
permission.ensureCanEditPost(forumID);// this method ALWAYS throws AuthenticationException
578
}
579
580         request.setAttribute("PostToEdit", postBean);
581         request.setAttribute("action", "update");
582
583         boolean isPreviewing = GenericParamUtil.getParameterBoolean(request, "preview");
584         if (isPreviewing) {
585             // Check if user enter some text or not
586
GenericParamUtil.getParameter(request, "PostTopic", true);
587             GenericParamUtil.getParameter(request, "message", true);// use message instead of MessageBody
588

589             MemberBean memberBean = MemberCache.getInstance().getMember_forPublic(onlineUser.getMemberID());
590             request.setAttribute("MemberBean", memberBean);
591         }
592     }
593
594     /**
595      * @todo: log the modification
596      * @todo: check the comment below, it's obsolete now :(
597      * @todo: check coi messageTopic co the la optional khi reply
598      * NOTE: This method MUST NOT get parameter MessageParent (need some process to figure out)
599      * so it needs to call setAttribute with messageParent for page updatepostsuccess.jsp
600      */

601     public void processUpdate(GenericRequest request)
602         throws ObjectNotFoundException, BadInputException, DatabaseException, CreateException,
603                ForeignKeyNotFoundException, AuthenticationException, AssertionException, InterceptorException {
604
605         OnlineUser onlineUser = onlineUserManager.getOnlineUser(request);
606         MVNForumPermission permission = onlineUser.getPermission();
607
608         // a guest CANNOT edit a post, because it need Authenticated Permission
609
permission.ensureIsAuthenticated();
610         Locale locale = I18nUtil.getLocaleInRequest(request);
611
612         Timestamp JavaDoc now = DateUtil.getCurrentGMTTimestamp();
613
614         int postID = GenericParamUtil.getParameterInt(request, "post");// dont change
615

616         // check constraint
617
PostBean postBean = null;
618         try {
619             postBean = DAOFactory.getPostDAO().getPost(postID);
620         } catch(ObjectNotFoundException ex) {
621             String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.ObjectNotFoundException.postid_not_exists", new Object JavaDoc[] {new Integer JavaDoc(postID)});
622             throw new ObjectNotFoundException(localizedMessage);
623         }
624         int forumID = postBean.getForumID();
625         int threadID = postBean.getThreadID();
626
627         ForumBean forumBean = ForumCache.getInstance().getBean(forumID);
628         forumBean.ensureNotDisabledForum();
629         forumBean.ensureNotLockedForum();
630
631         // now check if thread is locked, if it is, then cannot reply to a post
632
// Please note that if the threadStatus is closed, post can still be edited
633
ThreadBean threadBean = null;
634         try {
635             threadBean = DAOFactory.getThreadDAO().getThread(threadID);
636         } catch ( ObjectNotFoundException ex ) {
637             String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.ObjectNotFoundException.threadid_not_exists", new Object JavaDoc[] {new Integer JavaDoc(threadID)});
638             throw new ObjectNotFoundException(localizedMessage);
639         }
640         threadBean.ensureStatusCanEdit();
641
642         String JavaDoc postTopic = GenericParamUtil.getParameter(request, "PostTopic", true);
643         postTopic = DisableHtmlTagFilter.filter(postTopic);// always disable HTML
644
postTopic = InterceptorService.getInstance().validateContent(postTopic);
645
646         String JavaDoc postBody = GenericParamUtil.getParameter(request, "message", true);// use message instead of PostBody
647
postBody = DisableHtmlTagFilter.filter(postBody);// always disable HTML
648
postBody = InterceptorService.getInstance().validateContent(postBody);
649
650         int logonMemberID = onlineUser.getMemberID();
651         String JavaDoc logonMemberName = onlineUser.getMemberName();
652         int authorID = postBean.getMemberID();
653
654         // check constraint
655
if (permission.canEditPost(forumID)) {
656             // have permission, just do nothing, that is dont check the max day contraint
657
} else if (logonMemberID == authorID) {// same author
658
// make sure user have permission to edit his own post
659
permission.ensureCanEditOwnPost(forumID);
660
661             // check date here, usually must not older than 7 days
662
Timestamp JavaDoc postDate = postBean.getPostCreationDate();
663             int maxDays = MVNForumConfig.getMaxEditDays();
664             if ( (now.getTime() - postDate.getTime()) > (DateUtil.DAY * maxDays) ) {
665                 /** @todo choose a better Exception here */
666                 String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.BadInputException.cannot_edit.post_is_too_old", new Object JavaDoc[] {new Integer JavaDoc(maxDays)});
667                 throw new BadInputException(localizedMessage);
668                 //throw new BadInputException("You cannot edit a post which is older than " + maxDays + " days.");
669
}
670
671             // check status of this post
672
if (postBean.getPostStatus() == PostBean.POST_STATUS_DISABLED) {
673                 String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.BadInputException.cannot_edit_your_post.which_is_disabled");
674                 throw new BadInputException(localizedMessage);
675                 //throw new BadInputException("Cannot edit message which is disable.");
676
}
677         } else {//not an author, so this user must have Edit Permission
678
permission.ensureCanEditPost(forumID);// this method ALWAYS throws AuthenticationException
679
}
680
681         String JavaDoc postLastEditIP = request.getRemoteAddr();
682         int postFormatOption = 0;//@todo review and support it later
683
int postOption = 0;//@todo review and support it later
684
int postStatus = postBean.getPostStatus();// use old post status
685
String JavaDoc postIcon = GenericParamUtil.getParameter(request, "PostIcon");
686         postIcon = DisableHtmlTagFilter.filter(postIcon);// always disable HTML
687

688         /*
689          * Note that although the 2 methods below can be combined,
690          * I dont do that for clearness
691          */

692         /** @todo log the modification here */
693         DAOFactory.getPostDAO().update(postID, // primary key
694
logonMemberName, postTopic, postBody,
695                              now/*postLastEditDate*/, postLastEditIP, postFormatOption,
696                              postOption, postStatus, postIcon);
697         DAOFactory.getPostDAO().increaseEditCount(postID);
698
699         if (postBean.getParentPostID() == 0) {//edit a top post ( thread )
700
String JavaDoc threadIcon = postIcon;
701             DAOFactory.getThreadDAO().updateTopic_Body_Icon(threadID, postTopic, postBody, threadIcon);
702         }
703
704         boolean attachMore = GenericParamUtil.getParameterBoolean(request, "AttachMore");
705         boolean addFavoriteThread = GenericParamUtil.getParameterBoolean(request, "AddFavoriteParentThread");
706         boolean addWatchThread = GenericParamUtil.getParameterBoolean(request, "AddWatchParentThread");
707         //add favorite thread if user checked it
708
if (addFavoriteThread) {
709             permission.ensureIsAuthenticated();
710             //@todo: add checking of MVNForumConfig.getEnableFavoriteThread()
711
// check to make sure that this user doesnt exceed his favorite max
712
int currentFavoriteCount = DAOFactory.getFavoriteThreadDAO().getNumberOfFavoriteThreads_inMember(logonMemberID);
713             int maxFavorites = MVNForumConfig.getMaxFavoriteThread();
714             if (currentFavoriteCount < maxFavorites) {
715                 Timestamp JavaDoc favoriteCreationDate = now;
716                 int favoriteType = 0; //@todo implement it later
717
int favoriteOption = 0; //@todo implement it later
718
int favoriteStatus = 0; //@todo implement it later
719

720                 // now check permission the this user have the readPost permission
721
permission.ensureCanReadPost(forumID);
722
723                 // has the permission now, then insert to database
724
try {
725                     DAOFactory.getFavoriteThreadDAO().create(logonMemberID, threadID, forumID,
726                         favoriteCreationDate, favoriteType, favoriteOption, favoriteStatus);
727                 } catch (DuplicateKeyException ex) {
728                     // already add favorite thread, just ignore
729
}
730             }
731         }
732
733         //add watch if user checked it
734
if (addWatchThread) {
735             permission.ensureIsAuthenticated();
736             permission.ensureIsActivated();
737             if (MVNForumConfig.getEnableWatch() == false) {
738                 // should never happen, because if it happen, then the whole process is broken
739
String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.AssertionException.cannot_add_watch.watch_is_disabled");
740                 throw new AssertionException(localizedMessage);
741                 //throw new AssertionException("Cannot add Watch because Watch feature is disabled by administrator.");
742
}
743
744             int watchType = 0;//GenericParamUtil.getParameterInt(request, "WatchType");
745
int watchOption = 0;//GenericParamUtil.getParameterInt(request, "WatchOption");
746
int watchStatus = 0;//GenericParamUtil.getParameterInt(request, "WatchStatus");
747
Timestamp JavaDoc watchCreationDate = now;
748             Timestamp JavaDoc watchLastSentDate = now;
749             Timestamp JavaDoc watchEndDate = now;// @todo: check it !!!
750

751             try {
752                 DAOFactory.getWatchDAO().create(logonMemberID, 0/*watchCategoryID*/, 0/*watchForumID*/,
753                                            threadID, watchType, watchOption,
754                                            watchStatus, watchCreationDate, watchLastSentDate,
755                                            watchEndDate);
756             } catch (DuplicateKeyException ex) {
757                 // User try to create a duplicate watch, just ignore
758
}
759         }
760
761         request.setAttribute("PostID", String.valueOf(postID));
762         request.setAttribute("ForumID", String.valueOf(forumID));
763         request.setAttribute("ThreadID", String.valueOf(threadID));
764         request.setAttribute("AttachMore", new Boolean JavaDoc(attachMore));
765         request.setAttribute("PostBean", postBean);
766
767         // now update the search index
768
//@todo : modify for better performance here
769
PostIndexer.scheduleUpdatePostTask(DAOFactory.getPostDAO().getPost(postID));
770
771         // Clear the cache
772
PostCache.getInstance().clear();
773         ThreadCache.getInstance().clear();
774     }
775
776     public void prepareDelete(GenericRequest request)
777         throws ObjectNotFoundException, BadInputException, DatabaseException, AuthenticationException, AssertionException {
778
779         OnlineUser onlineUser = onlineUserManager.getOnlineUser(request);
780         MVNForumPermission permission = onlineUser.getPermission();
781
782         // user must have been authenticated before he can delete
783
permission.ensureIsAuthenticated();
784         Locale locale = I18nUtil.getLocaleInRequest(request);
785
786         // primary key column(s)
787
int postID = GenericParamUtil.getParameterInt(request, "post");
788
789         PostBean postBean = null;
790         try {
791             postBean = DAOFactory.getPostDAO().getPost(postID);
792         } catch(ObjectNotFoundException ex) {
793             String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.ObjectNotFoundException.postid_not_exists", new Object JavaDoc[] {new Integer JavaDoc(postID)});
794             throw new ObjectNotFoundException(localizedMessage);
795         }
796         int forumID = postBean.getForumID();
797
798         try {
799             ForumCache.getInstance().getBean(forumID).ensureNotDisabledForum();
800         } catch (ObjectNotFoundException e) {
801             String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.ObjectNotFoundException.forumid_not_exists", new Object JavaDoc[] {new Integer JavaDoc(forumID)});
802             throw new ObjectNotFoundException(localizedMessage);
803         }
804
805
806         if (postBean.getParentPostID() == 0) {
807             String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.BadInputException.cannot_delete_root_post");
808             throw new BadInputException(localizedMessage);
809             //throw new BadInputException("Cannot delete a root post. Use delete thread instead.");
810
}
811
812         // check constraint
813
int logonMemberID = onlineUser.getMemberID();
814         int authorID = postBean.getMemberID();
815         if (permission.canDeletePost(forumID)) {
816             // have permission, just do nothing, that is dont check the max day contraint
817
} else if (logonMemberID == authorID) {// same author
818
// check date here, usually must not older than 7 days
819
Timestamp JavaDoc now = DateUtil.getCurrentGMTTimestamp();
820             Timestamp JavaDoc postDate = postBean.getPostCreationDate();
821             int maxDays = MVNForumConfig.getMaxDeleteDays();
822             if ( (now.getTime() - postDate.getTime()) > (DateUtil.DAY * maxDays) ) {
823                 /** @todo choose a better Exception here */
824                 String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.BadInputException.cannot_delete.post_is_too_old");
825                 throw new BadInputException(localizedMessage);
826                 //throw new BadInputException("You cannot delete a post which is older than " + maxDays + " days.");
827
}
828
829             //Check to make sure that "no reply" for this post
830
int threadID = postBean.getThreadID();
831             Collection postBeans = DAOFactory.getPostDAO().getEnablePosts_inThread_limit(threadID, 0, 10000);
832             boolean foundReply = false;
833             for (Iterator ite = postBeans.iterator(); ite.hasNext(); ) {
834                 PostBean tPostBean = (PostBean) ite.next();
835                 if (tPostBean.getParentPostID() == postBean.getPostID()) {
836                     foundReply = true;
837                     break;
838                 }
839             }
840             if (foundReply) {
841                 String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.BadInputException.cannot_delete_post.post_has_reply");
842                 throw new BadInputException(localizedMessage);
843                 //throw new BadInputException("Cannot delete a post that has reply!");
844
}
845
846             if (postBean.getPostStatus() == PostBean.POST_STATUS_DISABLED) {
847                 String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.BadInputException.cannot_delete_your_own_post.post_is_in_pending_status");
848                 throw new BadInputException(localizedMessage);
849                 //throw new BadInputException("Cannot delete your own post in pending status.");
850
}
851         } else {//not an author, so this user must have Edit Permission
852
permission.ensureCanDeletePost(forumID);// this method ALWAYS throws AuthenticationException
853
}
854
855         request.setAttribute("PostBean", postBean);
856     }
857
858     public void processDelete(GenericRequest request)
859         throws BadInputException, DatabaseException, AuthenticationException, AssertionException, ObjectNotFoundException {
860
861         Locale locale = I18nUtil.getLocaleInRequest(request);
862
863         // primary key column(s)
864
int postID = GenericParamUtil.getParameterInt(request, "post");
865         PostBean postBean = null;
866         try {
867             postBean = DAOFactory.getPostDAO().getPost(postID);
868         } catch(ObjectNotFoundException ex) {
869             String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.ObjectNotFoundException.postid_not_exists", new Object JavaDoc[] {new Integer JavaDoc(postID)});
870             throw new ObjectNotFoundException(localizedMessage);
871         }
872
873         // now check the password
874
MyUtil.ensureCorrectCurrentPassword(request);
875
876         ForumCache.getInstance().getBean(postBean.getForumID()).ensureNotDisabledForum();
877
878         // delete the post and children attachments
879
deletePost(request, postBean);
880
881         int threadID = postBean.getThreadID();
882         int forumID = postBean.getForumID();
883
884
885         // now update the forum and thread statistics
886
StatisticsUtil.updateForumStatistics(forumID);
887         StatisticsUtil.updateThreadStatistics(threadID);
888
889         // Clear the cache
890
PostCache.getInstance().clear();
891
892         request.setAttribute("ForumID", String.valueOf(forumID));
893         request.setAttribute("ThreadID", String.valueOf(threadID));
894     }
895
896     // Note that this method does not update the forum statistics and thread statistics
897
private void deletePost(GenericRequest request, PostBean postBean)
898         throws AssertionException, DatabaseException, AuthenticationException,
899         BadInputException, ObjectNotFoundException {
900
901         OnlineUser onlineUser = onlineUserManager.getOnlineUser(request);
902         MVNForumPermission permission = onlineUser.getPermission();
903
904         // user must have been authenticated before he can delete
905
permission.ensureIsAuthenticated();
906
907         int parentPostID = postBean.getParentPostID();
908
909         Locale locale = I18nUtil.getLocaleInRequest(request);
910
911         if (parentPostID == 0) {
912             String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.BadInputException.cannot_delete_root_post");
913             throw new BadInputException(localizedMessage);
914             //throw new BadInputException("Cannot delete a root post. Use delete thread instead.");
915
}
916
917         int forumID = postBean.getForumID();
918
919         // check constraint
920
int logonMemberID = onlineUser.getMemberID();
921         int authorID = postBean.getMemberID();
922         if (permission.canDeletePost(forumID)) {
923             // have permission, just do nothing, that is dont check the max day contraint
924
} else if (logonMemberID == authorID) {// same author
925
// check date here, usually must not older than 7 days
926
Timestamp JavaDoc now = DateUtil.getCurrentGMTTimestamp();
927             Timestamp JavaDoc postDate = postBean.getPostCreationDate();
928             int maxDays = MVNForumConfig.getMaxDeleteDays();
929             if ( (now.getTime() - postDate.getTime()) > (DateUtil.DAY * maxDays) ) {
930                 /** @todo choose a better Exception here */
931                 String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.BadInputException.cannot_delete.post_is_too_old", new Object JavaDoc[] {new Integer JavaDoc(maxDays)});
932                 throw new BadInputException(localizedMessage);
933                 //throw new BadInputException("You cannot delete a post which is older than " + maxDays + " days.");
934
}
935
936             //Check to make sure that "no reply" for this post
937
int threadID = postBean.getThreadID();
938             Collection postBeans = DAOFactory.getPostDAO().getEnablePosts_inThread_limit(threadID, 0, 10000);
939             boolean foundReply = false;
940             for (Iterator ite = postBeans.iterator(); ite.hasNext(); ) {
941                 PostBean tPostBean = (PostBean) ite.next();
942                 if (tPostBean.getParentPostID() == postBean.getPostID()) {
943                     foundReply = true;
944                     break;
945                 }
946             }
947             if (foundReply) {
948                 String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.BadInputException.cannot_delete_post.post_has_reply");
949                 throw new BadInputException(localizedMessage);
950                 //throw new BadInputException("Cannot delete a post that has reply!");
951
}
952
953             if (postBean.getPostStatus() == PostBean.POST_STATUS_DISABLED) {
954                 String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.BadInputException.cannot_delete_your_own_post.post_is_in_pending_status");
955                 throw new BadInputException(localizedMessage);
956                 //throw new BadInputException("Cannot delete your own disabled post.");
957
}
958         } else {//not an author, so this user must have Edit Permission
959
permission.ensureCanDeletePost(forumID);// this method ALWAYS throws AuthenticationException
960
}
961
962         int postID = postBean.getPostID();
963
964         // Delete all attachments in this post,
965
// we must call this before any attempt to delete the post
966
AttachmentWebHandler.deleteAttachments_inPost(postID);
967
968         // now delete the post, note that we delete it after delete all child objects (attachment)
969
DAOFactory.getPostDAO().delete(postID);
970
971         try {
972             DAOFactory.getPostDAO().updateParentPostID(postID, parentPostID);
973         } catch (ObjectNotFoundException ex) {
974             // we just ignore if no post is affect by this method
975
}
976
977         int memberID = postBean.getMemberID();
978         StatisticsUtil.updateMemberStatistics(memberID);
979
980         // now update the search index
981
PostIndexer.scheduleDeletePostTask(postID, DeletePostIndexTask.OBJECT_TYPE_POST);
982     }
983
984     public void prepareModeratePendingPosts_limit(GenericRequest request)
985         throws AssertionException, DatabaseException, AuthenticationException, BadInputException,
986         DatabaseException, ObjectNotFoundException {
987
988         OnlineUser onlineUser = onlineUserManager.getOnlineUser(request);
989         MVNForumPermission permission = onlineUser.getPermission();
990
991         Locale locale = I18nUtil.getLocaleInRequest(request);
992
993         int threadID = GenericParamUtil.getParameterInt(request, "thread");
994         ThreadBean threadBean = null;
995         try {
996             threadBean = DAOFactory.getThreadDAO().getThread(threadID);
997         } catch ( ObjectNotFoundException ex ) {
998             String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.ObjectNotFoundException.threadid_not_exists", new Object JavaDoc[] {new Integer JavaDoc(threadID)});
999             throw new ObjectNotFoundException(localizedMessage);
1000        }
1001        int forumID = threadBean.getForumID();
1002
1003        try {
1004            ForumCache.getInstance().getBean(forumID).ensureNotDisabledForum();
1005        } catch (ObjectNotFoundException e) {
1006            String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.ObjectNotFoundException.forumid_not_exists", new Object JavaDoc[] {new Integer JavaDoc(forumID)});
1007            throw new ObjectNotFoundException(localizedMessage);
1008        }
1009
1010        int numberOfPosts = DAOFactory.getPostDAO().getNumberOfDisablePosts_inThread(threadID);
1011
1012        // user must have been authenticated before he can view pending/disabled threads
1013
permission.ensureIsAuthenticated();
1014
1015        // check normal permission
1016
permission.ensureCanModerateThread(forumID);
1017
1018        int postsPerPage = 10000;
1019        int offset = 0;
1020
1021        Collection postBeans = DAOFactory.getPostDAO().getDisablePosts_inThread_limit(threadID, offset, postsPerPage);
1022
1023        Iterator iterator = postBeans.iterator();
1024        while (iterator.hasNext()) {
1025            PostBean postBean = (PostBean) iterator.next();
1026            // very slow here
1027
/** @todo find a better solution */
1028            MemberBean memberBean = null;
1029            if (postBean.getMemberID() != 0 && postBean.getMemberID() != MVNForumConstant.MEMBER_ID_OF_GUEST) {
1030                memberBean = MemberCache.getInstance().getMember_forPublic(postBean.getMemberID());
1031            }
1032            postBean.setMemberBean(memberBean);
1033
1034            int postAttachCount = postBean.getPostAttachCount();
1035            if ((postAttachCount > 0) && MVNForumConfig.getEnableAttachment()) {
1036                int postID = postBean.getPostID();
1037                Collection attachBeans = DAOFactory.getAttachmentDAO().getAttachments_inPost(postID);
1038                int actualAttachCount = attachBeans.size();
1039
1040                // now check if the attachCount in talbe Post equals to the actual attachCount in table Attachment
1041
if (postAttachCount != actualAttachCount) {
1042                    if (actualAttachCount != DAOFactory.getAttachmentDAO().getNumberOfAttachments_inPost(postID)) {
1043                        String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.AssertionException.serious_error.cannot_process_attachment_count");
1044                        throw new AssertionException(localizedMessage);
1045                        //throw new AssertionException("AssertionException: Serious error: cannot process Attachment Count in table Attachment");
1046
}
1047                    log.warn("The attachment count in table Post and Attachment are not synchronized. In table Post = " +
1048                            postAttachCount + " and in table Attachment = " + actualAttachCount + ". Synchronize to " + actualAttachCount);
1049                    DAOFactory.getPostDAO().updateAttachCount(postID, actualAttachCount);
1050                }
1051                if (actualAttachCount > 0) {
1052                    postBean.setAttachmentBeans(attachBeans);
1053                }
1054            }
1055        }
1056
1057        PostBean firstPostBean = DAOFactory.getPostDAO().getFirstPost_inThread(threadID);
1058        if (firstPostBean.getMemberID() != 0 && firstPostBean.getMemberID() != MVNForumConstant.MEMBER_ID_OF_GUEST) {
1059            MemberBean memberBean = MemberCache.getInstance().getMember_forPublic(firstPostBean.getMemberID());
1060            firstPostBean.setMemberBean(memberBean);
1061        }
1062
1063
1064        request.setAttribute("ThreadBean", threadBean);
1065        request.setAttribute("FirstPostBean", firstPostBean);
1066        request.setAttribute("PostBeans", postBeans);
1067        request.setAttribute("NumberOfPosts", new Integer JavaDoc(numberOfPosts));
1068    }
1069
1070    public void processModeratePendingPosts(GenericRequest request)
1071        throws AssertionException, DatabaseException, AuthenticationException,
1072        BadInputException, DatabaseException, ObjectNotFoundException {
1073
1074        OnlineUser onlineUser = onlineUserManager.getOnlineUser(request);
1075        MVNForumPermission permission = onlineUser.getPermission();
1076        Locale locale = I18nUtil.getLocaleInRequest(request);
1077
1078        // user must have been authenticated before he can moderate pending/disabled posts
1079
permission.ensureIsAuthenticated();
1080
1081        // check normal permission, note that we dont check
1082
// permission on a forumID because we allow moderate posts
1083
// in multiple forums even if the web interface does not support it
1084
int threadID = -1;
1085        int forumID = -1;
1086        try {
1087            threadID = GenericParamUtil.getParameterInt(request, "thread");
1088            ThreadBean threadBean = null;
1089            try {
1090                threadBean = DAOFactory.getThreadDAO().getThread(threadID);
1091            } catch ( ObjectNotFoundException ex ) {
1092                String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.ObjectNotFoundException.threadid_not_exists", new Object JavaDoc[] {new Integer JavaDoc(threadID)});
1093                throw new ObjectNotFoundException(localizedMessage);
1094            }
1095            forumID = threadBean.getForumID();
1096            permission.ensureCanModerateThread(forumID);
1097            ForumCache.getInstance().getBean(forumID).ensureNotDisabledForum();
1098        } catch (BadInputException ex) {
1099            // just ignore, in case of use customized client
1100
}
1101        permission.ensureCanModerateThreadInAnyForum();
1102
1103        try {
1104            String JavaDoc prefix = "modpostaction_";
1105            for (Enumeration enumeration = request.getParameterNames(); enumeration.hasMoreElements(); ) {
1106                String JavaDoc param = (String JavaDoc) enumeration.nextElement();
1107                if (param.startsWith(prefix)) {
1108                    String JavaDoc modValue = GenericParamUtil.getParameter(request, param, true);
1109                    String JavaDoc strPostID = param.substring(prefix.length());
1110                    int postID = Integer.parseInt(strPostID);
1111                    if (modValue.equals("approve")) {
1112                        PostBean postBean = null;
1113                        try {
1114                            postBean = DAOFactory.getPostDAO().getPost(postID);
1115                        } catch(ObjectNotFoundException ex) {
1116                            String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.ObjectNotFoundException.postid_not_exists", new Object JavaDoc[] {new Integer JavaDoc(postID)});
1117                            throw new ObjectNotFoundException(localizedMessage);
1118                        }
1119                        int currentForumID = postBean.getForumID();
1120                        permission.ensureCanModerateThread(currentForumID);
1121                        DAOFactory.getPostDAO().updateStatus(postID, PostBean.POST_STATUS_DEFAULT);
1122                    } else if (modValue.equals("delete")) {
1123                        PostBean postBean = null;
1124                        try {
1125                            postBean = DAOFactory.getPostDAO().getPost(postID);
1126                        } catch(ObjectNotFoundException ex) {
1127                            String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.ObjectNotFoundException.postid_not_exists", new Object JavaDoc[] {new Integer JavaDoc(postID)});
1128                            throw new ObjectNotFoundException(localizedMessage);
1129                        }
1130                        deletePost(request, postBean);
1131                    } else {
1132                        // it means ignore, do nothing
1133
}
1134                }
1135            }
1136        } finally {
1137            // now update the forum statistics
1138
if (forumID != -1) {
1139                StatisticsUtil.updateForumStatistics(forumID);
1140            }
1141
1142            // now update the thread statistics
1143
if (threadID != -1) {
1144                StatisticsUtil.updateThreadStatistics(threadID);
1145            }
1146        }
1147
1148        // Now clear the cache
1149
PostCache.getInstance().clear();
1150        ThreadCache.getInstance().clear();
1151
1152        request.setAttribute("ForumID", String.valueOf(forumID));
1153        request.setAttribute("ThreadID", String.valueOf(threadID));
1154    }
1155
1156    /**
1157     * This method is for viewthread page and printthread page
1158     */

1159    public void prepareViewThread(GenericRequest request)
1160        throws DatabaseException, ObjectNotFoundException, BadInputException, AuthenticationException, AssertionException {
1161
1162        OnlineUser onlineUser = onlineUserManager.getOnlineUser(request);
1163        MVNForumPermission permission = onlineUser.getPermission();
1164
1165        Locale locale = I18nUtil.getLocaleInRequest(request);
1166
1167        int threadID = GenericParamUtil.getParameterInt(request, "thread");
1168        boolean printAll = GenericParamUtil.getParameterBoolean(request, "printall");
1169        ThreadBean threadBean = null;
1170        try {
1171            threadBean = DAOFactory.getThreadDAO().getThread(threadID);
1172        } catch ( ObjectNotFoundException ex ) {
1173            String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.ObjectNotFoundException.threadid_not_exists", new Object JavaDoc[] {new Integer JavaDoc(threadID)});
1174            throw new ObjectNotFoundException(localizedMessage);
1175        }
1176        int forumID = threadBean.getForumID();
1177        int numberOfPosts = DAOFactory.getPostDAO().getNumberOfEnablePosts_inThread(threadID);
1178
1179        // check normal permission
1180
permission.ensureCanReadPost(forumID);
1181
1182        //ForumBean forumBean = null;
1183
try {
1184            ForumCache.getInstance().getBean(forumID).ensureNotDisabledForum();
1185        } catch (ObjectNotFoundException e) {
1186            String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.ObjectNotFoundException.forumid_not_exists", new Object JavaDoc[] {new Integer JavaDoc(forumID)});
1187            throw new ObjectNotFoundException(localizedMessage);
1188        }
1189
1190        // Only moderator can view disable threads
1191
if (threadBean.getThreadStatus() == ThreadBean.THREAD_STATUS_DISABLED) {
1192            permission.ensureCanModerateThread(forumID);
1193        }
1194
1195        int postsPerPage = onlineUser.getPostsPerPage();
1196        int offset = 0;
1197        boolean lastPage = GenericParamUtil.getParameterBoolean(request, "lastpage");
1198        if (lastPage) {
1199            // note that in the worst case, numberOfPosts could equals 0 (bad database)
1200
int pageCount = numberOfPosts / postsPerPage;
1201            int odd = numberOfPosts % postsPerPage;
1202            if (odd > 0) {
1203                pageCount++;
1204            }
1205            if (pageCount < 1) {
1206                pageCount = 1;// at least, there is one page
1207
}
1208            offset = (pageCount-1) * postsPerPage;
1209        } else {
1210            try {
1211                offset = GenericParamUtil.getParameterInt(request, "offset");
1212            } catch (BadInputException e) {
1213                // do nothing
1214
}
1215        }
1216        if (printAll) {
1217            postsPerPage = 10000; //We assume that big number
1218
offset = 0;
1219        }
1220
1221        Collection postBeans = PostCache.getInstance().getEnablePosts_inThread_limit(threadID, offset, postsPerPage);
1222
1223        Iterator iterator = postBeans.iterator();
1224        while(iterator.hasNext()) {
1225            PostBean postBean = (PostBean)iterator.next();
1226            MemberBean memberBean = null;
1227            if (postBean.getMemberID() != 0 && postBean.getMemberID() != MVNForumConstant.MEMBER_ID_OF_GUEST) {
1228                // Use cache for maximum performance
1229
memberBean = MemberCache.getInstance().getMember_forPublic(postBean.getMemberID());
1230            }
1231            postBean.setMemberBean(memberBean);
1232
1233            int postAttachCount = postBean.getPostAttachCount();
1234            if ( (postAttachCount > 0) && MVNForumConfig.getEnableAttachment()) {
1235                int postID = postBean.getPostID();
1236                Collection attachBeans = DAOFactory.getAttachmentDAO().getAttachments_inPost(postID);
1237                int actualAttachCount = attachBeans.size();
1238
1239                // now check if the attachCount in talbe Post equals to the actual attachCount in table Attachment
1240
if (postAttachCount != actualAttachCount) {
1241                    if (actualAttachCount != DAOFactory.getAttachmentDAO().getNumberOfAttachments_inPost(postID)) {
1242                        String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.AssertionException.serious_error.cannot_process_attachment_count");
1243                        throw new AssertionException(localizedMessage);
1244                        //throw new AssertionException("AssertionException: Serious error: cannot process Attachment Count in table Attachment");
1245
}
1246                    log.warn("The attachment count in table Post and Attachment are not synchronized. In table Post = " + postAttachCount + " and in table Attachment = " + actualAttachCount + ". Synchronize to " + actualAttachCount);
1247                    DAOFactory.getPostDAO().updateAttachCount(postID, actualAttachCount);
1248                }
1249                if (actualAttachCount > 0) {
1250                    postBean.setAttachmentBeans(attachBeans);
1251                }
1252            }
1253        }
1254
1255        //int previousTopic = DAOFactory.getThreadDAO().getPreviousEnableThread(forumID, threadID);// can throw AssertionException
1256
//int nextTopic = DAOFactory.getThreadDAO().getNextEnableThread(forumID, threadID);// can throw AssertionException
1257
int previousTopic = ThreadCache.getInstance().getPreviousEnableThread(forumID, threadID);// can throw AssertionException
1258
int nextTopic = ThreadCache.getInstance().getNextEnableThread(forumID, threadID);// can throw AssertionException
1259

1260        int pendingPostCount = 0;
1261        if (permission.canModerateThread(forumID)) {
1262            pendingPostCount = DAOFactory.getPostDAO().getNumberOfDisablePosts_inThread(threadID);
1263        }
1264
1265        DAOFactory.getThreadDAO().increaseViewCount(threadID);
1266
1267        request.setAttribute("ThreadBean", threadBean);
1268        request.setAttribute("PostBeans", postBeans);
1269        request.setAttribute("NumberOfPosts", new Integer JavaDoc(numberOfPosts));
1270        request.setAttribute("PreviousTopic", new Integer JavaDoc(previousTopic));
1271        request.setAttribute("NextTopic", new Integer JavaDoc(nextTopic));
1272        request.setAttribute("PendingPostCount", new Integer JavaDoc(pendingPostCount));
1273    }
1274
1275    public void prepareSearch(GenericRequest request)
1276        throws AssertionException {
1277
1278        if (!MVNForumConfig.getEnableSearch()) {
1279            Locale locale = I18nUtil.getLocaleInRequest(request);
1280            String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.AssertionException.search_disabled");
1281            throw new AssertionException(localizedMessage);
1282        }
1283    }
1284
1285    public void processSearch(GenericRequest request, GenericResponse response)
1286        throws BadInputException, IOException JavaDoc, DatabaseException,
1287        ObjectNotFoundException, AuthenticationException, AssertionException {
1288
1289        OnlineUser onlineUser = onlineUserManager.getOnlineUser(request);
1290        MVNForumPermission permission = onlineUser.getPermission();
1291
1292        Locale locale = I18nUtil.getLocaleInRequest(request);
1293
1294        if (!MVNForumConfig.getEnableSearch()) {
1295            String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.AssertionException.search_disabled");
1296            throw new AssertionException(localizedMessage);
1297        }
1298
1299        MyUtil.saveVNTyperMode(request, response);
1300
1301        String JavaDoc memberName = GenericParamUtil.getParameter(request, "member");
1302        StringUtil.checkGoodName(memberName);
1303
1304        int minAttachmentCount = GenericParamUtil.getParameterInt(request, "minattach", 0);
1305
1306        // if user does not enter MemberName or attachment, then user must enter "key"
1307
boolean requireKey = ((memberName.length() == 0) && (minAttachmentCount == 0));
1308        String JavaDoc key = GenericParamUtil.getParameter(request, "key", requireKey);
1309
1310        int forumID = GenericParamUtil.getParameterInt(request, "forum", 0);//negative means category
1311
int offset = GenericParamUtil.getParameterUnsignedInt(request, "offset", 0);
1312        int rows = GenericParamUtil.getParameterUnsignedInt(request, "rows", 20);
1313        if (rows == 0) {
1314            rows = 20;// fix NullPointerException when rows = 0
1315
}
1316
1317        // offset should be even when divide with rowsToReturn
1318
offset = (offset / rows) * rows;
1319
1320        PostSearchQuery query = new PostSearchQuery();
1321
1322        if (key.length() > 0) {
1323            query.setSearchString(key);
1324            int scopeInPost = GenericParamUtil.getParameterInt(request, "scopeinpost", PostSearchQuery.SEARCH_ONLY_BODY|PostSearchQuery.SEARCH_ONLY_TITLE);
1325            query.setScopeInPost(scopeInPost);
1326        }
1327
1328        if (memberName.length() > 0) {
1329            try {
1330                int memberID = DAOFactory.getMemberDAO().getMemberIDFromMemberName(memberName);
1331                query.setMemberId(memberID);
1332            } catch(ObjectNotFoundException ex) {
1333                String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.ObjectNotFoundException.membername_not_exists", new Object JavaDoc[] {memberName});
1334                throw new ObjectNotFoundException(localizedMessage);
1335            }
1336        }
1337
1338        if (minAttachmentCount > 0) {
1339            query.setMinAttachmentCount(minAttachmentCount);
1340        }
1341
1342        int searchDate = GenericParamUtil.getParameterUnsignedInt(request, "date", PostSearchQuery.SEARCH_ANY_DATE);
1343        int searchBeforeAfter = GenericParamUtil.getParameterInt(request, "beforeafter", PostSearchQuery.SEARCH_NEWER);
1344
1345        if ((searchDate != PostSearchQuery.SEARCH_ANY_DATE) && (searchDate < 365 * 10)) { // 10 years
1346
long deltaTime = DateUtil.DAY * searchDate;
1347
1348            Timestamp JavaDoc now = DateUtil.getCurrentGMTTimestamp();
1349            Timestamp JavaDoc from = null;
1350            Timestamp JavaDoc to = null;
1351
1352            long currentTime = now.getTime();
1353
1354            if (searchBeforeAfter == PostSearchQuery.SEARCH_NEWER) {
1355                from = new Timestamp JavaDoc(currentTime - deltaTime);
1356            } else {// older
1357
to = new Timestamp JavaDoc(currentTime - deltaTime);
1358            }
1359
1360            query.setFromDate(from);
1361            query.setToDate(to);
1362        }
1363
1364        if (forumID > 0) {
1365            query.setForumId(forumID);
1366        } else if (forumID < 0) {
1367            // choose to search in a category
1368
query.setForumId(forumID);
1369        } else {
1370            // forumID equals to 0, it mean global searching
1371
// just do nothing, lucene will search all forums (globally)
1372
}
1373
1374        query.searchDocuments(offset, rows, permission);
1375        int hitCount = query.getHitCount();
1376        Collection result = query.getPostResult();
1377
1378        // Remove postd that current user dont have permission
1379
// NOTE: these below code does not remove the enable posts in
1380
// a disabled thread. This is not usually the case because
1381
// normally we will delete the thread instead of change it
1382
// from Enable to Disabled
1383
for (Iterator iter = result.iterator(); iter.hasNext(); ) {
1384            PostBean postBean = (PostBean)iter.next();
1385            int currentForumID = postBean.getForumID();
1386            if (ForumCache.getInstance().getBean(currentForumID).getForumStatus() == ForumBean.FORUM_STATUS_DISABLED) {
1387                iter.remove();
1388            } else if ( (permission.canReadPost(currentForumID) == false) ||
1389                 (postBean.getPostStatus() == PostBean.POST_STATUS_DISABLED)) {
1390                iter.remove();
1391            }
1392            else if (postBean.getParentPostID() == 0) {// first post
1393
// Please note that the first post is always Enable even if
1394
// the thread is Disable. In this case always show result
1395
// if the current user is moderator
1396
if (permission.canModerateThread(currentForumID) == false) {
1397                    int threadID = postBean.getThreadID();
1398                    ThreadBean threadBean = null;
1399                    try {
1400                        threadBean = DAOFactory.getThreadDAO().getThread(threadID);
1401                    } catch ( ObjectNotFoundException ex ) {
1402                        String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.ObjectNotFoundException.threadid_not_exists", new Object JavaDoc[] {new Integer JavaDoc(threadID)});
1403                        throw new ObjectNotFoundException(localizedMessage);
1404                    }
1405                    if (threadBean.getThreadStatus() == ThreadBean.THREAD_STATUS_DISABLED) {
1406                        iter.remove();
1407                    }
1408                }
1409            }
1410        }
1411
1412        if (offset > hitCount) {
1413            String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.BadInputException.offset_greater_than_total_rows");
1414            throw new BadInputException(localizedMessage);
1415            //throw new BadInputException("Cannot search with offset > total posts");
1416
}
1417
1418// request.setAttribute("key", Encoder.encodeURL(key));
1419
// request.setAttribute("member", memberName);
1420
// request.setAttribute("forum", new Integer(forumID));
1421
// request.setAttribute("offset", new Integer(offset));
1422
// request.setAttribute("attachment", new Boolean(withAttachment));
1423
request.setAttribute("rows", new Integer JavaDoc(rows));
1424        request.setAttribute("TotalPosts", new Integer JavaDoc(hitCount));
1425        request.setAttribute("PostBeans", result);
1426        request.setAttribute("SearchQuery", query);
1427    }
1428
1429}
1430
Popular Tags