KickJava   Java API By Example, From Geeks To Geeks.

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


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: Apr 24, 2003 / 10:15:07 PM
40  * The JForum Project
41  * http://www.jforum.net
42  */

43 package net.jforum.view.forum;
44
45 import java.text.SimpleDateFormat JavaDoc;
46 import java.util.GregorianCalendar JavaDoc;
47 import java.util.HashMap JavaDoc;
48 import java.util.Iterator JavaDoc;
49 import java.util.List JavaDoc;
50 import java.util.Map JavaDoc;
51
52 import net.jforum.Command;
53 import net.jforum.JForumExecutionContext;
54 import net.jforum.SessionFacade;
55 import net.jforum.dao.DataAccessDriver;
56 import net.jforum.dao.ForumDAO;
57 import net.jforum.dao.ModerationDAO;
58 import net.jforum.dao.SearchData;
59 import net.jforum.entities.Forum;
60 import net.jforum.entities.MostUsersEverOnline;
61 import net.jforum.entities.Topic;
62 import net.jforum.entities.UserSession;
63 import net.jforum.repository.ForumRepository;
64 import net.jforum.repository.SecurityRepository;
65 import net.jforum.security.SecurityConstants;
66 import net.jforum.util.I18n;
67 import net.jforum.util.preferences.ConfigKeys;
68 import net.jforum.util.preferences.SystemGlobals;
69 import net.jforum.util.preferences.TemplateKeys;
70 import net.jforum.view.admin.ModerationAction;
71 import net.jforum.view.forum.common.ForumCommon;
72 import net.jforum.view.forum.common.PostCommon;
73 import net.jforum.view.forum.common.TopicsCommon;
74 import net.jforum.view.forum.common.ViewCommon;
75 /**
76  * @author Rafael Steil
77  * @version $Id: ForumAction.java,v 1.51 2006/02/07 14:17:37 rafaelsteil Exp $
78  */

79 public class ForumAction extends Command
80 {
81     /**
82      * List all the forums (first page of forum index)?
83      */

84     public void list() throws Exception JavaDoc
85     {
86         this.setTemplateName(TemplateKeys.FORUMS_LIST);
87         
88         this.context.put("allCategories", ForumCommon.getAllCategoriesAndForums(true));
89         this.context.put("topicsPerPage", new Integer JavaDoc(SystemGlobals.getIntValue(ConfigKeys.TOPICS_PER_PAGE)));
90         this.context.put("rssEnabled", SystemGlobals.getBoolValue(ConfigKeys.RSS_ENABLED));
91         
92         this.context.put("totalMessages", I18n.getMessage("ForumListing.totalMessagesInfo",
93                         new Object JavaDoc[] {new Integer JavaDoc( ForumRepository.getTotalMessages() )}));
94         
95         this.context.put("totalUsers", I18n.getMessage("ForumListing.registeredUsers",
96                 new Object JavaDoc[] { ForumRepository.totalUsers() }));
97         this.context.put("lastUser", ForumRepository.lastRegisteredUser());
98         
99         SimpleDateFormat JavaDoc df = new SimpleDateFormat JavaDoc(SystemGlobals.getValue(ConfigKeys.DATE_TIME_FORMAT));
100         GregorianCalendar JavaDoc gc = new GregorianCalendar JavaDoc();
101         this.context.put("now", df.format(gc.getTime()));
102         
103         this.context.put("lastVisit", df.format(SessionFacade.getUserSession().getLastVisit()));
104         this.context.put("fir", new ForumRepository());
105         
106         // Online Users
107
this.context.put("totalOnlineUsers", new Integer JavaDoc(SessionFacade.size()));
108         int aid = SystemGlobals.getIntValue(ConfigKeys.ANONYMOUS_USER_ID);
109     
110         List JavaDoc onlineUsersList = SessionFacade.getLoggedSessions();
111         
112         // Check for an optional language parameter
113
UserSession currentUser = SessionFacade.getUserSession();
114         
115         if (currentUser.getUserId() == aid) {
116             String JavaDoc lang = this.request.getParameter("lang");
117             
118             if (lang != null && I18n.languageExists(lang)) {
119                 currentUser.setLang(lang);
120             }
121         }
122
123         // If there are only guest users, then just register
124
// a single one. In any other situation, we do not
125
// show the "guest" username
126
if (onlineUsersList.size() == 0) {
127             UserSession us = new UserSession();
128             
129             us.setUserId(aid);
130             us.setUsername(I18n.getMessage("Guest"));
131             
132             onlineUsersList.add(us);
133         }
134         
135         int registeredSize = SessionFacade.registeredSize();
136         int anonymousSize = SessionFacade.anonymousSize();
137         int totalUsers = registeredSize + anonymousSize;
138         
139         this.context.put("userSessions", onlineUsersList);
140         this.context.put("usersOnline", I18n.getMessage("ForumListing.numberOfUsersOnline",
141             new Object JavaDoc[] {
142                        new Integer JavaDoc(totalUsers),
143                        new Integer JavaDoc(registeredSize),
144                        new Integer JavaDoc(anonymousSize)
145             }));
146         
147         // Most users ever online
148
MostUsersEverOnline mostUsersEverOnline = ForumRepository.getMostUsersEverOnline();
149         
150         if (totalUsers > mostUsersEverOnline.getTotal()) {
151             mostUsersEverOnline.setTotal(totalUsers);
152             mostUsersEverOnline.setTimeInMillis(System.currentTimeMillis());
153
154             ForumRepository.updateMostUsersEverOnline(mostUsersEverOnline);
155         }
156         
157         this.context.put("mostUsersEverOnline", I18n.getMessage("ForumListing.mostUsersEverOnline",
158                 new String JavaDoc[] { Integer.toString(mostUsersEverOnline.getTotal()), mostUsersEverOnline.getDate() }));
159     }
160     
161     public void moderation() throws Exception JavaDoc
162     {
163         this.context.put("openModeration", true);
164         this.show();
165     }
166
167     /**
168      * Display all topics in a forum
169      * @throws Exception
170      */

171     public void show() throws Exception JavaDoc
172     {
173         int forumId = this.request.getIntParameter("forum_id");
174         ForumDAO fm = DataAccessDriver.getInstance().newForumDAO();
175         
176         // The user can access this forum?
177
Forum forum = ForumRepository.getForum(forumId);
178         
179         if (forum == null || !ForumRepository.isCategoryAccessible(forum.getCategoryId())) {
180             new ModerationHelper().denied(I18n.getMessage("ForumListing.denied"));
181             return;
182         }
183         
184         int start = ViewCommon.getStartPage();
185         
186         List JavaDoc tmpTopics = TopicsCommon.topicsByForum(forumId, start);
187         
188         this.setTemplateName(TemplateKeys.FORUMS_SHOW);
189         
190         // Moderation
191
boolean canApproveMessages = (SessionFacade.isLogged()
192             && SessionFacade.getUserSession().isModerator(forumId)
193             && SecurityRepository.canAccess(SecurityConstants.PERM_MODERATION_APPROVE_MESSAGES));
194         
195         Map JavaDoc topicsToApprove = new HashMap JavaDoc();
196         
197         if (canApproveMessages) {
198             ModerationDAO mdao = DataAccessDriver.getInstance().newModerationDAO();
199             topicsToApprove = mdao.topicsByForum(forumId);
200             this.context.put("postFormatter", PostCommon.getInstance());
201         }
202
203         this.context.put("topicsToApprove", topicsToApprove);
204         
205         this.context.put("attachmentsEnabled", SecurityRepository.canAccess(SecurityConstants.PERM_ATTACHMENTS_ENABLED,
206                 Integer.toString(forumId))
207                 || SecurityRepository.canAccess(SecurityConstants.PERM_ATTACHMENTS_DOWNLOAD));
208         
209         this.context.put("topics", TopicsCommon.prepareTopics(tmpTopics));
210         this.context.put("allCategories", ForumCommon.getAllCategoriesAndForums(false));
211         this.context.put("forum", forum);
212         this.context.put("rssEnabled", SystemGlobals.getBoolValue(ConfigKeys.RSS_ENABLED));
213         this.context.put("pageTitle", forum.getName());
214         this.context.put("canApproveMessages", canApproveMessages);
215         this.context.put("replyOnly", !SecurityRepository.canAccess(SecurityConstants.PERM_REPLY_ONLY,
216                 Integer.toString(forum.getId())));
217
218         this.context.put("readonly", !SecurityRepository.canAccess(SecurityConstants.PERM_READ_ONLY_FORUMS,
219                 Integer.toString(forumId)));
220         
221         this.context.put("watching", fm.isUserSubscribed(forumId, SessionFacade.getUserSession().getUserId()));
222         
223         // Pagination
224
int topicsPerPage = SystemGlobals.getIntValue(ConfigKeys.TOPICS_PER_PAGE);
225         int postsPerPage = SystemGlobals.getIntValue(ConfigKeys.POST_PER_PAGE);
226         int totalTopics = ForumRepository.getTotalTopics(forumId);
227         
228         ViewCommon.contextToPagination(start, totalTopics, topicsPerPage);
229         this.context.put("postsPerPage", new Integer JavaDoc(postsPerPage));
230
231         TopicsCommon.topicListingBase();
232     }
233
234     // Make an URL to some action
235
private String JavaDoc makeRedirect(String JavaDoc action)
236     {
237         String JavaDoc path = this.request.getContextPath() + "/forums/" + action + "/";
238         String JavaDoc thisPage = this.request.getParameter("start");
239         
240         if (thisPage != null && !thisPage.equals("0")) {
241             path += thisPage + "/";
242         }
243         
244         String JavaDoc forumId = this.request.getParameter("forum_id");
245         
246         if (forumId == null) {
247             forumId = this.request.getParameter("persistData");
248         }
249
250         path += forumId + SystemGlobals.getValue(ConfigKeys.SERVLET_EXTENSION);
251         
252         return path;
253     }
254     
255     // Mark all topics as read
256
public void readAll() throws Exception JavaDoc
257     {
258         SearchData sd = new SearchData();
259         sd.setTime(SessionFacade.getUserSession().getLastVisit());
260         
261         String JavaDoc forumId = this.request.getParameter("forum_id");
262         if (forumId != null) {
263             sd.setForumId(Integer.parseInt(forumId));
264         }
265         
266         List JavaDoc allTopics = DataAccessDriver.getInstance().newSearchDAO().search(sd);
267         for (Iterator JavaDoc iter = allTopics.iterator(); iter.hasNext(); ) {
268             Topic t = (Topic)iter.next();
269             
270             ((Map JavaDoc)SessionFacade.getAttribute(ConfigKeys.TOPICS_TRACKING)).put(new Integer JavaDoc(t.getId()),
271                 new Long JavaDoc(t.getLastPostDate().getTime()));
272         }
273         
274         if (forumId != null) {
275             JForumExecutionContext.setRedirect(this.makeRedirect("show"));
276         }
277         else {
278             JForumExecutionContext.setRedirect(this.request.getContextPath() + "/forums/list"
279                 + SystemGlobals.getValue(ConfigKeys.SERVLET_EXTENSION));
280         }
281     }
282     
283     // Messages since last visit
284
public void newMessages() throws Exception JavaDoc
285     {
286         this.request.addParameter("post_time", Long.toString(SessionFacade.getUserSession().getLastVisit().getTime()));
287         this.request.addParameter("clean", "true");
288         this.request.addParameter("sort_by", "t." + SystemGlobals.getValue(ConfigKeys.TOPIC_TIME_FIELD));
289         this.request.addParameter("sort_dir", "DESC");
290         
291         new SearchAction(this.request, this.response, this.context).search();
292         this.setTemplateName(TemplateKeys.SEARCH_NEW_MESSAGES);
293     }
294     
295     public void approveMessages() throws Exception JavaDoc
296     {
297         if (SessionFacade.getUserSession().isModerator(this.request.getIntParameter("forum_id"))) {
298             new ModerationAction(this.context, this.request).doSave();
299         }
300         
301         JForumExecutionContext.setRedirect(this.request.getContextPath()
302             + "/forums/show/" + this.request.getParameter("forum_id")
303             + SystemGlobals.getValue(ConfigKeys.SERVLET_EXTENSION));
304     }
305     
306     /**
307      * Action when users click on "watch this forum"
308      * It gets teh forum_id and userId, and put them into a watch_forum table in the database;
309      * To do: may need change other codes to "create/update" the new table.
310      *
311      * @throws Exception
312      */

313     public void watchForum() throws Exception JavaDoc {
314         int forumId = this.request.getIntParameter("forum_id");
315         int userId = SessionFacade.getUserSession().getUserId();
316
317         this.watchForum(DataAccessDriver.getInstance().newForumDAO(), forumId, userId);
318
319         JForumExecutionContext.setRedirect(this.redirectLinkToShowAction(forumId));
320     }
321     
322     private String JavaDoc redirectLinkToShowAction(int forumId)
323     {
324         int start = ViewCommon.getStartPage();
325         
326         return this.request.getContextPath()
327             + "/forums/show/"
328             + (start > 0 ? start + "/" : "")
329             + forumId
330             + SystemGlobals.getValue(ConfigKeys.SERVLET_EXTENSION);
331     }
332     
333     /**
334      *
335      * @param dao
336      * @param topicId
337      * @param userId
338      * @throws Exception
339      */

340     private void watchForum(ForumDAO dao, int forumId, int userId) throws Exception JavaDoc {
341         if (SessionFacade.isLogged() && !dao.isUserSubscribed(forumId, userId)) {
342             dao.subscribeUser(forumId, userId);
343         }
344     }
345     
346     /**
347      * Unwatch the forum watched.
348      * @throws Exception
349      */

350     public void unwatchForum() throws Exception JavaDoc{
351         if (SessionFacade.isLogged()) {
352             int forumId = this.request.getIntParameter("forum_id");
353             int userId = SessionFacade.getUserSession().getUserId();
354
355             DataAccessDriver.getInstance().newForumDAO().removeSubscription(forumId, userId);
356             
357             String JavaDoc returnPath = this.redirectLinkToShowAction(forumId);
358             
359             this.setTemplateName(TemplateKeys.POSTS_UNWATCH);
360             this.context.put("message", I18n.getMessage("ForumBase.forumUnwatched", new String JavaDoc[] { returnPath }));
361         }
362         else {
363             this.setTemplateName(ViewCommon.contextToLogin());
364         }
365     }
366 }
367
Popular Tags