MyUtil
/*
* $Header: /cvsroot/mvnforum/mvnforum/src/com/mvnforum/MyUtil.java,v 1.30 2005/01/29 11:58:09 minhnn Exp $
* $Author: minhnn $
* $Revision: 1.30 $
* $Date: 2005/01/29 11:58:09 $
*
* ====================================================================
*
* Copyright (C) 2002-2005 by MyVietnam.net
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or any later version.
*
* All copyright notices regarding mvnForum MUST remain intact
* in the scripts and in the outputted HTML.
* The "powered by" text/logo with a link back to
* http://www.mvnForum.com and http://www.MyVietnam.net in the
* footer of the pages MUST remain visible when the pages
* are viewed on the internet or intranet.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Support can be obtained from support forums at:
* http://www.mvnForum.com/mvnforum/index
*
* Correspondence and Marketing Questions can be sent to:
* [email protected]
*
* @author: Minh Nguyen [email protected]
* @author: Mai Nguyen [email protected]
*/
package com.mvnforum;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.*;
import javax.servlet.ServletContext;
import javax.servlet.http.*;
import com.mvnforum.auth.*;
import com.mvnforum.common.PrivateMessageUtil;
import com.mvnforum.db.*;
import com.mvnforum.search.member.MemberIndexer;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import net.myvietnam.mvncore.MVNCoreInfo;
import net.myvietnam.mvncore.exception.*;
import net.myvietnam.mvncore.filter.*;
import net.myvietnam.mvncore.util.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class MyUtil {
private static Log log = LogFactory.getLog(MyUtil.class);
private static RankCache rankCache = RankCache.getInstance();
public static String filter(String input, boolean enableHTML, boolean enableEmotion,
boolean enableMVNCode, boolean enableNewLine, boolean enableURL) {
String output = input;
if (enableHTML) {
output = EnableHtmlTagFilter.filter(output);
} else {
output = DisableHtmlTagFilter.filter(output);
}
if (enableEmotion) {
output = EnableEmotionFilter.filter(output, ParamUtil.getContextPath() + MVNForumGlobal.EMOTION_DIR);
}
if (enableMVNCode) {
output = EnableMVNCodeFilter.filter(output);
}
if (enableNewLine) {
output = HtmlNewLineFilter.filter(output);
}
if (enableURL) {
output = URLFilter.filter(output);
}
return output;
}
public static String getMemberTitle(int postCount) {
String title = "";
try {
ArrayList rankBeans = rankCache.getBeans();
for (int i = 0; i < rankBeans.size(); i++) {
RankBean rankBean = (RankBean)rankBeans.get(i);
if (rankBean.getRankMinPosts() <= postCount) {
title = EnableMVNCodeFilter.filter(rankBean.getRankTitle());
} else {
break;
}
}//for
} catch (Exception ex) {
log.error("Exception in getMemberTitile", ex);
}
return title;
}
public static String getForumIconName(long lastLogon, long lastPost) {
String forumIcon = null;
if (lastLogon > lastPost) {// no new post
forumIcon = "f_norm_no.gif";
} else {// new post
forumIcon = "f_norm_new.gif";
}
return forumIcon;
}
public static String getThreadIconName(long lastLogon, long lastPost, int postCount) {
String threadIcon = null;
if (postCount < MVNForumConfig.getHotTopicThreshold()) {//not hot topic
if (lastLogon > lastPost) {// no new post
threadIcon = "f_norm_no.gif";
} else {// new post
threadIcon = "f_norm_new.gif";
}
} else {// hot topic
if (lastLogon > lastPost) {// no new post
threadIcon = "f_hot_no.gif";
} else {// new post
threadIcon = "f_hot_new.gif";
}
}
return threadIcon;
}
public static String getThreadStatusName(Locale locale, int threadStatus) {
String result = null;
switch (threadStatus) {
case ThreadBean.THREAD_STATUS_DEFAULT:
result = MVNForumResourceBundle.getString(locale, "mvnforum.common.thread.status.normal");
break;
case ThreadBean.THREAD_STATUS_DISABLED:
result = MVNForumResourceBundle.getString(locale, "mvnforum.common.thread.status.disabled");
break;
case ThreadBean.THREAD_STATUS_LOCKED:
result = MVNForumResourceBundle.getString(locale, "mvnforum.common.thread.status.locked");
break;
case ThreadBean.THREAD_STATUS_CLOSED:
result = MVNForumResourceBundle.getString(locale, "mvnforum.common.thread.status.closed");
break;
default:
//throw new AssertionException("Cannot find matching thread status.");
}
return result;
}
public static String getThreadTypeName(Locale locale, int threadType) {
String result = "Unknown";
switch (threadType) {
case ThreadBean.THREAD_TYPE_DEFAULT:
result = MVNForumResourceBundle.getString(locale, "mvnforum.common.thread.type.normal_thread");
break;
case ThreadBean.THREAD_TYPE_STICKY:
result = MVNForumResourceBundle.getString(locale, "mvnforum.common.thread.type.sticky_thread");
break;
case ThreadBean.THREAD_TYPE_FORUM_ANNOUNCEMENT:
result = MVNForumResourceBundle.getString(locale, "mvnforum.common.thread.type.announcement_thread");
break;
case ThreadBean.THREAD_TYPE_GLOBAL_ANNOUNCEMENT:
result = MVNForumResourceBundle.getString(locale, "mvnforum.common.thread.type.global_announcement_thread");
break;
default:
//throw new AssertionException("Cannot find matching thread type.");
}
return result;
}
public static String getForumStatusName(Locale locale, int forumStatus) {
String result = null;
switch (forumStatus) {
case ForumBean.FORUM_STATUS_DEFAULT:
result = MVNForumResourceBundle.getString(locale, "mvnforum.common.forum.status.normal");
break;
case ForumBean.FORUM_STATUS_DISABLED:
result = MVNForumResourceBundle.getString(locale, "mvnforum.common.forum.status.disabled");
break;
case ForumBean.FORUM_STATUS_LOCKED:
result = MVNForumResourceBundle.getString(locale, "mvnforum.common.forum.status.locked");
break;
case ForumBean.FORUM_STATUS_CLOSED:
result = MVNForumResourceBundle.getString(locale, "mvnforum.common.forum.status.closed");
break;
default:
//throw new AssertionException("Cannot find matching forum status.");
}
return result;
}
public static boolean canViewAnyForumInCategory(int categoryID, MVNForumPermission permission) {
try {
Collection forumBeans = ForumCache.getInstance().getBeans();
for (Iterator iter = forumBeans.iterator(); iter.hasNext(); ) {
ForumBean forumBean = (ForumBean)iter.next();
if (forumBean.getCategoryID() == categoryID) {
if (canViewForum(forumBean, permission)) {
return true;
}
}
}
} catch (DatabaseException ex) {
log.error("Cannot load the data in table Forum", ex);
}
return false;
}
public static boolean canViewForum(ForumBean forumBean, MVNForumPermission permission) {
if (permission.canReadPost(forumBean.getForumID()) &&
(forumBean.getForumStatus() != ForumBean.FORUM_STATUS_DISABLED) ) {
return true;
}
return false;
}
public static int getViewablePosts(Collection forumBeans, MVNForumPermission permission) {
int count = 0;
for (Iterator iter = forumBeans.iterator(); iter.hasNext(); ) {
ForumBean forumBean = (ForumBean)iter.next();
if (canViewForum(forumBean, permission)) {
count += forumBean.getForumPostCount();
}
}
return count;
}
public static int getViewableThreads(Collection forumBeans, MVNForumPermission permission) {
int count = 0;
for (Iterator iter = forumBeans.iterator(); iter.hasNext(); ) {
ForumBean forumBean = (ForumBean)iter.next();
if (canViewForum(forumBean, permission)) {
count += forumBean.getForumThreadCount();
}
}
return count;
}
public static int getViewableForums(Collection forumBeans, MVNForumPermission permission) {
int count = 0;
for (Iterator iter = forumBeans.iterator(); iter.hasNext(); ) {
ForumBean forumBean = (ForumBean)iter.next();
if (canViewForum(forumBean, permission)) {
count++;
}
}
return count;
}
public static int getViewableCategories(Collection categoryBeans, MVNForumPermission permission) {
int count = 0;
for (Iterator iter = categoryBeans.iterator(); iter.hasNext(); ) {
CategoryBean categoryBean = (CategoryBean)iter.next();
if (canViewAnyForumInCategory(categoryBean.getCategoryID(), permission)) {
count++;
}
}
return count;
}
/**
* Get the String with a slash character '/' before the locale name
* @param localeName the user's preferred locale
* @return the String with a slash character '/' before the locale name if
* this locale is configed to support it. Otherwise,
* an empty String will be return
*/
public static String getLocaleNameAndSlash(String localeName) {
if ( (localeName == null) || (localeName.length() == 0) ) {
return "";
}
String retValue = "";
String[] supportedLocales = MVNForumConfig.getSupportedLocaleNames();
if (supportedLocales == null) {
log.error("Assertion in MyUtil.getLocaleNameAndSlash. Please check your configuration.");
return "";
}
for (int i = 0; i < supportedLocales.length; i++) {
if (localeName.equals(supportedLocales[i])) {
retValue = "/" + localeName;
break;
}
}
return retValue;
}
public static String getCompanyCssPath(CompanyBean companyBean, String contextPath) {
String cssPath = null;
if (companyBean.getCompanyCss().length() > 0) {
cssPath = companyBean.getCompanyCss();
} else {
// use default company css
cssPath = MVNForumGlobal.COMPANY_DEFAULT_CSS_PATH;
}
return contextPath + cssPath;
}
public static String getCompanyLogoPath(CompanyBean companyBean, String contextPath) {
String logoPath = null;
if (companyBean.getCompanyLogo().length() > 0) {
logoPath = companyBean.getCompanyLogo();
} else {
// use default company logo
logoPath = MVNForumGlobal.COMPANY_DEFAULT_LOGO_PATH;
}
return contextPath + logoPath;
}
/**
* Get the locale from locale name
* @param localeName : in this format la_CO_VA, eg. en_US
* @return the locale instance of the localeName
*/
public static Locale getLocale(String localeName) {
// now, find out the 3 elements of a locale: language, country, variant
String[] localeElement = StringUtil.getStringArray(localeName, "_");
String language = "";
String country = "";
String variant = "";
if (localeElement.length >= 1) {
language = localeElement[0];
}
if (localeElement.length >= 2) {
country = localeElement[1];
}
if (localeElement.length >= 3) {
variant = localeElement[2];
}
return new Locale(language, country, variant);
}
public static void ensureCorrectCurrentPassword(HttpServletRequest request)
throws BadInputException, AssertionException, DatabaseException, AuthenticationException {
OnlineUser onlineUser = OnlineUserManager.getInstance().getOnlineUser(request);
OnlineUserFactory onlineUserFactory = ManagerFactory.getOnlineUserFactory();
try {
if (onlineUser.getAuthenticationType() == OnlineUser.AUTHENTICATION_TYPE_REALM) {
onlineUserFactory.ensureCorrectPassword(onlineUser.getMemberName(), OnlineUserManager.PASSWORD_OF_METHOD_REALM, true);
} else if (onlineUser.getAuthenticationType() == OnlineUser.AUTHENTICATION_TYPE_CUSTOMIZATION) {
if(MVNForumConfig.getEnablePasswordlessAuth()) {
// dont need password
onlineUserFactory.ensureCorrectPassword(onlineUser.getMemberName(), OnlineUserManager.PASSWORD_OF_METHOD_CUSTOMIZATION, true);
} else {
// must have password
// @todo: implement this case by using Authenticator
onlineUserFactory.ensureCorrectPassword(onlineUser.getMemberName(), OnlineUserManager.PASSWORD_OF_METHOD_CUSTOMIZATION, true);
}
} else {
//This user did not login by REALM or CUSTOMIZATION
String memberPassword = "";
String memberPasswordMD5 = ParamUtil.getParameter(request, "md5pw", false);
if (memberPasswordMD5.length() == 0 || (memberPasswordMD5.endsWith("==") == false)) {
// md5 is not valid, try to use unencoded password method
memberPassword = ParamUtil.getParameterPassword(request, "MemberCurrentMatkhau", 3, 0);
}
if (memberPassword.length() > 0) {
// that is we cannot find the md5 password
onlineUserFactory.ensureCorrectPassword(onlineUser.getMemberName(), memberPassword, false);
} else {
// have the md5, go ahead
onlineUserFactory.ensureCorrectPassword(onlineUser.getMemberName(), memberPasswordMD5, true);
}
}
} catch (AuthenticationException e) {
Locale locale = I18nUtil.getLocaleInRequest(request);
String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.BadInputException.wrong_password");
throw new BadInputException(localizedMessage);
//throw new BadInputException("You have typed the wrong password. Cannot proceed.");
}
}
public static void writeMvnForumImage(HttpServletRequest request, HttpServletResponse response) throws IOException {
BufferedImage image = MVNForumInfo.getImage();
OutputStream outputStream = null;
try {
outputStream = response.getOutputStream();
response.setContentType("image/jpeg");
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(outputStream);
encoder.encode(image);
outputStream.flush();
} catch (IOException ex) {
throw ex;
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException ex) { }
}
}
}
public static void writeMvnCoreImage(HttpServletRequest request, HttpServletResponse response) throws IOException {
BufferedImage image = MVNCoreInfo.getImage();
OutputStream outputStream = null;
try {
outputStream = response.getOutputStream();
response.setContentType("image/jpeg");
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(outputStream);
encoder.encode(image);
outputStream.flush();
} catch (IOException ex) {
throw ex;
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException ex) { }
}
}
}
public static void checkClassName(Locale locale, String className, boolean required) throws BadInputException {
if (required == false) {
if (className.length() == 0) return;
}
try {
Class.forName(className);
} catch (ClassNotFoundException ex) {
throw new BadInputException("Cannot load class: " + className);
}
}
public static void saveVNTyperMode(HttpServletRequest request, HttpServletResponse response) {
String vnTyperMode = ParamUtil.getParameter(request, "vnselector");
if (vnTyperMode.equals("VNI") || vnTyperMode.equals("TELEX") ||
vnTyperMode.equals("VIQR") || vnTyperMode.equals("NOVN")) {
Cookie typerModeCookie = new Cookie(MVNForumConstant.VN_TYPER_MODE, vnTyperMode);
typerModeCookie.setPath("/");
response.addCookie(typerModeCookie);
}
}
public static Hashtable checkMembers(String[] memberNames, Locale locale)
throws AssertionException, DatabaseException, BadInputException {
Hashtable memberMap = new Hashtable();
boolean isFailed = false;
StringBuffer missingNames = new StringBuffer(512);
for (int i = 0; i < memberNames.length; i++) {
int receivedMemberID = -1;
String memberName = memberNames[i];
StringUtil.checkGoodName(memberName);
try {
receivedMemberID = DAOFactory.getMemberDAO().getMemberIDFromMemberName(memberName);
} catch (ObjectNotFoundException ex) {
isFailed = true;
if (missingNames.length() > 0) {
missingNames.append(", ");
}
missingNames.append(memberName);
continue;
}
memberMap.put(new Integer(receivedMemberID), memberName);
} // end for
if (isFailed) { // the receivers does not exist.
String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.BadInputException.receivers_are_not_members", new Object[] {missingNames});
throw new BadInputException(localizedMessage);
}
return memberMap;
}
}