KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > jforum > view > forum > PostAction


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  * This file creation date: May 3, 2003 / 5:05:18 PM
40  * The JForum Project
41  * http://www.jforum.net
42  */

43 package net.jforum.view.forum;
44
45 import java.io.File JavaDoc;
46 import java.io.FileInputStream JavaDoc;
47 import java.io.OutputStream JavaDoc;
48 import java.text.SimpleDateFormat JavaDoc;
49 import java.util.Collections JavaDoc;
50 import java.util.Date 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.Command;
57 import net.jforum.JForumExecutionContext;
58 import net.jforum.SessionFacade;
59 import net.jforum.dao.AttachmentDAO;
60 import net.jforum.dao.DataAccessDriver;
61 import net.jforum.dao.ForumDAO;
62 import net.jforum.dao.KarmaDAO;
63 import net.jforum.dao.PollDAO;
64 import net.jforum.dao.PostDAO;
65 import net.jforum.dao.TopicDAO;
66 import net.jforum.dao.UserDAO;
67 import net.jforum.entities.Attachment;
68 import net.jforum.entities.Forum;
69 import net.jforum.entities.Poll;
70 import net.jforum.entities.PollChanges;
71 import net.jforum.entities.Post;
72 import net.jforum.entities.QuotaLimit;
73 import net.jforum.entities.Topic;
74 import net.jforum.entities.User;
75 import net.jforum.entities.UserSession;
76 import net.jforum.exceptions.AttachmentException;
77 import net.jforum.exceptions.AttachmentSizeTooBigException;
78 import net.jforum.exceptions.ForumException;
79 import net.jforum.repository.ForumRepository;
80 import net.jforum.repository.PostRepository;
81 import net.jforum.repository.RankingRepository;
82 import net.jforum.repository.SecurityRepository;
83 import net.jforum.repository.SmiliesRepository;
84 import net.jforum.repository.TopicRepository;
85 import net.jforum.security.PermissionControl;
86 import net.jforum.security.SecurityConstants;
87 import net.jforum.util.I18n;
88 import net.jforum.util.preferences.ConfigKeys;
89 import net.jforum.util.preferences.SystemGlobals;
90 import net.jforum.util.preferences.TemplateKeys;
91 import net.jforum.view.forum.common.AttachmentCommon;
92 import net.jforum.view.forum.common.ForumCommon;
93 import net.jforum.view.forum.common.PollCommon;
94 import net.jforum.view.forum.common.PostCommon;
95 import net.jforum.view.forum.common.TopicsCommon;
96 import net.jforum.view.forum.common.ViewCommon;
97
98 /**
99  * @author Rafael Steil
100  * @version $Id: PostAction.java,v 1.141 2006/02/21 13:59:49 rafaelsteil Exp $
101  */

102 public class PostAction extends Command
103 {
104     public void list() throws Exception JavaDoc
105     {
106         PostDAO pm = DataAccessDriver.getInstance().newPostDAO();
107         PollDAO pollDao = DataAccessDriver.getInstance().newPollDAO();
108         UserDAO um = DataAccessDriver.getInstance().newUserDAO();
109         TopicDAO tm = DataAccessDriver.getInstance().newTopicDAO();
110
111         UserSession us = SessionFacade.getUserSession();
112         int anonymousUser = SystemGlobals.getIntValue(ConfigKeys.ANONYMOUS_USER_ID);
113         boolean logged = SessionFacade.isLogged();
114         
115         int topicId = this.request.getIntParameter("topic_id");
116         
117         Topic topic = TopicRepository.getTopic(new Topic(topicId));
118         
119         if (topic == null) {
120             topic = tm.selectById(topicId);
121         }
122
123         // The topic exists?
124
if (topic.getId() == 0) {
125             this.topicNotFound();
126             return;
127         }
128
129         // Shall we proceed?
130
Forum forum = ForumRepository.getForum(topic.getForumId());
131         
132         if (!logged) {
133             if (forum == null || !ForumRepository.isCategoryAccessible(forum.getCategoryId())) {
134                 this.setTemplateName(ViewCommon.contextToLogin());
135                 return;
136             }
137         }
138         else if (!TopicsCommon.isTopicAccessible(topic.getForumId())) {
139             return;
140         }
141
142         int count = SystemGlobals.getIntValue(ConfigKeys.POST_PER_PAGE);
143         int start = ViewCommon.getStartPage();
144
145         PermissionControl pc = SecurityRepository.get(us.getUserId());
146
147         boolean canEdit = false;
148         if (pc.canAccess(SecurityConstants.PERM_MODERATION_POST_EDIT)) {
149             canEdit = true;
150         }
151
152         List JavaDoc helperList = PostCommon.topicPosts(pm, canEdit, us.getUserId(), topic.getId(), start, count);
153         
154         // Ugly assumption:
155
// Is moderation pending for the topic?
156
if (topic.isModerated() && helperList.size() == 0) {
157             this.notModeratedYet();
158             return;
159         }
160
161         // Set the topic status as read
162
if (logged) {
163             tm.updateReadStatus(topic.getId(), us.getUserId(), true);
164         }
165
166         boolean canVoteOnPoll = logged && SecurityRepository.canAccess(SecurityConstants.PERM_VOTE);
167         Poll poll = null;
168         
169         if (topic.isVote()) {
170             // It has a poll associated with the topic
171
poll = pollDao.selectById(topic.getVoteId());
172             
173             if (canVoteOnPoll) {
174                 canVoteOnPoll = !pollDao.hasUserVotedOnPoll(topic.getVoteId(), us.getUserId());
175             }
176         }
177         
178         tm.incrementTotalViews(topic.getId());
179         topic.setTotalViews(topic.getTotalViews() + 1);
180
181         if (us.getUserId() != anonymousUser) {
182             ((Map JavaDoc)SessionFacade.getAttribute(ConfigKeys.TOPICS_TRACKING)).put(new Integer JavaDoc(topic.getId()),
183                 new Long JavaDoc(System.currentTimeMillis()));
184         }
185         
186         boolean karmaEnabled = SecurityRepository.canAccess(SecurityConstants.PERM_KARMA_ENABLED);
187         Map JavaDoc userVotes = new HashMap JavaDoc();
188         
189         if (logged && karmaEnabled) {
190             userVotes = DataAccessDriver.getInstance().newKarmaDAO().getUserVotes(topic.getId(), us.getUserId());
191         }
192         
193         this.setTemplateName(TemplateKeys.POSTS_LIST);
194         this.context.put("attachmentsEnabled", pc.canAccess(
195                 SecurityConstants.PERM_ATTACHMENTS_ENABLED, Integer.toString(topic.getForumId())));
196         this.context.put("canDownloadAttachments", pc.canAccess(
197                 SecurityConstants.PERM_ATTACHMENTS_DOWNLOAD));
198         this.context.put("thumbShowBox", SystemGlobals.getBoolValue(ConfigKeys.ATTACHMENTS_IMAGES_THUMB_BOX_SHOW));
199         this.context.put("am", new AttachmentCommon(this.request, topic.getForumId()));
200         this.context.put("karmaVotes", userVotes);
201         this.context.put("rssEnabled", SystemGlobals.getBoolValue(ConfigKeys.RSS_ENABLED));
202         this.context.put("canRemove", pc.canAccess(SecurityConstants.PERM_MODERATION_POST_REMOVE));
203         this.context.put("canEdit", canEdit);
204         this.context.put("allCategories", ForumCommon.getAllCategoriesAndForums(false));
205         this.context.put("topic", topic);
206         this.context.put("poll", poll);
207         this.context.put("canVoteOnPoll", canVoteOnPoll);
208         this.context.put("rank", new RankingRepository());
209         this.context.put("posts", helperList);
210         this.context.put("forum", forum);
211         
212         Map JavaDoc topicPosters = tm.topicPosters(topic.getId());
213         
214         for (Iterator JavaDoc iter = topicPosters.values().iterator(); iter.hasNext(); ) {
215             ViewCommon.prepareUserSignature((User)iter.next());
216         }
217         
218         this.context.put("users", topicPosters);
219         this.context.put("anonymousPosts", pc.canAccess(SecurityConstants.PERM_ANONYMOUS_POST,
220                 Integer.toString(topic.getForumId())));
221         this.context.put("watching", tm.isUserSubscribed(topicId, SessionFacade.getUserSession().getUserId()));
222         this.context.put("pageTitle", topic.getTitle());
223         this.context.put("isAdmin", pc.canAccess(SecurityConstants.PERM_ADMINISTRATION));
224         this.context.put("readonly", !pc.canAccess(SecurityConstants.PERM_READ_ONLY_FORUMS,
225                 Integer.toString(topic.getForumId())));
226         this.context.put("replyOnly", !pc.canAccess(SecurityConstants.PERM_REPLY_ONLY,
227                 Integer.toString(topic.getForumId())));
228
229         this.context.put("isModerator", us.isModerator(topic.getForumId()));
230
231         // Pagination
232
ViewCommon.contextToPagination(start, topic.getTotalReplies() + 1, count);
233         
234         TopicsCommon.topicListingBase();
235         TopicRepository.updateTopic(topic);
236     }
237     
238     /**
239      * Given a postId, sends the user to the right page
240      * @throws Exception
241      */

242     public void preList() throws Exception JavaDoc
243     {
244         int postId = this.request.getIntParameter("post_id");
245         
246         PostDAO pdao = DataAccessDriver.getInstance().newPostDAO();
247         
248         int count = pdao.countPreviousPosts(postId);
249         int postsPerPage = SystemGlobals.getIntValue(ConfigKeys.POST_PER_PAGE);
250         
251         int topicId = this.request.getIntParameter("topic_id");
252         String JavaDoc page = "";
253         
254         if (count > postsPerPage) {
255             page = Integer.toString(postsPerPage * ((count - 1) / postsPerPage)) + "/";
256         }
257
258         JForumExecutionContext.setRedirect(this.request.getContextPath() + "/posts/list/"
259             + page + topicId
260             + SystemGlobals.getValue(ConfigKeys.SERVLET_EXTENSION)
261             + "#" + postId);
262     }
263     
264     /**
265      * Votes on a poll.
266      * @throws Exception
267      */

268     public void vote() throws Exception JavaDoc
269     {
270         int pollId = this.request.getIntParameter("poll_id");
271         int topicId = this.request.getIntParameter("topic_id");
272         
273         if (SessionFacade.isLogged() && this.request.getParameter("poll_option") != null) {
274             Topic topic = TopicRepository.getTopic(new Topic(topicId));
275             
276             if (topic == null) {
277                 topic = DataAccessDriver.getInstance().newTopicDAO().selectRaw(topicId);
278             }
279             
280             if (topic.getStatus() == Topic.STATUS_LOCKED) {
281                 this.topicLocked();
282                 return;
283             }
284             
285             // They voted, save the value
286
int optionId = this.request.getIntParameter("poll_option");
287             
288             PollDAO dao = DataAccessDriver.getInstance().newPollDAO();
289             
290             //vote on the poll
291
UserSession user = SessionFacade.getUserSession();
292             dao.voteOnPoll(pollId, optionId, user.getUserId(), request.getRemoteAddr());
293         }
294
295         JForumExecutionContext.setRedirect(this.request.getContextPath()
296             + "/posts/list/"
297             + topicId
298             + SystemGlobals.getValue(ConfigKeys.SERVLET_EXTENSION));
299     }
300
301     public void listByUser() throws Exception JavaDoc
302     {
303         PostDAO pm = DataAccessDriver.getInstance().newPostDAO();
304         UserDAO um = DataAccessDriver.getInstance().newUserDAO();
305         TopicDAO tm = DataAccessDriver.getInstance().newTopicDAO();
306         
307         UserSession us = SessionFacade.getUserSession();
308         int anonymousUser = SystemGlobals.getIntValue(ConfigKeys.ANONYMOUS_USER_ID);
309         
310         User u = um.selectById(this.request.getIntParameter("user_id"));
311         
312         if (u.getId() == 0) {
313             this.context.put("message", I18n.getMessage("User.notFound"));
314             this.setTemplateName(TemplateKeys.USER_NOT_FOUND);
315             return;
316         }
317             
318         int count = SystemGlobals.getIntValue(ConfigKeys.POST_PER_PAGE);
319         int start = ViewCommon.getStartPage();
320         int postsPerPage = SystemGlobals.getIntValue(ConfigKeys.POST_PER_PAGE);
321         
322         List JavaDoc posts = pm.selectByUserByLimit(u.getId(), start, postsPerPage);
323         int totalMessages = u.getTotalPosts();
324         
325         // get list of forums
326
Map JavaDoc topics = new HashMap JavaDoc();
327         Map JavaDoc forums = new HashMap JavaDoc();
328         
329         for (Iterator JavaDoc iter = posts.iterator(); iter.hasNext(); ) {
330             Post p = (Post)iter.next();
331
332             if (!topics.containsKey(new Integer JavaDoc(p.getTopicId()))) {
333                 Topic t = TopicRepository.getTopic(new Topic(p.getTopicId()));
334                 
335                 if (t == null) {
336                     t = tm.selectRaw(p.getTopicId());
337                 }
338                 
339                 this.context.put("attachmentsEnabled", SecurityRepository.canAccess(
340                         SecurityConstants.PERM_ATTACHMENTS_ENABLED, Integer.toString(t.getForumId())));
341                 this.context.put("am", new AttachmentCommon(this.request, t.getForumId()));
342     
343                 topics.put(new Integer JavaDoc(t.getId()), t);
344             }
345             
346             if (!forums.containsKey(new Integer JavaDoc(p.getForumId()))) {
347                 Forum f = ForumRepository.getForum(p.getForumId());
348                 
349                 if (f == null) {
350                     // Ok, probably the user does not have permission to see this forum
351
iter.remove();
352                     totalMessages--;
353                     continue;
354                 }
355                 
356                 forums.put(new Integer JavaDoc(f.getId()), f);
357             }
358             
359             PostCommon.preparePostForDisplay(p);
360         }
361         
362         this.setTemplateName(TemplateKeys.POSTS_USER_POSTS_LIST);
363         
364         this.context.put("canDownloadAttachments", SecurityRepository.canAccess(
365                 SecurityConstants.PERM_ATTACHMENTS_DOWNLOAD));
366         this.context.put("rssEnabled", SystemGlobals.getBoolValue(ConfigKeys.RSS_ENABLED));
367         this.context.put("allCategories", ForumCommon.getAllCategoriesAndForums(false));
368         this.context.put("posts", posts);
369         this.context.put("topics", topics);
370         this.context.put("forums", forums);
371         this.context.put("u", u);
372         this.context.put("pageTitle", I18n.getMessage("PostShow.userPosts") + " " + u.getUsername());
373         
374         ViewCommon.contextToPagination(start, totalMessages, count);
375     }
376
377     public void review() throws Exception JavaDoc
378     {
379         PostDAO pm = DataAccessDriver.getInstance().newPostDAO();
380         UserDAO um = DataAccessDriver.getInstance().newUserDAO();
381         TopicDAO tm = DataAccessDriver.getInstance().newTopicDAO();
382
383         int userId = SessionFacade.getUserSession().getUserId();
384         int topicId = this.request.getIntParameter("topic_id");
385         
386         Topic topic = TopicRepository.getTopic(new Topic(topicId));
387         
388         if (topic == null) {
389             topic = tm.selectById(topicId);
390         }
391
392         if (!TopicsCommon.isTopicAccessible(topic.getForumId())) {
393             return;
394         }
395
396         int count = SystemGlobals.getIntValue(ConfigKeys.POST_PER_PAGE);
397         int start = ViewCommon.getStartPage();
398
399         Map JavaDoc usersMap = tm.topicPosters(topic.getId());
400         List JavaDoc helperList = PostCommon.topicPosts(pm, false, userId, topic.getId(), start, count);
401         Collections.reverse(helperList);
402
403         this.setTemplateName(SystemGlobals.getValue(ConfigKeys.TEMPLATE_DIR) + "/empty.htm");
404
405         this.setTemplateName(TemplateKeys.POSTS_REVIEW);
406         this.context.put("posts", helperList);
407         this.context.put("users", usersMap);
408     }
409
410     private void topicNotFound() {
411         this.setTemplateName(TemplateKeys.POSTS_TOPIC_NOT_FOUND);
412         this.context.put("message", I18n.getMessage("PostShow.TopicNotFound"));
413     }
414
415     private void postNotFound() {
416         this.setTemplateName(TemplateKeys.POSTS_POST_NOT_FOUND);
417         this.context.put("message", I18n.getMessage("PostShow.PostNotFound"));
418     }
419     
420     private void replyOnly()
421     {
422         this.setTemplateName(TemplateKeys.POSTS_REPLY_ONLY);
423         this.context.put("message", I18n.getMessage("PostShow.replyOnly"));
424     }
425     
426     private boolean isReplyOnly(int forumId) throws Exception JavaDoc
427     {
428         return !SecurityRepository.canAccess(SecurityConstants.PERM_REPLY_ONLY,
429                 Integer.toString(forumId));
430     }
431     
432     public void reply() throws Exception JavaDoc
433     {
434         this.insert();
435     }
436
437     public void insert() throws Exception JavaDoc
438     {
439         int forumId = -1;
440         
441         // If we have a topic_id, then it should be a reply
442
if (this.request.getParameter("topic_id") != null) {
443             int topicId = this.request.getIntParameter("topic_id");
444             
445             Topic t = TopicRepository.getTopic(new Topic(topicId));
446             
447             if (t == null) {
448                 t = DataAccessDriver.getInstance().newTopicDAO().selectRaw(topicId);
449                 
450                 if (t == null) {
451                     throw new ForumException("Could not find a topic with id #" + topicId);
452                 }
453             }
454             
455             forumId = t.getForumId();
456             
457             if (!TopicsCommon.isTopicAccessible(t.getForumId())) {
458                 return;
459             }
460
461             if (t.getStatus() == Topic.STATUS_LOCKED) {
462                 this.topicLocked();
463                 return;
464             }
465
466             this.context.put("topic", t);
467             this.context.put("setType", false);
468             this.context.put("pageTitle", I18n.getMessage("PostForm.reply")+" "+t.getTitle());
469         }
470         else {
471             forumId = this.request.getIntParameter("forum_id");
472
473             if (this.isReplyOnly(forumId)) {
474                 this.replyOnly();
475                 return;
476             }
477             this.context.put("setType", true);
478             this.context.put("pageTitle", I18n.getMessage("PostForm.title"));
479         }
480         
481         Forum forum = ForumRepository.getForum(forumId);
482         
483         if (forum == null) {
484             throw new ForumException("Could not find a forum with id #" + forumId);
485         }
486         
487         if (!TopicsCommon.isTopicAccessible(forumId)) {
488             return;
489         }
490         
491         if (!this.anonymousPost(forumId)
492                 || this.isForumReadonly(forumId, this.request.getParameter("topic_id") != null)) {
493             return;
494         }
495         
496         int userId = SessionFacade.getUserSession().getUserId();
497         
498         this.setTemplateName(TemplateKeys.POSTS_INSERT);
499         
500         // Attachments
501
boolean attachmentsEnabled = SecurityRepository.canAccess(
502                 SecurityConstants.PERM_ATTACHMENTS_ENABLED, Integer.toString(forumId));
503         
504         if (attachmentsEnabled && !SessionFacade.isLogged()
505                 && !SystemGlobals.getBoolValue(ConfigKeys.ATTACHMENTS_ANONYMOUS)) {
506             attachmentsEnabled = false;
507         }
508
509         this.context.put("attachmentsEnabled", attachmentsEnabled);
510         
511         if (attachmentsEnabled) {
512             QuotaLimit ql = new AttachmentCommon(this.request, forumId).getQuotaLimit(userId);
513             this.context.put("maxAttachmentsSize", new Long JavaDoc(ql != null ? ql.getSizeInBytes() : 1));
514             this.context.put("maxAttachments", SystemGlobals.getValue(ConfigKeys.ATTACHMENTS_MAX_POST));
515         }
516         
517         boolean needCaptcha = SystemGlobals.getBoolValue(ConfigKeys.CAPTCHA_POSTS);
518         
519         if (needCaptcha) {
520             SessionFacade.getUserSession().createNewCaptcha();
521         }
522         
523         this.context.put("smilies", SmiliesRepository.getSmilies());
524         this.context.put("forum", forum);
525         this.context.put("action", "insertSave");
526         this.context.put("start", this.request.getParameter("start"));
527         this.context.put("isNewPost", true);
528         this.context.put("needCaptcha", needCaptcha);
529         this.context.put("htmlAllowed",
530                 SecurityRepository.canAccess(SecurityConstants.PERM_HTML_DISABLED, Integer.toString(forumId)));
531         this.context.put("canCreateStickyOrAnnouncementTopics",
532                 SecurityRepository.canAccess(SecurityConstants.PERM_CREATE_STICKY_ANNOUNCEMENT_TOPICS));
533         this.context.put("canCreatePolls",
534                 SecurityRepository.canAccess(SecurityConstants.PERM_CREATE_POLL));
535
536         User user = DataAccessDriver.getInstance().newUserDAO().selectById(userId);
537         user.setSignature(PostCommon.processText(user.getSignature()));
538         user.setSignature(PostCommon.processSmilies(user.getSignature(), SmiliesRepository.getSmilies()));
539
540         if (this.request.getParameter("preview") != null) {
541             user.setNotifyOnMessagesEnabled(this.request.getParameter("notify") != null);
542         }
543
544         this.context.put("user", user);
545     }
546
547     public void edit() throws Exception JavaDoc {
548         this.edit(false, null);
549     }
550
551     private void edit(boolean preview, Post p) throws Exception JavaDoc
552     {
553         int userId = SessionFacade.getUserSession().getUserId();
554         int aId = SystemGlobals.getIntValue(ConfigKeys.ANONYMOUS_USER_ID);
555         boolean canAccess = false;
556
557         if (!preview) {
558             PostDAO pm = DataAccessDriver.getInstance().newPostDAO();
559             p = pm.selectById(this.request.getIntParameter("post_id"));
560
561             // The post exist?
562
if (p.getId() == 0) {
563                 this.postNotFound();
564                 return;
565             }
566         }
567
568         boolean isModerator = SecurityRepository.canAccess(SecurityConstants.PERM_MODERATION_POST_EDIT);
569         canAccess = (isModerator || p.getUserId() == userId);
570
571         if ((userId != aId) && canAccess) {
572             Topic topic = TopicRepository.getTopic(new Topic(p.getTopicId()));
573                 
574             if (topic == null) {
575                 topic = DataAccessDriver.getInstance().newTopicDAO().selectRaw(p.getTopicId());
576             }
577
578             if (!TopicsCommon.isTopicAccessible(topic.getForumId())) {
579                 return;
580             }
581
582             if (topic.getStatus() == Topic.STATUS_LOCKED && !isModerator) {
583                 this.topicLocked();
584                 return;
585             }
586
587             if (preview && this.request.getParameter("topic_type") != null) {
588                 topic.setType(this.request.getIntParameter("topic_type"));
589             }
590             
591             if (p.hasAttachments()) {
592                 this.context.put("attachments",
593                         DataAccessDriver.getInstance().newAttachmentDAO().selectAttachments(p.getId()));
594             }
595
596             Poll poll = null;
597             
598             if (topic.isVote() && topic.getFirstPostId() == p.getId()) {
599                 //it has a poll associated with the topic
600
PollDAO poolDao = DataAccessDriver.getInstance().newPollDAO();
601                 poll = poolDao.selectById(topic.getVoteId());
602             }
603             
604             this.setTemplateName(TemplateKeys.POSTS_EDIT);
605
606             this.context.put("attachmentsEnabled", SecurityRepository.canAccess(
607                     SecurityConstants.PERM_ATTACHMENTS_ENABLED, Integer.toString(p.getForumId())));
608         
609             QuotaLimit ql = new AttachmentCommon(this.request, p.getForumId()).getQuotaLimit(userId);
610             this.context.put("maxAttachmentsSize", new Long JavaDoc(ql != null ? ql.getSizeInBytes() : 1));
611             this.context.put("isEdit", true);
612             this.context.put("maxAttachments", SystemGlobals.getValue(ConfigKeys.ATTACHMENTS_MAX_POST));
613             this.context.put("smilies", SmiliesRepository.getSmilies());
614             this.context.put("forum", ForumRepository.getForum(p.getForumId()));
615             this.context.put("action", "editSave");
616             this.context.put("post", p);
617             this.context.put("setType", p.getId() == topic.getFirstPostId());
618             this.context.put("topic", topic);
619             this.context.put("poll", poll);
620             this.context.put("pageTitle", I18n.getMessage("PostShow.messageTitle") + " " + p.getSubject());
621             this.context.put("start", this.request.getParameter("start"));
622             this.context.put("htmlAllowed", SecurityRepository.canAccess(SecurityConstants.PERM_HTML_DISABLED,
623                     Integer.toString(topic.getForumId())));
624             this.context.put("canCreateStickyOrAnnouncementTopics",
625                     SecurityRepository.canAccess(SecurityConstants.PERM_CREATE_STICKY_ANNOUNCEMENT_TOPICS));
626             this.context.put("canCreatePolls",
627                     SecurityRepository.canAccess(SecurityConstants.PERM_CREATE_POLL));
628         }
629         else {
630             this.setTemplateName(TemplateKeys.POSTS_EDIT_CANNOTEDIT);
631             this.context.put("message", I18n.getMessage("CannotEditPost"));
632         }
633
634         UserDAO udao = DataAccessDriver.getInstance().newUserDAO();
635         User u = udao.selectById(userId);
636         ViewCommon.prepareUserSignature(u);
637
638         if (preview) {
639             u.setNotifyOnMessagesEnabled(this.request.getParameter("notify") != null);
640             
641             if (u.getId() != p.getUserId()) {
642                 // Probably a moderator is editing the message
643
User previewUser = udao.selectById(p.getUserId());
644                 ViewCommon.prepareUserSignature(previewUser);
645                 this.context.put("previewUser", previewUser);
646             }
647         }
648
649         this.context.put("user", u);
650     }
651     
652     public void quote() throws Exception JavaDoc
653     {
654         PostDAO pm = DataAccessDriver.getInstance().newPostDAO();
655         Post p = pm.selectById(this.request.getIntParameter("post_id"));
656         
657         if (p.getId() == 0) {
658             this.postNotFound();
659             return;
660         }
661         
662         if (p.isModerationNeeded()) {
663             this.notModeratedYet();
664             return;
665         }
666
667         if (!this.anonymousPost(p.getForumId())) {
668             return;
669         }
670
671         Topic topic = TopicRepository.getTopic(new Topic(p.getTopicId()));
672         
673         if (topic == null) {
674             topic = DataAccessDriver.getInstance().newTopicDAO().selectRaw(p.getTopicId());
675         }
676
677         if (!TopicsCommon.isTopicAccessible(topic.getForumId())) {
678             return;
679         }
680
681         if (topic.getStatus() == Topic.STATUS_LOCKED) {
682             this.topicLocked();
683             return;
684         }
685         
686         this.setTemplateName(TemplateKeys.POSTS_QUOTE);
687
688         this.context.put("forum", ForumRepository.getForum(p.getForumId()));
689         this.context.put("action", "insertSave");
690         this.context.put("post", p);
691
692         UserDAO um = DataAccessDriver.getInstance().newUserDAO();
693         User u = um.selectById(p.getUserId());
694
695         int userId = SessionFacade.getUserSession().getUserId();
696         
697         this.context.put("attachmentsEnabled", SecurityRepository.canAccess(
698                 SecurityConstants.PERM_ATTACHMENTS_ENABLED, Integer.toString(topic.getForumId())));
699         
700         QuotaLimit ql = new AttachmentCommon(this.request, topic.getForumId()).getQuotaLimit(userId);
701         this.context.put("maxAttachmentsSize", new Long JavaDoc(ql != null ? ql.getSizeInBytes() : 1));
702         
703         this.context.put("maxAttachments", SystemGlobals.getValue(ConfigKeys.ATTACHMENTS_MAX_POST));
704         this.context.put("isNewPost", true);
705         this.context.put("topic", topic);
706         this.context.put("quote", "true");
707         this.context.put("quoteUser", u.getUsername());
708         this.context.put("setType", false);
709         this.context.put("htmlAllowed", SecurityRepository.canAccess(SecurityConstants.PERM_HTML_DISABLED,
710                 Integer.toString(topic.getForumId())));
711         this.context.put("start", this.request.getParameter("start"));
712         this.context.put("user", DataAccessDriver.getInstance().newUserDAO().selectById(userId));
713         this.context.put("pageTitle", I18n.getMessage("PostForm.reply") + " " + topic.getTitle());
714         this.context.put("smilies", SmiliesRepository.getSmilies());
715     }
716
717     public void editSave() throws Exception JavaDoc
718     {
719         PostDAO postDao = DataAccessDriver.getInstance().newPostDAO();
720         PollDAO pollDao = DataAccessDriver.getInstance().newPollDAO();
721         TopicDAO topicDao = DataAccessDriver.getInstance().newTopicDAO();
722
723         Post p = postDao.selectById(this.request.getIntParameter("post_id"));
724         p = PostCommon.fillPostFromRequest(p, true);
725
726         // The user wants to preview the message before posting it?
727
if ("1".equals(this.request.getParameter("preview"))) {
728             this.context.put("preview", true);
729
730             Post postPreview = new Post(p);
731             this.context.put("postPreview", PostCommon.preparePostForDisplay(postPreview));
732
733             this.edit(true, p);
734         }
735         else {
736             AttachmentCommon attachments = new AttachmentCommon(this.request, p.getForumId());
737             
738             try {
739                 attachments.preProcess();
740             }
741             catch (AttachmentException e) {
742                 JForumExecutionContext.enableRollback();
743                 p.setText(this.request.getParameter("message"));
744                 this.context.put("errorMessage", e.getMessage());
745                 this.context.put("post", p);
746                 this.edit(false, p);
747                 return;
748             }
749             
750             Topic t = TopicRepository.getTopic(new Topic(p.getTopicId()));
751             
752             if (t == null) {
753                 t = topicDao.selectById(p.getTopicId());
754             }
755
756             if (!TopicsCommon.isTopicAccessible(t.getForumId())) {
757                 return;
758             }
759
760             if (t.getStatus() == Topic.STATUS_LOCKED
761                     && !SecurityRepository.canAccess(SecurityConstants.PERM_MODERATION_POST_EDIT)) {
762                 this.topicLocked();
763                 return;
764             }
765
766             postDao.update(p);
767             
768             // Attachments
769
attachments.editAttachments(p.getId(), p.getForumId());
770             attachments.insertAttachments(p);
771
772             // Updates the topic title
773
if (t.getFirstPostId() == p.getId()) {
774                 t.setTitle(p.getSubject());
775                 
776                 int newType = this.request.getIntParameter("topic_type");
777                 boolean changeType = SecurityRepository.canAccess(SecurityConstants.PERM_CREATE_STICKY_ANNOUNCEMENT_TOPICS)
778                     && newType != t.getType();
779                 
780                 if (changeType) {
781                     t.setType(newType);
782                 }
783
784                 // Poll
785
Poll poll = PollCommon.fillPollFromRequest();
786                 
787                 if (poll != null && !t.isVote()) {
788                     // They added a poll
789
poll.setTopicId(t.getId());
790                     
791                     if (!this.ensurePollMinimumOptions(p, poll)) {
792                         return;
793                     }
794                     
795                     pollDao.addNew(poll);
796                     t.setVoteId(poll.getId());
797
798                 }
799                 else if (poll != null) {
800                     if (!this.ensurePollMinimumOptions(p, poll)) {
801                         return;
802                     }
803                     
804                     // They edited the poll in the topic
805
Poll existing = pollDao.selectById(t.getVoteId());
806                     PollChanges changes = new PollChanges(existing, poll);
807                     
808                     if (changes.hasChanges()) {
809                         poll.setId(existing.getId());
810                         poll.setChanges(changes);
811                         pollDao.update(poll);
812                     }
813                     
814                 }
815                 else if (t.isVote()) {
816                     // They deleted the poll from the topic
817
pollDao.delete(t.getVoteId());
818                     t.setVoteId(0);
819                 }
820                 
821                 topicDao.update(t);
822                 
823                 User u = DataAccessDriver.getInstance().newUserDAO().selectById(p.getUserId());
824                 
825                 if (changeType) {
826                     TopicRepository.addTopic(t);
827                 }
828                 else {
829                     TopicRepository.updateTopic(t);
830                 }
831             }
832
833             if (this.request.getParameter("notify") == null) {
834                 topicDao.removeSubscription(p.getTopicId(), SessionFacade.getUserSession().getUserId());
835             }
836
837             String JavaDoc path = this.request.getContextPath() + "/posts/list/";
838             int start = ViewCommon.getStartPage();
839             
840             if (start > 0) {
841                 path += start + "/";
842             }
843
844             path += p.getTopicId() + SystemGlobals.getValue(ConfigKeys.SERVLET_EXTENSION) + "#" + p.getId();
845             JForumExecutionContext.setRedirect(path);
846             
847             if (SystemGlobals.getBoolValue(ConfigKeys.POSTS_CACHE_ENABLED)) {
848                 PostRepository.update(p.getTopicId(), PostCommon.preparePostForDisplay(p));
849             }
850         }
851     }
852     
853     private boolean ensurePollMinimumOptions(Post p, Poll poll) throws Exception JavaDoc
854     {
855         if (poll.getOptions().size() < 2) {
856             // It is not a valid poll, cancel the post
857
JForumExecutionContext.enableRollback();
858             p.setText(this.request.getParameter("message"));
859             p.setId(0);
860             this.context.put("errorMessage", I18n.getMessage("PostForm.needMorePollOptions"));
861             this.context.put("post", p);
862             this.context.put("poll", poll);
863             this.edit();
864             return false;
865         }
866         
867         return true;
868     }
869     
870     public void waitingModeration()
871     {
872         this.setTemplateName(TemplateKeys.POSTS_WAITING);
873         
874         int topicId = this.request.getIntParameter("topic_id");
875         String JavaDoc path = this.request.getContextPath();
876         
877         if (topicId == 0) {
878             path += "/forums/show/" + this.request.getParameter("forum_id");
879         }
880         else {
881             path += "/posts/list/" + topicId;
882         }
883         
884         this.context.put("message", I18n.getMessage("PostShow.waitingModeration",
885                 new String JavaDoc[] { path + SystemGlobals.getValue(ConfigKeys.SERVLET_EXTENSION) }));
886     }
887     
888     private void notModeratedYet()
889     {
890         this.setTemplateName(TemplateKeys.POSTS_NOT_MODERATED);
891         this.context.put("message", I18n.getMessage("PostShow.notModeratedYet"));
892     }
893
894     public void insertSave() throws Exception JavaDoc
895     {
896         int forumId = this.request.getIntParameter("forum_id");
897         boolean firstPost = false;
898
899         if (!this.anonymousPost(forumId)) {
900             SessionFacade.setAttribute(ConfigKeys.REQUEST_DUMP, this.request.dumpRequest());
901             return;
902         }
903         
904         Topic t = new Topic(-1);
905         t.setForumId(forumId);
906
907         boolean newTopic = (this.request.getParameter("topic_id") == null);
908         
909         if (!TopicsCommon.isTopicAccessible(t.getForumId())
910                 || this.isForumReadonly(t.getForumId(), newTopic)) {
911             return;
912         }
913
914         TopicDAO topicDao = DataAccessDriver.getInstance().newTopicDAO();
915         PostDAO postDao = DataAccessDriver.getInstance().newPostDAO();
916         PollDAO poolDao = DataAccessDriver.getInstance().newPollDAO();
917         ForumDAO forumDao = DataAccessDriver.getInstance().newForumDAO();
918
919         if (!newTopic) {
920             int topicId = this.request.getIntParameter("topic_id");
921             
922             t = TopicRepository.getTopic(new Topic(topicId));
923             
924             if (t == null) {
925                 t = topicDao.selectById(topicId);
926             }
927             
928             if (!TopicsCommon.isTopicAccessible(t.getForumId())) {
929                 return;
930             }
931
932             // Cannot insert new messages on locked topics
933
if (t.getStatus() == Topic.STATUS_LOCKED) {
934                 this.topicLocked();
935                 return;
936             }
937         }
938         else {
939             if (this.isReplyOnly(forumId)) {
940                 this.replyOnly();
941                 return;
942             }
943         }
944         
945         if (this.request.getParameter("topic_type") != null) {
946             t.setType(this.request.getIntParameter("topic_type"));
947             
948             if (t.getType() != Topic.TYPE_NORMAL
949                     && !SecurityRepository.canAccess(SecurityConstants.PERM_CREATE_STICKY_ANNOUNCEMENT_TOPICS)) {
950                 t.setType(Topic.TYPE_NORMAL);
951             }
952         }
953
954         UserSession us = SessionFacade.getUserSession();
955         User u = new User();
956         
957         if ("1".equals(this.request.getParameter("quick")) && SessionFacade.isLogged()) {
958             u = DataAccessDriver.getInstance().newUserDAO().selectById(us.getUserId());
959             this.request.addParameter("notify", u.isNotifyOnMessagesEnabled() ? "1" : null);
960             this.request.addParameter("attach_sig", u.getAttachSignatureEnabled() ? "1" : "0");
961         }
962         else {
963             u.setId(us.getUserId());
964             u.setUsername(us.getUsername());
965         }
966
967         // Set the Post
968
Post p = PostCommon.fillPostFromRequest();
969         
970         if (p.getText() == null || p.getText().trim().equals("")) {
971             this.insert();
972             return;
973         }
974         
975         // Check the elapsed time since the last post from the user
976
int delay = SystemGlobals.getIntValue(ConfigKeys.POSTS_NEW_DELAY);
977         
978         if (delay > 0) {
979             Long JavaDoc lastPostTime = (Long JavaDoc)SessionFacade.getAttribute(ConfigKeys.LAST_POST_TIME);
980             
981             if (lastPostTime != null) {
982                 if (System.currentTimeMillis() < (lastPostTime.longValue() + delay)) {
983                     this.context.put("post", p);
984                     this.context.put("start", this.request.getParameter("start"));
985                     this.context.put("error", I18n.getMessage("PostForm.tooSoon"));
986                     this.insert();
987                     return;
988                 }
989             }
990         }
991         
992         p.setForumId(this.request.getIntParameter("forum_id"));
993         
994         if (p.getSubject() == null || p.getSubject() == "") {
995             p.setSubject(t.getTitle());
996         }
997         
998         boolean needCaptcha = SystemGlobals.getBoolValue(ConfigKeys.CAPTCHA_POSTS);
999         
1000        if (needCaptcha) {
1001            if (!us.validateCaptchaResponse(this.request.getParameter("captcha_anwser"))) {
1002                this.context.put("post", p);
1003                this.context.put("start", this.request.getParameter("start"));
1004                this.context.put("error", I18n.getMessage("CaptchaResponseFails"));
1005                
1006                this.insert();
1007                
1008                return;
1009            }
1010        }
1011
1012        boolean preview = "1".equals(this.request.getParameter("preview"));
1013        
1014        if (!preview) { //mean users hit "submit"?
1015
AttachmentCommon attachments = new AttachmentCommon(this.request, forumId);
1016            
1017            try {
1018                attachments.preProcess();
1019            }
1020            catch (AttachmentSizeTooBigException e) {
1021                JForumExecutionContext.enableRollback();
1022                p.setText(this.request.getParameter("message"));
1023                p.setId(0);
1024                this.context.put("errorMessage", e.getMessage());
1025                this.context.put("post", p);
1026                this.insert();
1027                return;
1028            }
1029            
1030            Forum forum = ForumRepository.getForum(forumId);
1031            PermissionControl pc = SecurityRepository.get(us.getUserId());
1032
1033            // Moderators and admins don't need to have their messages moderated
1034
boolean moderate = (forum.isModerated()
1035                && !pc.canAccess(SecurityConstants.PERM_MODERATION)
1036                && !pc.canAccess(SecurityConstants.PERM_ADMINISTRATION));
1037            
1038            
1039            if (newTopic) {
1040                t.setTime(new Date JavaDoc());
1041                t.setTitle(this.request.getParameter("subject"));
1042                t.setModerated(moderate);
1043                t.setPostedBy(u);
1044                t.setFirstPostTime(ViewCommon.formatDate(t.getTime()));
1045
1046                int topicId = topicDao.addNew(t);
1047                t.setId(topicId);
1048                firstPost = true;
1049            }
1050            
1051            if (!firstPost && pc.canAccess(
1052                    SecurityConstants.PERM_REPLY_WITHOUT_MODERATION, Integer.toString(t.getForumId()))) {
1053                moderate = false;
1054            }
1055
1056            // Topic watch
1057
if (this.request.getParameter("notify") != null) {
1058                this.watch(topicDao, t.getId(), u.getId());
1059            }
1060
1061            p.setTopicId(t.getId());
1062
1063            // add a poll
1064
Poll poll = PollCommon.fillPollFromRequest();
1065            if (poll != null && newTopic) {
1066                poll.setTopicId(t.getId());
1067                
1068                if (poll.getOptions().size() < 2) {
1069                    //it is not a valid poll, cancel the post
1070
JForumExecutionContext.enableRollback();
1071                    p.setText(this.request.getParameter("message"));
1072                    p.setId(0);
1073                    this.context.put("errorMessage", I18n.getMessage("PostForm.needMorePollOptions"));
1074                    this.context.put("post", p);
1075                    this.context.put("poll", poll);
1076                    this.insert();
1077                    return;
1078                }
1079                
1080                poolDao.addNew(poll);
1081                t.setVoteId(poll.getId());
1082            }
1083
1084            // Save the remaining stuff
1085
p.setModerate(moderate);
1086            int postId = postDao.addNew(p);
1087
1088            if (newTopic) {
1089                t.setFirstPostId(postId);
1090            }
1091            
1092            if (!moderate) {
1093                t.setLastPostId(postId);
1094                t.setLastPostBy(u);
1095                t.setLastPostDate(p.getTime());
1096                t.setLastPostTime(p.getFormatedTime());
1097            }
1098            
1099            topicDao.update(t);
1100            
1101            attachments.insertAttachments(p);
1102            
1103            if (!moderate) {
1104                // Sets the url to redirect to
1105
String JavaDoc path = this.request.getContextPath() + "/posts/list/";
1106                int start = ViewCommon.getStartPage();
1107    
1108                path += this.startPage(t, start) + "/";
1109                path += t.getId() + SystemGlobals.getValue(ConfigKeys.SERVLET_EXTENSION) + "#" + postId;
1110    
1111                JForumExecutionContext.setRedirect(path);
1112                
1113                // Updates forum stats, cache and etc
1114
if (!newTopic) {
1115                    TopicsCommon.notifyUsers(t, topicDao);
1116                    t.setTotalReplies(t.getTotalReplies() + 1);
1117                }else{//notify "forum new topic" users
1118
ForumCommon.notifyUsers(forum, t, forumDao);
1119                }
1120                
1121                t.setTotalViews(t.getTotalViews() + 1);
1122                
1123                DataAccessDriver.getInstance().newUserDAO().incrementPosts(p.getUserId());
1124                
1125                TopicsCommon.updateBoardStatus(t, postId, firstPost, topicDao, forumDao);
1126                ForumRepository.updateForumStats(t, u, p);
1127                
1128                int anonymousUser = SystemGlobals.getIntValue(ConfigKeys.ANONYMOUS_USER_ID);
1129                if (u.getId() != anonymousUser) {
1130                    ((Map JavaDoc) SessionFacade.getAttribute(ConfigKeys.TOPICS_TRACKING)).put(new Integer JavaDoc(t.getId()),
1131                        new Long JavaDoc(p.getTime().getTime()));
1132                }
1133                
1134                if (SystemGlobals.getBoolValue(ConfigKeys.POSTS_CACHE_ENABLED)) {
1135                    SimpleDateFormat JavaDoc df = new SimpleDateFormat JavaDoc(SystemGlobals.getValue(ConfigKeys.DATE_TIME_FORMAT));
1136                    p.setFormatedTime(df.format(p.getTime()));
1137                    
1138                    PostRepository.append(p.getTopicId(), PostCommon.preparePostForDisplay(p));
1139                }
1140            }
1141            else {
1142                JForumExecutionContext.setRedirect(this.request.getContextPath()
1143                    + "/posts/waitingModeration/"
1144                    + (firstPost ? 0 : t.getId())
1145                    + "/" + t.getForumId()
1146                    + SystemGlobals.getValue(ConfigKeys.SERVLET_EXTENSION));
1147            }
1148            
1149            if (delay > 0) {
1150                SessionFacade.setAttribute(ConfigKeys.LAST_POST_TIME, new Long JavaDoc(System.currentTimeMillis()));
1151            }
1152        }
1153        else {
1154            this.context.put("preview", true);
1155            this.context.put("post", p);
1156            this.context.put("start", this.request.getParameter("start"));
1157
1158            Post postPreview = new Post(p);
1159            this.context.put("postPreview", PostCommon.preparePostForDisplay(postPreview));
1160
1161            this.insert();
1162        }
1163    }
1164
1165    private int startPage(Topic t, int currentStart) {
1166        int postsPerPage = SystemGlobals.getIntValue(ConfigKeys.POST_PER_PAGE);
1167
1168        int newStart = (t.getTotalReplies() + 1) / postsPerPage * postsPerPage;
1169        
1170        return (newStart > currentStart) ? newStart : currentStart;
1171    }
1172
1173    public void delete() throws Exception JavaDoc
1174    {
1175        if (!SecurityRepository.canAccess(SecurityConstants.PERM_MODERATION_POST_REMOVE)) {
1176            this.setTemplateName(TemplateKeys.POSTS_CANNOT_DELETE);
1177            this.context.put("message", I18n.getMessage("CannotRemovePost"));
1178
1179            return;
1180        }
1181
1182        // Post
1183
PostDAO pm = DataAccessDriver.getInstance().newPostDAO();
1184        Post p = pm.selectById(this.request.getIntParameter("post_id"));
1185        
1186        if (p.getId() == 0) {
1187            this.postNotFound();
1188            return;
1189        }
1190
1191        TopicDAO tm = DataAccessDriver.getInstance().newTopicDAO();
1192        Topic t = TopicRepository.getTopic(new Topic(p.getTopicId()));
1193        
1194        if (t == null) {
1195            t = tm.selectRaw(p.getTopicId());
1196        }
1197
1198        if (!TopicsCommon.isTopicAccessible(t.getForumId())) {
1199            return;
1200        }
1201
1202        pm.delete(p);
1203        DataAccessDriver.getInstance().newUserDAO().decrementPosts(p.getUserId());
1204        
1205        // Karma
1206
KarmaDAO karmaDao = DataAccessDriver.getInstance().newKarmaDAO();
1207        karmaDao.updateUserKarma(p.getUserId());
1208        
1209        // Attachments
1210
new AttachmentCommon(this.request, p.getForumId()).deleteAttachments(p.getId(), p.getForumId());
1211
1212        // It was the last remaining post in the topic?
1213
int totalPosts = tm.getTotalPosts(p.getTopicId());
1214
1215        if (totalPosts > 0) {
1216            // Topic
1217
tm.decrementTotalReplies(p.getTopicId());
1218
1219            int maxPostId = tm.getMaxPostId(p.getTopicId());
1220            if (maxPostId > -1) {
1221                tm.setLastPostId(p.getTopicId(), maxPostId);
1222            }
1223
1224            int minPostId = tm.getMinPostId(p.getTopicId());
1225            if (minPostId > -1) {
1226              tm.setFirstPostId(p.getTopicId(), minPostId);
1227            }
1228            
1229            // Forum
1230
ForumDAO fm = DataAccessDriver.getInstance().newForumDAO();
1231
1232            maxPostId = fm.getMaxPostId(p.getForumId());
1233            if (maxPostId > -1) {
1234                fm.setLastPost(p.getForumId(), maxPostId);
1235            }
1236
1237            String JavaDoc returnPath = this.request.getContextPath() + "/posts/list/";
1238
1239            int page = ViewCommon.getStartPage();
1240            
1241            if (page > 0) {
1242                int postsPerPage = SystemGlobals.getIntValue(ConfigKeys.POST_PER_PAGE);
1243
1244                if (totalPosts % postsPerPage == 0) {
1245                    page -= postsPerPage;
1246                }
1247
1248                returnPath += page + "/";
1249            }
1250
1251            JForumExecutionContext.setRedirect(returnPath
1252                + p.getTopicId()
1253                + SystemGlobals.getValue(ConfigKeys.SERVLET_EXTENSION));
1254            
1255            // Update the cache
1256
t = tm.selectById(t.getId());
1257            TopicRepository.updateTopic(t);
1258        }
1259        else {
1260            // Ok, all posts were removed. Time to say goodbye
1261
TopicsCommon.deleteTopic(p.getTopicId(), p.getForumId(), false);
1262
1263            JForumExecutionContext.setRedirect(this.request.getContextPath()
1264                + "/forums/show/"
1265                + p.getForumId()
1266                + SystemGlobals.getValue(ConfigKeys.SERVLET_EXTENSION));
1267        }
1268        
1269        PostRepository.remove(t.getId(), p.getId());
1270        ForumRepository.reloadForum(p.getForumId());
1271    }
1272
1273    private void watch(TopicDAO tm, int topicId, int userId) throws Exception JavaDoc {
1274        if (!tm.isUserSubscribed(topicId, userId)) {
1275            tm.subscribeUser(topicId, userId);
1276        }
1277    }
1278
1279    public void watch() throws Exception JavaDoc {
1280        int topicId = this.request.getIntParameter("topic_id");
1281        int userId = SessionFacade.getUserSession().getUserId();
1282
1283        this.watch(DataAccessDriver.getInstance().newTopicDAO(), topicId, userId);
1284        this.list();
1285    }
1286
1287    public void unwatch() throws Exception JavaDoc {
1288        if (SessionFacade.isLogged()) {
1289            int topicId = this.request.getIntParameter("topic_id");
1290            int userId = SessionFacade.getUserSession().getUserId();
1291            int start = ViewCommon.getStartPage();
1292
1293            DataAccessDriver.getInstance().newTopicDAO().removeSubscription(topicId, userId);
1294
1295            String JavaDoc returnPath = this.request.getContextPath() + "/posts/list/";
1296            
1297            if (start > 0) {
1298                returnPath += start + "/";
1299            }
1300
1301            returnPath += topicId + SystemGlobals.getValue(ConfigKeys.SERVLET_EXTENSION);
1302
1303            this.setTemplateName(TemplateKeys.POSTS_UNWATCH);
1304            this.context.put("pageTitle", I18n.getMessage("PostShow.unwatch"));
1305            this.context.put("message", I18n.getMessage("ForumBase.unwatched", new String JavaDoc[] { returnPath }));
1306        }
1307        else {
1308            this.setTemplateName(ViewCommon.contextToLogin());
1309        }
1310    }
1311    
1312    public void downloadAttach() throws Exception JavaDoc
1313    {
1314        if ((SecurityRepository.canAccess(SecurityConstants.PERM_ATTACHMENTS_ENABLED) &&
1315                !SecurityRepository.canAccess(SecurityConstants.PERM_ATTACHMENTS_DOWNLOAD))
1316                || (!SessionFacade.isLogged() && !SystemGlobals.getBoolValue(ConfigKeys.ATTACHMENTS_ANONYMOUS))) {
1317            this.setTemplateName(TemplateKeys.POSTS_CANNOT_DOWNLOAD);
1318            this.context.put("message", I18n.getMessage("Attachments.featureDisabled"));
1319            return;
1320        }
1321        
1322        int id = this.request.getIntParameter("attach_id");
1323        
1324        AttachmentDAO am = DataAccessDriver.getInstance().newAttachmentDAO();
1325        Attachment a = am.selectAttachmentById(id);
1326        
1327        String JavaDoc filename = SystemGlobals.getValue(ConfigKeys.ATTACHMENTS_STORE_DIR)
1328            + "/"
1329            + a.getInfo().getPhysicalFilename();
1330        
1331        if (!new File JavaDoc(filename).exists()) {
1332            this.setTemplateName(TemplateKeys.POSTS_ATTACH_NOTFOUND);
1333            this.context.put("message", I18n.getMessage("Attachments.notFound"));
1334            return;
1335        }
1336        
1337        a.getInfo().setDownloadCount(a.getInfo().getDownloadCount() + 1);
1338        am.updateAttachment(a);
1339        
1340        FileInputStream JavaDoc fis = new FileInputStream JavaDoc(filename);
1341        OutputStream JavaDoc os = response.getOutputStream();
1342        
1343        if(am.isPhysicalDownloadMode(a.getInfo().getExtension().getExtensionGroupId())) {
1344            this.response.setContentType("application/octet-stream");
1345        }
1346        else {
1347            this.response.setContentType(a.getInfo().getMimetype());
1348        }
1349        
1350        if (this.request.getHeader("User-Agent").indexOf("Firefox") != -1) {
1351            this.response.setHeader("Content-Disposition", "attachment; filename=\""
1352                + new String JavaDoc(a.getInfo().getRealFilename().getBytes(SystemGlobals.getValue(ConfigKeys.ENCODING)),
1353                    SystemGlobals.getValue(ConfigKeys.DEFAULT_CONTAINER_ENCODING)) + "\";");
1354        }
1355        else {
1356            this.response.setHeader("Content-Disposition", "attachment; filename=\""
1357                + ViewCommon.toUtf8String(a.getInfo().getRealFilename()) + "\";");
1358        }
1359        
1360        this.response.setContentLength((int)a.getInfo().getFilesize());
1361        
1362        int c = 0;
1363        byte[] b = new byte[4096];
1364        while ((c = fis.read(b)) != -1) {
1365            os.write(b, 0, c);
1366        }
1367        
1368        fis.close();
1369        os.close();
1370        
1371        JForumExecutionContext.enableCustomContent(true);
1372    }
1373    
1374    private void topicLocked() {
1375        this.setTemplateName(TemplateKeys.POSTS_TOPIC_LOCKED);
1376        this.context.put("message", I18n.getMessage("PostShow.topicLocked"));
1377    }
1378    
1379    public void listSmilies()
1380    {
1381        this.setTemplateName(SystemGlobals.getValue(ConfigKeys.TEMPLATE_DIR) + "/empty.htm");
1382        this.setTemplateName(TemplateKeys.POSTS_LIST_SMILIES);
1383        this.context.put("smilies", SmiliesRepository.getSmilies());
1384    }
1385
1386    private boolean isForumReadonly(int forumId, boolean isReply) throws Exception JavaDoc {
1387        if (!SecurityRepository.canAccess(SecurityConstants.PERM_READ_ONLY_FORUMS, Integer.toString(forumId))) {
1388            if (isReply) {
1389                this.list();
1390            }
1391            else {
1392                JForumExecutionContext.setRedirect(this.request.getContextPath() + "/forums/show/" + forumId
1393                        + SystemGlobals.getValue(ConfigKeys.SERVLET_EXTENSION));
1394            }
1395
1396            return true;
1397        }
1398
1399        return false;
1400    }
1401
1402    private boolean anonymousPost(int forumId) throws Exception JavaDoc {
1403        // Check if anonymous posts are allowed
1404
if (!SessionFacade.isLogged()
1405                && !SecurityRepository.canAccess(SecurityConstants.PERM_ANONYMOUS_POST, Integer.toString(forumId))) {
1406            this.setTemplateName(ViewCommon.contextToLogin());
1407
1408            return false;
1409        }
1410
1411        return true;
1412    }
1413}
1414
Popular Tags