KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > jforum > view > forum > common > PostCommon


1 /*
2  * Copyright (c) Rafael Steil
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms,
6  * with or without modification, are permitted provided
7  * that the following conditions are met:
8  *
9  * 1) Redistributions of source code must retain the above
10  * copyright notice, this list of conditions and the
11  * following disclaimer.
12  * 2) Redistributions in binary form must reproduce the
13  * above copyright notice, this list of conditions and
14  * the following disclaimer in the documentation and/or
15  * other materials provided with the distribution.
16  * 3) Neither the name of "Rafael Steil" nor
17  * the names of its contributors may be used to endorse
18  * or promote products derived from this software without
19  * specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT
22  * HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
23  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
24  * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
25  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR
26  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
27  * THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES
30  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
31  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
32  * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
33  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
34  * IN CONTRACT, STRICT LIABILITY, OR TORT
35  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
36  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
37  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE
38  *
39  * This file creation date: 21/05/2004 - 15:33:36
40  * The JForum Project
41  * http://www.jforum.net
42  */

43 package net.jforum.view.forum.common;
44
45 import java.util.ArrayList JavaDoc;
46 import java.util.Collection JavaDoc;
47 import java.util.Date JavaDoc;
48 import java.util.Iterator JavaDoc;
49 import java.util.List JavaDoc;
50 import java.util.regex.Matcher JavaDoc;
51 import java.util.regex.Pattern JavaDoc;
52
53 import net.jforum.ActionServletRequest;
54 import net.jforum.JForumExecutionContext;
55 import net.jforum.SessionFacade;
56 import net.jforum.dao.PostDAO;
57 import net.jforum.entities.Post;
58 import net.jforum.entities.Smilie;
59 import net.jforum.repository.BBCodeRepository;
60 import net.jforum.repository.PostRepository;
61 import net.jforum.repository.SecurityRepository;
62 import net.jforum.repository.SmiliesRepository;
63 import net.jforum.security.SecurityConstants;
64 import net.jforum.util.SafeHtml;
65 import net.jforum.util.bbcode.BBCode;
66 import net.jforum.util.preferences.ConfigKeys;
67 import net.jforum.util.preferences.SystemGlobals;
68
69 /**
70  * @author Rafael Steil
71  * @version $Id: PostCommon.java,v 1.29 2006/02/21 13:59:48 rafaelsteil Exp $
72  */

73 public class PostCommon
74 {
75     private static PostCommon instance = new PostCommon();
76     
77     /**
78      * Gets the instance.
79      * This method only exists to situations where an instance is
80      * needed in the template context, so we don't need to
81      * create a new instance every time.
82      * @return
83      */

84     public static PostCommon getInstance()
85     {
86         return instance;
87     }
88     
89     public static Post preparePostForDisplay(Post p)
90     {
91         if (p.getText() == null) {
92             return p;
93         }
94         
95         if (!p.isHtmlEnabled()) {
96             p.setText(p.getText().replaceAll("<", "&lt;").replaceAll(">", "&gt;"));
97         }
98         
99         // DO NOT remove the trailing blank space
100
p.setText(p.getText().replaceAll("\n", "<br/> "));
101         
102         p.setText(alwaysProcess(p.getText(), BBCodeRepository.getBBCollection().getAlwaysProcessList()));
103
104         // Then, search for bb codes
105
if (p.isBbCodeEnabled()) {
106             p.setText(PostCommon.processText(p.getText()));
107         }
108
109         // Smilies...
110
if (p.isSmiliesEnabled()) {
111             p.setText(processSmilies(p.getText(), SmiliesRepository.getSmilies()));
112         }
113         
114         p.setText(SafeHtml.avoidJavascript(p.getText()));
115
116         return p;
117     }
118     
119     private static String JavaDoc alwaysProcess(String JavaDoc text, Collection JavaDoc bbList)
120     {
121         for (Iterator JavaDoc iter = bbList.iterator(); iter.hasNext(); ) {
122             BBCode bb = (BBCode)iter.next();
123             text = text.replaceAll(bb.getRegex(), bb.getReplace());
124         }
125         
126         return text;
127     }
128
129     public static String JavaDoc processText(String JavaDoc text)
130     {
131         if (text == null) {
132             return null;
133         }
134
135         if (text.indexOf('[') > -1 && text.indexOf(']') > -1) {
136             Iterator JavaDoc tmpIter = BBCodeRepository.getBBCollection().getBbList().iterator();
137
138             while (tmpIter.hasNext()) {
139                 BBCode bb = (BBCode) tmpIter.next();
140
141                 // Another hack for the quotes
142
if (bb.getTagName().equals("openQuote") || bb.getTagName().equals("openSimpleQuote")) {
143                     Matcher JavaDoc matcher = Pattern.compile(bb.getRegex()).matcher(text);
144
145                     while (matcher.find()) {
146                         text = text.replaceFirst(bb.getRegex(), bb.getReplace());
147                     }
148                 }
149                 else if (bb.getTagName().equals("closeQuote")) {
150                     Matcher JavaDoc matcher = Pattern.compile(bb.getRegex()).matcher(text);
151                     
152                     while (matcher.find()) {
153                         text = text.replaceFirst(bb.getRegex(), bb.getReplace());
154                     }
155                 }
156                 else if (bb.getTagName().equals("code")) {
157                     Matcher JavaDoc matcher = Pattern.compile(bb.getRegex()).matcher(text);
158                     StringBuffer JavaDoc sb = new StringBuffer JavaDoc(text);
159
160                     while (matcher.find()) {
161                         String JavaDoc contents = matcher.group(1);
162
163                         // Firefox seems to interpret <br/> inside <pre>,
164
// so we need this bizarre workaround
165
contents = contents.replaceAll("<br/>", "\n");
166
167                         // Do not allow other bb tags inside "code"
168
contents = contents.replaceAll("\\[", "&#91;").replaceAll("\\]", "&#93;");
169
170                         // Try to bypass smilies interpretation
171
contents = contents.replaceAll("\\(", "&#40;").replaceAll("\\)", "&#41;");
172
173                         // XML-like tags
174
contents = contents.replaceAll("<", "&lt;").replaceAll(">", "&gt;");
175
176                         StringBuffer JavaDoc replace = new StringBuffer JavaDoc(bb.getReplace());
177                         int index = replace.indexOf("$1");
178                         
179                         if (index > -1) {
180                             replace.replace(index, index + 2, contents);
181                         }
182
183                         index = sb.indexOf("[code]");
184                         int lastIndex = sb.indexOf("[/code]") + "[/code]".length();
185
186                         if (lastIndex > index) {
187                             sb.replace(index, lastIndex, replace.toString());
188                             text = sb.toString();
189                         }
190                     }
191                 }
192                 else {
193                     text = text.replaceAll(bb.getRegex(), bb.getReplace());
194                 }
195             }
196         }
197
198         return text;
199     }
200
201     public static String JavaDoc processSmilies(String JavaDoc text, List JavaDoc smilies)
202     {
203         if (text == null || text.equals("")) {
204             return text;
205         }
206
207         Iterator JavaDoc iter = smilies.iterator();
208         while (iter.hasNext()) {
209             Smilie s = (Smilie) iter.next();
210
211             int index = text.indexOf(s.getCode());
212             if (index > -1) {
213                 text = text.replaceAll("\\Q" + s.getCode() + "\\E", s.getUrl());
214             }
215         }
216
217         return text;
218     }
219
220     public static Post fillPostFromRequest() throws Exception JavaDoc
221     {
222         Post p = new Post();
223         p.setTime(new Date JavaDoc());
224
225         return fillPostFromRequest(p, false);
226     }
227
228     public static Post fillPostFromRequest(Post p, boolean isEdit) throws Exception JavaDoc
229     {
230         ActionServletRequest request = JForumExecutionContext.getRequest();
231         
232         p.setSubject(SafeHtml.makeSafe(request.getParameter("subject")));
233         p.setBbCodeEnabled(request.getParameter("disable_bbcode") != null ? false : true);
234         p.setSmiliesEnabled(request.getParameter("disable_smilies") != null ? false : true);
235         p.setSignatureEnabled(request.getParameter("attach_sig") != null ? true : false);
236
237         if (!isEdit) {
238             p.setUserIp(request.getRemoteAddr());
239             p.setUserId(SessionFacade.getUserSession().getUserId());
240         }
241         
242         boolean htmlEnabled = SecurityRepository.canAccess(SecurityConstants.PERM_HTML_DISABLED,
243                 request.getParameter("forum_id"));
244         p.setHtmlEnabled(htmlEnabled && request.getParameter("disable_html") == null);
245
246         if (p.isHtmlEnabled()) {
247             p.setText(SafeHtml.makeSafe(request.getParameter("message")));
248         }
249         else {
250             p.setText(request.getParameter("message"));
251         }
252
253         return p;
254     }
255
256     public static List JavaDoc topicPosts(PostDAO dao, boolean canEdit, int userId, int topicId, int start, int count) throws Exception JavaDoc
257     {
258         List JavaDoc posts = null;
259         boolean needPrepare = true;
260         
261         if (SystemGlobals.getBoolValue(ConfigKeys.POSTS_CACHE_ENABLED)) {
262             posts = PostRepository.selectAllByTopicByLimit(topicId, start, count);
263             needPrepare = false;
264         }
265         else {
266             posts = dao.selectAllByTopicByLimit(topicId, start, count);
267         }
268         
269         List JavaDoc helperList = new ArrayList JavaDoc();
270
271         int anonymousUser = SystemGlobals.getIntValue(ConfigKeys.ANONYMOUS_USER_ID);
272
273         for (Iterator JavaDoc iter = posts.iterator(); iter.hasNext(); ) {
274             Post p;
275             
276             if (needPrepare) {
277                 p = (Post)iter.next();
278             }
279             else {
280                 p = new Post((Post)iter.next());
281             }
282             
283             if (canEdit || (p.getUserId() != anonymousUser && p.getUserId() == userId)) {
284                 p.setCanEdit(true);
285             }
286
287             helperList.add(needPrepare ? PostCommon.preparePostForDisplay(p) : p);
288         }
289
290         return helperList;
291     }
292 }
293
Popular Tags