PostCommon.java
Upload User: gdxydsw
Upload Date: 2019-01-29
Package Size: 16721k
Code Size: 11k
Category:

Java Develop

Development Platform:

Java

  1. /*
  2.  * Copyright (c) JForum Team
  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. import java.util.ArrayList;
  45. import java.util.Collection;
  46. import java.util.Date;
  47. import java.util.Iterator;
  48. import java.util.List;
  49. import java.util.regex.Matcher;
  50. import java.util.regex.Pattern;
  51. import net.jforum.JForumExecutionContext;
  52. import net.jforum.SessionFacade;
  53. import net.jforum.context.RequestContext;
  54. import net.jforum.dao.PostDAO;
  55. import net.jforum.entities.Post;
  56. import net.jforum.entities.Smilie;
  57. import net.jforum.repository.BBCodeRepository;
  58. import net.jforum.repository.PostRepository;
  59. import net.jforum.repository.SecurityRepository;
  60. import net.jforum.repository.SmiliesRepository;
  61. import net.jforum.security.SecurityConstants;
  62. import net.jforum.util.SafeHtml;
  63. import net.jforum.util.bbcode.BBCode;
  64. import net.jforum.util.preferences.ConfigKeys;
  65. import net.jforum.util.preferences.SystemGlobals;
  66. /**
  67.  * @author Rafael Steil
  68.  * @version $Id: PostCommon.java,v 1.59 2007/09/24 03:29:17 rafaelsteil Exp $
  69.  */
  70. public class PostCommon
  71. {
  72. public static Post preparePostForDisplay(Post post)
  73. {
  74. if (post.getText() == null) {
  75. return post;
  76. }
  77. StringBuffer text = new StringBuffer(post.getText());
  78. if (!post.isHtmlEnabled()) {
  79. ViewCommon.replaceAll(text, "<", "&lt;");
  80. ViewCommon.replaceAll(text, ">", "&gt;");
  81. }
  82. // Do not remove the trailing blank space, as it would
  83. // cause some regular expressions to fail
  84. ViewCommon.replaceAll(text, "n", "<br /> ");
  85. SafeHtml safeHtml = new SafeHtml();
  86. post.setText(text.toString());
  87. post.setText(safeHtml.makeSafe(post.getText()));
  88. processText(post);
  89. post.setText(safeHtml.ensureAllAttributesAreSafe(post.getText()));
  90. return post;
  91. }
  92. private static void processText(Post post)
  93. {
  94. int codeIndex = post.getText().indexOf("[code");
  95. int codeEndIndex = codeIndex > -1 ? post.getText().indexOf("[/code]") : -1;
  96. boolean hasCodeBlock = false;
  97. if (codeIndex == -1 || codeEndIndex == -1 || codeEndIndex < codeIndex) {
  98. post.setText(prepareTextForDisplayExceptCodeTag(post.getText().toString(),
  99. post.isBbCodeEnabled(), post.isSmiliesEnabled()));
  100. }
  101. else if (post.isBbCodeEnabled()) {
  102. hasCodeBlock = true;
  103. int nextStartPos = 0;
  104. StringBuffer result = new StringBuffer(post.getText().length());
  105. while (codeIndex > -1 && codeEndIndex > -1 && codeEndIndex > codeIndex) {
  106. codeEndIndex += "[/code]".length();
  107. String nonCodeResult = prepareTextForDisplayExceptCodeTag(post.getText().substring(nextStartPos, codeIndex), 
  108. post.isBbCodeEnabled(), post.isSmiliesEnabled());
  109. String codeResult = parseCode(post.getText().substring(codeIndex, codeEndIndex));
  110. result.append(nonCodeResult).append(codeResult);
  111. nextStartPos = codeEndIndex;
  112. codeIndex = post.getText().indexOf("[code", codeEndIndex);
  113. codeEndIndex = codeIndex > -1 ? post.getText().indexOf("[/code]", codeIndex) : -1;
  114. }
  115. if (nextStartPos > -1) {
  116. String nonCodeResult = prepareTextForDisplayExceptCodeTag(post.getText().substring(nextStartPos), 
  117. post.isBbCodeEnabled(), post.isSmiliesEnabled());
  118. result.append(nonCodeResult);
  119. }
  120. post.setText(result.toString());
  121. }
  122. if (hasCodeBlock) {
  123. JForumExecutionContext.getTemplateContext().put("hasCodeBlock", hasCodeBlock);
  124. }
  125. }
  126. private static String parseCode(String text)
  127. {
  128. for (Iterator iter = BBCodeRepository.getBBCollection().getBbList().iterator(); iter.hasNext();) {
  129. BBCode bb = (BBCode)iter.next();
  130. if (bb.getTagName().startsWith("code")) {
  131. Matcher matcher = Pattern.compile(bb.getRegex()).matcher(text);
  132. StringBuffer sb = new StringBuffer(text);
  133. while (matcher.find()) {
  134. StringBuffer lang = null;
  135. StringBuffer contents = null;
  136. if ("code".equals(bb.getTagName())) {
  137.     contents = new StringBuffer(matcher.group(1));
  138. else {
  139. lang = new StringBuffer(matcher.group(1));
  140. contents = new StringBuffer(matcher.group(2));
  141. }
  142. ViewCommon.replaceAll(contents, "<br /> ", "n");
  143. // XML-like tags
  144. ViewCommon.replaceAll(contents, "<", "&lt;");
  145. ViewCommon.replaceAll(contents, ">", "&gt;");
  146. // Note: there is no replacing for spaces and tabs as
  147. // we are relying on the Javascript SyntaxHighlighter library
  148. // to do it for us
  149. StringBuffer replace = new StringBuffer(bb.getReplace());
  150. int index = replace.indexOf("$1");
  151. if ("code".equals(bb.getTagName())) {
  152. if (index > -1) {
  153. replace.replace(index, index + 2, contents.toString());
  154. }
  155. index = sb.indexOf("[code]");
  156. }
  157. else {
  158. if (index > -1) {
  159. replace.replace(index, index + 2, lang.toString());
  160. }
  161. index = replace.indexOf("$2");
  162. if (index > -1) {
  163. replace.replace(index, index + 2, contents.toString());
  164. }
  165. index = sb.indexOf("[code=");
  166. int lastIndex = sb.indexOf("[/code]", index) + "[/code]".length();
  167. if (lastIndex > index) {
  168. sb.replace(index, lastIndex, replace.toString());
  169. }
  170. }
  171. text = sb.toString();
  172. }
  173. }
  174. return text;
  175. }
  176. public static String prepareTextForDisplayExceptCodeTag(String text, boolean isBBCodeEnabled, boolean isSmilesEnabled)
  177. {
  178. if (text == null) {
  179. return text;
  180. }
  181. if (isSmilesEnabled) {
  182. text = processSmilies(new StringBuffer(text));
  183. }
  184. if (isBBCodeEnabled && text.indexOf('[') > -1 && text.indexOf(']') > -1) {
  185. for (Iterator iter = BBCodeRepository.getBBCollection().getBbList().iterator(); iter.hasNext();) {
  186. BBCode bb = (BBCode)iter.next();
  187. if (!bb.getTagName().startsWith("code")) {
  188. text = text.replaceAll(bb.getRegex(), bb.getReplace());
  189. }
  190. }
  191. }
  192. text = parseDefaultRequiredBBCode(text);
  193. return text;
  194. }
  195. public static String parseDefaultRequiredBBCode(String text)
  196. {
  197. Collection list = BBCodeRepository.getBBCollection().getAlwaysProcessList();
  198. for (Iterator iter = list.iterator(); iter.hasNext(); ) {
  199. BBCode bb = (BBCode)iter.next();
  200. text = text.replaceAll(bb.getRegex(), bb.getReplace());
  201. }
  202. return text;
  203. }
  204. /**
  205.  * Replace the smlies code by the respective URL.
  206.  * @param text The text to process
  207.  * @return the parsed text. Note that the StringBuffer you pass as parameter
  208.  * will already have the right contents, as the replaces are done on the instance
  209.  */
  210. public static String processSmilies(StringBuffer text)
  211. {
  212. List smilies = SmiliesRepository.getSmilies();
  213. for (Iterator iter = smilies.iterator(); iter.hasNext(); ) {
  214. Smilie s = (Smilie) iter.next();
  215. int pos = text.indexOf(s.getCode());
  216. // The counter is used as prevention, in case
  217. // the while loop turns into an always true 
  218. // expression, for any reason
  219. int counter = 0;
  220. while (pos > -1 && counter++ < 300) {
  221. text.replace(pos, pos + s.getCode().length(), s.getUrl());
  222. pos = text.indexOf(s.getCode());
  223. }
  224. }
  225. return text.toString();
  226. }
  227. public static Post fillPostFromRequest()
  228. {
  229. Post p = new Post();
  230. p.setTime(new Date());
  231. return fillPostFromRequest(p, false);
  232. }
  233. public static Post fillPostFromRequest(Post p, boolean isEdit) 
  234. {
  235. RequestContext request = JForumExecutionContext.getRequest();
  236. p.setSubject(request.getParameter("subject"));
  237. p.setBbCodeEnabled(request.getParameter("disable_bbcode") == null);
  238. p.setSmiliesEnabled(request.getParameter("disable_smilies") == null);
  239. p.setSignatureEnabled(request.getParameter("attach_sig") != null);
  240. if (!isEdit) {
  241. p.setUserIp(request.getRemoteAddr());
  242. p.setUserId(SessionFacade.getUserSession().getUserId());
  243. }
  244. boolean htmlEnabled = SecurityRepository.canAccess(SecurityConstants.PERM_HTML_DISABLED, 
  245. request.getParameter("forum_id"));
  246. p.setHtmlEnabled(htmlEnabled && request.getParameter("disable_html") == null);
  247. if (p.isHtmlEnabled()) {
  248. p.setText(new SafeHtml().makeSafe(request.getParameter("message")));
  249. }
  250. else {
  251. p.setText(request.getParameter("message"));
  252. }
  253. return p;
  254. }
  255. public static boolean canEditPost(Post post)
  256. {
  257. return SessionFacade.isLogged()
  258. && (post.getUserId() == SessionFacade.getUserSession().getUserId()
  259. || SecurityRepository.canAccess(SecurityConstants.PERM_MODERATION_POST_EDIT));
  260. }
  261. public static List topicPosts(PostDAO dao, boolean canEdit, int userId, int topicId, int start, int count)
  262. {
  263. boolean needPrepare = true;
  264. List posts;
  265.   if (SystemGlobals.getBoolValue(ConfigKeys.POSTS_CACHE_ENABLED)) {
  266.   posts = PostRepository.selectAllByTopicByLimit(topicId, start, count);
  267.   needPrepare = false;
  268.   }
  269.   else {
  270.   posts = dao.selectAllByTopicByLimit(topicId, start, count);
  271.   }
  272.  
  273. List helperList = new ArrayList();
  274. int anonymousUser = SystemGlobals.getIntValue(ConfigKeys.ANONYMOUS_USER_ID);
  275. for (Iterator iter = posts.iterator(); iter.hasNext(); ) {
  276. Post p;
  277. if (needPrepare) {
  278. p = (Post)iter.next();
  279. }
  280. else {
  281. p = new Post((Post)iter.next());
  282. }
  283. if (canEdit || (p.getUserId() != anonymousUser && p.getUserId() == userId)) {
  284. p.setCanEdit(true);
  285. }
  286. helperList.add(needPrepare ? PostCommon.preparePostForDisplay(p) : p);
  287. }
  288. return helperList;
  289. }
  290. }