KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jboss > portlet > forums > ForumsPortlet


1 /*****************************************
2  * *
3  * JBoss Portal: The OpenSource Portal *
4  * *
5  * Forums JBoss Portlet *
6  * *
7  * Distributable under GPL license. *
8  * See terms of license at gnu.org. *
9  * *
10  *****************************************/

11 package org.jboss.portlet.forums;
12
13 import org.jboss.portal.common.command.CommandException;
14 import org.jboss.portal.common.command.filter.CommandFilter;
15 import org.jboss.portal.common.command.filter.CompositeFilter;
16 import org.jboss.portal.common.command.filter.ExecuteFilter;
17 import org.jboss.portal.common.command.result.Result;
18 import org.jboss.portal.common.command.result.ResultType;
19 import org.jboss.portal.common.context.DelegateContext;
20 import org.jboss.portal.common.util.ProxyInfo;
21 import org.jboss.portal.core.model.User;
22 import org.jboss.portal.core.modules.ModuleException;
23 import org.jboss.portal.core.modules.RoleModule;
24 import org.jboss.portal.core.modules.UserModule;
25 import org.jboss.portal.core.servlet.jsp.PortalJsp;
26 import org.jboss.portal.format.render.bbcodehtml.ToHTMLConfig;
27 import org.jboss.portal.format.render.bbcodehtml.ToHTMLRenderer;
28 import org.jboss.portal.format.util.CLLoader;
29 import org.jboss.portlet.forums.commands.CommandConstants;
30 import org.jboss.portlet.forums.commands.admin.OrderCategoryCommand;
31 import org.jboss.portlet.forums.commands.admin.CreateCategoryCommand;
32 import org.jboss.portlet.forums.commands.admin.CreateForumCommand;
33 import org.jboss.portlet.forums.commands.admin.OrderForumCommand;
34 import org.jboss.portlet.forums.commands.admin.DeleteMoveCategoryCommand;
35 import org.jboss.portlet.forums.commands.admin.DeleteForumCommand;
36 import org.jboss.portlet.forums.commands.admin.DeleteMoveForumCommand;
37 import org.jboss.portlet.forums.commands.admin.UpdateCategoryCommand;
38 import org.jboss.portlet.forums.commands.admin.UpdateForumCommand;
39 import org.jboss.portlet.forums.commands.post.EditPostCommand;
40 import org.jboss.portlet.forums.commands.post.ForumCommand;
41 import org.jboss.portlet.forums.commands.post.NewTopicCommand;
42 import org.jboss.portlet.forums.commands.post.ReplyCommand;
43 import org.jboss.portlet.forums.impl.ForumsModuleImpl;
44 import org.jboss.portlet.forums.interceptors.FloodControlInterceptor;
45 import org.jboss.portlet.forums.interceptors.NotificationInterceptor;
46
47 import org.jboss.portlet.forums.properties.TCCLXProperties;
48 import org.jboss.portlet.forums.theme.FolderType;
49 import org.jboss.portlet.forums.theme.ForumsTheme;
50 import org.jboss.portlet.forums.action.Action;
51 import org.jboss.portlet.forums.action.ProcessCommandAction;
52 import org.jboss.portlet.forums.action.ForumAction;
53 import org.jboss.portlet.forums.action.TopicAction;
54 import org.jboss.portlet.forums.action.EditPostAction;
55 import org.jboss.portlet.forums.action.ReplyAction;
56 import org.jboss.portlet.forums.action.NewTopicAction;
57 import org.jboss.portlet.forums.action.PostAction;
58 import org.jboss.portlet.forums.model.Post;
59 import org.jboss.portlet.forums.model.Forum;
60 import org.jboss.portlet.forums.model.Category;
61 import org.jboss.portlet.forums.model.Message;
62 import org.jboss.portlet.forums.model.Poster;
63 import org.jboss.portlet.forums.model.AuthType;
64 import org.jboss.portlet.forums.model.Topic;
65 import org.jboss.portlet.forums.model.ForumWatch;
66 import org.jboss.portlet.forums.model.TopicWatch;
67 import org.jboss.portlet.forums.helper.ForumsTools;
68 import org.jboss.portlet.forums.helper.SimpleDateFormatPool;
69 import org.jboss.portlet.forums.helper.Goto;
70 import org.jboss.portlet.forums.helper.IndexIterator;
71 import org.jboss.portlet.forums.helper.GotoWithOffset;
72 import org.jboss.portlet.JBossPortlet;
73 import org.jboss.portlet.JBossRenderRequest;
74 import org.jboss.portlet.JBossRenderResponse;
75 import org.jboss.portlet.JBossActionRequest;
76 import org.jboss.portlet.JBossActionResponse;
77 import org.jboss.util.collection.CompoundIterator;
78
79 import javax.portlet.PortletException;
80 import javax.portlet.PortletRequestDispatcher;
81 import javax.portlet.PortletURL;
82 import javax.portlet.WindowState;
83 import java.io.IOException JavaDoc;
84 import java.io.PrintWriter JavaDoc;
85 import java.io.StringWriter JavaDoc;
86 import java.util.ResourceBundle JavaDoc;
87 import java.util.Iterator JavaDoc;
88 import java.util.Date JavaDoc;
89 import java.util.List JavaDoc;
90 import java.util.Calendar JavaDoc;
91 import java.util.HashSet JavaDoc;
92 import java.util.Set JavaDoc;
93 import java.util.Collection JavaDoc;
94
95 /**
96  * @author <a HREF="mailto:theute@jboss.org">Thomas Heute</a>
97  * @author <a HREF="mailto:julien@jboss.org">Julien Viet</a>
98  * @version $Revision: 1.22 $
99  */

100 public class ForumsPortlet
101    extends JBossPortlet
102    implements ForumsConstants
103 {
104    private UserModule userModule;
105
106    private RoleModule roleModule;
107
108    private ForumsModule forumsModule;
109
110    private final String JavaDoc OP_MAIN = "main";
111
112    public static final String JavaDoc OP_SHOWFORUM = "showForum";
113
114    private final String JavaDoc OP_POSTING = "showPosting";
115
116    public final static String JavaDoc OP_SHOWTOPIC = "showTopic";
117
118    public static final String JavaDoc OP_SHOWADMINFORUMS = "showAdminForums";
119
120    private final String JavaDoc OP_SHOWADDEDITFORUM = "showAddEditForum";
121
122    private final String JavaDoc OP_SHOWEDITCATEGORY = "showEditCategory";
123
124    private final String JavaDoc OP_SHOWDELETEFORUM = "showDeleteForum";
125
126    private final String JavaDoc OP_CONFIRM = "showConfirm";
127
128    private final String JavaDoc OP_SHOWWATCHEDTOPICS = "showWatchedTopics";
129
130    private final String JavaDoc OP_SHOWWATCHEDFORUMS = "showWatchedForums";
131
132    private ForumsTheme theme;
133
134    // Interceptors
135
private CompositeFilter compositeInterceptor;
136
137    // private final ResourceCacheInvalidatorInterceptor resourceInterceptor;
138
// private final IndexInterceptor indexInterceptor;
139
private NotificationInterceptor notificationInterceptor;
140
141    private FloodControlInterceptor floodControlInterceptor;
142
143    private ExecuteFilter executeInterceptor;
144
145    private CommandFilter chain;
146
147    private ToHTMLRenderer toHTMLRenderer;
148
149    private ProxyInfo proxyInfo;
150
151    /**
152     * Initialization method of the portlet
153     *
154     * @throws PortletException DOCUMENT_ME
155     */

156    public void init() throws PortletException
157    {
158       super.init();
159       forumsModule = new ForumsModuleImpl();
160       getPortletContext().setAttribute("forumsModule", forumsModule);
161
162       // Define the chain of interceptors
163
chain = compositeInterceptor = new CompositeFilter();
164
165       // resourceInterceptor = new ResourceCacheInvalidatorInterceptor();
166
// indexInterceptor = new IndexInterceptor();
167
notificationInterceptor = new NotificationInterceptor(this, forumsModule);
168       notificationInterceptor.setFrom(getPortletConfig().getInitParameter("fromAddress"));
169
170       floodControlInterceptor = new FloodControlInterceptor();
171       String JavaDoc floodInterval = getPortletConfig().getInitParameter("floodInterval");
172       if (floodInterval != null)
173       {
174          int floodIntervalInt = Integer.parseInt(floodInterval);
175          floodControlInterceptor.setFloodInterval(floodIntervalInt);
176       }
177
178       executeInterceptor = new ExecuteFilter();
179
180       // compositeInterceptor.setNext(resourceInterceptor);
181
// resourceInterceptor.setNext(indexInterceptor);
182
// indexInterceptor.setNext(notificationInterceptor);
183
compositeInterceptor.setNext(notificationInterceptor);
184       notificationInterceptor.setNext(floodControlInterceptor);
185       floodControlInterceptor.setNext(executeInterceptor);
186
187       /*
188        try
189        {
190        userModule = (UserModule) new InitialContext()
191        .lookup(ModuleConstants.USERMODULE_JNDINAME);
192        roleModule = (RoleModule) new InitialContext()
193        .lookup(ModuleConstants.ROLEMODULE_JNDINAME);
194        }
195        catch (NamingException e)
196        {
197        throw new PortletException(e);
198        }
199        */

200       // Start the theme
201
theme = new ForumsTheme();
202       try
203       {
204          // start theme
205
theme.setExtendedProperties(new TCCLXProperties(ForumsConstants.THEMENAME, "theme.properties"));
206          theme.start();
207       }
208       catch (IOException JavaDoc e)
209       {
210          throw new PortletException("Cannot start the forums theme, can't read template files", e);
211       }
212       catch (Exception JavaDoc e)
213       {
214          throw new PortletException("Cannot start the forums theme", e);
215       }
216
217       // Create the HTMLRenderer for BBCode
218
String JavaDoc location = "org/jboss/portal/format/template";
219       ToHTMLConfig config = new ToHTMLConfig();
220       config.setLoader(new CLLoader(location));
221       toHTMLRenderer = new ToHTMLRenderer(config);
222
223       // Preferences proxy
224
/*
225        Class proxyClass = Proxy.getProxyClass(Thread.currentThread().getContextClassLoader(), new Class[]{PreferencesProxy.class});
226        try
227        {
228        proxyInfo = new ProxyInfo(proxyClass);
229        }
230        catch (Exception e1)
231        {
232        throw new PortletException();
233        }
234        */

235    }
236
237    public String JavaDoc getDefaultOperation()
238    {
239       return OP_MAIN;
240    }
241
242    /**
243     * doEdit Portlet method
244     *
245     * @param req Portlet render request
246     * @param resp Portlet response request
247     * @throws PortletException For any unexpected exception
248     * @throws IOException If cannot write HTML chunk
249     */

250    protected void doEdit(JBossRenderRequest req, JBossRenderResponse resp)
251       throws PortletException, IOException JavaDoc
252    {
253    }
254
255    /**
256     * doView Portlet method
257     *
258     * @param req Portlet render request
259     * @param resp Portlet response request
260     * @throws PortletException For any unexpected exception
261     * @throws IOException If cannot write HTML chunk
262     */

263    protected void doView(JBossRenderRequest req, JBossRenderResponse resp)
264       throws PortletException, IOException JavaDoc
265    {
266       ResourceBundle JavaDoc bundle = getResourceBundle(req.getLocale());
267
268       resp.setContentType("text/html");
269       PrintWriter JavaDoc writer = resp.getWriter();
270       writer.write("<div class=\"bb\">");
271       String JavaDoc op = req.getParameters().get(getOperationName(),
272          getDefaultOperation());
273       if (req.getWindowState() != WindowState.MAXIMIZED)
274       {
275          writer.write("<table width=\"100%\" cellpadding=\"2\" cellspacing=\"2\"><tr class=\"portlet-section-body\">");
276
277          // Window is is normal mode
278
// Check if the user is an administrator
279
boolean isAdmin = req.hasPermission("Admin");
280          if (isAdmin)
281          {
282             writer.write("<td width=\"50%\" align=\"center\" class=\"portlet-menu-item\">");
283
284             // Create a link to the administration interface
285
PortletURL adminURL = resp.createRenderURL();
286             adminURL.setParameter("op", "" + OP_SHOWADMINFORUMS);
287             adminURL.setWindowState(WindowState.MAXIMIZED);
288             writer.write("<a HREF=\"" + adminURL.toString() + "\">"
289                + "<img border=\"0\" SRC=\"" + req.getContextPath() + "/subSilver/images/icon_forums_admin.gif\"><br>"
290                + bundle.getString("Admin_panel") + "</a>");
291             writer.write("</td>");
292             writer.write("<td width=\"50%\" align=\"center\" class=\"portlet-menu-item\">");
293          }
294          else
295          {
296             writer.write("<td align=\"center\" class=\"portlet-menu-item\">");
297          }
298
299          //Create a link to the forum index
300
PortletURL showForumsURL = resp.createRenderURL();
301          showForumsURL.setWindowState(WindowState.MAXIMIZED);
302          showForumsURL.setParameter("op", "" + OP_MAIN);
303          writer.write("<a HREF=\"" + showForumsURL.toString() + "\">"
304             + "<img border=\"0\" SRC=\"" + req.getContextPath() + "/subSilver/images/icon_forums.gif" + "\"><br>"
305             + bundle.getString("Main_index") + "</a>");
306          writer.write("</td></tr></table>");
307       }
308       else
309       {
310          DelegateContext root = new DelegateContext();
311          if (req.getUser() != null)
312          {
313             root.next("switch_user_logged_in");
314          }
315
316          req.setAttribute(PortalJsp.CTX_REQUEST, root);
317          PortletRequestDispatcher rdisp = getPortletContext()
318             .getRequestDispatcher("/WEB-INF/subSilver/jsp/small_header.jsp");
319          rdisp.include(req, resp);
320
321          if (OP_MAIN.equals(op))
322          {
323             // Forum index
324
resp.setTitle("Forums");
325             req.setAttribute(PortalJsp.CTX_REQUEST, fillShowIndexContext(req,
326                resp, root));
327
328             boolean isAdmin = req.hasPermission("Admin");
329             if (isAdmin)
330             {
331                // Create a link to the administration interface
332
PortletURL adminURL = resp.createRenderURL();
333                adminURL.setParameter("op", "" + OP_SHOWADMINFORUMS);
334                writer.write("<a id=\"adminPanel\" HREF=\"" + adminURL.toString() + "\">"
335                   + bundle.getString("Admin_panel") + "</a><br/>");
336             }
337
338             PortletRequestDispatcher rd = getPortletContext()
339                .getRequestDispatcher("/WEB-INF/subSilver/jsp/index_body.jsp");
340             rd.include(req, resp);
341          }
342          else if (OP_SHOWFORUM.equals(op))
343          {
344             // Display topics of a forums
345
resp.setTitle("Forums");
346             req.setAttribute(PortalJsp.CTX_REQUEST, fillShowForumContext(req,
347                resp, root));
348             PortletRequestDispatcher rd = getPortletContext()
349                .getRequestDispatcher("/WEB-INF/subSilver/jsp/viewforum_body.jsp");
350             rd.include(req, resp);
351          }
352          else if (OP_POSTING.equals(op))
353          {
354             // Display new post form
355
resp.setTitle("Forums");
356             req.setAttribute(PortalJsp.CTX_REQUEST, fillShowNewTopicContext(req, resp, root));
357             PortletRequestDispatcher rd = getPortletContext()
358                .getRequestDispatcher("/WEB-INF/subSilver/jsp/posting_body.jsp");
359             rd.include(req, resp);
360          }
361          else if (OP_SHOWTOPIC.equals(op))
362          {
363             // Display a topic
364
resp.setTitle("Forums");
365             req.setAttribute(PortalJsp.CTX_REQUEST, fillShowTopicContext(req,
366                resp, root));
367             PortletRequestDispatcher rd = getPortletContext()
368                .getRequestDispatcher("/WEB-INF/subSilver/jsp/viewtopic_body.jsp");
369             rd.include(req, resp);
370          }
371          else if (OP_SHOWADMINFORUMS.equals(op))
372          {
373             // Display administration interface
374
resp.setTitle("Forums");
375             boolean auth = req.hasPermission("Admin");
376             if (auth)
377             {
378                req.setAttribute(PortalJsp.CTX_REQUEST,
379                   fillShowAdminForumsContext(req, resp, root));
380                PortletRequestDispatcher rd = getPortletContext()
381                   .getRequestDispatcher("/WEB-INF/subSilver/jsp/admin/forum_admin_body.jsp");
382                rd.include(req, resp);
383             }
384          }
385          else if (OP_SHOWADDEDITFORUM.equals(op))
386          {
387             // Display new or edit a forum form
388
resp.setTitle("Forums");
389             boolean auth = req.hasPermission("Admin");
390             if (auth)
391             {
392                req.setAttribute(PortalJsp.CTX_REQUEST,
393                   fillShowAddEditForumContext(req, resp, root));
394                PortletRequestDispatcher rd = getPortletContext()
395                   .getRequestDispatcher("/WEB-INF/subSilver/jsp/admin/forum_edit_body.jsp");
396                rd.include(req, resp);
397             }
398          }
399          else if (OP_SHOWDELETEFORUM.equals(op))
400          {
401             // Show form to delete an exisiting forum
402
resp.setTitle("Forums");
403             boolean auth = req.hasPermission("Admin");
404             if (auth)
405             {
406                req.setAttribute(PortalJsp.CTX_REQUEST, root);
407                root.put("NAME", req.getParameter("NAME"));
408                root.put("S_SELECT_TO", req.getParameter("S_SELECT_TO"));
409                root.put("S_HIDDEN_FIELDS", req.getParameter("S_HIDDEN_FIELDS"));
410                PortletURL postURL = resp.createActionURL();
411                root.put("POST_URL", postURL.toString());
412                PortletRequestDispatcher rd = getPortletContext()
413                   .getRequestDispatcher("/WEB-INF/subSilver/jsp/admin/forum_delete_body.jsp");
414                rd.include(req, resp);
415             }
416          }
417          else if (OP_SHOWEDITCATEGORY.equals(op))
418          {
419             // Show form to edit or create a category
420
resp.setTitle("Forums");
421             boolean auth = req.hasPermission("Admin");
422             if (auth)
423             {
424                req.setAttribute(PortalJsp.CTX_REQUEST, root);
425                root.put("CAT_TITLE", req.getParameter("CAT_TITLE"));
426                root.put("S_HIDDEN_FIELDS", req.getParameter("S_HIDDEN_FIELDS"));
427                PortletURL postURL = resp.createActionURL();
428                root.put("POST_URL", postURL.toString());
429                PortletRequestDispatcher rd = getPortletContext()
430                   .getRequestDispatcher("/WEB-INF/subSilver/jsp/admin/category_edit_body.jsp");
431                rd.include(req, resp);
432             }
433          }
434          else if (OP_CONFIRM.equals(op))
435          {
436             // Show form to edit or create a category
437
resp.setTitle("Forums");
438             boolean auth = req.hasPermission("Delete");
439             if (auth)
440             {
441                req.setAttribute(PortalJsp.CTX_REQUEST, root);
442                root.put("MESSAGE_TITLE", req.getParameter("MESSAGE_TITLE"));
443                root.put("MESSAGE_TEXT", req.getParameter("MESSAGE_TEXT"));
444                root.put("S_HIDDEN_FIELDS", req.getParameter("S_HIDDEN_FIELDS"));
445                PortletURL postURL = resp.createActionURL();
446                root.put("POST_URL", postURL.toString());
447                PortletRequestDispatcher rd = getPortletContext()
448                   .getRequestDispatcher("/WEB-INF/subSilver/jsp/confirm_body.jsp");
449                rd.include(req, resp);
450             }
451          }
452          else if (OP_SHOWWATCHEDFORUMS.equals(op))
453          {
454             resp.setTitle("Forums");
455             req.setAttribute(PortalJsp.CTX_REQUEST, fillShowWatchedForums(req,
456                resp, root));
457             PortletRequestDispatcher rd = getPortletContext()
458                .getRequestDispatcher("/WEB-INF/subSilver/jsp/watched_forums_body.jsp");
459             rd.include(req, resp);
460          }
461       }
462
463       writer.write("</div>");
464       writer.close();
465    }
466
467    /**
468     * posting operation
469     *
470     * @param request JBoss action request
471     * @param response JBoss action response
472     * @throws CommandException
473     * @throws CommandException DOCUMENT_ME
474     */

475    public void posting(JBossActionRequest request, JBossActionResponse response)
476       throws CommandException
477    {
478       ResourceBundle JavaDoc bundle = getResourceBundle(request.getLocale());
479
480       Context ctx = new Context();
481       ctx.update(request, response);
482
483       /*
484        // Was cancel pressed? If so then redirect to the appropriate page
485        if (ctx.p_cancel)
486        {
487        if (ctx.p_post_id != -1)
488        {
489        response.sendRedirect("index.html?module=bb&op=viewtopic&p="
490        + ctx.p_post_id + "#" + ctx.p_post_id);
491        }
492        else if (ctx.p_topic_id != -1)
493        {
494        response.sendRedirect("index.html?module=bb&op=viewtopic&t="
495        + ctx.p_topic_id);
496        }
497        else if (ctx.p_forum_id != -1)
498        {
499        response.sendRedirect("index.html?module=bb&op=viewforum&f="
500        + ctx.p_forum_id);
501        }
502        else
503        {
504        response.sendRedirect("index.html?module=bb");
505        }
506        return;
507        }
508        */

509
510       // If the variable mode is empty we don't go farther in the process
511
if (ctx.p_mode == PMODE_NO_MODE)
512       {
513          addErrorMessage(response, "posting",
514             "Unexpected error: No mode defined");
515          return;
516       }
517
518       /*
519        // If the mode is set to topic review then output that review
520        switch (ctx.p_mode)
521        {
522        case PMODE_TOPIC_REVIEW:
523        // display(theme.TPL_THEME_POSTING_TOPIC_REVIEW, topicReview(ctx.p_topic_id), page);
524        return;
525        case PMODE_SMILIES:
526        // generate_smilies('window', PAGE_POSTING);
527        // exit;
528        return;
529        }
530        */

531
532       // Output the confirm message in no confirm variable is found when we delete something
533
if ((((ctx.p_mode == PMODE_EDIT_POST) && ctx.p_poll_delete) || (ctx.p_mode == PMODE_DELETE))
534          && !ctx.p_confirm)
535       {
536          response.setRenderParameter("MESSAGE_TITLE", bundle
537             .getString("Information"));
538          response.setRenderParameter("MESSAGE_TEXT",
539             (ctx.p_mode == PMODE_DELETE) ? bundle
540             .getString("Confirm_delete") : bundle
541             .getString("Confirm_delete_poll"));
542          response
543             .setRenderParameter("S_HIDDEN_FIELDS",
544                "<input type=\"hidden\" name=\"p\" value=\""
545             + ctx.p_post_id
546             + "\"/>"
547             + "<input type=\"hidden\" name=\"module\" value=\"bb\"/>"
548             + "<input type=\"hidden\" name=\"op\" value=\"posting\"/>"
549             + ((ctx.p_mode == PMODE_DELETE) ? "<input type=\"hidden\" name=\"mode\" value=\"delete\"/>"
550             : "<input type=\"hidden\" name=\"mode\" value=\"poll_delete\"/>"));
551
552          // display(theme.TPL_THEME_CONFIRM_BODY, temp, page);
553
response.setRenderParameter("op", OP_CONFIRM);
554          return;
555       }
556
557       // Get user informations
558
User currentUser = request.getUser();
559
560       //
561
Action action = ctx.action(request, response);
562
563       if (action instanceof ProcessCommandAction)
564       {
565          // Get the encapsulated command
566
ForumCommand cmd = ((ProcessCommandAction)action).getCommand();
567
568          // Set the current user on it
569
cmd.setCurrentUser(currentUser);
570
571          // Execute it
572
// Finish the command configuration
573
cmd.setModule(forumsModule);
574
575          // Execute the command
576
Result result = chain.filter(cmd);
577
578          // Switch on the result
579
ResultType type = result.getType();
580
581          /*
582           if (type == CommandConstants.TYPE_ALREADY_VOTED)
583           {
584           // Die.exit(GENERAL_MESSAGE,
585           // "${bb.Already_voted}<br/><br/>${bb.Click_view_message_0}<a HREF=\"index.html?module=bb&op=viewtopic&t=" +
586           // ((VoteTopicCommand)cmd).topic.getId() + "\">${bb.Click_view_message_1}</a>${bb.Click_view_message_2}");
587           }
588           else if (type == CommandConstants.TYPE_CANNOT_INSERT_VOTE)
589           {
590           // Die.rollback(GENERAL_ERROR, "Could not insert user_id for poll");
591           }
592           else if (type == CommandConstants.TYPE_CANNOT_OBTAIN_USER_DATA)
593           {
594           // Die.exit(GENERAL_ERROR, "Could not obtain user vote data for this topic");
595           }
596           else if (type == CommandConstants.TYPE_VOTE_CAST)
597           {
598           // Die.exit(GENERAL_MESSAGE,
599           // "${bb.Vote_cast}<br/><br/>${bb.Click_view_message_0}<a HREF=\"index.html?module=bb&op=viewtopic&t=" +
600           // ((VoteTopicCommand)cmd).topic.getId() + "\">${bb.Click_view_message_1}</a>${bb.Click_view_message_2}");
601           }
602           else if (type == CommandConstants.TYPE_NO_VOTE_OPTION)
603           {
604           // Die.exit(GENERAL_MESSAGE,
605           // "${bb.No_vote_option}<br/><br/>${bb.Click_view_message_0}<a HREF=\"index.html?module=bb&op=viewtopic&t=" +
606           // ((VoteTopicCommand)cmd).topic.getId() + "\">${bb.Click_view_message_1}</a>${bb.Click_view_message_2}");
607           }
608           else if (type == CommandConstants.TYPE_COULD_NOT_OBTAIN_VOTE_DATA)
609           {
610           // Die.exit(GENERAL_ERROR, "Could not obtain vote data for this topic");
611           }
612           else if (type == CommandConstants.TYPE_REDIRECT)
613           {
614           response.sendRedirect("index.html?module=bb&op=viewtopic&t=" + ((VoteTopicCommand) cmd).topic.getId());
615           }
616           else
617           */

618          if (type == CommandConstants.TYPE_ERROR_IN_POSTING)
619          {
620             addErrorMessage(response, "postingfailed", "Error in posting");
621             return;
622          }
623          else if ((type == CommandConstants.TYPE_NEW_TOPIC_POSTED)
624             || (type == CommandConstants.TYPE_EDIT_POST_POSTED)
625             || (type == CommandConstants.TYPE_REPLY_POSTED))
626          {
627             Post post = null;
628             if (cmd instanceof NewTopicCommand)
629             {
630                post = ((NewTopicCommand)cmd).post;
631             }
632             else if (cmd instanceof EditPostCommand)
633             {
634                post = ((EditPostCommand)cmd).post;
635             }
636             else
637             {
638                post = ((ReplyCommand)cmd).newPost;
639             }
640
641             addSuccessMessage(response, "posting", "Stored");
642             return;
643          }
644          else if (type == CommandConstants.TYPE_ERROR_IN_DELETING_POST)
645          {
646             addErrorMessage(response, "posting", "Error in deleting post");
647             return;
648          }
649          else if (type == CommandConstants.TYPE_ERROR_IN_DELETING_POLL)
650          {
651             addErrorMessage(response, "posting", "Error in deleting poll");
652             return;
653          }
654          else if ((type == CommandConstants.TYPE_POLL_DELETED)
655             || (type == CommandConstants.TYPE_POST_DELETED))
656          {
657             // Die.exit(GENERAL_MESSAGE,
658
// "<br/><br/>${bb.Click_return_forum_0}<a HREF=\"index.html?module=bb&op=viewforum&f=" +
659
// cmd.forum.getId() + "\">${bb.Click_return_forum_1}</a>" +
660
// "${bb.Click_return_forum_2}");
661
}
662          else if (type == CommandConstants.TYPE_FORUM_LOCKED)
663          {
664             addErrorMessage(response, "postingfailed", "Forum_locked");
665             return;
666          }
667          else if (type == CommandConstants.TYPE_TOPIC_IS_LOCKED)
668          {
669             addErrorMessage(response, "postingfailed", "Topic_locked");
670             return;
671          }
672          else if (type == CommandConstants.TYPE_NOT_AUTHORIZED)
673          {
674             if (currentUser != null)
675             {
676                // Die.exit(GENERAL_MESSAGE, "${bb." + AUTH_TYPE_TO_MESSAGE[cmd.authType()] + "0}" +
677
// "todo" + // $is_auth[$is_auth_type . "_type"]
678
// "${bb." + AUTH_TYPE_TO_MESSAGE[cmd.authType()] + "1}");
679
return;
680             }
681             else
682             {
683                if (cmd instanceof EditPostCommand)
684                {
685                   // redirect after = index.html?module=bb&op=posting&mode=quote& + POST_POST_URL + = post_id
686
}
687                else if (cmd instanceof NewTopicCommand)
688                {
689                   // redirect after = index.html?module=bb&op=posting&mode=newtopic& + POST_FORUM_URL + = forum_id
690
}
691                else if (cmd instanceof ReplyCommand)
692                {
693                   // if (((ReplyCommand)cmd).quote)
694
// {
695
// // redirect after = index.html?module=bb&op=posting&mode=quote& + POST_POST_URL + = post_id
696
// }
697
// else
698
// {
699
// // beware mode=reply switched from topic to topic.lastPost
700
// // redirect after = index.html?module=bb&op=posting&mode=reply& + POST_TOPIC_URL + = topic_id
701
// }
702
}
703                else
704                {
705                }
706
707                // response.sendRedirect("index.html?module=user&op=getlogin");
708
}
709          }
710          else if (type == CommandConstants.TYPE_CANNOT_XXX_OTHER_POST_WHEN_NOT_MODERATOR)
711          {
712             // Die.exit(GENERAL_MESSAGE, (cmd instanceof DeletePollCommand || cmd instanceof DeletePostCommand) ?
713
// "${bb.Delete_own_posts}" : "${bb.Edit_own_posts}" +
714
// "<br/><br/>${bb.Click_return_topic_0}<a HREF=\"index.html?module=bb&op=viewtopic&t=" +
715
// ((TopicCommand)cmd).topic.getId() +
716
// "\">${bb.Click_return_topic_1}</a>${bb.Click_return_topic_2}");
717
}
718          else if (type == CommandConstants.TYPE_CANNOT_DELETE_REPLIED)
719          {
720             addErrorMessage(response, "postingfailed", "Cannot_delete_replied");
721             return;
722          }
723          else if (type == CommandConstants.TYPE_CANNOT_DELETE_POLL)
724          {
725             addErrorMessage(response, "postingfailed", "Cannot_delete_poll");
726             return;
727          }
728          else if (type == CommandConstants.TYPE_NO_SUCH_POST)
729          {
730             addErrorMessage(response, "postingfailed", "No_such_Post");
731             return;
732          }
733          else if (type == CommandConstants.TYPE_NO_SUCH_TOPIC)
734          {
735             addErrorMessage(response, "postingfailed", "No_topic_id");
736             return;
737          }
738          else if (type == CommandConstants.TYPE_NO_SUCH_FORUM)
739          {
740             addErrorMessage(response, "postingfailed", "Forum_not_exist");
741             return;
742          }
743          else if (type == CommandConstants.TYPE_CANNOT_QUERY)
744          {
745             addErrorMessage(response, "postingfailed",
746                "Could not query forum/topic/post information");
747             return;
748          }
749          else if (type == CommandConstants.TYPE_INVALID_POST_SUBJECT)
750          {
751             addErrorMessage(response, "postingfailed", "Empty_subject");
752             return;
753          }
754          else if (type == CommandConstants.TYPE_INVALID_POST_MESSAGE)
755          {
756             addErrorMessage(response, "postingfailed", "Empty_message");
757             return;
758          }
759          else if (type == CommandConstants.TYPE_TOO_MANY_POLL_OPTION)
760          {
761             addErrorMessage(response, "postingfailed", "To_many_poll_options");
762             return;
763          }
764          else if (type == CommandConstants.TYPE_INVALID_POLL_OPTION)
765          {
766             addErrorMessage(response, "postingfailed", "Empty_poll_option");
767             return;
768          }
769          else if (type == CommandConstants.TYPE_INVALID_POLL_TITLE)
770          {
771             addErrorMessage(response, "postingfailed", "Empty_poll_title");
772             return;
773          }
774          else if (type == CommandConstants.TYPE_TOO_FEW_POLL_OPTION)
775          {
776             addErrorMessage(response, "postingfailed", "To_few_poll_options");
777             return;
778          }
779          else if (type == CommandConstants.TYPE_REPOSTED)
780          {
781             addErrorMessage(response, "postingfailed", "Reposted");
782             return;
783
784             // Die.exit(GENERAL_MESSAGE,
785
// "${bb.Reposted}<br/><br/>" +
786
// "${bb.Click_view_message_0}" +
787
// "<a HREF=\"index.html?module=bb&op=viewtopic&t=" +
788
// ((RepostCommand)cmd).topic.getId() + "\">${bb.Click_view_message_1}</a>${bb.Click_view_message_2}");
789
}
790          else if (type == CommandConstants.TYPE_FLOODING_CANNOT_CREATE)
791          {
792             addErrorMessage(response, "postingfailed", "Flood_Error");
793             return;
794          }
795          else if (type == CommandConstants.TYPE_CANNOT_ADD_ATTACHMENT)
796          {
797             addErrorMessage(response, "postingfailed",
798                "You are not authorized to add an attachment");
799             return;
800          }
801          else if (type == CommandConstants.TYPE_CANNOT_DELETE_ATTACHMENT)
802          {
803             addErrorMessage(response, "postingfailed",
804                "You are not authorized to delete an attachment");
805             return;
806          }
807          else if (type == CommandConstants.TYPE_ERROR_IN_DELETING_ATTACHMENT)
808          {
809             addErrorMessage(response, "postingfailed",
810                "Problem when deleting an attachment");
811             return;
812          }
813          else
814          {
815             throw new RuntimeException JavaDoc("This statement should not be reached");
816          }
817       }
818       else
819       {
820          ForumAction faction = (ForumAction)action;
821
822          faction.init();
823
824          Forum forum = faction.getForum();
825          Category category = forum.getCategory();
826          Message msg = faction.getMessage();
827          Poster poster = faction.getPoster();
828
829          // Level level = secGetLevel(category.getTitle() + ":" + forum.getName() + ":", currentUser);
830
boolean loggedIn = currentUser != null;
831          int[] types = new int[]{AuthType.READ, AuthType.DELETE,
832                                  AuthType.STICKY, AuthType.ANNOUNCE, AuthType.POLL,
833                                  AuthType.ATTACH};
834
835          // boolean[] auths = forum.getAuth().can(types, loggedIn, level);
836
// boolean isAuthRead = auths[0];
837
// boolean isAuthDelete = auths[1];
838
// boolean isAuthSticky = auths[2];
839
// boolean isAuthAnnounce = auths[3];
840
// boolean isAuthPollCreate = auths[4];
841
// boolean isAuthAttachments = auths[5];
842
// boolean isAuthMod = Auth.hasLevel(Auth.LEVEL_MOD, loggedIn, level);
843
// We are sure to have forumEJB not null and we always target a forum
844
int forum_id = forum.getID().intValue();
845          String JavaDoc forum_name = forum.getName();
846          Integer JavaDoc topic_id = (faction instanceof TopicAction) ? ((TopicAction)faction)
847             .getTopic().getID()
848             : new Integer JavaDoc(-1);
849
850          // julien : is it utile ?
851
// if (topic_id.intValue() > -1 && (cmd instanceof NewTopicCommand || cmd instanceof ReplyCommand))
852
// {
853
// Map trackingTopics = getTrackingTopics(page);
854
// trackingTopics.put(topic_id, new Date());
855
// }
856
// if (!"".equals(error_msg))
857
// {
858
// DelegateContext temp = provider.instantiate(TPL_THEME_ERROR_BODY);
859
// temp.put("ERROR_MESSAGE", error_msg);
860
// errorBox = temp.render();
861
// }
862
String JavaDoc previewBox = "";
863          String JavaDoc errorBox = "";
864
865          if (ctx.p_preview)
866          {
867             String JavaDoc preview_message = formatMessage(msg.getText(), msg
868                .getBBCodeEnabled(), msg.getHTMLEnabled());
869             if ((currentUser != null) && msg.getSignatureEnabled())
870             {
871                String JavaDoc signature = currentUser.getSignature();
872                if (!ForumsTools.isNullOrBlank(signature))
873                {
874                   preview_message += formatSignature(signature, msg
875                      .getBBCodeEnabled(), msg.getHTMLEnabled());
876                }
877             }
878
879             String JavaDoc preview_subject = formatTitle(msg.getSubject());
880             String JavaDoc preview_username = formatUserName(poster.getUser());
881
882             //
883
// Date formater
884
//
885
SimpleDateFormatPool dateFormatPool = new SimpleDateFormatPool(128,
886                16);
887
888             // PortletURL postingURL = response.createRenderURL();
889
// postingURL.setParameter("op", OP_POSTING);
890
response.setRenderParameter("op", OP_POSTING);
891             response.setRenderParameter("preview", "true");
892             if (request.getParameters().getParameterExists("f"))
893             {
894                response.setRenderParameter("f", request.getParameter("f"));
895             }
896
897             if (request.getParameters().getParameterExists("p"))
898             {
899                response.setRenderParameter("p", request.getParameter("p"));
900             }
901
902             response.setRenderParameter("mode", request.getParameter("mode"));
903             response.setRenderParameter("TOPIC_TITLE", preview_subject);
904             response.setRenderParameter("POST_SUBJECT", msg.getSubject());
905             response.setRenderParameter("PREVIEW_SUBJECT", preview_subject);
906             response.setRenderParameter("POSTER_NAME", preview_username);
907             response.setRenderParameter("POST_DATE", dateFormatPool
908                .formatDate(new Date JavaDoc()));
909             response.setRenderParameter("MESSAGE", msg.getText());
910             response.setRenderParameter("PREVIEW_MESSAGE", preview_message);
911
912             // response.sendRedirect(postingURL.toString());
913
}
914
915          DelegateContext root = new DelegateContext();
916
917          /*
918           if (htmlEnabled)
919           {
920           root.next("switch_html_checkbox");
921           root.put("HTML_STATUS", "${bb.HTML_is_ON}");
922           }
923           else
924           {
925           root.put("HTML_STATUS", "${bb.HTML_is_OFF}");
926           }
927           if (codeEnabled)
928           {
929           root.next("switch_bbcode_checkbox");
930           root.put("BBCODE_STATUS", "${bb.BBCode_is_ON_0}<a HREF=\"index.html?module=bb&op=faq\" " +
931           "target=\"_phpbbcode\">" +
932           "${bb.BBCode_is_ON_1}</a>${bb.BBCode_is_ON_2}");
933           }
934           else
935           {
936           root.put("BBCODE_STATUS", "${bb.BBCode_is_OFF_0}<a HREF=\"index.html?module=bb&op=faq\"" +
937           "target=\"_phpbbcode\">" +
938           "${bb.BBCode_is_OFF_1}</a>${bb.BBCode_is_OFF_2}");
939           }
940           if (smiliesEnabled)
941           {
942           root.next("switch_smilies_checkbox");
943           root.put("SMILIES_STATUS", "${bb.Smilies_are_ON}");
944           }
945           else
946           {
947           root.put("SMILIES_STATUS", "${bb.Smilies_are_OFF}");
948           }
949           */

950          if ((currentUser == null)
951             || (faction instanceof EditPostAction && (((EditPostAction)faction)
952             .getPost().getPoster().getUser() == null)))
953          {
954             root.next("switch_username_select");
955          }
956
957          // Set the notify toggle on the template
958
if (currentUser != null)
959          {
960             root.next("switch_notify_checkbox");
961             boolean notify = ctx.p_notify;
962             if ((faction instanceof EditPostAction && (faction.getMode() == ForumAction.INIT))
963                || (faction instanceof ReplyAction && (faction.getMode() == ForumAction.INIT)))
964             {
965                /*
966                 try
967                 {
968                 homesRW.topicWatch.findByPrimaryKey(new TopicWatchEJBPK(currentUser.getId(), ((TopicAction)faction).getTopic().getId()));
969                 notify = true;
970                 }
971                 catch (ObjectNotFoundException e)
972                 {
973                 // no watch
974                 }
975                 catch (FinderException e)
976                 {
977                 Die.exit(GENERAL_ERROR, "Could not obtain watch information", e);
978                 }
979                 */

980             }
981
982             root.put("S_NOTIFY_CHECKED", notify ? "checked=\"checked\"" : "");
983          }
984
985          // Set the signature toggle on the template
986
if (currentUser != null)
987          {
988             root.next("switch_signature_checkbox");
989          }
990
991          // BLAH todo
992
// Set set delete toggle on the template
993
// if (action instanceof EditPostAction && (isAuthMod || isAuthDelete))
994
// {
995
// EditPostAction epa = (EditPostAction)action;
996
// if (epc.pd_last_post && (!epc.topic.getVote() || epc.pd_edit_poll))
997
// {
998
// root.next("switch_delete_checkbox");
999
// }
1000
// }
1001
// Topic type selection
1002
if (faction instanceof NewTopicAction
1003            || (faction instanceof EditPostAction && ((EditPostAction)faction)
1004            .isFirstPost()))
1005         {
1006            int topic_type = ctx.p_topic_type;
1007
1008            // If we edit the post we override the topic type with the one loaded from the DB
1009
if (faction instanceof EditPostAction
1010               && (faction.getMode() == EditPostAction.INIT))
1011            {
1012               topic_type = ((EditPostAction)faction).getTopic().getType();
1013            }
1014
1015            /*
1016             // Create the topic type selected
1017             if (isAuthSticky || isAuthAnnounce)
1018             {
1019             StringBuffer selector = new StringBuffer("${bb.Post_topic_as}:");
1020             BBTools.radioButton(selector, "topictype", "" + POST_NORMAL, topic_type == POST_NORMAL);
1021             selector.append("${bb.Post_Normal}&nbsp;&nbsp;");
1022             if (isAuthSticky)
1023             {
1024             BBTools.radioButton(selector, "topictype", "" + POST_STICKY, topic_type == POST_STICKY);
1025             selector.append("${bb.Post_Sticky}&nbsp;&nbsp;");
1026             }
1027             if (isAuthAnnounce)
1028             {
1029             BBTools.radioButton(selector, "topictype", "" + POST_ANNOUNCE, topic_type == POST_ANNOUNCE);
1030             selector.append("${bb.Post_Announcement}&nbsp;&nbsp;");
1031             }
1032             root.next("switch_type_toggle");
1033             root.put("S_TYPE_TOGGLE", selector.toString());
1034             }
1035             */

1036         }
1037
1038         // Hidden form fields
1039
StringBuffer JavaDoc hidden_form_fields = new StringBuffer JavaDoc();
1040         hidden_form_fields.append("<input type=\"hidden\" name=\"mode\" value=\"").append(ModeDecoder.encodePosting(ctx.p_mode)).append("\"/>").append("<input type=\"hidden\" name=\"op\" value=\"posting\"/>");
1041         if (faction instanceof NewTopicAction)
1042         {
1043            hidden_form_fields.append("<input type=\"hidden\" name=\"f\" value=\"")
1044               .append(forum_id).append("\"/>");
1045         }
1046         else if (faction instanceof ReplyAction
1047            || faction instanceof EditPostAction)
1048         {
1049            hidden_form_fields.append("<input type=\"hidden\" name=\"p\" value=\"").append(((PostAction)faction).getPost().getID()).append("\"/>");
1050         }
1051
1052         // generate smilies listing for page output
1053
// generate_smilies('inline', PAGE_POSTING);
1054
/*
1055          String pollBox = "";
1056          boolean canCreatePoll = false;
1057          if (action instanceof EditPostAction)
1058          {
1059          
1060          switch (((EditPostAction)faction).getTopic().getPollLevel())
1061          {
1062          case TopicEJB.POLL_LEVEL_EMPTY:
1063          canCreatePoll = isAuthPollCreate || isAuthMod;
1064          break;
1065          case TopicEJB.POLL_LEVEL_NO_POLL:
1066          canCreatePoll = isAuthPollCreate || isAuthMod;
1067          break;
1068          case TopicEJB.POLL_LEVEL_NON_EMPTY:
1069          canCreatePoll = isAuthMod;
1070          break;
1071          default:
1072          throw new RuntimeException();
1073          }
1074          
1075          }
1076          else
1077          {
1078          canCreatePoll = action instanceof NewTopicAction;
1079          }
1080          if (canCreatePoll)
1081          {
1082          Poll poll = action instanceof NewTopicAction ? ((NewTopicAction)faction).getPoll() : ((EditPostAction)faction).getPoll();
1083          DelegateContext temp = new DelegateContext();
1084          temp.put("POLL_TITLE", poll.getTitle());
1085          temp.put("POLL_LENGTH", Integer.toString(poll.getLength()));
1086          if (action instanceof EditPostAction)
1087          {
1088          temp.next("switch_poll_delete_toggle");
1089          }
1090          int index = 0;
1091          for (Iterator iterator = poll.getOptions().iterator();iterator.hasNext();)
1092          {
1093          String text = (String)iterator.next();
1094          if (text != null)
1095          {
1096          DelegateContext poll_option_rows = temp.next("poll_option_rows");
1097          poll_option_rows.put("POLL_OPTION", text);
1098          poll_option_rows.put("S_POLL_OPTION_NUM", "" + index++);
1099          }
1100          }
1101          pollBox = theme.TPL_THEME_POSTING_POLL_BODY.render(temp);
1102          }
1103          */

1104         // attachBox
1105
// get HTMLCode for attachment form
1106
// TODO: Check the if condition for attachBox
1107
// String attachBox = "";
1108
// if (/*(action instanceof NewTopicAction || action instanceof EditPostAction) && */isAuthAttachments)
1109
/* {
1110          DelegateContext temp = new DelegateContext();
1111          if (showApcp)
1112          {
1113          temp.next("show_apcp");
1114          temp.next("switch_posted_attachments");
1115          }
1116          String addAttachmentBox = "";
1117          if (ctx.p_attach_box || !showApcp)
1118          {
1119          root.put("S_FORM_ENCTYPE", " enctype=\"multipart/form-data\"");
1120          DelegateContext addAttachmentCtx = new DelegateContext();
1121          addAttachmentBox = theme.TPL_THEME_ADD_ATTACHMENT_BODY.render(addAttachmentCtx);
1122          DelegateContext hidden_row = temp.next("hidden_row");
1123          hidden_row.put("S_HIDDEN", "<input type=\"hidden\" name=\"add_attachment_box_flag\" value=\"1\"/>\n");
1124          temp.put("ADD_ATTACHMENT_BODY", addAttachmentBox);
1125          }
1126          String postedAttachmentsBox = "";
1127          if ((ctx.p_posted_attach) || (!showApcp))
1128          {
1129          DelegateContext postedAttachmentsCtx = new DelegateContext();
1130          if (faction instanceof EditPostAction)
1131          {
1132          EditPostAction epa = (EditPostAction)faction;
1133          PostEJBLocal post = epa.getPost();
1134          for (Iterator i = post.getAttachments().iterator();i.hasNext();)
1135          {
1136          AttachmentEJBLocal attachmentEJB = (AttachmentEJBLocal)i.next();
1137          if (!ctx.p_deleted_attachments.contains(attachmentEJB.getId()))
1138          {
1139          DelegateContext attachRowContext = postedAttachmentsCtx.next("attach_row");
1140          attachRowContext.put("FILE_NAME", attachmentEJB.getRealFilename());
1141          attachRowContext.put("FILE_COMMENT", attachmentEJB.getComment());
1142          attachRowContext.put("ATTACH_FILENAME", "" + attachmentEJB.getId());
1143          attachRowContext.put("ATTACH_ID", "" + attachmentEJB.getId());
1144          }
1145          //attachRowContext.next("switch_update_attachment");
1146          }
1147          }
1148          for (IndexIterator i = IndexIterator.wrap(faction.getAttachments().iterator(), -1);i.hasNext();)
1149          {
1150          Attachment attachment = (Attachment)i.next();
1151          DelegateContext attachRowContext = postedAttachmentsCtx.next("attach_row");
1152          attachRowContext.put("FILE_NAME", attachment.getFile().getName());
1153          attachRowContext.put("FILE_COMMENT", attachment.getComment());
1154          attachRowContext.put("ATTACH_FILENAME", "session_" + i.getIndex());
1155          attachRowContext.put("ATTACH_ID", "session_" + i);
1156          //attachRowContext.next("switch_update_attachment");
1157          //attachRowContext.next("switch_thumbnail");
1158          }
1159          DelegateContext hidden_row = temp.next("hidden_row");
1160          hidden_row.put("S_HIDDEN", "<input type=\"hidden\" name=\"posted_attachments_flag\" value=\"1\"/>\n");
1161          postedAttachmentsBox = theme.TPL_THEME_POSTED_ATTACHMENTS_BODY.render(postedAttachmentsCtx);
1162          temp.put("POSTED_ATTACHMENTS_BODY", postedAttachmentsBox);
1163          }
1164          
1165          // if (ctx.p_attach)
1166          // {
1167          // UploadedFile webFile = page.getParameterAsFile("fileupload");
1168          // if (webFile != null)
1169          // {
1170          // // Create the command
1171          // return new StoreAttachmentCommand(
1172          // context.getFileHome(),
1173          // id,
1174          // fileId,
1175          // webFile.getContentType(),
1176          // webFile.getContent(),
1177          // user,
1178          // makeProd);
1179          //Die.exit(GENERAL_ERROR, webFile.getContentType());
1180          }
1181          }
1182          attachBox = theme.TPL_THEME_POSTING_ATTACH_BODY.render(temp);
1183          }
1184          // end attachBox
1185          */

1186         //String topicReviewBox = "";
1187
/*
1188          if (isAuthRead && faction instanceof ReplyAction)
1189          {
1190          DelegateContext sub = topicReview(((ReplyAction)faction).getTopic());
1191          // sub.next("switch_inline_mode");
1192          // topicReviewBox = theme.TPL_THEME_POSTING_TOPIC_REVIEW.render(sub);
1193          }
1194          */

1195         // We don't handle PM for now
1196
/*
1197          root.next("switch_not_privmsg");
1198          // Output the data to the template
1199          root.put("FORUM_NAME", forum_name);
1200          root.put("CATEGORY_NAME",
1201          category.getTitle());
1202          root.put("L_POST_A", ""); // not used, this is for the page title
1203          root.put("U_VIEW_CATEGORY", "index.html?module=bb&op=main&c=" + category.getId().toString());
1204          root.put("U_VIEW_FORUM", "index.html?module=bb&op=viewforum&f=" + forum_id);
1205          root.put("USERNAME",
1206          poster.getUserName());
1207          root.put("L_EMOTICONS", ""); // todo
1208          root.put("U_VIEWTOPIC",
1209          (ctx.p_mode == PMODE_REPLY)
1210          ? ("index.html?module=bb&op=viewtopic&t=" + topic_id + "&postorder=desc") : "");
1211          root.put("U_REVIEW_TOPIC",
1212          (ctx.p_mode == PMODE_REPLY) ? ("index.html?module=bb&op=posting&mode=topicreview&t=" + topic_id)
1213          : "");
1214          root.put("S_HTML_CHECKED", msg.getHTMLEnabled() ? "" : "checked=\"checked\"");
1215          root.put("S_BBCODE_CHECKED", msg.getBBCodeEnabled() ? "" : "checked=\"checked\"");
1216          root.put("S_SMILIES_CHECKED", msg.getSmiliesEnabled() ? "" : "checked=\"checked\"");
1217          root.put("S_SIGNATURE_CHECKED", msg.getSignatureEnabled() ? "checked=\"checked\"" : "");
1218          root.put("S_TOPIC_ID",
1219          topic_id.toString());
1220          // root.put("JUMPBOX", makeJumpBox("viewforum", currentUser != null));
1221          root.put("ERROR_BOX", errorBox);
1222          root.put("POST_PREVIEW_BOX", previewBox);
1223          // root.put("POLLBOX", pollBox);
1224          // root.put("ATTACHBOX", attachBox);
1225          root.put("TOPIC_REVIEW_BOX", topicReviewBox);
1226          */

1227         response.setRenderParameter("S_HIDDEN_FORM_FIELDS", hidden_form_fields
1228            .toString());
1229         response.setRenderParameter("op", OP_POSTING);
1230         if (request.getParameters().getParameterExists("f"))
1231         {
1232            response.setRenderParameter("f", request.getParameter("f"));
1233         }
1234
1235         if (request.getParameters().getParameterExists("p"))
1236         {
1237            response.setRenderParameter("p", request.getParameter("p"));
1238         }
1239         response.setRenderParameter("SUBJECT", msg.getSubject());
1240
1241         if (ctx.p_mode == PMODE_QUOTE)
1242         {
1243            Post post;
1244            try
1245            {
1246               post = forumsModule.findPostByID(new Integer JavaDoc(ctx.p_post_id));
1247               msg.setText("[quote=" + post.getPoster().getUser().getUserName() + "]" + post.getMessage().getText() + "[/quote]");
1248            }
1249            catch (ModuleException e1)
1250            {
1251               // TODO Auto-generated catch block
1252
e1.printStackTrace();
1253            }
1254         }
1255         else if (ctx.p_mode == PMODE_EDIT_POST)
1256         {
1257            Post post;
1258            try
1259            {
1260               post = forumsModule.findPostByID(new Integer JavaDoc(ctx.p_post_id));
1261               msg.setText(post.getMessage().getText());
1262            }
1263            catch (ModuleException e1)
1264            {
1265               // TODO Auto-generated catch block
1266
e1.printStackTrace();
1267            }
1268         }
1269         response.setRenderParameter("MESSAGE", msg.getText());
1270      }
1271   }
1272
1273   /**
1274    * admin_forums operation
1275    *
1276    * @param req JBoss Action Request
1277    * @param resp JBoss Action Response
1278    */

1279   public void admin_forums(JBossActionRequest req, JBossActionResponse resp)
1280   {
1281      ResourceBundle JavaDoc bundle = getResourceBundle(req.getLocale());
1282
1283      String JavaDoc mode = req.getParameters().get("mode", "");
1284      boolean addCategory = req.getParameter("addcategory") != null;
1285      Category addforum = null;
1286
1287      try
1288      {
1289         for (Iterator i = forumsModule.findCategories().iterator(); i
1290            .hasNext();)
1291         {
1292            Category category = (Category)i.next();
1293            if (req.getParameter("addforum_" + category.getID()) != null)
1294            {
1295               addforum = category;
1296               break;
1297            }
1298         }
1299      }
1300      catch (ModuleException e)
1301      {
1302         e.printStackTrace();
1303         addErrorMessage(resp, "admin", "Cannot process command");
1304         return;
1305      }
1306
1307      if ((addforum != null) || addCategory)
1308      {
1309         if (addforum != null)
1310         {
1311            mode = "addforum";
1312         }
1313         else
1314         {
1315            mode = "addcat";
1316         }
1317      }
1318
1319      if ("addforum".equals(mode) || "editforum".equals(mode))
1320      {
1321         PortletURL addOrEditForumURL = resp.createRenderURL();
1322         addOrEditForumURL.setParameters(req.getParameterMap());
1323         addOrEditForumURL.setParameter("mode", mode);
1324         addOrEditForumURL.setParameter("op", OP_SHOWADDEDITFORUM);
1325         if ("addforum".equals(mode))
1326         {
1327            addOrEditForumURL.setParameter("c", "" + addforum.getID());
1328         }
1329
1330         try
1331         {
1332            resp.sendRedirect(addOrEditForumURL.toString());
1333         }
1334         catch (IOException JavaDoc e1)
1335         {
1336            // TODO Auto-generated catch block
1337
e1.printStackTrace();
1338         }
1339      }
1340      else if ("cat_order".equals(mode))
1341      {
1342         try
1343         {
1344            Category category = forumsModule.findCategoryByID(req
1345               .getParameters().getIntObject(POST_CAT_URL));
1346            String JavaDoc[] test = new String JavaDoc[]{category.getTitle()};
1347            if (req.hasPermission(test, "AdminCategory"))
1348            {
1349               OrderCategoryCommand cmd = new OrderCategoryCommand(req, resp);
1350               cmd.move = req.getParameters().getInt("move", 0);
1351               cmd.category = category;
1352               cmd.module = forumsModule;
1353               Result result = chain.filter(cmd);
1354               ResultType type = result.getType();
1355               if (type == CommandConstants.TYPE_CATEGORIES_ORDERED)
1356               {
1357                  addSuccessMessage(resp, "catorder", "Forums_updated");
1358                  resp.setRenderParameter("op", OP_SHOWADMINFORUMS);
1359                  return;
1360               }
1361               else if (type == CommandConstants.TYPE_CANNOT_ORDER_CATEGORIES)
1362               {
1363                  addErrorMessage(resp, "catorder",
1364                     "Can't change category order");
1365                  return;
1366               }
1367            }
1368            else
1369            {
1370               addErrorMessage(resp, "catorder",
1371                  "Not authorized to change the category order");
1372               return;
1373            }
1374         }
1375         catch (Exception JavaDoc e)
1376         {
1377            e.printStackTrace();
1378            addErrorMessage(resp, "catorder", "Couldn't order categories");
1379            return;
1380         }
1381      }
1382      else if ("addcat".equals(mode))
1383      {
1384         if (req.hasPermission("Admin"))
1385         {
1386            CreateCategoryCommand cmd = new CreateCategoryCommand(req, resp);
1387            cmd.name = req.getParameters().get("categoryname", "").trim();
1388            cmd.module = forumsModule;
1389            Result result;
1390            try
1391            {
1392               result = chain.filter(cmd);
1393               ResultType type = result.getType();
1394               if (type == CommandConstants.TYPE_CANNOT_CREATE_CATEGORY_INVALID_NAME)
1395               {
1396                  addErrorMessage(resp, "addcat",
1397                     "Can't create a category without a name");
1398                  return;
1399               }
1400               else if (type == CommandConstants.TYPE_CANNOT_CREATE_CATEGORY_INSERTION_FAILED)
1401               {
1402                  addErrorMessage(resp, "addcat",
1403                     "Couldn't insert row in categories table");
1404                  return;
1405               }
1406               else if (type == CommandConstants.TYPE_CATEGORY_CREATED)
1407               {
1408                  resp.setRenderParameter("op", OP_SHOWADMINFORUMS);
1409                  addSuccessMessage(resp, "addcat", "Forums_updated");
1410               }
1411            }
1412            catch (CommandException e1)
1413            {
1414               e1.printStackTrace();
1415            }
1416         }
1417         else
1418         {
1419            addErrorMessage(resp, "addcat", "Not authorized to add a category");
1420            return;
1421         }
1422      }
1423      else if ("createforum".equals(mode))
1424      {
1425         try
1426         {
1427            Category category = forumsModule.findCategoryByID(req
1428               .getParameters().getIntObject(POST_CAT_URL));
1429            String JavaDoc[] test = new String JavaDoc[]{category.getTitle()};
1430            if (req.hasPermission(test, "AdminCategory"))
1431            {
1432               CreateForumCommand cmd = new CreateForumCommand(req, resp);
1433               cmd.name = req.getParameters().get("forumname", "");
1434               cmd.description = req.getParameters().get("forumdesc", "")
1435                  .trim();
1436               cmd.category = category;
1437               cmd.module = forumsModule;
1438
1439               Result result = chain.filter(cmd);
1440               ResultType type = result.getType();
1441
1442               if (type == CommandConstants.TYPE_FORUM_CREATED)
1443               {
1444                  resp.setRenderParameter("op", OP_SHOWADMINFORUMS);
1445                  addSuccessMessage(resp, "addforum", "Forums_updated");
1446                  return;
1447               }
1448               else if (type == CommandConstants.TYPE_CANNOT_CREATE_FORUM_INVALID_NAME)
1449               {
1450                  addErrorMessage(resp, "addforum", "Forum_missing_name");
1451                  return;
1452               }
1453               else if (type == CommandConstants.TYPE_CANNOT_CREATE_FORUM_INVALID_CATEGORY)
1454               {
1455                  addErrorMessage(resp, "addforum", "Forum_missing_category");
1456                  return;
1457               }
1458               else if (type == CommandConstants.TYPE_CANNOT_CREATE_FORUM_INSERTION_FAILED)
1459               {
1460                  addErrorMessage(resp, "addforum", "Forum_failed");
1461                  return;
1462               }
1463            }
1464            else
1465            {
1466               addErrorMessage(resp, "addforum", "Forum_not_authorized");
1467               return;
1468            }
1469         }
1470         catch (ModuleException e)
1471         {
1472            e.printStackTrace();
1473
1474            // Die.exit(GENERAL_ERROR, "Couldn't get order number from forums table", e);
1475
}
1476
1477            // if( $HTTP_POST_VARS['prune_enable'] )
1478
// {
1479
// if( $HTTP_POST_VARS['prune_days'] == "" || $HTTP_POST_VARS['prune_freq'] == "")
1480
// {
1481
// message_die(GENERAL_MESSAGE, $lang['Set_prune_data']);
1482
// }
1483
// $sql = "INSERT INTO " . PRUNE_TABLE . " (forum_id, prune_days, prune_freq)
1484
// VALUES('" . $next_id . "', " . intval($HTTP_POST_VARS['prune_days']) . ", " . intval($HTTP_POST_VARS['prune_freq']) . ")";
1485
// if( !$result = $db->sql_query($sql) )
1486
// {
1487
// message_die(GENERAL_ERROR, "Couldn't insert row in prune table", "", __LINE__, __FILE__, $sql);
1488
// }
1489
// }
1490
catch (CommandException e)
1491         {
1492            // TODO Auto-generated catch block
1493
e.printStackTrace();
1494         }
1495      }
1496      else if ("forum_order".equals(mode))
1497      {
1498         try
1499         {
1500            Forum forum = forumsModule.findForumByID(req.getParameters()
1501               .getIntObject("f"));
1502            String JavaDoc[] test = new String JavaDoc[]{forum.getCategory().getTitle()};
1503            if (req.hasPermission(test, "AdminCategory"))
1504            {
1505               OrderForumCommand cmd = new OrderForumCommand(req, resp);
1506               cmd.module = forumsModule;
1507               cmd.forum = forum;
1508               cmd.move = req.getParameters().getIntObject("move", 0)
1509                  .intValue();
1510               Result result = chain.filter(cmd);
1511               ResultType type = result.getType();
1512               if (type == CommandConstants.TYPE_FORUMS_ORDERED)
1513               {
1514                  resp.setRenderParameter("op", OP_SHOWADMINFORUMS);
1515                  addSuccessMessage(resp, "ordersuccess", "Forums_updated");
1516                  return;
1517               }
1518               else if (type == CommandConstants.TYPE_CANNOT_ORDER_FORUMS)
1519               {
1520                  addErrorMessage(resp, "orderfailed",
1521                     "Couldn't change category order");
1522                  return;
1523               }
1524            }
1525            else
1526            {
1527               addErrorMessage(resp, "forum",
1528                  "Not authorized to change order in this category");
1529               return;
1530            }
1531         }
1532         catch (Exception JavaDoc e)
1533         {
1534            addErrorMessage(resp, "orderfailed",
1535               "Couldn't change category order");
1536            return;
1537         }
1538      }
1539      else if ("forum_sync".equals(mode))
1540      {
1541         // sync('forum', intval($HTTP_GET_VARS[POST_FORUM_URL]));
1542
// $show_index = TRUE;
1543
}
1544      else if ("deletecat".equals(mode))
1545      {
1546         try
1547         {
1548            Integer JavaDoc catId = req.getParameters().getIntObject(POST_CAT_URL);
1549            Category category = forumsModule.findCategoryByID(catId);
1550            String JavaDoc selectTo = "";
1551            if (forumsModule.findCategories().size() == 1)
1552            {
1553               if (forumsModule.findForumsByCategoryID(catId).size() > 0)
1554               {
1555                  addErrorMessage(resp, "deletecat", "Must_delete_forums");
1556                  return;
1557               }
1558               else
1559               {
1560                  selectTo = bundle.getString("Nowhere_to_move");
1561               }
1562            }
1563            else
1564            {
1565               selectTo = "<select name=\"to_id\">"
1566                  + ForumsTools.listCategories(forumsModule.findCategories(), catId.intValue())
1567                  + "</select>";
1568            }
1569
1570            resp.setRenderParameter("op", OP_SHOWDELETEFORUM);
1571            resp.setRenderParameter("NAME", category.getTitle());
1572            resp.setRenderParameter("S_SELECT_TO", selectTo);
1573            resp
1574               .setRenderParameter("S_HIDDEN_FIELDS",
1575                  "<input type=\"hidden\" name=\"mode\" value=\"movedelcat\"/>"
1576               + "<input type=\"hidden\" name=\"module\" value=\"bb\"/>"
1577               + "<input type=\"hidden\" name=\"op\" value=\"admin_forums\"/>"
1578               + "<input type=\"hidden\" name=\"from_id\" value=\""
1579               + catId + "\"/>");
1580
1581            /*
1582             DelegateContext root = new DelegateContext();
1583             root.put("NAME", category.getTitle());
1584             root.put("S_SELECT_TO", selectTo);
1585             root.put("S_HIDDEN_FIELDS", "<input type=\"hidden\" name=\"mode\" value=\"movedelcat\"/>" +
1586             "<input type=\"hidden\" name=\"module\" value=\"bb\"/>" +
1587             "<input type=\"hidden\" name=\"op\" value=\"admin_forums\"/>" +
1588             "<input type=\"hidden\" name=\"from_id\" value=\"" + catId + "\"/>");
1589             display(theme.TPL_THEME_ADMIN_FORUM_DELETE_BODY, root, page);
1590             */

1591         }
1592         catch (ModuleException e)
1593         {
1594            addErrorMessage(resp, "deletefailed", "Couldn't get Forum info");
1595            return;
1596         }
1597      }
1598      else if ("movedelcat".equals(mode))
1599      {
1600         try
1601         {
1602            Category fromCategory = forumsModule.findCategoryByID(req
1603               .getParameters().getIntObject("from_id"));
1604            Category toCategory = forumsModule.findCategoryByID(req
1605               .getParameters().getIntObject("to_id"));
1606
1607            String JavaDoc[] test1 = new String JavaDoc[]{fromCategory.getTitle()};
1608            String JavaDoc[] test2 = new String JavaDoc[]{toCategory.getTitle()};
1609            if ((req.hasPermission(test1, "DeleteForumInCategory"))
1610               && (req.hasPermission(test2, "AddForumInCategory")))
1611            {
1612               DeleteMoveCategoryCommand cmd = new DeleteMoveCategoryCommand(req, resp);
1613               cmd.source = fromCategory;
1614               cmd.target = toCategory;
1615               cmd.module = forumsModule;
1616               Result result = chain.filter(cmd);
1617               ResultType type = result.getType();
1618               if (type == CommandConstants.TYPE_CANNOT_REMOVE_CATEGORY)
1619               {
1620                  addErrorMessage(resp, "deletecategory",
1621                     "Couldn't delete category");
1622                  return;
1623               }
1624               else if (type == CommandConstants.TYPE_CATEGORY_REMOVED)
1625               {
1626                  resp.setRenderParameter("op", OP_SHOWADMINFORUMS);
1627                  addSuccessMessage(resp, "deletecategory", "Forums_updated");
1628                  return;
1629               }
1630            }
1631            else
1632            {
1633               addErrorMessage(resp, "deletecategory",
1634                  "You can't delete and move this category");
1635               return;
1636            }
1637         }
1638         catch (Exception JavaDoc e)
1639         {
1640            addErrorMessage(resp, "deletefailed", "Couldn't delete category");
1641            e.printStackTrace();
1642            return;
1643         }
1644      }
1645      else if ("deleteforum".equals(mode))
1646      {
1647         try
1648         {
1649            Integer JavaDoc forumId = req.getParameters().getIntObject("f");
1650            Forum forum = forumsModule.findForumByID(forumId);
1651            resp.setRenderParameter("op", OP_SHOWDELETEFORUM);
1652            resp.setRenderParameter("NAME", forum.getName());
1653            resp
1654               .setRenderParameter("S_HIDDEN_FIELDS",
1655                  "<input type=\"hidden\" name=\"mode\" value=\"movedelforum\"/>"
1656               + "<input type=\"hidden\" name=\"module\" value=\"bb\"/>"
1657               + "<input type=\"hidden\" name=\"op\" value=\"admin_forums\"/>"
1658               + "<input type=\"hidden\" name=\"from_id\" value=\""
1659               + forum.getID() + "\"/>");
1660            resp.setRenderParameter("S_SELECT_TO",
1661               "<select name=\"to_id\"><option value=\"-1\">"
1662               + bundle.getString("Delete_all_posts")
1663               + "</option>\n" // $s
1664
+ ForumsTools.listForums(forumsModule.findForums(),
1665                  forumId.intValue()) + "</select>");
1666
1667            // display(theme.TPL_THEME_ADMIN_FORUM_DELETE_BODY, root, page);
1668
}
1669         catch (ModuleException e)
1670         {
1671            addErrorMessage(resp, "deletefailed",
1672               "Could not obtain forum information");
1673            e.printStackTrace();
1674            return;
1675         }
1676      }
1677      else if ("movedelforum".equals(mode))
1678      {
1679         // int deleteOld = page.getParameterAsInt("delete_old", -1);
1680
try
1681         {
1682            Integer JavaDoc fromId = req.getParameters().getIntObject("from_id", -1);
1683            Forum fromForum = forumsModule.findForumByID(fromId);
1684            Integer JavaDoc toId = req.getParameters().getIntObject("to_id", -1);
1685            if ((toId.intValue() < 0) && (fromId.intValue() >= 0))
1686            {
1687               String JavaDoc[] test = new String JavaDoc[]{
1688                  fromForum.getCategory().getTitle(), fromForum.getName()};
1689               if (req.hasPermission(test, "DeletePostInForum"))
1690               {
1691                  DeleteForumCommand cmd = new DeleteForumCommand(req, resp);
1692                  cmd.forum = fromForum;
1693                  cmd.module = forumsModule;
1694                  Result result = chain.filter(cmd);
1695                  ResultType type = result.getType();
1696                  if (type == CommandConstants.TYPE_FORUM_REMOVED)
1697                  {
1698                     resp.setRenderParameter("op", OP_SHOWADMINFORUMS);
1699                     addSuccessMessage(resp, "delete", "Forums_updated");
1700                     return;
1701                  }
1702                  else if (type == CommandConstants.TYPE_CANNOT_REMOVE_FORUM_REMOVAL_FAILED)
1703                  {
1704                     addErrorMessage(resp, "delete", "Could not delete forum");
1705                  }
1706               }
1707            }
1708            else if (!fromId.equals(toId) && (fromId.intValue() >= 0)
1709               && (toId.intValue() >= 0))
1710            {
1711               Forum toForum = forumsModule.findForumByID(toId);
1712               String JavaDoc[] test1 = new String JavaDoc[]{
1713                  fromForum.getCategory().getTitle(), fromForum.getName()};
1714               String JavaDoc[] test2 = new String JavaDoc[]{
1715                  toForum.getCategory().getTitle(), toForum.getName()};
1716               if ((req.hasPermission(test1, "DeletePostInForum"))
1717                  && (req.hasPermission(test2, "AddPostInForum")))
1718               {
1719                  DeleteMoveForumCommand cmd = new DeleteMoveForumCommand(req, resp);
1720                  cmd.source = fromForum;
1721                  cmd.target = toForum;
1722                  cmd.module = forumsModule;
1723                  Result result = chain.filter(cmd);
1724                  ResultType type = result.getType();
1725                  if (type == CommandConstants.TYPE_FORUM_MOVED_AND_REMOVED)
1726                  {
1727                     resp.setRenderParameter("op", OP_SHOWADMINFORUMS);
1728                     addSuccessMessage(resp, "delete", "Forums_updated");
1729                     return;
1730                  }
1731                  else if (type == CommandConstants.TYPE_CANNOT_MOVE_AND_REMOVE_FORUM)
1732                  {
1733                     addErrorMessage(resp, "delete", "Could not delete forum");
1734                     return;
1735                  }
1736
1737                  /*
1738                   cmd.sourceId = fromId;
1739                   cmd.targetId = toId;
1740                   cmd.topicDataSource = topicDataSource;
1741                   cmd.topicTableName = topicTableName;
1742                   cmd.topicForumFKColumnName = topicForumRelationColumnName;
1743                   cmd.postDataSource = postDataSource;
1744                   cmd.postTableName = postTableName;
1745                   cmd.postForumFKColumnName = postForumRelationColumnName;
1746                   cmd.forumHome = homesRW.forum;
1747                   cmd.postHome = homesRW.post;
1748                   cmd.topicHome = homesRW.topic;
1749                   Result result = chain.filter(req, resp, cmd);
1750                   */

1751               }
1752            }
1753            else
1754            {
1755               // todo provide a nice message
1756
}
1757         }
1758         catch (Exception JavaDoc e)
1759         {
1760            addErrorMessage(resp, "delete", "Could not delete forum");
1761            e.printStackTrace();
1762            return;
1763         }
1764      }
1765      else if ("editcat".equals(mode))
1766      {
1767         try
1768         {
1769            Integer JavaDoc catId = req.getParameters().getIntObject(POST_CAT_URL);
1770            Category category = forumsModule.findCategoryByID(catId);
1771            String JavaDoc hiddenFields = "<input type=\"hidden\" name=\"mode\" value=\"modcat\"/>"
1772               + "<input type=\"hidden\" name=\""
1773               + POST_CAT_URL
1774               + "\" value=\""
1775               + category.getID()
1776               + "\"/>"
1777               + "<input type=\"hidden\" name=\"module\" value=\"bb\"/>"
1778               + "<input type=\"hidden\" name=\"op\" value=\"admin_forums\"/>";
1779            resp.setRenderParameter("op", OP_SHOWEDITCATEGORY);
1780            resp.setRenderParameter("CAT_TITLE", category.getTitle());
1781            resp.setRenderParameter("S_HIDDEN_FIELDS", hiddenFields);
1782
1783            // display(theme.TPL_THEME_ADMIN_CATEGORY_EDIT_BODY, root, page);
1784
}
1785         catch (ModuleException e)
1786         {
1787            addErrorMessage(resp, "deletefailed", "Cannot edit category");
1788            e.printStackTrace();
1789            return;
1790         }
1791      }
1792      else if ("modcat".equals(mode))
1793      {
1794         try
1795         {
1796            Category category = forumsModule.findCategoryByID(req
1797               .getParameters().getIntObject(POST_CAT_URL));
1798            String JavaDoc[] test = new String JavaDoc[]{category.getTitle()};
1799            if (req.hasPermission(test, "EditCategory"))
1800            {
1801               UpdateCategoryCommand cmd = new UpdateCategoryCommand(req, resp);
1802               cmd.title = req.getParameters().get("cat_title", "").trim();
1803               cmd.category = category;
1804               Result result = chain.filter(cmd);
1805               ResultType type = result.getType();
1806               if (type == CommandConstants.TYPE_CATEGORY_UPDATED)
1807               {
1808                  resp.setRenderParameter("op", OP_SHOWADMINFORUMS);
1809                  addSuccessMessage(resp, "update", "Forums_updated");
1810                  return;
1811               }
1812            }
1813         }
1814         catch (Exception JavaDoc e)
1815         {
1816            addErrorMessage(resp, "update", "Cannot update category");
1817            e.printStackTrace();
1818            return;
1819         }
1820      }
1821      else if ("modforum".equals(mode))
1822      {
1823         // if( isset($HTTP_POST_VARS['prune_enable']))
1824
// {
1825
// if( $HTTP_POST_VARS['prune_enable'] != 1 )
1826
// {
1827
// $HTTP_POST_VARS['prune_enable'] = 0;
1828
// }
1829
// }
1830
try
1831         {
1832            Category category = forumsModule.findCategoryByID(req
1833               .getParameters().getIntObject(POST_CAT_URL));
1834            Forum forum = forumsModule.findForumByID(req.getParameters()
1835               .getIntObject("f"));
1836            String JavaDoc[] test1 = new String JavaDoc[]{category.getTitle(), };
1837            String JavaDoc[] test2 = new String JavaDoc[]{forum.getCategory().getTitle(), };
1838            if ((req.hasPermission(test1, "AddForumInCategory"))
1839               && (req.hasPermission(test2, "EditForumInCategory")))
1840            {
1841               UpdateForumCommand cmd = new UpdateForumCommand(req, resp);
1842               cmd.name = req.getParameters().get("forumname", "");
1843               cmd.description = req.getParameters().get("forumdesc", "");
1844               cmd.category = category;
1845               cmd.forum = forum;
1846               Result result = chain.filter(cmd);
1847               ResultType type = result.getType();
1848               if (type == CommandConstants.TYPE_FORUM_UPDATED)
1849               {
1850                  resp.setRenderParameter("op", OP_SHOWADMINFORUMS);
1851                  addSuccessMessage(resp, "edit", "Forums_updated");
1852                  return;
1853               }
1854            }
1855            addErrorMessage(resp, "edit", "Cannot update forums");
1856
1857            // forum_status = intval($HTTP_POST_VARS['forumstatus'])
1858
// prune_enable = intval($HTTP_POST_VARS['prune_enable']
1859
}
1860         catch (Exception JavaDoc e)
1861         {
1862            addErrorMessage(resp, "edit", "Couldn't update forum information");
1863            e.printStackTrace();
1864            return;
1865         }
1866
1867         // if( $HTTP_POST_VARS['prune_enable'] == 1 )
1868
// {
1869
// if( $HTTP_POST_VARS['prune_days'] == "" || $HTTP_POST_VARS['prune_freq'] == "" )
1870
// {
1871
// message_die(GENERAL_MESSAGE, $lang['Set_prune_data']);
1872
// }
1873
// $sql = "SELECT *
1874
// FROM " . PRUNE_TABLE . "
1875
// WHERE forum_id = " . intval($HTTP_POST_VARS[POST_FORUM_URL]);
1876
// if( !$result = $db->sql_query($sql) )
1877
// {
1878
// message_die(GENERAL_ERROR, "Couldn't get forum Prune Information","",__LINE__, __FILE__, $sql);
1879
// }
1880
// if( $db->sql_numrows($result) > 0 )
1881
// {
1882
// $sql = "UPDATE " . PRUNE_TABLE . "
1883
// SET prune_days = " . intval($HTTP_POST_VARS['prune_days']) . ", prune_freq = " . intval($HTTP_POST_VARS['prune_freq']) . "
1884
// WHERE forum_id = " . intval($HTTP_POST_VARS[POST_FORUM_URL]);
1885
// }
1886
// else
1887
// {
1888
// $sql = "INSERT INTO " . PRUNE_TABLE . " (forum_id, prune_days, prune_freq)
1889
// VALUES(" . intval($HTTP_POST_VARS[POST_FORUM_URL]) . ", " . intval($HTTP_POST_VARS['prune_days']) . ", " . intval($HTTP_POST_VARS['prune_freq']) . ")";
1890
// }
1891
// if( !$result = $db->sql_query($sql) )
1892
// {
1893
// message_die(GENERAL_ERROR, "Couldn't Update Forum Prune Information","",__LINE__, __FILE__, $sql);
1894
// }
1895
// }
1896
// Die.exit(GENERAL_MESSAGE, "${bb.Forums_updated}<br/><br/>${bb.Click_return_forumadmin_0}<a HREF=\"" +
1897
// "index.html?module=bb&op=admin_forums\">${bb.Click_return_forumadmin_1}</a>" +
1898
// "${bb.Click_return_forumadmin_2}<br/><br/>${bb.Click_return_admin_index_0}" +
1899
// "<a HREF=\"index.html?module=bb&pane=right\">${bb.Click_return_admin_index_1}</a>" +
1900
// "${bb.Click_return_admin_index_2}");
1901
}
1902   }
1903
1904   private DelegateContext fillShowIndexContext(JBossRenderRequest req,
1905                                                JBossRenderResponse resp, DelegateContext root)
1906   {
1907      ResourceBundle JavaDoc bundle = getResourceBundle(req.getLocale());
1908
1909      Integer JavaDoc c = req.getParameters().getIntObject("c", -1);
1910      try
1911      {
1912         if (c.intValue() != -1)
1913         {
1914            Category category = forumsModule.findCategoryByID(c);
1915            fillShowCategoryContext(req, resp, root, category);
1916         }
1917         else
1918         {
1919            // Fill context with categories
1920
Iterator iterator = forumsModule.findCategories().iterator();
1921            while (iterator.hasNext())
1922            {
1923               Category currentCategory = (Category)iterator.next();
1924
1925               fillShowCategoryContext(req, resp, root, currentCategory);
1926            }
1927         }
1928      }
1929      catch (ModuleException e)
1930      {
1931         // TODO Auto-generated catch block
1932
e.printStackTrace();
1933      }
1934      return root;
1935   }
1936
1937   private DelegateContext fillShowCategoryContext(JBossRenderRequest req,
1938                                                   JBossRenderResponse resp, DelegateContext root, Category category)
1939   {
1940      ResourceBundle JavaDoc bundle = getResourceBundle(req.getLocale());
1941      try
1942      {
1943         String JavaDoc[] testArray = new String JavaDoc[]{category.getTitle()};
1944
1945         boolean authRead = req.hasPermission(testArray, "ReadCategory");
1946
1947         if (authRead)
1948         {
1949            DelegateContext catrow = root.next("catrow");
1950            catrow.put("CAT_DESC", category.getTitle());
1951            PortletURL viewCatURL = resp.createRenderURL();
1952            viewCatURL.setParameter("op", OP_MAIN);
1953            viewCatURL.setParameter("c", "" + category.getID());
1954            catrow.put("U_VIEWCAT", viewCatURL.toString());
1955
1956            // Fill context with forums
1957
Iterator forumsIterator = forumsModule.findForumsByCategoryID(category.getID()).iterator();
1958            while (forumsIterator.hasNext())
1959            {
1960               Forum currentForum = (Forum)forumsIterator.next();
1961               Integer JavaDoc currentCategoryId = category.getID();
1962               String JavaDoc currentCategoryTitle = category.getTitle();
1963               String JavaDoc currentForumName = currentForum.getName();
1964               testArray = new String JavaDoc[]{currentCategoryTitle,
1965                                        currentForumName};
1966
1967               authRead = req.hasPermission(testArray, "ReadForum");
1968               boolean authView = authRead;
1969
1970               // We display the forum only if needed
1971
if (authView)
1972               {
1973                  // Get forum data
1974
int currentForumStatus = currentForum.getStatus();
1975                  Integer JavaDoc currentForumId = currentForum.getID();
1976                  Post lastPost = currentForum.getLastPost();
1977                  String JavaDoc currentForumDescription = currentForum
1978                     .getDescription();
1979                  int currentForumPostSize = currentForum.getPostCount();
1980                  int currentForumTopicSize = currentForum.getTopicCount();
1981                  String JavaDoc folderImage = theme.resourceForumURL;
1982                  String JavaDoc folderAlt = bundle.getString("No_new_posts");
1983                  if (currentForumStatus == FORUM_LOCKED)
1984                  {
1985                     folderImage = theme.resourceForumLockedURL;
1986                     folderAlt = bundle.getString("Forum_locked");
1987                  }
1988
1989                  /*
1990                   else
1991                   {
1992                   Date when1 = (Date)dates.get(currentForumId);
1993                   Date when2 = (Date)trackingForums.get(currentForumId);
1994                   if ((Time.compare(when1, when2) & (Time.LEFT_AFTER | Time.RIGHT_NULL)) != 0)
1995                   {
1996                   folderImage = theme.resourceForumNewBigURL;
1997                   folderAlt = "${bb.New_posts}";
1998                   }
1999                   }
2000                   */

2001
2002                  // Get the last post text
2003
String JavaDoc lastPostText = bundle.getString("No_Posts");
2004                  if (lastPost != null)
2005                  {
2006                     Integer JavaDoc lastPostId = lastPost.getID();
2007                     StringBuffer JavaDoc temp = new StringBuffer JavaDoc();
2008                     Date JavaDoc lastPostDate = lastPost.getCreateDate();
2009
2010                     // temp.append(dateFormatPool.formatDate(lastPostDate)).append("<br/>");
2011
// temp.append(lastPost.getPoster().getAuthor(true));
2012
temp.append(lastPostDate).append("<br/>");
2013                     temp.append(lastPost.getPoster().getUser().getUserName());
2014                     PortletURL postURL = resp.createRenderURL();
2015                     postURL.setParameter("op", OP_SHOWTOPIC);
2016                     postURL.setParameter("p", "" + lastPostId);
2017                     temp.append("<a HREF=\"").append(postURL.toString())
2018                        .append("\"><img SRC=\"").append(theme.resourceIconLatestReplyURL).append("\" border=\"0\" alt=\""
2019                        + bundle.getString("View_latest_post")
2020                        + "\" title=\""
2021                        + bundle.getString("View_latest_post")
2022                        + "\"/></a>");
2023                     lastPostText = temp.toString();
2024                  }
2025
2026                  // Fetch the moderator list
2027
String JavaDoc moderatorList = "&nbsp";
2028                  String JavaDoc moderatorsMessage = "&nbsp;";
2029
2030                  /*
2031                   Set moderators = moderators(currentCategoryTitle, currentForumName);
2032                   if (moderators.size() > 0)
2033                   {
2034                   StringBuffer temp = new StringBuffer();
2035                   for (Iterator j = moderators.iterator();j.hasNext();temp.append(j.hasNext() ? "," : ""))
2036                   {
2037                   temp.append(j.next());
2038                   }
2039                   moderatorList = temp.toString();
2040                   moderatorsMessage = moderators.size() == 1 ? "${bb.Moderator}" : "${bb.Moderators}";
2041                   }
2042                   */

2043
2044                  // Build the template
2045
DelegateContext forumrow = catrow.next("forumrow");
2046
2047                  /* forumrow.put("ROW_COLOR", theme.getProperty(i.getIndex() % 2 == 0 ? "td_color1" : "td_color2"));
2048                   forumrow.put("ROW_CLASS", theme.getProperty(i.getIndex() % 2 == 0 ? "td_class1" : "td_class2"));
2049                   */

2050                  forumrow.put("FORUM_FOLDER_IMG", folderImage);
2051                  forumrow.put("FORUM_NAME", currentForumName);
2052                  forumrow.put("FORUM_DESC", currentForumDescription);
2053                  forumrow.put("POSTS", "" + currentForumPostSize);
2054                  forumrow.put("TOPICS", "" + currentForumTopicSize);
2055                  forumrow.put("LAST_POST", lastPostText);
2056                  forumrow.put("MODERATORS", moderatorList);
2057                  forumrow.put("L_MODERATOR", moderatorsMessage);
2058                  forumrow.put("L_FORUM_FOLDER_ALT", folderAlt);
2059                  PortletURL viewForumURL = resp.createRenderURL();
2060                  viewForumURL.setParameter("op", OP_SHOWFORUM);
2061                  viewForumURL.setParameter("f", currentForumId.toString());
2062                  forumrow.put("U_VIEWFORUM", viewForumURL.toString());
2063               }
2064            }
2065         }
2066      }
2067      catch (ModuleException e)
2068      {
2069         // TODO Auto-generated catch block
2070
e.printStackTrace();
2071      }
2072
2073      return root;
2074   }
2075
2076   private DelegateContext fillShowForumContext(JBossRenderRequest req,
2077                                                JBossRenderResponse resp, DelegateContext root)
2078   {
2079      ResourceBundle JavaDoc bundle = getResourceBundle(req.getLocale());
2080
2081      // JBossPortletPreferences prefs =
2082
// new JBossPortletPreferences(null,
2083
// req.getUser().getPreferenceStore().get(new FQN("org.jboss.portlet.forums")),
2084
// null, PortletPreferencesImpl.RENDER, proxyInfo);
2085
// PreferencesProxy proxy = (PreferencesProxy) prefs.getProxy();
2086

2087      // TODO: use user preferences
2088
int topicsPerPage = 10;
2089      int hotThreshold = 10;
2090      int postsPerPage = 10;
2091
2092      Integer JavaDoc forumId = req.getParameters().getIntObject("f", -1);
2093      int start = req.getParameters().getInt("start", 0);
2094
2095      // String markRead = page.getParameter("mark", "");
2096
int topicDays = req.getParameters().getInt("topicdays", 0);
2097
2098      Forum forum = null;
2099      try
2100      {
2101         forum = forumsModule.findForumByID(forumId);
2102      }
2103      catch (ModuleException e1)
2104      {
2105         // TODO Auto-generated catch block
2106
e1.printStackTrace();
2107      }
2108
2109      Category category = forum.getCategory();
2110      User user = req.getUser();
2111      boolean loggedIn = user != null;
2112      Date JavaDoc lastVisit = loggedIn ? user.getLastVisitDate() : null;
2113      String JavaDoc categoryTitle = category.getTitle();
2114      String JavaDoc forumName = forum.getName();
2115
2116      // Level level = secGetLevel(categoryTitle + ":" + forumName + ":");
2117
// Auth auth = forum.getAuth();
2118
//TODO: add security here
2119
String JavaDoc[] testArray = new String JavaDoc[]{categoryTitle, forumName};
2120      boolean authRead = req.hasPermission(testArray, "ReadForum"); //auth.can(Auth.TYPE_READ, loggedIn, level);
2121
boolean authView = req.hasPermission(testArray, "ReadForum"); //auth.can(Auth.TYPE_VIEW, loggedIn, level);
2122
boolean authPost = req.hasPermission(testArray, "AddPostInForum");
2123      boolean authMod = req.hasPermission(testArray, "ModerateForum"); //Auth.hasLevel(Auth.LEVEL_MOD, loggedIn, level);
2124

2125      if (authPost)
2126      {
2127         root.next("AUTH_POST");
2128      }
2129
2130      if (!authRead || !authView)
2131      {
2132         System.out.println("You are not authorized to see this forum");
2133         return root;
2134
2135         /*
2136          if (!loggedIn)
2137          {
2138          // $redirect = POST_FORUM_URL . "=$forum_id" . ( ( isset($start) ) ? "&start=$start" : '' );
2139          // redirect(append_sid("login.$phpEx?redirect=viewforum.$phpEx&$redirect", true));
2140          // page.sendRedirect("index.html?module=user&op=getlogin");
2141          // return root;
2142          }
2143          Die.exit(GENERAL_MESSAGE, !authView ? "${bb.Forum_not_exist}" : "sprintf($lang['Sorry_auth_read'], $is_auth['auth_read_type'])");
2144          */

2145      }
2146
2147      /*
2148       if ("topics".equals(markRead) && loggedIn)
2149       {
2150       PostEJBLocal lastPost = forum.getLastPost();
2151       if (lastPost != null)
2152       {
2153       if (lastPost.getPostDate().after(lastVisit))
2154       {
2155       getTrackingForums(page).put(forumId, new Date());
2156       }
2157       }
2158       Die.exit(GENERAL_MESSAGE, "${bb.Topics_marked_read}<br/><br/>" +
2159       "${bb.Click_return_forum_0}<a HREF=\"index.html?module=bb&op=viewforum&f=" +
2160       forumId + "\">${bb.Click_return_forum_1}</a>" +
2161       "${bb.Click_return_forum_2}");
2162       }
2163       if (authMod && pruneEnable)
2164       {
2165       // if ( $forum_row['prune_next'] < time() && $forum_row['prune_enable'] )
2166       // {
2167       // include($phpbb_root_path . 'includes/prune.'.$phpEx);
2168       // require($phpbb_root_path . 'includes/functions_admin.'.$phpEx);
2169       // auto_prune($forum_id);
2170       // }
2171       }
2172       // todo put that in statistics
2173       Set moderators = moderators(categoryTitle, forumName);
2174       String moderatorMessage = "${bb.Moderators}";
2175       String moderatorList = "${bb.None}";
2176       if (moderators.size() > 0)
2177       {
2178       StringBuffer temp = new StringBuffer();
2179       if (moderators.size() == 1)
2180       {
2181       moderatorMessage = "${bb.Moderator}";
2182       }
2183       for (Iterator iterator = moderators.iterator();iterator.hasNext();)
2184       {
2185       temp.append((String)iterator.next());
2186       if (iterator.hasNext())
2187       {
2188       temp.append(", ");
2189       }
2190       }
2191       moderatorList = temp.toString();
2192       }
2193       // int topicCount = 0;
2194       */

2195      Date JavaDoc minTopicTime = null;
2196      if (topicDays > 0)
2197      {
2198         Calendar JavaDoc c = Calendar.getInstance();
2199         c.add(Calendar.DATE, -topicDays);
2200         minTopicTime = c.getTime();
2201
2202         // Collection temp = null;
2203
// try
2204
// {
2205
// temp = homes.topic.selectGeneric("SELECT t.id FROM topic AS t WHERE t.forum=?1 AND t.lastPost.postDate>=?2",
2206
// new Object[]{forum, minTopicTime});
2207
// }
2208
// catch(FinderException e)
2209
// {
2210
// Die.exit(GENERAL_ERROR, "Could not obtain limited topics count information");
2211
// }
2212
// topicCount = temp.size();
2213
}
2214      else
2215      {
2216         // topicCount = forum.getTopicSize();
2217
topicDays = 0;
2218      }
2219
2220      List JavaDoc announcements = null;
2221      List JavaDoc topics = null;
2222
2223      try
2224      {
2225         announcements = forumsModule.findAnnouncements(forum);
2226         topics = (minTopicTime == null) ? forumsModule.findTopicsDesc(forum,
2227            POST_ANNOUNCE, start, topicsPerPage) : forumsModule
2228            .findTopicsBefore(forum, POST_ANNOUNCE, start, topicsPerPage,
2229               minTopicTime);
2230      }
2231      catch (ModuleException e)
2232      {
2233         // TODO Auto-generated catch block
2234
e.printStackTrace();
2235      }
2236
2237      int totalAnnoucements = announcements.size();
2238      int totalTopicsAndStickies = forum.getTopicCount();
2239      int totalTopics = totalTopicsAndStickies; // + totalAnnoucements;
2240

2241      /*
2242       StringBuffer authCan = new StringBuffer();
2243       BBTools.authCan(authCan, forum, loggedIn, level);
2244       if (authMod)
2245       {
2246       authCan.append("${bb.Rules_moderate_0}<a HREF=\"index.html?module=bb&op=modcp&f=").append(forumId).
2247       append("&start=").append(start).
2248       append("\">${bb.Rules_moderate_1}</a>${bb.Rules_moderate_2}");
2249       }
2250       */

2251      Iterator ci = new CompoundIterator(new Iterator[]{
2252         announcements.iterator(), topics.iterator()});
2253
2254      /*
2255       if (!ci.hasNext())
2256       {
2257       }
2258       */

2259
2260      // if
2261
// No topics
2262
// $no_topics_msg = ( $forum_row['forum_status'] == FORUM_LOCKED ) ? $lang['Forum_locked'] : $lang['No_topics_post_one'];
2263
// $template->assign_vars(array(
2264
// 'L_NO_TOPICS' => $no_topics_msg)
2265
/*
2266       Map trackingForums = getTrackingForums(page);
2267       Map trackingTopics = getTrackingTopics(page);
2268       Date trackingAllForums = (Date)page.getSession().getAttribute(cookieName + "_f_all");
2269       */

2270      Goto toPost = new Goto(postsPerPage, bundle.getString("Goto_page"));
2271      toPost.setImgUrl(theme.resourceIconGotopostURL);
2272
2273      for (IndexIterator iterator = IndexIterator.wrap(ci, -1); iterator
2274         .hasNext();)
2275      {
2276         Topic topic = (Topic)iterator.next();
2277
2278         int replies = topic.getReplies();
2279         int status = topic.getStatus();
2280         Integer JavaDoc topicId = (status == TOPIC_MOVED) ? topic.getTarget().getID()
2281            : topic.getID();
2282         String JavaDoc type = bundle.getString("Topic_Moved");
2283         String JavaDoc folderImage = theme.resourceFolderURL;
2284         String JavaDoc folderAlt = bundle.getString("Topic_Moved");
2285         String JavaDoc newestPostImg = "";
2286         Date JavaDoc topicLastPostDate = topic.getLastPost().getCreateDate();
2287         Post firstPost = topic.getFirstPost();
2288         Post lastPost = topic.getLastPost();
2289         Poster lastPostUser = lastPost.getPoster();
2290         Poster poster = topic.getPoster();
2291
2292         if (status != TOPIC_MOVED)
2293         {
2294            FolderType folderType = theme.getFolderType(topic.getType(),
2295               status, replies >= hotThreshold);
2296            boolean newest = loggedIn; /* &&
2297             ((Time.compare(topicLastPostDate, lastVisit) & Time.LEFT_AFTER) != 0) &&
2298             ((Time.compare(topicLastPostDate, trackingAllForums) & (Time.LEFT_AFTER | Time.RIGHT_NULL)) != 0) &&
2299             ((Time.compare(topicLastPostDate, (Date)trackingTopics.get(topicId)) & (Time.LEFT_AFTER | Time.RIGHT_NULL)) != 0) &&
2300             ((Time.compare(topicLastPostDate, (Date)trackingForums.get(forumId)) & (Time.LEFT_AFTER | Time.RIGHT_NULL)) != 0);
2301             */

2302
2303            if (newest)
2304            {
2305               folderImage = folderType.folderNew;
2306               folderAlt = (status == TOPIC_LOCKED) ? bundle
2307                  .getString("Topic_locked") : bundle.getString("New_posts");
2308               newestPostImg = "<a HREF=\"index.html?module=bb&op=viewtopic&t="
2309                  + topicId + "&view=newest\"><img SRC=\""
2310                  + theme.resourceIconNewestReplyURL + "\" alt=\""
2311                  + bundle.getString("View_newest_post") + "\" title=\""
2312                  + bundle.getString("View_newest_post")
2313                  + "\" border=\"0\"/></a>";
2314            }
2315            else
2316            {
2317               folderImage = folderType.folder;
2318               folderAlt = (status == TOPIC_LOCKED) ? bundle
2319                  .getString("Topic_locked") : bundle
2320                  .getString("No_new_posts");
2321               newestPostImg = "";
2322            }
2323
2324            try
2325            {
2326               type = bundle.getString(folderType.type);
2327            }
2328            catch (java.util.MissingResourceException JavaDoc e)
2329            {
2330               type = "";
2331            }
2332
2333            /*
2334             if (topic.getVote())
2335             {
2336             type += "${bb.Topic_Poll} ";
2337             }
2338             */

2339         }
2340
2341         toPost.setPostSize(replies);
2342         toPost.setTopicId(topicId.intValue());
2343         String JavaDoc gotoPage = toPost.generate();
2344         String JavaDoc rowColor = theme
2345            .getProperty(((iterator.getIndex() % 2) == 0) ? "td_color1"
2346            : "td_color2");
2347         String JavaDoc rowClass = theme
2348            .getProperty(((iterator.getIndex() % 2) == 0) ? "td_class1"
2349            : "td_class2");
2350         String JavaDoc topicAuthor = firstPost.getPoster().getUser().getUserName();
2351         String JavaDoc lastPostAuthor = lastPost.getPoster().getUser().getUserName();
2352
2353         PortletURL lastPostURL = resp.createRenderURL();
2354         lastPostURL.setParameter("op", OP_SHOWTOPIC);
2355         lastPostURL.setParameter("p", "" + lastPost.getID());
2356
2357         String JavaDoc lastPostUrl = "<a HREF=\"" + lastPostURL.toString() + "\">"
2358            + "<img SRC=\"" + theme.resourceIconLatestReplyURL + "\" alt=\""
2359            + bundle.getString("View_latest_post") + "\" title=\""
2360            + bundle.getString("View_latest_post") + "\" border=\"0\"/></a>";
2361
2362         DelegateContext topicrow = root.next("topicrow");
2363         topicrow.put("ROW_COLOR", rowColor);
2364         topicrow.put("ROW_CLASS", rowClass);
2365         topicrow.put("FORUM_ID", forumId.toString());
2366         topicrow.put("TOPIC_ID", topicId.toString());
2367         topicrow.put("TOPIC_FOLDER_IMG", folderImage);
2368         topicrow.put("TOPIC_AUTHOR", topicAuthor);
2369         topicrow.put("GOTO_PAGE", gotoPage);
2370         topicrow.put("REPLIES", "" + replies);
2371         topicrow.put("NEWEST_POST_IMG", newestPostImg);
2372         topicrow.put("TOPIC_TITLE", formatTitle(topic.getSubject()));
2373         topicrow.put("TOPIC_TYPE", type);
2374         topicrow.put("VIEWS", "" + topic.getViewCount());
2375
2376         // topicrow.put("FIRST_POST_TIME", dateFormatPool.formatDate(topic.getCreationDate()));
2377
topicrow.put("LAST_POST_TIME", topic.getLastPostDate().toString());
2378         topicrow.put("LAST_POST_AUTHOR", lastPostAuthor);
2379         topicrow.put("LAST_POST_IMG", lastPostUrl);
2380         topicrow.put("L_TOPIC_FOLDER_ALT", folderAlt);
2381         PortletURL viewTopicURL = resp.createRenderURL();
2382         viewTopicURL.setParameter("op", OP_SHOWTOPIC);
2383         viewTopicURL.setParameter("t", "" + topicId);
2384         topicrow.put("U_VIEW_TOPIC", viewTopicURL.toString());
2385      }
2386
2387      GotoWithOffset toTopic = new GotoWithOffset(totalTopicsAndStickies,
2388         start, topicsPerPage, "index.html?module=bb&op=viewforum&f="
2389         + forumId + "&topicDays=" + topicDays + "&start=", bundle
2390         .getString("Goto_page"), bundle.getString("Previous"), bundle
2391         .getString("Next"));
2392
2393      String JavaDoc pageNumber = bundle.getString("Page_of_0")
2394         + ((int)Math.floor((double)start / topicsPerPage) + 1)
2395         + bundle.getString("Page_of_1")
2396         + ((int)Math.ceil((double)totalTopicsAndStickies / topicsPerPage));
2397
2398      PortletURL postNewURL = resp.createRenderURL();
2399      postNewURL.setParameter("op", OP_POSTING);
2400      postNewURL.setParameter("f", "" + forumId);
2401      postNewURL.setParameter("mode", "newtopic");
2402      root.put("U_POST_NEW_TOPIC", postNewURL.toString());
2403
2404      // root.put("S_SELECT_TOPIC_DAYS", BBTools.selectDays("topicdays", topicDays));
2405
root.put("S_POST_DAYS_ACTION", "index.html?module=bb&op=viewforum&f="
2406         + forumId + "&start=" + start);
2407      root.put("FORUM_ID", forum.getID().toString());
2408      root.put("FORUM_NAME", forum.getName());
2409      root.put("CATEGORY_NAME", categoryTitle);
2410
2411      // root.put("MODERATORS", moderatorList);
2412
root.put("POST_IMG",
2413         (forum.getStatus() == FORUM_LOCKED) ? theme.resourcePostLockedURL
2414         : theme.resourcePostNewURL);
2415      root.put("FOLDER_IMG", theme.resourceFolderURL);
2416      root.put("FOLDER_NEW_IMG", theme.resourceFolderNewURL);
2417      root.put("FOLDER_HOT_IMG", theme.resourceFolderHotURL);
2418      root.put("FOLDER_HOT_NEW_IMG", theme.resourceFolderHotNewURL);
2419      root.put("FOLDER_LOCKED_IMG", theme.resourceFolderLockedURL);
2420      root.put("FOLDER_LOCKED_NEW_IMG", theme.resourceFolderLockedNewURL);
2421      root.put("FOLDER_STICKY_IMG", theme.resourceFolderStickyURL);
2422      root.put("FOLDER_STICKY_NEW_IMG", theme.resourceFolderStickyNewURL);
2423      root.put("FOLDER_ANNOUNCE_IMG", theme.resourceFolderAnnounceURL);
2424      root.put("FOLDER_ANNOUNCE_NEW_IMG", theme.resourceFolderAnnounceNewURL);
2425
2426      // root.put("L_MODERATOR", moderatorMessage);
2427
root.put("L_POST_NEW_TOPIC", (forum.getStatus() == FORUM_LOCKED) ? bundle
2428         .getString("Forum_locked") : bundle.getString("Post_new_topic"));
2429
2430      // root.put("S_AUTH_LIST", authCan.toString());
2431
PortletURL viewCategoryURL = resp.createRenderURL();
2432      viewCategoryURL.setParameter("op", OP_MAIN);
2433      viewCategoryURL.setParameter("c", "" + category.getID());
2434      root.put("U_VIEW_CATEGORY", viewCategoryURL.toString());
2435      PortletURL viewForumURL = resp.createRenderURL();
2436      viewForumURL.setParameter("op", OP_SHOWFORUM);
2437      viewForumURL.setParameter("f", "" + forumId);
2438      root.put("U_VIEW_FORUM", viewForumURL.toString());
2439      root.put("U_MARK_READ", "index.html?module=bb&op=viewforum&f=" + forumId
2440         + "&mark=topics");
2441      root.put("PAGE_NUMBER", pageNumber.toString());
2442      root.put("PAGINATION", toTopic.generate());
2443
2444      // root.put("JUMPBOX", makeJumpBox("viewforum", loggedIn));
2445
return root;
2446   }
2447
2448   private DelegateContext fillShowNewTopicContext(JBossRenderRequest req,
2449                                                   JBossRenderResponse resp, DelegateContext root)
2450   {
2451      PortletURL topicSubmitURL = resp.createActionURL();
2452      topicSubmitURL.setParameter("op", "posting");
2453      String JavaDoc forumID = req.getParameter("f");
2454      if (forumID != null)
2455      {
2456         topicSubmitURL.setParameter("f", forumID);
2457      }
2458
2459      String JavaDoc postID = req.getParameter("p");
2460      if (postID != null)
2461      {
2462         topicSubmitURL.setParameter("p", postID);
2463      }
2464
2465      if (req.getParameter("S_HIDDEN_FORM_FIELDS") != null)
2466      {
2467         root.put("S_HIDDEN_FORM_FIELDS", req
2468            .getParameter("S_HIDDEN_FORM_FIELDS"));
2469      }
2470      else
2471      {
2472         root.put("S_HIDDEN_FORM_FIELDS",
2473            "<input type=\"hidden\" name=\"mode\" value=\""
2474            + req.getParameter("mode") + "\" />");
2475      }
2476
2477      root.put("U_FORM_SUBMIT", topicSubmitURL.toString());
2478
2479      String JavaDoc instantReplyHiddenFormFields = "<input type=\"hidden\" name=\"attach_sig\" value=\"-1\"/>\n";
2480      root.put("S_INSTANT_REPLY_HIDDEN_FORM_FIELDS",
2481         instantReplyHiddenFormFields);
2482
2483      if (req.getParameters().getParameterExists("preview"))
2484      {
2485         DelegateContext preview = root.next("preview");
2486         preview.put("PREVIEW_SUBJECT", req.getParameter("PREVIEW_SUBJECT"));
2487         preview.put("TOPIC_TITLE", req.getParameter("TOPIC_TITLE"));
2488         preview.put("POSTER_NAME", req.getParameter("POSTER_NAME"));
2489         preview.put("POST_DATE", req.getParameter("POST_DATE"));
2490         preview.put("PREVIEW_MESSAGE", req.getParameter("PREVIEW_MESSAGE"));
2491      }
2492
2493      root.put("SUBJECT", req.getParameter("SUBJECT"));
2494      root.put("MESSAGE", req.getParameter("MESSAGE"));
2495      root.next("switch_notify_checkbox");
2496      root.put("S_NOTIFY_CHECKED", "checked");
2497
2498      Forum forum = null;
2499      try
2500      {
2501         Integer JavaDoc forumId = req.getParameters().getIntObject("f");
2502         forum = forumsModule.findForumByID(forumId);
2503      }
2504      catch (ModuleException e1)
2505      {
2506         // TODO Auto-generated catch block
2507
e1.printStackTrace();
2508      }
2509      Category category = forum.getCategory();
2510      String JavaDoc forumName = forum.getName();
2511      String JavaDoc[] testArray = new String JavaDoc[]{category.getTitle(), forum.getName()};
2512      boolean authMod = req.hasPermission(testArray, "ModerateForum"); //Auth.hasLevel(Auth.LEVEL_MOD, loggedIn, level);
2513
if (authMod)
2514      {
2515         root.next("auth_mod");
2516         root.next("switch_type_toggle");
2517      }
2518
2519      return root;
2520   }
2521
2522   private DelegateContext fillShowTopicContext(JBossRenderRequest req,
2523                                                JBossRenderResponse resp, DelegateContext root)
2524   {
2525      ResourceBundle JavaDoc bundle = getResourceBundle(req.getLocale());
2526
2527      Integer JavaDoc topicId = req.getParameters().getIntObject("t", -1);
2528      Integer JavaDoc postId = req.getParameters().getIntObject("p", -1);
2529      int start = req.getParameters().getInt("start", 0);
2530      String JavaDoc view = req.getParameter("view");
2531      int postDays = req.getParameters().getInt("postdays", 0);
2532      String JavaDoc vote = req.getParameter("vote");
2533
2534      if ((topicId.intValue() == -1) && (postId.intValue() == -1))
2535      {
2536         // Die.exit(GENERAL_MESSAGE, "${bb.Topic_post_not_exist}");
2537
}
2538
2539      Topic topic = null;
2540      Forum forum = null;
2541      Category category = null;
2542      User user = req.getUser();
2543      boolean loggedIn = user != null;
2544
2545      // try
2546
// {
2547
if (postId.intValue() == -1)
2548      {
2549         if (view != null)
2550         {
2551            if ("newest".equals(view))
2552            {
2553               if (user != null)
2554               {
2555                  // Date lastVisit = user.getPreviousLastVisitDate();
2556
Date JavaDoc lastVisit = user.getLastVisitDate();
2557                  try
2558                  {
2559                     topic = forumsModule.findTopicByID(topicId);
2560                     Post post = topic.getLastPost();
2561
2562                     // homesRO.post.findLatestPost(lastVisit, topic);
2563
// resp. sendRedirect("index.html?module=bb&op=viewtopic&p=" + post.getID() + "#" + post.getID());
2564
return null;
2565                  }
2566                  catch (ModuleException e)
2567                  {
2568                     // Die.exit(GENERAL_MESSAGE, "${No_new_posts_last_visit}");
2569
}
2570               }
2571               else
2572               {
2573                  // page.sendRedirect("index.html?module=bb&op=viewtopic&t=" + topicId);
2574
// return;
2575
}
2576            }
2577            else if ("next".equals(view))
2578            {
2579               /*
2580                try
2581                {
2582                topic = (TopicEJBLocal)BBTools.head(homesRO.topic.findNext(topicId));
2583                }
2584                catch (FinderException e)
2585                {
2586                Die.exit(GENERAL_ERROR, "Could not obtain newer/older topic information", e);
2587                }
2588                */

2589            }
2590            else if ("previous".equals(view))
2591            {
2592               /*
2593                try
2594                {
2595                topic = (TopicEJBLocal)BBTools.head(homesRO.topic.findPrevious(topicId));
2596                }
2597                catch (FinderException e)
2598                {
2599                Die.exit(GENERAL_ERROR, "Could not obtain newer/older topic information", e);
2600                }
2601                */

2602            }
2603
2604            /*
2605             if (topic == null)
2606             {
2607             Die.exit(GENERAL_MESSAGE, "next".equals(view) ? "${bb.No_newer_topics}" : "${bb.No_older_topics}");
2608             }
2609             topicId = topic.getId();
2610             forum = topic.getForum();
2611             category = forum.getCategory();
2612             */

2613         }
2614         else
2615         // Common use case, showing the topic with topicID as is, no postId defined
2616
{
2617            try
2618            {
2619               topic = forumsModule.findTopicByID(topicId);
2620               forum = topic.getForum();
2621               category = forum.getCategory();
2622            }
2623            catch (ModuleException e)
2624            {
2625               // TODO Auto-generated catch block
2626
e.printStackTrace();
2627            }
2628         }
2629      }
2630      else
2631      {
2632         Post post;
2633         try
2634         {
2635            post = forumsModule.findPostByID(postId);
2636            topic = post.getTopic();
2637            forum = topic.getForum();
2638            category = forum.getCategory();
2639
2640            // start = (int)(Math.floor(((double)(size.intValue() - 1) / postPerPage)) * postPerPage);
2641
topicId = topic.getID();
2642         }
2643         catch (ModuleException e1)
2644         {
2645            // TODO Auto-generated catch block
2646
e1.printStackTrace();
2647         }
2648
2649         // Long size = homesRO.post.countPostsBefore(post);
2650
}
2651
2652      // }
2653
// catch (ObjectNotFoundException e)
2654
// {
2655
// Die.exit(GENERAL_MESSAGE, "${bb.Topic_post_not_exist}");
2656
// }
2657
// catch (FinderException e)
2658
// {
2659
// Die.exit(GENERAL_ERROR, "Could not obtain topic information", e);
2660
// }
2661
String JavaDoc[] testArray = {category.getTitle(), forum.getName()};
2662      boolean authView = req.hasPermission(testArray, "ReadForum");
2663      boolean authRead = req.hasPermission(testArray, "ReadForum");
2664      boolean authDelete = req.hasPermission(testArray, "DeletePostInForum");
2665      boolean authPost = req.hasPermission(testArray, "AddPostInForum");
2666      boolean authVote = req.hasPermission(testArray, "AddPostInForum");
2667      boolean authEdit = req.hasPermission(testArray, "EditPostInForum");
2668      boolean authMod = req.hasPermission(testArray, "ModerateForum");
2669
2670      if (authPost)
2671      {
2672         root.next("DISPLAY_REPLY_BOX");
2673      }
2674
2675      // if (!authView || !authRead)
2676
// {
2677
if (loggedIn)
2678      {
2679         // $redirect = ( isset($post_id) ) ? POST_POST_URL . "=$post_id" : POST_TOPIC_URL . "=$topic_id";
2680
// $redirect .= ( isset($start) ) ? "&start=$start" : '';
2681
// redirect(append_sid("login.$phpEx?redirect=viewtopic.$phpEx&$redirect", true));
2682
// page.sendRedirect("index.html?module=user&=getlogin");
2683
// return;
2684
}
2685
2686      // Die.exit(GENERAL_MESSAGE, !authView ? "${bb.Topic_post_not_exist}" : "${bb.Sorry_auth_read_0}TODO:$is_auth['auth_read_type']${bb.Sorry_auth_read_1}");
2687
// }
2688
Integer JavaDoc forumId = forum.getID();
2689      int forumStatus = forum.getStatus();
2690      int topicStatus = topic.getStatus();
2691      String JavaDoc forumName = forum.getName();
2692      String JavaDoc topicTitle = topic.getSubject();
2693
2694      // Is user watching this thread ?
2695
boolean isWatching = false;
2696      boolean canWatch = false;
2697      if (loggedIn)
2698      {
2699         // try
2700
// {
2701
canWatch = true;
2702
2703         /*
2704          try
2705          {
2706          TopicWatchEJBPK key = new TopicWatchEJBPK(user.getId(), topic.getId());
2707          TopicWatchEJBLocal watch = homesRO.topicWatch.findByPrimaryKey(key);
2708          String unwatch = page.getParameter("unwatch");
2709          if (unwatch != null)
2710          {
2711          if ("topic".equals(unwatch))
2712          {
2713          isWatching = false;
2714          watch.remove();
2715          }
2716          Die.exit(GENERAL_MESSAGE, "${bb.No_longer_watching}<br/><br/>${bb.Click_return_topic_0}" +
2717          "<a HREF=\"index.html?module=bb&op=viewtopic&t=" + topicId +
2718          "&start=" + start + "\">${bb.Click_return_topic_1}</a>${bb.Click_return_topic_2}");
2719          }
2720          else
2721          {
2722          isWatching = true;
2723          }
2724          }
2725          catch (ObjectNotFoundException e)
2726          {
2727          String watch = page.getParameter("watch");
2728          if (watch != null)
2729          {
2730          if ("topic".equals(watch))
2731          {
2732          homesRO.topicWatch.create(user, topic);
2733          isWatching = true;
2734          }
2735          String message = "${bb.You_are_watching}<br/><br/>${bb.Click_return_topic_0}" +
2736          "<a HREF=\"index.html?module=bb&op=viewtopic&t=" + topicId +
2737          "&start=" + start + "\">${bb.Click_return_topic_1}</a>${bb.Click_return_topic_2}";
2738          Die.exit(GENERAL_MESSAGE, message);
2739          }
2740          else
2741          {
2742          isWatching = false;
2743          }
2744          }
2745          }
2746          catch (RemoveException e)
2747          {
2748          Die.rollback(GENERAL_ERROR, "Could not delete topic watch information", e);
2749          }
2750          catch (CreateException ce)
2751          {
2752          Die.rollback(GENERAL_ERROR, "Could not insert topic watch information", ce);
2753          }
2754          catch (FinderException e)
2755          {
2756          Die.exit(GENERAL_ERROR, "Could not obtain topic watch information", e);
2757          }*/

2758      }
2759      else
2760      {
2761         /*
2762          if ("topic".equals(page.getParameter("unwatch")))
2763          {
2764          // redirect(append_sid("login.$phpEx?redirect=viewtopic.$phpEx&" . POST_TOPIC_URL . "=$topic_id&unwatch=topic", true));
2765          // page.sendRedirect("index.html?module=user&op=getlogin");
2766          // return;
2767          }
2768          else
2769          {
2770          canWatch = false;
2771          isWatching = false;
2772          }
2773          */

2774      }
2775
2776      int totalReplies = 0;
2777      Date JavaDoc minPostDate = null;
2778      if (postDays > 0)
2779      {
2780         Calendar JavaDoc c = Calendar.getInstance();
2781         c.add(Calendar.DATE, -postDays);
2782         minPostDate = c.getTime();
2783
2784         /*
2785          try
2786          {
2787          Collection result = homesRO.post.selectGeneric("SELECT p.id FROM post AS p WHERE p.topic=?1 AND p.postDate>=?2",
2788          new Object[]{topic, minPostDate});
2789          totalReplies = result.size();
2790          }
2791          catch (FinderException e)
2792          {
2793          Die.exit(GENERAL_ERROR, "Could not obtain limited topics count information", e);
2794          }
2795          */

2796
2797         // if ( !empty($HTTP_POST_VARS['postdays']))
2798
// {
2799
// $start = 0;
2800
// }
2801
}
2802      else
2803      {
2804         totalReplies = topic.getReplies();
2805         postDays = 0;
2806      }
2807
2808      // String selectPostDays = BBTools.selectDays("postdays", postDays);
2809
// TODO: get from User pref
2810
boolean postOrderAsc = true;
2811
2812      // String asc = req.getParameter("postorder");
2813
// boolean postOrderAsc = asc != null ? "asc".equals(asc) : user == null ? true : !user.getSortOrderDescending();
2814
// Decide how to order the post display
2815
// String selectPostOrder = "<select name=\"postorder\"><option value=\"asc\">" +
2816
// "${bb.Oldest_First}</option><option value=\"desc\" selected=\"selected\">" +
2817
// "${bb.Newest_First}</option></select>";
2818

2819      /* if (postOrderAsc)
2820       {
2821       selectPostOrder = "<select name=\"postorder\"><option value=\"asc\" selected=\"selected\">" +
2822       "${bb.Oldest_First}</option><option value=\"desc\">" +
2823       "${bb.Newest_First}</option></select>";
2824       }
2825       */

2826      List JavaDoc posts = null;
2827      int totalPosts = 0;
2828
2829      // TODO: get from user pref
2830
int postsPerPage = 10;
2831      try
2832      {
2833         /*
2834          posts = postOrderAsc ?
2835          (minPostDate != null ?
2836          homesRO.post.findByTopicBeforeAsc(topic, minPostDate, start, postPerPage) :
2837          homesRO.post.findByTopicAsc(topic, start, postPerPage)) :
2838          (minPostDate != null ?
2839          homesRO.post.findByTopicBeforeDesc(topic, minPostDate, start, postPerPage) :
2840          homesRO.post.findByTopicDesc(topic, start, postPerPage));
2841          */

2842         posts = forumsModule.findPostsByTopicIDAsc(topicId, start,
2843            postsPerPage);
2844         totalPosts = posts.size();
2845      }
2846      catch (ModuleException e)
2847      {
2848         e.printStackTrace();
2849
2850         //Die.exit(GENERAL_ERROR, "Could not obtain post/user information.", e);
2851
}
2852
2853      if (totalPosts == 0)
2854      {
2855         // Die.exit(GENERAL_MESSAGE, "${bb.No_posts_topic}");
2856
}
2857
2858      // $sql = "SELECT *
2859
// FROM " . RANKS_TABLE . "
2860
// ORDER BY rank_special, rank_min";
2861
// if ( !($result = $db->sql_query($sql)) )
2862
// {
2863
// message_die(GENERAL_ERROR, "Could not obtain ranks information.", '', __LINE__, __FILE__, $sql);
2864
// }
2865
//
2866
// $ranksrow = array();
2867
// while ( $row = $db->sql_fetchrow($result) )
2868
// {
2869
// $ranksrow[] = $row;
2870
// }
2871
// $db->sql_freeresult($result);
2872
//
2873
////
2874
topicTitle = formatTitle(topicTitle);
2875
2876      //
2877
////
2878
//// Was a highlight request part of the URI?
2879
////
2880
// $highlight_match = $highlight = '';
2881
// if (isset($HTTP_GET_VARS['highlight']))
2882
// {
2883
// // Split words and phrases
2884
// $words = explode(' ', trim(htmlspecialchars(urldecode($HTTP_GET_VARS['highlight']))));
2885
//
2886
// for($i = 0; $i < sizeof($words); $i++)
2887
// {
2888
// if (trim($words[$i]) != '')
2889
// {
2890
// $highlight_match .= (($highlight_match != '') ? '|' : '') . str_replace('*', '\w*', phpbb_preg_quote($words[$i], '#'));
2891
// }
2892
// }
2893
// unset($words);
2894
//
2895
// $highlight = urlencode($HTTP_GET_VARS['highlight']);
2896
// }
2897
PortletURL newTopicURL;
2898      newTopicURL = resp.createRenderURL();
2899      newTopicURL.setParameter("op", OP_POSTING);
2900      newTopicURL.setParameter("f", "" + forumId);
2901      newTopicURL.setParameter("mode", "newtopic");
2902
2903      /*
2904       PortletURL replyTopicURL;
2905       replyTopicURL = resp.createRenderURL();
2906       replyTopicURL.setParameter("op", OP_POSTING);
2907       replyTopicURL.setParameter("mode", "reply");
2908       replyTopicURL.setParameter("p", "" + topic.getLastPost().getID());
2909       */

2910      PortletURL replyTopicURL;
2911      replyTopicURL = resp.createActionURL();
2912      replyTopicURL.setParameter("op", "posting");
2913      replyTopicURL.setParameter("mode", "reply");
2914      replyTopicURL.setParameter("p", "" + topic.getLastPost().getID());
2915      replyTopicURL.setParameter("f", "" + forumId);
2916
2917      // replyTopicURL.setParameter("f", "" + forumId);
2918
// String replyTopicUrl = "index.html?module=bb&op=posting&mode=reply&p=" + topic.getLastPost().getID();
2919
PortletURL viewForumURL = resp.createRenderURL();
2920      viewForumURL.setParameter("op", OP_SHOWFORUM);
2921      viewForumURL.setParameter("f", "" + forumId);
2922      PortletURL viewCategoryURL = resp.createRenderURL();
2923      viewCategoryURL.setParameter("op", OP_MAIN);
2924      viewCategoryURL.setParameter("c", "" + category.getID());
2925      PortletURL replySubmitURL = resp.createActionURL();
2926      replySubmitURL.setParameter("op", "posting");
2927
2928      String JavaDoc viewPrevTopicUrl = "index.html?module=bb&op=viewtopic&t="
2929         + topicId + "&view=previous";
2930      String JavaDoc viewNextTopicUrl = "index.html?module=bb&op=viewtopic&t="
2931         + topicId + "&view=next";
2932
2933      String JavaDoc replyImg = theme.resourceReplyNewURL;
2934      String JavaDoc replyAlt = bundle.getString("Reply_to_topic");
2935      String JavaDoc postImg = theme.resourcePostNewURL;
2936      String JavaDoc postAlt = bundle.getString("Post_new_topic");
2937      if (forumStatus == FORUM_LOCKED)
2938      {
2939         replyImg = theme.resourceReplyLockedURL;
2940         replyAlt = bundle.getString("Topic_locked");
2941         postImg = theme.resourcePostLockedURL;
2942         postAlt = bundle.getString("Forum_locked");
2943      }
2944      else if (topicStatus == TOPIC_LOCKED)
2945      {
2946         replyImg = theme.resourceReplyLockedURL;
2947         replyAlt = bundle.getString("Topic_locked");
2948      }
2949
2950      if (authPost)
2951      {
2952         root.next("AUTH_POST");
2953      }
2954
2955      if (loggedIn)
2956      {
2957         // Map trackingTopics = getTrackingTopics(page);
2958
// Map trackingForums = getTrackingForums(page);
2959
// Date topicDate = (Date)trackingTopics.get(topicId);
2960
// Date forumDate = (Date)trackingForums.get(forumId);
2961

2962         /*
2963          Date topicLastRead = null;
2964          if (topicDate != null && forumDate != null)
2965          {
2966          topicLastRead = topicDate.after(forumDate) ? topicDate : forumDate;
2967          }
2968          else if (topicDate != null || forumDate != null)
2969          {
2970          topicLastRead = topicDate != null ? topicDate : forumDate;
2971          }
2972          else
2973          {
2974          // topicLastRead = user.getPreviousLastVisitDate();
2975          topicLastRead = user.getLastVisitDate();
2976          }
2977          // if ( count($tracking_topics) >= 150 && empty($tracking_topics[$topic_id]) )
2978          // {
2979          // asort($tracking_topics);
2980          // unset($tracking_topics[key($tracking_topics)]);
2981          // }
2982          trackingTopics.put(topicId, new Date());
2983          */

2984      }
2985
2986      StringBuffer JavaDoc authCan = new StringBuffer JavaDoc();
2987
2988      // BBTools.authCan(authCan, forum, loggedIn, level);
2989
String JavaDoc topicMod = "";
2990
2991      /*
2992       if (authMod)
2993       {
2994       authCan.append(bundle.getString("Rules_moderate_0") + "<a HREF=\"index.html?module=bb&op=modcp&f=")
2995       .append(forumId).append("\">" + bundle.getString("Rules_moderate_1") + "</a>"
2996       + bundle.getString("Rules_moderate_2"));
2997       topicMod =
2998       "<a HREF=\"index.html?module=bb&op=modcp&t=" + topic.getId() + "&mode=delete\">" + "<img SRC=\""
2999       + theme.resourceTopicModeDeleteURL + "\" alt=\"" + bundle.getString("Delete_topic") + "\" title=\""
3000       + bundle.getString("Delete_topic") + "\" " + "border=\"0\"/></a>&nbsp;"
3001       + "<a HREF=\"index.html?module=bb&op=modcp&t=" + topic.getId() + "&mode=move\">" + "<img SRC=\""
3002       + theme.resourceTopicModMoveURL + "\" alt=" + bundle.getString("Move_topic") + "\" " + "title=\""
3003       + bundle.getString("Move_topic") + "\" border=\"0\"/></a>&nbsp;"
3004       + ((topicStatus == TOPIC_UNLOCKED)
3005       ? ("<a HREF=\"index.html?module=bb&op=modcp&t=" + topic.getId() + "&mode=lock\">" + "<img SRC=\""
3006       + theme.resourceTopicModLockURL + "\" alt=\"" + bundle.getString("Lock_topic") + "\" " + "title=\""
3007       + bundle.getString("Lock_topic") + "\" border=\"0\" /></a>&nbsp;")
3008       : ("<a HREF=\"index.html?module=bb&op=modcp&t=" + topic.getId() + "&mode=unlock\">" + "<img SRC=\""
3009       + theme.resourceTopicModUnlockURL + "\" alt=\"" + bundle.getString("Unlock_topic") + "\" "
3010       + "title=\"" + bundle.getString("Unlock_topic") + "\" border=\"0\"/></a>&nbsp;"))
3011       + "<a HREF=\"index.html?module=bb&op=modcp&t=" + topic.getId() + "&mode=split\">" + "<img SRC=\""
3012       + theme.resourceTopicModSplitURL + "\" " + "alt=\"" + bundle.getString("Split_topic") + "\" title=\""
3013       + bundle.getString("Split_topic") + "\" border=\"0\"/></a>&nbsp;";
3014       }
3015       */

3016      String JavaDoc watchingTopic = "";
3017      String JavaDoc watchingTopicImg = "";
3018
3019      /*
3020       if (canWatch)
3021       {
3022       if (isWatching)
3023       {
3024       watchingTopic = "<a HREF=\"index.html?module=bb&op=viewtopic&t=" + topicId +
3025       "&unwatch=topic&start=" + start + "\">${bb.Stop_watching_topic}</a>";
3026       String url = theme.resourceTopicUnWatchURL;
3027       watchingTopicImg = "".equals(url) ? "" : "<a HREF=\"index.html?module=bb&op=viewtopic&t=" +
3028       topicId + "&unwatch=topic&start=" + start + "\"><img SRC=\"" + url +
3029       "\" alt=\"" + bundle.getString("Stop_watching_topic") + "\" title=\"" + bundle.getString("Stop_watching_topic") + "\" border=\"0\"></a>";
3030       }
3031       else
3032       {
3033       watchingTopic = "<a HREF=\"index.html?module=bb&op=viewtopic&t=" + topicId +
3034       "&watch=topic&start=" + start + "\">${bb.Start_watching_topic}</a>";
3035       String url = theme.resourceTopicWatchURL;
3036       watchingTopicImg = "".equals(url) ? "" : "<a HREF=\"index.html?module=bb&op=viewtopic&t=" +
3037       topicId + "&watch=topic&start=" + start + "\"><img SRC=\"" + url +
3038       "\" alt=\"" + bundle.getString("Start_watching_topic") + "\" title=\"" + bundle.getString("Start_watching_topic") + "\" border=\"0\"></a>";
3039       }
3040       }
3041       */

3042
3043      // $pagination = ( $highlight != '' ) ? generate_pagination("viewtopic.$phpEx?" . POST_TOPIC_URL . "=$topic_id&amp;postdays=$post_days&amp;postorder=$post_order&amp;highlight=$highlight", $total_replies, $board_config['posts_per_page'], $start) : ;
3044
// TODO: get from user preferences
3045
int postPerPage = 10;
3046
3047      PortletURL gotoURL = resp.createRenderURL();
3048      gotoURL.setParameter("op", OP_SHOWTOPIC);
3049      gotoURL.setParameter("t", "" + topicId);
3050      gotoURL.setParameter("postDays", "" + postDays);
3051      gotoURL.setParameter("postorder", (postOrderAsc ? "asc" : "desc"));
3052      GotoWithOffset toPost = new GotoWithOffset(1 + totalReplies, start,
3053         postPerPage, gotoURL.toString() + "&start=", bundle
3054         .getString("Goto_page"), bundle.getString("Previous"), bundle
3055         .getString("Next"));
3056
3057      String JavaDoc pageNumber = bundle.getString("Page_of_0")
3058         + ((int)Math.floor((double)start / (postPerPage)) + 1)
3059         + bundle.getString("Page_of_1")
3060         + ((int)Math.ceil((double)(totalReplies + 1) / postPerPage))
3061         + bundle.getString("Page_of_2");
3062
3063      String JavaDoc instantReplyHiddenFormFields = "<input type=\"hidden\" name=\"attach_sig\" value=\"-1\"/>\n"
3064         + "<input type=\"hidden\" name=\"mode\" value=\"reply\"/>\n"
3065         + "<input type=\"hidden\" name=\"subject\" value=\"Re: "
3066         + topic.getSubject()
3067         + "\"/>\n"
3068         + "<input type=\"hidden\" name=\"p\" value=\""
3069         + topic.getLastPost().getID() + "\"/>\n";
3070
3071      // "<input type=\"hidden\" name=\"notify\" value=\"" + "checked" + "\"/>\n";
3072
// DelegateContext root = new DelegateContext();
3073
root.put("S_INSTANT_REPLY_HIDDEN_FORM_FIELDS",
3074         instantReplyHiddenFormFields);
3075      root.put("FORUM_ID", forumId.toString());
3076      root.put("FORUM_NAME", forumName);
3077      root.put("CATEGORY_NAME", category.getTitle());
3078      root.put("TOPIC_ID", topicId.toString());
3079      root.put("TOPIC_TITLE", topicTitle);
3080      root.put("PAGINATION", toPost.generate());
3081      root.put("PAGE_NUMBER", pageNumber);
3082      root.put("POST_IMG", postImg);
3083      root.put("REPLY_IMG", replyImg);
3084      root.put("L_POST_NEW_TOPIC", postAlt);
3085      root.put("L_POST_REPLY_TOPIC", replyAlt);
3086      root.put("S_TOPIC_LINK", "t");
3087
3088      // root.put("S_SELECT_POST_DAYS", selectPostDays);
3089
// root.put("S_SELECT_POST_ORDER", selectPostOrder);
3090
root.put("S_POST_DAYS_ACTION", "index.html?module=bb&op=viewtopic&t="
3091         + topicId + "&start=" + start);
3092      root.put("S_AUTH_LIST", authCan.toString());
3093      root.put("S_TOPIC_ADMIN", topicMod);
3094      root.put("S_WATCH_TOPIC", watchingTopic);
3095      root.put("S_WATCH_TOPIC_IMG", watchingTopicImg);
3096      root.put("U_VIEW_FORUM", viewForumURL.toString());
3097      root.put("U_VIEW_OLDER_TOPIC", viewPrevTopicUrl);
3098      root.put("U_VIEW_NEWER_TOPIC", viewNextTopicUrl);
3099      root.put("U_POST_NEW_TOPIC", newTopicURL.toString());
3100      root.put("U_POST_REPLY_TOPIC", replyTopicURL.toString());
3101
3102      // root.put("JUMPBOX", makeJumpBox("viewforum", loggedIn));
3103
root.put("U_VIEW_CATEGORY", viewCategoryURL.toString());
3104      root.put("U_VIEW_TOPIC", "index.html?module=bb&op=viewtopic&t=" + topicId
3105         + "&start=" + start + "&postdays=" + "postDays" + "&postorder="
3106         + "postOrder" + "&highlight=" + "highlight");
3107      root.put("U_REPLY_SUBMIT", replySubmitURL.toString());
3108
3109      /*
3110       PollEJBLocal poll = topic.getPoll();
3111       String pollBox = "";
3112       if (poll != null)
3113       {
3114       int voteOptions = -1;
3115       Collection options = null;
3116       try
3117       {
3118       options = homesRO.option.findByPoll(poll);
3119       voteOptions = options.size();
3120       }
3121       catch (FinderException e)
3122       {
3123       Die.exit(GENERAL_ERROR, "Could not obtain vote data for this topic", e);
3124       }
3125       String hiddenFields = "";
3126       if (voteOptions > 0)
3127       {
3128       String voteTitle = poll.getText();
3129       boolean userVoted = false;
3130       if (user != null)
3131       {
3132       try
3133       {
3134       userVoted = true;
3135       homesRO.vote.findByPollAndUser(poll, user);
3136       }
3137       catch (ObjectNotFoundException e)
3138       {
3139       userVoted = false;
3140       }
3141       catch (FinderException e)
3142       {
3143       Die.exit(GENERAL_ERROR, "Could not obtain user vote data for this topic", e);
3144       }
3145       }
3146       Template pollTpl = null;
3147       DelegateContext pollRoot = new DelegateContext();
3148       boolean viewResult = "viewresult".equals(vote);
3149       Calendar c = Calendar.getInstance();
3150       c.setTime(poll.getCreationDate());
3151       c.add(Calendar.DATE, poll.getLength());
3152       boolean pollExpired = c.before(new Date());
3153       if (userVoted || viewResult || pollExpired || !authVote || topic.getStatus() == TOPIC_LOCKED)
3154       {
3155       pollTpl = theme.TPL_THEME_VIEWTOPIC_POLL_RESULT;
3156       float voteResultsSum = 0;
3157       for (Iterator iterator = options.iterator();iterator.hasNext();)
3158       {
3159       OptionEJBLocal option = (OptionEJBLocal)iterator.next();
3160       voteResultsSum += option.getResult();
3161       }
3162       int voteGraphic = 0;
3163       for (Iterator iterator = options.iterator();iterator.hasNext();)
3164       {
3165       OptionEJBLocal option = (OptionEJBLocal)iterator.next();
3166       float votePercent = voteResultsSum > 0 ? option.getResult() / voteResultsSum : 0f;
3167       int voteGraphicLength = Math.round(votePercent * 205); // 205 == voteGraphicLength
3168       String voteGraphicImg = theme.getResourceURL("voting_graphic_" + voteGraphic);
3169       if ("".equals(voteGraphicImg))
3170       {
3171       voteGraphicImg = theme.getResourceURL("voting_graphic_0");
3172       voteGraphic = 0;
3173       }
3174       else
3175       {
3176       voteGraphic++;
3177       }
3178       DelegateContext optionRoot = pollRoot.next("poll_option");
3179       optionRoot.put("POLL_OPTION_CAPTION", formatVoteInfo(option.getText()));
3180       optionRoot.put("POLL_OPTION_RESULT", "" + option.getResult());
3181       optionRoot.put("POLL_OPTION_PERCENT", "" + votePercent); // sprintf("%.1d%%", ($vote_percent * 100))
3182       optionRoot.put("POLL_OPTION_IMG", voteGraphicImg);
3183       optionRoot.put("POLL_OPTION_IMG_WIDTH", "" + voteGraphicLength);
3184       }
3185       pollRoot.put("TOTAL_VOTES", "" + voteResultsSum);
3186       }
3187       else
3188       {
3189       pollTpl = theme.TPL_THEME_VIEWTOPIC_POLL_BALLOT;
3190       for (Iterator iterator = options.iterator();iterator.hasNext();)
3191       {
3192       Option option = (Option)iterator.next();
3193       DelegateContext optionRoot = pollRoot.next("poll_option");
3194       optionRoot.put("POLL_OPTION_ID", option.getId().toString());
3195       optionRoot.put("POLL_OPTION_CAPTION", formatVoteInfo(option.getText()));
3196       }
3197       pollRoot.put("U_VIEW_RESULTS", "index.html?module=bb&op=viewtopic&t=" + topicId +
3198       "&postdays=" + postDays + "&postorder=" + (postOrderAsc ? "asc" : "desc") +
3199       "&vote=viewresult");
3200       hiddenFields += "<input type=\"hidden\" name=\"module\" value=\"bb\"/>" +
3201       "<input type=\"hidden\" name=\"op\" value=\"posting\"/>" +
3202       "<input type=\"hidden\" name=\"t\" value=\"" + topicId +
3203       "\"/><input type=\"hidden\" name=\"mode\" value=\"vote\"/>";
3204       }
3205       // pollRoot.put("POLL_QUESTION", formatVoteTitle(voteTitle));
3206       pollRoot.put("S_HIDDEN_FIELDS", hiddenFields);
3207       pollBox = pollTpl.render(pollRoot);
3208       }
3209       }
3210       root.put("POLL_DISPLAY", pollBox);
3211       */

3212      topic.setViewCount(topic.getViewCount() + 1);
3213
3214      for (IndexIterator iterator = IndexIterator.wrap(posts.iterator(), -1); iterator
3215         .hasNext();)
3216      {
3217         Post post = (Post)iterator.next();
3218         User poster = post.getPoster().getUser();
3219
3220         int posterId = (poster != null) ? poster.getID().intValue() : 0;
3221         String JavaDoc postDate = post.getCreateDate().toString();
3222         String JavaDoc posterPosts = (poster != null) ? (bundle.getString("Posts")
3223            + ":" + poster.getUserName()) : "";
3224         String JavaDoc location = (String JavaDoc)poster.getProperties().get("LOCATION");
3225         String JavaDoc posterFrom = ((poster != null) && (location != null)) ? (bundle
3226            .getString("Location")
3227            + ":" + location) : "";
3228         String JavaDoc posterJoined = (poster != null) ? (bundle.getString("Joined")
3229            + ":" + poster.getRegistrationDate()) : "";
3230
3231         // String posterAvatar = "";
3232
// $poster_avatar = '';
3233
// if ( $postrow[$i]['user_avatar_type'] && $poster_id != ANONYMOUS && $postrow[$i]['user_allowavatar'] )
3234
// {
3235
// switch( $postrow[$i]['user_avatar_type'] )
3236
// {
3237
// case USER_AVATAR_UPLOAD:
3238
// $poster_avatar = ( $board_config['allow_avatar_upload'] ) ? '<img SRC="' . $board_config['avatar_path'] . '/' . $postrow[$i]['user_avatar'] . '" alt="" border="0" />' : '';
3239
// break;
3240
// case USER_AVATAR_REMOTE:
3241
// $poster_avatar = ( $board_config['allow_avatar_remote'] ) ? '<img SRC="' . $postrow[$i]['user_avatar'] . '" alt="" border="0" />' : '';
3242
// break;
3243
// case USER_AVATAR_GALLERY:
3244
// $poster_avatar = ( $board_config['allow_avatar_local'] ) ? '<img SRC="' . $board_config['avatar_gallery_path'] . '/' . $postrow[$i]['user_avatar'] . '" alt="" border="0" />' : '';
3245
// break;
3246
// }
3247
// }
3248
String JavaDoc miniPostImg = theme.resourceIconMinipostURL;
3249         String JavaDoc miniPostAlt = bundle.getString("Post");
3250         if (loggedIn && false) // $postrow[$i]['post_time'] > $userdata['user_lastvisit'] && $postrow[$i]['post_time'] > $topic_last_read
3251
{
3252            miniPostImg = theme.resourceIconMinipostNewURL;
3253            miniPostAlt = bundle.getString("New_post");
3254         }
3255
3256         // String miniPostUrl = "index.html?module=bb&op=viewtopic&p=" + post.getID() + "#" + postImg;
3257
// //
3258
// // Generate ranks, set them to empty string initially.
3259
// //
3260
// $poster_rank = '';
3261
// $rank_image = '';
3262
// if ( $postrow[$i]['user_id'] == ANONYMOUS )
3263
// {
3264
// }
3265
// else if ( $postrow[$i]['user_rank'] )
3266
// {
3267
// for($j = 0; $j < count($ranksrow); $j++)
3268
// {
3269
// if ( $postrow[$i]['user_rank'] == $ranksrow[$j]['rank_id'] && $ranksrow[$j]['rank_special'] )
3270
// {
3271
// $poster_rank = $ranksrow[$j]['rank_title'];
3272
// $rank_image = ( $ranksrow[$j]['rank_image'] ) ? '<img SRC="' . $ranksrow[$j]['rank_image'] . '" alt="' . $poster_rank . '" title="' . $poster_rank . '" border="0" /><br />' : '';
3273
// }
3274
// }
3275
// }
3276
// else
3277
// {
3278
// for($j = 0; $j < count($ranksrow); $j++)
3279
// {
3280
// if ( $postrow[$i]['user_posts'] >= $ranksrow[$j]['rank_min'] && !$ranksrow[$j]['rank_special'] )
3281
// {
3282
// $poster_rank = $ranksrow[$j]['rank_title'];
3283
// $rank_image = ( $ranksrow[$j]['rank_image'] ) ? '<img SRC="' . $ranksrow[$j]['rank_image'] . '" alt="' . $poster_rank . '" title="' . $poster_rank . '" border="0" /><br />' : '';
3284
// }
3285
// }
3286
// }
3287
//
3288
// compute the displayed poster name
3289
String JavaDoc posterName = post.getPoster().getUser().getUserName();
3290         String JavaDoc profileImgLnk = "";
3291         String JavaDoc profileLnk = "";
3292         String JavaDoc pmImgLnk = "";
3293         String JavaDoc pmLnk = "";
3294         String JavaDoc emailImgLnk = "";
3295         String JavaDoc emailLnk = "";
3296         String JavaDoc wwwImgLnk = "";
3297         String JavaDoc wwwLnk = "";
3298         String JavaDoc icqStatusImgLnk = "";
3299         String JavaDoc icqImgLnk = "";
3300         String JavaDoc icqLnk = "";
3301         String JavaDoc aimImgLnk = "";
3302         String JavaDoc aimLnk = "";
3303         String JavaDoc msnImgLnk = "";
3304         String JavaDoc msnLnk = "";
3305         String JavaDoc yimImgLnk = "";
3306         String JavaDoc yimLnk = "";
3307         String JavaDoc editImgLnk = "";
3308         String JavaDoc editLnk = "";
3309         String JavaDoc repostImgLnk = "";
3310         String JavaDoc repostLnk = "";
3311         String JavaDoc ipImgLnk = "";
3312         String JavaDoc ipLnk = "";
3313
3314         /*
3315          if (poster != null)
3316          {
3317          String posterIcq = poster.getMessengerICQ();
3318          String posterAim = poster.getMessengerAIM();
3319          String posterMsn = poster.getMessengerMSNM();
3320          String posterYim = poster.getMessengerYIM();
3321          String profileUrl = "index.html?module=user&op=userinfo&uid=" + posterId;
3322          profileImgLnk = BBTools.createImageLink(profileUrl, theme.resourceIconProfileURL, "${bb.Read_profile}");
3323          profileLnk = BBTools.createLink(profileUrl, "${bb.Read_profile}");
3324          // String pmUrl = "privmsg.php?mode=post&u=" + posterId;
3325          String pmUrl = ""; // todo private message
3326          pmImgLnk = BBTools.createImageLink(pmUrl, theme.resourceIconPMURL, "${bb.Send_private_message}");
3327          pmLnk = BBTools.createLink(pmUrl, "${bb.Send_private_message}");
3328          if (!poster.getViewEmail() || authMod)
3329          {
3330          String emailUrl = emailForm ? "index.html?module=user&op=userinfo&uid=" + posterId :
3331          "mailto:" + poster.getEmail();
3332          emailImgLnk = BBTools.createImageLink(emailUrl, theme.resourceIconEmailURL, "${bb.Send_email}");
3333          emailLnk = BBTools.createLink(emailUrl, "${bb.Send_email}");
3334          }
3335          String websiteUrl = poster.getURL();
3336          if (websiteUrl != null && websiteUrl.length() > 0)
3337          {
3338          wwwImgLnk = BBTools.createImageLink(websiteUrl, "userwww", theme.resourceIconWWWURL, "${bb.Visit_website}", "${bb.Visit_website}");
3339          wwwLnk = BBTools.createLink(websiteUrl, "userwww", "${bb.Visit_website}");
3340          }
3341          if (posterIcq != null && posterIcq.length() > 0)
3342          {
3343          icqStatusImgLnk = "<a HREF=\"http://wwp.icq.com/" + posterIcq + "#pager\">" +
3344          "<img SRC=\"http://web.icq.com/" +
3345          "whitepages/online?icq=\"" + posterIcq +
3346          "&img=5\" width=\"18\" height=\"18\" border=\"0\"/></a>";
3347          String icqUrl = "http://wwp.icq.com/scripts/search.dll?to=" + posterIcq;
3348          icqImgLnk = BBTools.createImageLink(icqUrl, theme.resourceIconICQURL, "${bb.ICQ}");
3349          icqLnk = BBTools.createLink(icqUrl, "${bb.ICQ}");
3350          }
3351          if (posterAim != null && posterAim.length() > 0)
3352          {
3353          String aimUrl = "aim:goim?screenname=\"" + posterAim + "&message=Hello+Are+you+there?";
3354          aimImgLnk = BBTools.createImageLink(aimUrl, theme.resourceIconAIMURL, "${bb.AIM}");
3355          aimLnk = BBTools.createLink(aimUrl, "${bb.AIM}");
3356          }
3357          if (posterMsn != null && posterMsn.length() > 0)
3358          {
3359          String msnUrl = "index.html?module=user&op=userinfo&uid=" + posterId;
3360          msnImgLnk = BBTools.createImageLink(msnUrl, theme.resourceIconMSNMURL, "${bb.MSNM}");
3361          msnLnk = BBTools.createLink(msnUrl, "${bb.MSNM}");
3362          }
3363          if (posterYim != null && posterYim.length() > 0)
3364          {
3365          String yimUrl = "http://edit.yahoo.com/config/send_webmesg?.target=" + posterYim + "&src=pg";
3366          yimImgLnk = BBTools.createImageLink(yimUrl, theme.resourceIconYIMURL, "${bb.YIM}");
3367          yimLnk = BBTools.createLink(yimUrl, "${bb.YIM}");
3368          }
3369          }
3370          */

3371         /*
3372          String searchUrl = "index.html?module=bb&op=search&search_authors=${encodeurl:" + post.getPoster().getAuthor(false) + "}" + "&showresults=posts";
3373          String searchImg = BBTools.createImageLink(searchUrl, theme.resourceIconSearchURL, "${bb.Search_user_posts}");
3374          String search = BBTools.createLink(searchUrl, "${bb.Search_user_posts}");
3375          if ((EJB.areIdentical(user, poster) && authEdit) || authMod)
3376          {
3377          String editUrl = "index.html?module=bb&op=posting&mode=editpost&p=" + post.getId();
3378          editImgLnk = "<a HREF=\"" + editUrl + "\"><img SRC=\"" + theme.resourceIconEditURL +
3379          "\" alt=\"${bb.Edit_delete_post}\" title=\"${bb.Edit_delete_post}\" border=\"0\"/></a>";
3380          editLnk = "<a HREF=\"" + editUrl + "\">${bb.Edit_delete_post}</a>";
3381          String repostUrl = "index.html?module=bb&op=posting&mode=repost&p=" + post.getId();
3382          repostImgLnk = "<a HREF=\"" + repostUrl + "\"><img SRC=\"" + theme.resourceIconRepostURL +
3383          "\" alt=\"${bb.Repost_post}\" title=\"${bb.Repost_post}\" border=\"0\"/></a>";
3384          repostLnk = "<a HREF=\"" + repostUrl + "\">${bb.Repost_post}</a>";
3385          }
3386          */

3387         boolean canDelete = false;
3388         boolean canIP = false;
3389
3390         if (authMod)
3391         {
3392            canDelete = true;
3393            canIP = true;
3394         }
3395         else
3396         {
3397            canDelete = authDelete
3398               && poster.getUserName().equals(user.getUserName())
3399               && topic.getLastPost().getID().equals(post.getID());
3400         }
3401
3402         // only moderators can use the IP function on a given topic
3403
if (canIP)
3404         {
3405            String JavaDoc url = "index.html?module=bb&op=modcp&mode=ip&p="
3406               + post.getID() + "&t=" + topicId;
3407
3408            // ipImgLnk = BBTools.createImageLink(url, theme.resourceIconIPURL, "${bb.View_IP}");
3409
// ipLnk = BBTools.createLink(url, "${bb.View_IP}");
3410
}
3411
3412         Message message = post.getMessage();
3413         String JavaDoc postSubject = message.getSubject();
3414         if (postSubject == null)
3415         {
3416            postSubject = "";
3417         }
3418
3419         String JavaDoc text = message.getText();
3420         if (text == null)
3421         {
3422            text = "";
3423         }
3424
3425         String JavaDoc signature = "";
3426
3427         /*
3428          if (message.getSignatureEnabled() && signatureEnabled)
3429          {
3430          signature = poster.getSignature();
3431          if (!BBTools.isNullOrBlank(signature))
3432          {
3433          signature = formatSignature(signature, message.getBBCodeEnabled(), message.getHTMLEnabled());
3434          }
3435          }
3436          */

3437         text = formatMessage(text, message.getBBCodeEnabled(), message
3438            .getHTMLEnabled());
3439         postSubject = formatTitle(postSubject);
3440
3441         // //
3442
// // Highlight active words (primarily for search)
3443
// //
3444
// if ($highlight_match)
3445
// {
3446
// // This was shamelessly 'borrowed' from volker at multiartstudio dot de
3447
// // via php.net's annotated manual
3448
// $message = str_replace('\"', '"', substr(preg_replace('#(\>(((?>([^><]+|(?R)))*)\<))#se', "preg_replace('#\b(" . $highlight_match . ")\b#i', '<span style=\"color:#" . $theme['fontcolor3'] . "\"><b>\\\\1</b></span>', '\\0')", '>' . $message . '<'), 1, -1));
3449
// }
3450
int editCount = post.getEditCount();
3451         String JavaDoc editedBy = "";
3452         if (editCount > 0)
3453         {
3454            String JavaDoc[] ett = (editCount == 1) ? new String JavaDoc[]{
3455               bundle.getString("Edited_time_total_0"),
3456               bundle.getString("Edited_time_total_1"),
3457               bundle.getString("Edited_time_total_2")} : new String JavaDoc[]{
3458                  bundle.getString("Edited_times_total_0"),
3459                  bundle.getString("Edited_times_total_1"),
3460                  bundle.getString("Edited_times_total_2")};
3461
3462            // editedBy = "<br/><br/>" + ett[0] + dateFormatPool.formatDate(post.getEditDate()) + ett[1] + editCount + ett[2];
3463
}
3464
3465         String JavaDoc rowColor = theme
3466            .getProperty(((iterator.getIndex() % 2) == 0) ? "td_color1"
3467            : "td_color2");
3468         String JavaDoc rowClass = theme
3469            .getProperty(((iterator.getIndex() % 2) == 0) ? "td_class1"
3470            : "td_class2");
3471
3472         DelegateContext postRow = root.next("postrow");
3473
3474         postRow.put("ROW_COLOR", rowColor);
3475         postRow.put("ROW_CLASS", rowClass);
3476         postRow.put("POSTER_NAME", posterName);
3477         postRow.put("POSTER_RANK", ""); // $poster_rank
3478
postRow.put("RANK_IMAGE", ""); // $rank_image
3479
postRow.put("POSTER_JOINED", posterJoined);
3480
3481         // postRow.put("POSTER_POSTS", posterPosts);
3482
postRow.put("POSTER_FROM", posterFrom);
3483         postRow.put("POSTER_AVATAR", ""); // $poster_avatar
3484
postRow.put("POST_DATE", postDate);
3485         postRow.put("POST_SUBJECT", postSubject);
3486         postRow.put("MESSAGE", text);
3487         postRow.put("SIGNATURE", signature);
3488         postRow.put("EDITED_MESSAGE", editedBy);
3489         postRow.put("MINI_POST_IMG", miniPostImg);
3490         postRow.put("PROFILE_IMG", profileImgLnk);
3491         postRow.put("PROFILE", profileLnk);
3492
3493         // postRow.put("SEARCH_IMG", searchImg);
3494
// postRow.put("SEARCH", search);
3495
postRow.put("PM_IMG", pmImgLnk);
3496         postRow.put("PM", pmLnk);
3497         postRow.put("EMAIL_IMG", emailImgLnk);
3498         postRow.put("EMAIL", emailLnk);
3499         postRow.put("WWW_IMG", wwwImgLnk);
3500         postRow.put("WWW", wwwLnk);
3501         postRow.put("ICQ_STATUS_IMG", icqStatusImgLnk);
3502         postRow.put("ICQ_IMG", icqImgLnk);
3503         postRow.put("ICQ", icqLnk);
3504         postRow.put("AIM_IMG", aimImgLnk);
3505         postRow.put("AIM", aimLnk);
3506         postRow.put("MSN_IMG", msnImgLnk);
3507         postRow.put("MSN", msnLnk);
3508         postRow.put("YIM_IMG", yimImgLnk);
3509         postRow.put("YIM", yimLnk);
3510         //postRow.put("EDIT_IMG", editImgLnk);
3511
//postRow.put("EDIT", editLnk);
3512
postRow.put("REPOST_IMG", repostImgLnk);
3513         postRow.put("REPOST", repostLnk);
3514
3515         if (authPost)
3516         {
3517            PortletURL quoteURL = resp.createActionURL();
3518            quoteURL.setParameter("mode", "quote");
3519            quoteURL.setParameter("op", "posting");
3520            quoteURL.setParameter("p", String.valueOf(post.getID()));
3521            quoteURL.setParameter("f", String.valueOf(forum.getID()));
3522
3523            //String quoteUrl = "index.html?module=bb&op=posting&mode=quote&p=" + post.getID();
3524
String JavaDoc quoteImg = ForumsTools.createImageLink(quoteURL.toString(),
3525               theme.resourceIconQuoteURL, bundle
3526               .getString("Reply_with_quote"));
3527            String JavaDoc quote = ForumsTools.createLink(quoteURL.toString(), bundle
3528               .getString("Reply_with_quote"));
3529            postRow.put("QUOTE_IMG", quoteImg);
3530            postRow.put("QUOTE", quote);
3531         }
3532
3533         if (authMod)
3534         {
3535            PortletURL editURL = resp.createActionURL();
3536            editURL.setParameter("mode", "editpost");
3537            editURL.setParameter("op", "posting");
3538            editURL.setParameter("p", String.valueOf(post.getID()));
3539            editURL.setParameter("f", String.valueOf(forum.getID()));
3540            String JavaDoc editImg = ForumsTools.createImageLink(editURL.toString(),
3541               theme.resourceIconEditURL, bundle
3542               .getString("Edit_Post"));
3543            String JavaDoc edit = ForumsTools.createLink(editURL.toString(), bundle
3544               .getString("Edit_Post"));
3545            postRow.put("EDIT_IMG", editImg);
3546            postRow.put("EDIT", edit);
3547         }
3548
3549
3550         postRow.put("IP_IMG", ipImgLnk);
3551         postRow.put("IP", ipLnk);
3552
3553         // only moderators can delete all messages from a given topic
3554
// if a user has the delete privilege on a forum that means he
3555
// in this forum can delete his own posts
3556
if (canDelete)
3557         {
3558            PortletURL deleteURL = resp.createActionURL();
3559            deleteURL.setParameter("mode", "delete");
3560            deleteURL.setParameter("op", "posting");
3561            deleteURL.setParameter("p", "" + post.getID());
3562
3563            String JavaDoc delPostImgLnk = ForumsTools.createImageLink(deleteURL
3564               .toString(), theme.resourceIconDelpostURL, bundle
3565               .getString("Delete_post"));
3566            String JavaDoc delPostLnk = ForumsTools.createLink(deleteURL.toString(),
3567               bundle.getString("Delete_post"));
3568            postRow.put("DELETE_IMG", delPostImgLnk);
3569            postRow.put("DELETE", delPostLnk);
3570         }
3571
3572         postRow.put("L_MINI_POST_ALT", miniPostAlt);
3573
3574         // postRow.put("U_MINI_POST", miniPostUrl);
3575
postRow.put("U_POST_ID", post.getID().toString());
3576
3577         // @author theute
3578
// Attachments TODO
3579

3580         /*
3581          Collection attachmentsCollection = post.getAttachments();
3582          String attachments = "";
3583          DelegateContext attachmentsContext = new DelegateContext();
3584          DelegateContext attachContext = attachmentsContext.next("attach");
3585          Iterator i = attachmentsCollection.iterator();
3586          AttachmentEJBLocal attachment = null;
3587          while (i.hasNext())
3588          {
3589          attachment = (AttachmentEJBLocal)i.next();
3590          if (attachment.getMimetype().startsWith("image/"))
3591          {
3592          DelegateContext catImagesContext = attachContext.next("cat_images");
3593          catImagesContext.put("COMMENT", attachment.getComment());
3594          catImagesContext.put("DOWNLOAD_NAME", attachment.getRealFilename());
3595          catImagesContext.put("IMG_SRC", "modules/bb/attach?id=" + attachment.getId());
3596          catImagesContext.put("FILESIZE", "" + attachment.getFilesize());
3597          catImagesContext.put("SIZE_VAR", "${bb.Bytes}");
3598          }
3599          else
3600          {
3601          DelegateContext attachRowContext = attachContext.next("attachrow");
3602          attachRowContext.put("COMMENT", attachment.getComment());
3603          attachRowContext.put("DOWNLOAD_NAME", attachment.getRealFilename());
3604          attachRowContext.put("U_DOWNLOAD_LINK", "modules/bb/attach?id=" + attachment.getId());
3605          attachRowContext.put("FILESIZE", attachment.getFilesize() + " ${bb.Bytes}");
3606          }
3607          }
3608          attachments = theme.TPL_THEME_VIEWTOPIC_ATTACH_BODY.render(attachmentsContext);
3609          postRow.put("ATTACHMENTS", attachments);
3610          */

3611      }
3612
3613      return root;
3614   }
3615
3616   private DelegateContext fillShowAddEditForumContext(JBossRenderRequest req,
3617                                                       JBossRenderResponse resp, DelegateContext root)
3618   {
3619      ResourceBundle JavaDoc bundle = getResourceBundle(req.getLocale());
3620
3621      String JavaDoc mode = req.getParameters().get("mode", "");
3622
3623      // default values for addforum case, miss only the forum name which is calculated under
3624
String JavaDoc title = bundle.getString("Create_forum");
3625      String JavaDoc newMode = "createforum";
3626      String JavaDoc buttonValue = bundle.getString("Create_forum");
3627      String JavaDoc forumName = "";
3628      String JavaDoc forumDesc = "";
3629      int forumStatus = FORUM_UNLOCKED;
3630      int forumId = -1;
3631      int categoryId = -1;
3632      String JavaDoc pruneEnabled = "";
3633
3634      if ("editforum".equals(mode))
3635      {
3636         // if edit forum, we override the addforum values
3637
title = bundle.getString("Edit_forum");
3638         newMode = "modforum";
3639         buttonValue = bundle.getString("Update");
3640         try
3641         {
3642            Forum forum = forumsModule.findForumByID(req.getParameters()
3643               .getIntObject("f"));
3644            forumId = forum.getID().intValue();
3645            categoryId = forum.getCategory().getID().intValue();
3646            forumName = forum.getName();
3647            forumDesc = forum.getDescription();
3648            forumStatus = forum.getStatus();
3649
3650            /*
3651             if (forum.getPruneEnable())
3652             {
3653             pruneEnabled = "checked=\"checked\"";
3654             // $sql = "SELECT *
3655             // FROM " . PRUNE_TABLE . "
3656             // WHERE forum_id = $forum_id";
3657             // if(!$pr_result = $db->sql_query($sql))
3658             // {
3659             // message_die(GENERAL_ERROR, "Auto-Prune: Couldn't read auto_prune table.", __LINE__, __FILE__);
3660             // }
3661             // $pr_row = $db->sql_fetchrow($pr_result);
3662             }
3663             */

3664         }
3665         catch (ModuleException e)
3666         {
3667            e.printStackTrace();
3668
3669            // Die.exit(GENERAL_ERROR, "Couldn't get Forum/Category information", e);
3670
}
3671      }
3672      else
3673      {
3674         categoryId = req.getParameters().getInt("c", -1);
3675
3676         // for the addforum mode we setup the forum name
3677
forumName = req.getParameter("forumname_" + categoryId);
3678      }
3679
3680      String JavaDoc forumLocked = "";
3681      String JavaDoc forumUnlocked = "selected=\"selected\"";
3682      if (forumStatus == FORUM_LOCKED)
3683      {
3684         forumLocked = forumUnlocked;
3685         forumUnlocked = "";
3686      }
3687
3688      String JavaDoc catList;
3689      try
3690      {
3691         catList = ForumsTools.listCategories(forumsModule.findCategories(),
3692            categoryId);
3693         root.put("S_CAT_LIST", catList);
3694      }
3695      catch (ModuleException e)
3696      {
3697         // TODO Auto-generated catch block
3698
e.printStackTrace();
3699      }
3700
3701      String JavaDoc statusList = "<option value=\"" + FORUM_UNLOCKED + "\" "
3702         + forumUnlocked + ">" + bundle.getString("Status_unlocked")
3703         + "</option>\n" + "<option value=\"" + FORUM_LOCKED + "\" "
3704         + forumLocked + ">" + bundle.getString("Status_locked")
3705         + "</option>\n";
3706      String JavaDoc hiddenFields = "<input type=\"hidden\" name=\"mode\" value=\""
3707         + newMode + "\"/>" + "<input type=\"hidden\" name=\"f\" value=\""
3708         + forumId + "\"/>"
3709         + "<input type=\"hidden\" name=\"module\" value=\"bb\"/>"
3710         + "<input type=\"hidden\" name=\"op\" value=\"admin_forums\"/>";
3711
3712      PortletURL postURL = resp.createActionURL();
3713      root.put("POST_URL", postURL.toString());
3714      root.put("S_HIDDEN_FIELDS", hiddenFields);
3715      root.put("S_SUBMIT_VALUE", buttonValue);
3716      root.put("S_STATUS_LIST", statusList);
3717      root.put("S_PRUNE_ENABLED", pruneEnabled);
3718      root.put("L_FORUM_TITLE", title);
3719      root.put("PRUNE_DAYS", "TODO_PRUNE_DAYS"); // ( isset($pr_row['prune_days']) ) ? $pr_row['prune_days'] : 7
3720
root.put("PRUNE_FREQ", "TODO_PRUNE_FREQ"); // ( isset($pr_row['prune_freq']) ) ? $pr_row['prune_freq'] : 1
3721
root.put("FORUM_NAME", forumName);
3722      root.put("DESCRIPTION", forumDesc);
3723
3724      return root;
3725   }
3726
3727   private DelegateContext fillShowAdminForumsContext(JBossRenderRequest req,
3728                                                      JBossRenderResponse resp, DelegateContext root)
3729   {
3730      String JavaDoc mode = req.getParameters().get("mode", "");
3731      boolean addCategory = req.getParameter("addcategory") != null;
3732      Category addforum = null;
3733
3734      try
3735      {
3736         for (Iterator i = forumsModule.findCategories().iterator(); i
3737            .hasNext();)
3738         {
3739            Category category = (Category)i.next();
3740            if (req.getParameter("addforum_" + category.getID()) != null)
3741            {
3742               addforum = category;
3743               break;
3744            }
3745         }
3746      }
3747      catch (ModuleException e)
3748      {
3749         e.printStackTrace();
3750
3751         // Die.exit(GENERAL_ERROR, "Cannot process command", e);
3752
}
3753
3754      if ((addforum != null) || addCategory)
3755      {
3756         if (addforum != null)
3757         {
3758            mode = "addforum";
3759         }
3760         else
3761         {
3762            mode = "addcat";
3763         }
3764      }
3765
3766      try
3767      {
3768         PortletURL postURL = resp.createActionURL();
3769         postURL.setParameters(req.getParameterMap());
3770         postURL.setParameter("op", "admin_forums");
3771         root.put("POST_URL", postURL.toString());
3772         for (Iterator i = forumsModule.findCategories().iterator(); i
3773            .hasNext();)
3774         {
3775            Category category = (Category)i.next();
3776            Integer JavaDoc categoryId = category.getID();
3777
3778            DelegateContext catrow = root.next("catrow");
3779            catrow.put("S_ADD_FORUM_SUBMIT", "addforum_" + categoryId);
3780            catrow.put("S_ADD_FORUM_NAME", "forumname_" + categoryId);
3781            catrow.put("CAT_ID", categoryId.toString());
3782            catrow.put("CAT_DESC", category.getTitle());
3783            PortletURL categoryEditURL = resp.createActionURL();
3784            categoryEditURL.setParameter("op", "admin_forums");
3785            categoryEditURL.setParameter("mode", "editcat");
3786            categoryEditURL.setParameter(POST_CAT_URL, "" + categoryId);
3787            catrow.put("U_CAT_EDIT", categoryEditURL.toString());
3788            PortletURL categoryDeleteURL = resp.createActionURL();
3789            categoryDeleteURL.setParameter("op", "admin_forums");
3790            categoryDeleteURL.setParameter("mode", "deletecat");
3791            categoryDeleteURL.setParameter(POST_CAT_URL, "" + categoryId);
3792            catrow.put("U_CAT_DELETE", categoryDeleteURL.toString());
3793            PortletURL catMoveUp = resp.createActionURL();
3794            catMoveUp.setParameter("op", "admin_forums");
3795            catMoveUp.setParameter("mode", "cat_order");
3796            catMoveUp.setParameter("move", "-15");
3797            catMoveUp.setParameter(POST_CAT_URL, "" + categoryId);
3798            catrow.put("U_CAT_MOVE_UP", catMoveUp.toString());
3799            PortletURL catMoveDown = resp.createActionURL();
3800            catMoveDown.setParameter("op", "admin_forums");
3801            catMoveDown.setParameter("mode", "cat_order");
3802            catMoveDown.setParameter("move", "15");
3803            catMoveDown.setParameter(POST_CAT_URL, "" + categoryId);
3804            catrow.put("U_CAT_MOVE_DOWN", catMoveDown.toString());
3805            PortletURL categoryViewURL = resp.createRenderURL();
3806            categoryViewURL.setParameter("op", OP_MAIN);
3807            categoryViewURL.setParameter(POST_CAT_URL, "" + categoryId);
3808            catrow.put("U_VIEWCAT", categoryViewURL.toString());
3809
3810            for (Iterator j = forumsModule.findForumsByCategoryID(categoryId)
3811               .iterator(); j.hasNext();)
3812            {
3813               Forum forum = (Forum)j.next();
3814               Integer JavaDoc forumId = forum.getID();
3815               DelegateContext forumrow = catrow.next("forumrow");
3816               forumrow.put("FORUM_NAME", forum.getName());
3817               forumrow.put("FORUM_DESC", forum.getDescription());
3818               forumrow.put("ROW_COLOR'", "$row_color");
3819               forumrow.put("NUM_TOPICS", "" + forum.getTopicCount());
3820               forumrow.put("NUM_POSTS", "" + forum.getPostCount());
3821               PortletURL viewForumURL = resp.createRenderURL();
3822               viewForumURL.setParameter(getOperationName(), OP_SHOWFORUM);
3823               viewForumURL.setParameter("f", "" + forumId);
3824               forumrow.put("U_VIEWFORUM", viewForumURL.toString());
3825               PortletURL forumEditURL = resp.createActionURL();
3826               forumEditURL.setParameter("op", "admin_forums");
3827               forumEditURL.setParameter("mode", "editforum");
3828               forumEditURL.setParameter("f", "" + forumId);
3829               forumrow.put("U_FORUM_EDIT", forumEditURL.toString());
3830               PortletURL forumDeleteURL = resp.createActionURL();
3831               forumDeleteURL.setParameter("op", "admin_forums");
3832               forumDeleteURL.setParameter("mode", "deleteforum");
3833               forumDeleteURL.setParameter("f", "" + forumId);
3834               forumrow.put("U_FORUM_DELETE", forumDeleteURL.toString());
3835               PortletURL forumMoveUpURL = resp.createActionURL();
3836               forumMoveUpURL.setParameter("op", "admin_forums");
3837               forumMoveUpURL.setParameter("mode", "forum_order");
3838               forumMoveUpURL.setParameter("move", "-15");
3839               forumMoveUpURL.setParameter("f", "" + forumId);
3840               forumrow.put("U_FORUM_MOVE_UP", forumMoveUpURL.toString());
3841               PortletURL forumMoveDownURL = resp.createActionURL();
3842               forumMoveDownURL.setParameter("op", "admin_forums");
3843               forumMoveDownURL.setParameter("mode", "forum_order");
3844               forumMoveDownURL.setParameter("move", "15");
3845               forumMoveDownURL.setParameter("f", "" + forumId);
3846               forumrow.put("U_FORUM_MOVE_DOWN", forumMoveDownURL.toString());
3847
3848               /*
3849                PortletURL forumResyncURL = resp.createActionURL();
3850                forumResyncURL.setParameter("op", "admin_forums");
3851                forumResyncURL.setParameter("mode", "forum_sync");
3852                forumResyncURL.setParameter("f", "" + forumId);
3853                forumrow.put("U_FORUM_RESYNC", forumResyncURL.toString());
3854                */

3855            }
3856         }
3857      }
3858      catch (ModuleException e)
3859      {
3860         e.printStackTrace();
3861
3862         // Die.exit(GENERAL_ERROR, "Could not query categories list");
3863
}
3864
3865      // display(theme.TPL_THEME_ADMIN_FORUM_ADMIN_BODY, root, page);
3866
return root;
3867   }
3868
3869   /**
3870    * DOCUMENT_ME
3871    *
3872    * @param req DOCUMENT_ME
3873    * @param resp DOCUMENT_ME
3874    */

3875   public void forum_watches(JBossActionRequest req, JBossActionResponse resp)
3876   {
3877      try
3878      {
3879         if (req.getParameters().getParameterExists("watch"))
3880         {
3881            Integer JavaDoc id = req.getParameters().getIntObject("forum_id", -1);
3882            boolean linked = "linked".equals(req.getParameter("watch_mode"));
3883            Forum forum = forumsModule.findForumByID(id);
3884            Poster poster = forumsModule.findPosterByUserID(req.getUser()
3885               .getID());
3886            String JavaDoc[] test = new String JavaDoc[]{forum.getCategory().getTitle(),
3887                                         forum.getName()};
3888            if (req.hasPermission(test, "ReadForum"))
3889            {
3890               if (poster == null)
3891               {
3892                  poster = forumsModule.createPoster(req.getUser().getID());
3893               }
3894               forumsModule.createWatch(poster, forum,
3895                  linked ? ForumsConstants.WATCH_MODE_LINKED
3896                  : ForumsConstants.WATCH_MODE_EMBEDED);
3897            }
3898         }
3899         else if (req.getParameters().getParameterExists("update"))
3900         {
3901            Integer JavaDoc forumWatchId = req.getParameters().getIntObject("forumwatch_id", -1);
3902            boolean linked = "linked".equals(req.getParameter("watch_mode"));
3903            ForumWatch watch = forumsModule.findForumWatchByID(forumWatchId);
3904            watch.setMode(linked ? ForumsConstants.WATCH_MODE_LINKED
3905               : ForumsConstants.WATCH_MODE_EMBEDED);
3906         }
3907         else if (req.getParameters().getParameterExists("unwatch"))
3908         {
3909            Integer JavaDoc forumWatchId = req.getParameters().getIntObject("forumwatch_id", -1);
3910            ForumWatch watch = forumsModule.findForumWatchByID(forumWatchId);
3911            forumsModule.removeWatch(watch);
3912         }
3913      }
3914      catch (ModuleException e)
3915      {
3916         e.printStackTrace();
3917      }
3918   }
3919
3920   /**
3921    * DOCUMENT_ME
3922    *
3923    * @param req DOCUMENT_ME
3924    * @param resp DOCUMENT_ME
3925    */

3926   public void topic_watches(JBossActionRequest req, JBossActionResponse resp)
3927   {
3928      try
3929      {
3930         Integer JavaDoc topicWatchId = req.getParameters().getIntObject("topicwatch_id", -1);
3931         TopicWatch watch = forumsModule.findTopicWatchByID(topicWatchId);
3932         forumsModule.removeWatch(watch);
3933      }
3934      catch (ModuleException e)
3935      {
3936         e.printStackTrace();
3937      }
3938   }
3939
3940   private DelegateContext fillShowWatchedForums(JBossRenderRequest req,
3941                                                 JBossRenderResponse resp, DelegateContext root)
3942   {
3943      Set JavaDoc forumIds = new HashSet JavaDoc();
3944      Collection JavaDoc watches;
3945      try
3946      {
3947         watches = forumsModule.findForumWatchByUser(req.getUser());
3948         if (watches.size() > 0)
3949         {
3950            root.next("switch_watched_forums_block");
3951            for (IndexIterator i = IndexIterator.wrap(watches.iterator()); i
3952               .hasNext();)
3953            {
3954               ForumWatch watch = (ForumWatch)i.next();
3955               Forum forum = watch.getForum();
3956
3957               // See if the user is authorized
3958
Category category = forum.getCategory();
3959               String JavaDoc[] test = new String JavaDoc[]{category.getTitle(),
3960                                            forum.getName()};
3961               if (req.hasPermission(test, "ReadForum"))
3962               {
3963                  boolean linked = watch.getMode() == ForumsConstants.WATCH_MODE_LINKED;
3964                  Integer JavaDoc forumId = forum.getID();
3965                  forumIds.add(forumId);
3966                  String JavaDoc forumIdAsString = forumId.toString();
3967                  root
3968                     .next("forum_watch_row")
3969                     .put("ROW_CLASS",
3970                        theme
3971                     .getProperty(((i.getIndex() & 1) == 0) ? "td_class1"
3972                     : "td_class2")).put("U_FORUM_LINK",
3973                        "index.html?module=bb&op=viewforum&f="
3974                     + forumIdAsString).put("FORUMWATCH_ID",
3975                        watch.getID()).put("FORUM_ID", forumIdAsString)
3976                     .put("S_FORUM_TITLE", forum.getName()).put("LINKED",
3977                        linked ? "checked=\"checked\"" : "").put("EMBEDED", linked ? "" : "checked=\"checked\"");
3978               }
3979            }
3980         }
3981         else
3982         {
3983            root.next("switch_no_watched_forums");
3984         }
3985
3986         StringBuffer JavaDoc select = new StringBuffer JavaDoc("<select name=\"forum_id\"><option value=\"\"></option>");
3987         Collection JavaDoc forums = forumsModule.findForums();
3988         for (Iterator i = forums.iterator(); i.hasNext();)
3989         {
3990            Forum forum = (Forum)i.next();
3991
3992            // Get the forum level
3993
Category category = forum.getCategory();
3994            String JavaDoc[] test = new String JavaDoc[]{category.getTitle(), forum.getName()};
3995
3996            // Display it only if the user is authorized
3997
if (req.hasPermission(test, "ReadForum"))
3998            {
3999               Integer JavaDoc forumid = forum.getID();
4000               if (!forumIds.contains(forumid))
4001               {
4002                  select.append("<option value=\"").append(forum.getID())
4003                     .append("\">").append(forum.getName()).append("</option>");
4004               }
4005            }
4006         }
4007
4008         select.append("</select>");
4009         root.put("S_FORUM_WATCH_SELECT", select.toString());
4010
4011         // display(theme.TPL_THEME_WATCHED_FORUMS_BODY, root, page);
4012
// }
4013
// catch(Exception e)
4014
// {
4015
// Die.rollback(GENERAL_ERROR, "Could not obtain watch forum information");
4016
// }
4017
}
4018      catch (ModuleException e)
4019      {
4020         // TODO Auto-generated catch block
4021
e.printStackTrace();
4022      }
4023
4024      return root;
4025   }
4026
4027   /**
4028    * DOCUMENT_ME
4029    *
4030    * @param text DOCUMENT_ME
4031    * @return DOCUMENT_ME
4032    */

4033   public String JavaDoc formatTitle(String JavaDoc text)
4034   {
4035      StringWriter JavaDoc stringWriter = new StringWriter JavaDoc();
4036      toHTMLRenderer.setWriter(stringWriter);
4037
4038      toHTMLRenderer.render(text.toCharArray(), 0, text.length());
4039      return stringWriter.toString();
4040   }
4041
4042   /**
4043    * DOCUMENT_ME
4044    *
4045    * @param text DOCUMENT_ME
4046    * @param allowBBCode DOCUMENT_ME
4047    * @param allowHTML DOCUMENT_ME
4048    * @return DOCUMENT_ME
4049    */

4050   public String JavaDoc formatMessage(String JavaDoc text, boolean allowBBCode,
4051                               boolean allowHTML)
4052   {
4053      return formatTitle(text);
4054   }
4055
4056   /**
4057    * DOCUMENT_ME
4058    *
4059    * @param text DOCUMENT_ME
4060    * @param allowBBCode DOCUMENT_ME
4061    * @param allowHTML DOCUMENT_ME
4062    * @return DOCUMENT_ME
4063    */

4064   public String JavaDoc formatSignature(String JavaDoc text, boolean allowBBCode,
4065                                 boolean allowHTML)
4066   {
4067      return "<br/>_________________<br/>" + formatTitle(text);
4068   }
4069
4070   /**
4071    *
4072    */

4073   public String JavaDoc formatUserName(User user)
4074   {
4075      return user.getUserName();
4076   }
4077
4078   /**
4079    * DOCUMENT_ME
4080    *
4081    * @param cmd DOCUMENT_ME
4082    * @return DOCUMENT_ME
4083    * @throws CommandException DOCUMENT_ME
4084    */

4085   public Result executeForumCommand(JBossActionRequest request,
4086                                     JBossActionResponse response, ForumCommand cmd)
4087      throws CommandException
4088   {
4089      // Finish the command configuration
4090
cmd.setModule(forumsModule);
4091
4092      // cmd.setHomes(homesRW);
4093
// Execute the command
4094
return chain.filter(cmd);
4095   }
4096
4097   /**
4098    * DOCUMENT_ME
4099    *
4100    * @param resp DOCUMENT_ME
4101    * @param key DOCUMENT_ME
4102    * @param error DOCUMENT_ME
4103    */

4104   public void addErrorMessage(JBossActionResponse resp, String JavaDoc key,
4105                               String JavaDoc error)
4106   {
4107      resp.setRenderParameter(key.toLowerCase() + "_error", error);
4108   }
4109
4110   /**
4111    * DOCUMENT_ME
4112    *
4113    * @param resp DOCUMENT_ME
4114    * @param key DOCUMENT_ME
4115    * @param success DOCUMENT_ME
4116    */

4117   public void addSuccessMessage(JBossActionResponse resp, String JavaDoc key,
4118                                 String JavaDoc success)
4119   {
4120      resp.setRenderParameter(key.toLowerCase() + "_success", success);
4121   }
4122}
Popular Tags