001: /*
002: * $Header: /cvsroot/mvnforum/mvnforum/src/com/mvnforum/MyUtil.java,v 1.121 2008/01/17 09:15:33 minhnn Exp $
003: * $Author: minhnn $
004: * $Revision: 1.121 $
005: * $Date: 2008/01/17 09:15:33 $
006: *
007: * ====================================================================
008: *
009: * Copyright (C) 2002-2007 by MyVietnam.net
010: *
011: * All copyright notices regarding mvnForum MUST remain
012: * intact in the scripts and in the outputted HTML.
013: * The "powered by" text/logo with a link back to
014: * http://www.mvnForum.com and http://www.MyVietnam.net in
015: * the footer of the pages MUST remain visible when the pages
016: * are viewed on the internet or intranet.
017: *
018: * This program is free software; you can redistribute it and/or modify
019: * it under the terms of the GNU General Public License as published by
020: * the Free Software Foundation; either version 2 of the License, or
021: * any later version.
022: *
023: * This program is distributed in the hope that it will be useful,
024: * but WITHOUT ANY WARRANTY; without even the implied warranty of
025: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
026: * GNU General Public License for more details.
027: *
028: * You should have received a copy of the GNU General Public License
029: * along with this program; if not, write to the Free Software
030: * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
031: *
032: * Support can be obtained from support forums at:
033: * http://www.mvnForum.com/mvnforum/index
034: *
035: * Correspondence and Marketing Questions can be sent to:
036: * info at MyVietnam net
037: *
038: * @author: Minh Nguyen
039: * @author: Mai Nguyen
040: */
041: package com.mvnforum;
042:
043: import java.awt.image.BufferedImage;
044: import java.io.*;
045: import java.sql.Timestamp;
046: import java.util.*;
047:
048: import javax.imageio.ImageIO;
049: import javax.servlet.http.*;
050:
051: import net.myvietnam.mvncore.MVNCoreResourceBundle;
052: import net.myvietnam.mvncore.exception.*;
053: import net.myvietnam.mvncore.filter.*;
054: import net.myvietnam.mvncore.service.MvnCoreInfoService;
055: import net.myvietnam.mvncore.service.MvnCoreServiceFactory;
056: import net.myvietnam.mvncore.util.*;
057: import net.myvietnam.mvncore.web.GenericRequest;
058: import net.myvietnam.mvncore.web.GenericResponse;
059:
060: import org.apache.commons.logging.Log;
061: import org.apache.commons.logging.LogFactory;
062:
063: import com.mvnforum.auth.*;
064: import com.mvnforum.common.ThreadIconLegend;
065: import com.mvnforum.db.*;
066: import com.mvnforum.service.MvnForumInfoService;
067: import com.mvnforum.service.MvnForumServiceFactory;
068:
069: import freemarker.template.*;
070:
071: public class MyUtil {
072:
073: private static Log log = LogFactory.getLog(MyUtil.class);
074:
075: public static final String FORUM_ICON_READ_ACTIVE = "f_read_active.gif";
076: public static final String FORUM_ICON_READ_CLOSED = "f_read_closed.gif";
077: public static final String FORUM_ICON_READ_LOCKED = "f_read_locked.gif";
078: public static final String FORUM_ICON_READ_DISABLED = "f_read_disabled.gif";
079: public static final String FORUM_ICON_UNREAD_ACTIVE = "f_unread_active.gif";
080: public static final String FORUM_ICON_UNREAD_CLOSED = "f_unread_closed.gif";
081: public static final String FORUM_ICON_UNREAD_LOCKED = "f_unread_locked.gif";
082: public static final String FORUM_ICON_UNREAD_DISABLED = "f_unread_disabled.gif";
083:
084: public static final String[] KEY_WORDS_OF_MOBILE_DEVICE = new String[] {
085: "phone", "fone", "midp", "palm", "windows ce", "mmp",
086: "mobile", "pda", "wii", "nintendo", "symbian", "j2me" };
087:
088: private static RankCache rankCache = RankCache.getInstance();
089:
090: private static MvnForumInfoService mvnForumInfo = MvnForumServiceFactory
091: .getMvnForumService().getMvnForumInfoService();
092: private static MvnCoreInfoService mvnCoreInfo = MvnCoreServiceFactory
093: .getMvnCoreService().getMvnCoreInfoService();
094:
095: public static String filter(String input, boolean enableHTML,
096: boolean enableEmotion, boolean enableMVNCode,
097: boolean enableNewLine, boolean enableURL) {
098: String output = input;
099:
100: if (enableHTML) {
101: output = EnableHtmlTagFilter.filter(output);
102: } else {
103: output = DisableHtmlTagFilter.filter(output);
104: }
105:
106: if (enableEmotion) {
107: output = EnableEmotionFilter.filter(output, ParamUtil
108: .getContextPath()
109: + MVNForumGlobal.EMOTION_DIR);
110: }
111:
112: if (enableMVNCode) {
113: output = EnableMVNCodeFilter.filter(output);
114: }
115:
116: if (enableNewLine) {
117: output = HtmlNewLineFilter.filter(output);
118: }
119:
120: if (enableURL) {
121: output = URLFilter.filter(output);
122: }
123: return output;
124: }
125:
126: public static String getMemberTitle(int postCount) {
127: String title = "";
128: try {
129: ArrayList rankBeans = rankCache.getBeans();
130: for (int i = 0; i < rankBeans.size(); i++) {
131: RankBean rankBean = (RankBean) rankBeans.get(i);
132: if (rankBean.getRankMinPosts() <= postCount) {
133: title = EnableMVNCodeFilter.filter(rankBean
134: .getRankTitle());
135: } else {
136: break;
137: }
138: }//for
139: } catch (Exception ex) {
140: log.error("Exception in getMemberTitle", ex);
141: }
142: return title;
143: }
144:
145: public static String getForumIconName(long lastLogon,
146: long lastPost, int forumStatus, int forumThreadCount) {
147: String forumIcon = null;
148: if ((lastLogon <= lastPost) && (forumThreadCount > 0)) {// new post
149: if (forumStatus == ForumBean.FORUM_STATUS_DEFAULT) {
150: forumIcon = FORUM_ICON_UNREAD_ACTIVE;
151: } else if (forumStatus == ForumBean.FORUM_STATUS_CLOSED) {
152: forumIcon = FORUM_ICON_UNREAD_CLOSED;
153: } else if (forumStatus == ForumBean.FORUM_STATUS_LOCKED) {
154: forumIcon = FORUM_ICON_UNREAD_LOCKED;
155: } else if (forumStatus == ForumBean.FORUM_STATUS_DISABLED) {
156: forumIcon = FORUM_ICON_UNREAD_DISABLED;
157: }
158: } else {// no new post
159: if (forumStatus == ForumBean.FORUM_STATUS_DEFAULT) {
160: forumIcon = FORUM_ICON_READ_ACTIVE;
161: } else if (forumStatus == ForumBean.FORUM_STATUS_CLOSED) {
162: forumIcon = FORUM_ICON_READ_CLOSED;
163: } else if (forumStatus == ForumBean.FORUM_STATUS_LOCKED) {
164: forumIcon = FORUM_ICON_READ_LOCKED;
165: } else if (forumStatus == ForumBean.FORUM_STATUS_DISABLED) {
166: forumIcon = FORUM_ICON_READ_DISABLED;
167: }
168: }
169: if (forumIcon == null) {
170: log.warn("Cannot get the forumIcon");
171: forumIcon = FORUM_ICON_READ_ACTIVE;
172: }
173: return forumIcon;
174: }
175:
176: public static String getThreadIconName(long lastLogon,
177: long lastPost, int postCount, int threadStatus) {
178: String threadIcon = null;
179: if (postCount < MVNForumConfig.maxHotTopics()) {//not hot topic
180: if (lastLogon > lastPost) {// no new post
181: if (threadStatus == ThreadBean.THREAD_STATUS_DEFAULT) {
182: threadIcon = ThreadIconLegend.THREAD_ICON_COLD_READ_ACTIVE;
183: } else if (threadStatus == ThreadBean.THREAD_STATUS_CLOSED) {
184: threadIcon = ThreadIconLegend.THREAD_ICON_COLD_READ_CLOSED;
185: } else if (threadStatus == ThreadBean.THREAD_STATUS_LOCKED) {
186: threadIcon = ThreadIconLegend.THREAD_ICON_COLD_READ_LOCKED;
187: }
188:
189: } else {// new post
190: if (threadStatus == ThreadBean.THREAD_STATUS_DEFAULT) {
191: threadIcon = ThreadIconLegend.THREAD_ICON_COLD_UNREAD_ACTIVE;
192: } else if (threadStatus == ThreadBean.THREAD_STATUS_CLOSED) {
193: threadIcon = ThreadIconLegend.THREAD_ICON_COLD_UNREAD_CLOSED;
194: } else if (threadStatus == ThreadBean.THREAD_STATUS_LOCKED) {
195: threadIcon = ThreadIconLegend.THREAD_ICON_COLD_UNREAD_LOCKED;
196: }
197: }
198: } else {// hot topic
199: if (lastLogon > lastPost) {// no new post
200: if (threadStatus == ThreadBean.THREAD_STATUS_DEFAULT) {
201: threadIcon = ThreadIconLegend.THREAD_ICON_HOT_READ_ACTIVE;
202: } else if (threadStatus == ThreadBean.THREAD_STATUS_CLOSED) {
203: threadIcon = ThreadIconLegend.THREAD_ICON_HOT_READ_CLOSED;
204: } else if (threadStatus == ThreadBean.THREAD_STATUS_LOCKED) {
205: threadIcon = ThreadIconLegend.THREAD_ICON_HOT_READ_LOCKED;
206: }
207: } else {// new post
208: if (threadStatus == ThreadBean.THREAD_STATUS_DEFAULT) {
209: threadIcon = ThreadIconLegend.THREAD_ICON_HOT_UNREAD_ACTIVE;
210: } else if (threadStatus == ThreadBean.THREAD_STATUS_CLOSED) {
211: threadIcon = ThreadIconLegend.THREAD_ICON_HOT_UNREAD_CLOSED;
212: } else if (threadStatus == ThreadBean.THREAD_STATUS_LOCKED) {
213: threadIcon = ThreadIconLegend.THREAD_ICON_HOT_UNREAD_LOCKED;
214: }
215: }
216: }
217: if (threadIcon == null) {
218: log.warn("Cannot get the threadIcon");
219: threadIcon = ThreadIconLegend.THREAD_ICON_COLD_READ_ACTIVE;
220: }
221: return threadIcon;
222: }
223:
224: public static boolean canViewAnyForumInCategory(int categoryID,
225: MVNForumPermission permission) {
226: try {
227: Collection forumBeans = ForumCache.getInstance().getBeans();
228: for (Iterator iter = forumBeans.iterator(); iter.hasNext();) {
229: ForumBean forumBean = (ForumBean) iter.next();
230: if (forumBean.getCategoryID() == categoryID) {
231: if (canViewForum(forumBean, permission)) {
232: return true;
233: }
234: }
235: }
236: } catch (DatabaseException ex) {
237: log.error("Cannot load the data in table Forum", ex);
238: }
239: return false;
240: }
241:
242: public static boolean canViewForum(ForumBean forumBean,
243: MVNForumPermission permission) {
244: if (permission.canReadPost(forumBean.getForumID())
245: && (forumBean.getForumStatus() != ForumBean.FORUM_STATUS_DISABLED)) {
246: return true;
247: }
248: return false;
249: }
250:
251: public static int getViewablePosts(Collection forumBeans,
252: MVNForumPermission permission) {
253: int count = 0;
254: for (Iterator iter = forumBeans.iterator(); iter.hasNext();) {
255: ForumBean forumBean = (ForumBean) iter.next();
256: if (canViewForum(forumBean, permission)) {
257: count += forumBean.getForumPostCount();
258: }
259: }
260: return count;
261: }
262:
263: public static int getViewableThreads(Collection forumBeans,
264: MVNForumPermission permission) {
265: int count = 0;
266: for (Iterator iter = forumBeans.iterator(); iter.hasNext();) {
267: ForumBean forumBean = (ForumBean) iter.next();
268: if (canViewForum(forumBean, permission)) {
269: count += forumBean.getForumThreadCount();
270: }
271: }
272: return count;
273: }
274:
275: public static int getViewableForums(Collection forumBeans,
276: MVNForumPermission permission) {
277: int count = 0;
278: for (Iterator iter = forumBeans.iterator(); iter.hasNext();) {
279: ForumBean forumBean = (ForumBean) iter.next();
280: if (canViewForum(forumBean, permission)) {
281: count++;
282: }
283: }
284: return count;
285: }
286:
287: public static int getViewableCategories(Collection categoryBeans,
288: MVNForumPermission permission) {
289: int count = 0;
290: for (Iterator iter = categoryBeans.iterator(); iter.hasNext();) {
291: CategoryBean categoryBean = (CategoryBean) iter.next();
292: if (canViewAnyForumInCategory(categoryBean.getCategoryID(),
293: permission)) {
294: count++;
295: }
296: }
297: return count;
298: }
299:
300: /**
301: * Get the String with a slash character '/' before the locale name
302: * @param localeName the user's preferred locale
303: * @return the String with a slash character '/' before the locale name if
304: * this locale is configed to support it. Otherwise,
305: * an empty String will be return
306: */
307: public static String getLocaleNameAndSlash(String localeName) {
308: if ((localeName == null) || (localeName.length() == 0)) {
309: return "";
310: }
311:
312: String retValue = "";
313: String[] supportedLocales = MVNForumConfig
314: .getSupportedLocaleNames();
315:
316: if (supportedLocales == null) {
317: log
318: .error("Assertion in MyUtil.getLocaleNameAndSlash. Please check your configuration.");
319: return "";
320: }
321:
322: for (int i = 0; i < supportedLocales.length; i++) {
323: if (localeName.equals(supportedLocales[i])) {
324: retValue = "/" + localeName;
325: break;
326: }
327: }
328: return retValue;
329: }
330:
331: /**
332: * Get the locale from locale name
333: * @param localeName : in this format la_CO_VA, eg. en_US
334: * @return the locale instance of the localeName
335: */
336: public static Locale getLocale(String localeName) {
337: // now, find out the 3 elements of a locale: language, country, variant
338: String[] localeElement = StringUtil.getStringArray(localeName,
339: "_");
340: String language = "";
341: String country = "";
342: String variant = "";
343: if (localeElement.length >= 1) {
344: language = localeElement[0];
345: }
346: if (localeElement.length >= 2) {
347: country = localeElement[1];
348: }
349: if (localeElement.length >= 3) {
350: variant = localeElement[2];
351: }
352: return new Locale(language, country, variant);
353: }
354:
355: public static void ensureCorrectCurrentPassword(
356: GenericRequest request) throws BadInputException,
357: DatabaseException, AuthenticationException {
358:
359: OnlineUser onlineUser = OnlineUserManager.getInstance()
360: .getOnlineUser(request);
361: String password = "";
362: String passwordMD5 = GenericParamUtil.getParameter(request,
363: "md5pw", false);
364:
365: if ((passwordMD5.length() == 0)
366: || (passwordMD5.endsWith("==") == false)
367: || (onlineUser.getAuthenticationType() == OnlineUser.AUTHENTICATION_TYPE_CUSTOMIZATION)) {
368: password = GenericParamUtil.getParameterPassword(request,
369: "MemberCurrentMatkhau", 3, 0);
370: }
371:
372: ensureCorrectCurrentPassword(request, password, passwordMD5);
373: }
374:
375: public static void ensureCorrectCurrentPassword(
376: GenericRequest request, String password, String passwordMD5)
377: throws BadInputException, DatabaseException,
378: AuthenticationException {
379:
380: if (password == null) {
381: password = "";
382: }
383: if (passwordMD5 == null) {
384: passwordMD5 = "";
385: }
386:
387: OnlineUser onlineUser = OnlineUserManager.getInstance()
388: .getOnlineUser(request);
389: OnlineUserFactory onlineUserFactory = ManagerFactory
390: .getOnlineUserFactory();
391: String memberName = onlineUser.getMemberName();
392:
393: try {
394: if (onlineUser.getAuthenticationType() == OnlineUser.AUTHENTICATION_TYPE_REALM) {
395: onlineUserFactory.ensureCorrectPassword(memberName,
396: OnlineUserManager.PASSWORD_OF_METHOD_REALM,
397: true);
398: } else if (onlineUser.getAuthenticationType() == OnlineUser.AUTHENTICATION_TYPE_CUSTOMIZATION) {
399: /*
400: if (MVNForumConfig.getEnablePasswordlessAuth()) {
401: // dont need password
402: onlineUserFactory.ensureCorrectPassword(memberName, OnlineUserManager.PASSWORD_OF_METHOD_CUSTOMIZATION, true);
403: } else {
404: // must have password
405: // @todo: implement this case by using Authenticator
406: onlineUserFactory.ensureCorrectPassword(memberName, OnlineUserManager.PASSWORD_OF_METHOD_CUSTOMIZATION, true);
407: }*/
408: //String password = GenericParamUtil.getParameterPassword(request, "MemberCurrentMatkhau", 3, 0);
409: if (password.length() < 3) {
410: Locale locale = I18nUtil
411: .getLocaleInRequest(request);
412: String localizedMessage = MVNCoreResourceBundle
413: .getString(
414: locale,
415: "mvncore.exception.BadInputException.password_too_short",
416: new Object[] { new Integer(3) });
417: throw new BadInputException(localizedMessage);
418: }
419: boolean isCorrectPassword = ManagerFactory
420: .getAuthenticator().isCorrectCurrentPassword(
421: memberName, password, false);
422: if (isCorrectPassword == false) {
423: throw new AuthenticationException(
424: NotLoginException.WRONG_PASSWORD);
425: }
426: } else {
427: //This user did not login by REALM or CUSTOMIZATION
428: String memberPassword = "";
429: //String passwordMD5 = GenericParamUtil.getParameter(request, "md5pw", false);
430: if (passwordMD5.length() == 0
431: || (passwordMD5.endsWith("==") == false)) {
432: // md5 is not valid, try to use unencoded password method
433: //memberPassword = GenericParamUtil.getParameterPassword(request, "MemberCurrentMatkhau", 3, 0);
434: if (password.length() < 3) {
435: Locale locale = I18nUtil
436: .getLocaleInRequest(request);
437: String localizedMessage = MVNCoreResourceBundle
438: .getString(
439: locale,
440: "mvncore.exception.BadInputException.password_too_short",
441: new Object[] { new Integer(3) });
442: throw new BadInputException(localizedMessage);
443: }
444: memberPassword = password;
445:
446: AssertionUtil
447: .doAssert(memberPassword.length() > 0,
448: "Cannot allow memberPassword's length is 0. Serious Assertion Failed.");
449: }
450:
451: // Please note that below code ONLY CORRECT when the ParamUtil.getParameterPassword
452: // return a NON-EMPTY string
453: if (memberPassword.length() > 0) {
454: // that is we cannot find the md5 password
455: onlineUserFactory.ensureCorrectPassword(memberName,
456: memberPassword, false);
457: } else {
458: // have the md5, go ahead
459: onlineUserFactory.ensureCorrectPassword(memberName,
460: passwordMD5, true);
461: }
462: }
463: } catch (AuthenticationException e) {
464: Locale locale = I18nUtil.getLocaleInRequest(request);
465: String localizedMessage = MVNForumResourceBundle
466: .getString(locale,
467: "mvncore.exception.BadInputException.wrong_password");
468: throw new BadInputException(localizedMessage);
469: //throw new BadInputException("You have typed the wrong password. Cannot proceed.");
470: }
471: }
472:
473: public static void writeMvnForumImage(HttpServletResponse response)
474: throws IOException {
475:
476: BufferedImage image = mvnForumInfo.getImage();
477: OutputStream outputStream = null;
478: try {
479: outputStream = response.getOutputStream();
480: response.setContentType("image/jpeg");
481:
482: //JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(outputStream);
483: //encoder.encode(image);
484: ImageIO.write(image, "jpeg", outputStream);
485: outputStream.flush();
486: } catch (IOException ex) {
487: throw ex;
488: } finally {
489: if (outputStream != null) {
490: try {
491: outputStream.close();
492: } catch (IOException ex) {
493: }
494: }
495: }
496: }
497:
498: public static void writeMvnCoreImage(HttpServletResponse response)
499: throws IOException {
500:
501: BufferedImage image = mvnCoreInfo.getImage();
502: OutputStream outputStream = null;
503: try {
504: outputStream = response.getOutputStream();
505: response.setContentType("image/jpeg");
506:
507: // JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(outputStream);
508: //encoder.encode(image);
509: ImageIO.write(image, "jpeg", outputStream);
510:
511: outputStream.flush();
512: } catch (IOException ex) {
513: throw ex;
514: } finally {
515: if (outputStream != null) {
516: try {
517: outputStream.close();
518: } catch (IOException ex) {
519: }
520: }
521: }
522: }
523:
524: public static void checkClassName(Locale locale, String className,
525: boolean required) throws BadInputException {
526: if (required == false) {
527: if (className.length() == 0)
528: return;
529: }
530:
531: try {
532: Class.forName(className);
533: } catch (ClassNotFoundException ex) {
534: throw new BadInputException("Cannot load class: "
535: + className);
536: }
537: }
538:
539: public static void saveVNTyperMode(GenericRequest request,
540: GenericResponse response) {
541:
542: if (request.isServletRequest()) {
543: saveVNTyperMode(request.getServletRequest(), response
544: .getServletResponse());
545: }
546: }
547:
548: public static void saveVNTyperMode(HttpServletRequest request,
549: HttpServletResponse response) {
550:
551: String vnTyperMode = ParamUtil.getParameter(request,
552: "vnselector");
553: if (vnTyperMode.equals("VNI") || vnTyperMode.equals("TELEX")
554: || vnTyperMode.equals("VIQR")
555: || vnTyperMode.equals("NOVN")
556: || vnTyperMode.equals("AUTO")) {
557: Cookie typerModeCookie = new Cookie(
558: MVNForumConstant.VN_TYPER_MODE, vnTyperMode);
559: typerModeCookie.setPath("/");
560: response.addCookie(typerModeCookie);
561: }
562: }
563:
564: // note that this method can check for duplicate but difference in case: Admin,admin,ADMIN
565: public static Hashtable checkMembers(String[] memberNames,
566: Locale locale) throws DatabaseException, BadInputException {
567:
568: Hashtable memberMap = new Hashtable();
569: boolean isFailed = false;
570: StringBuffer missingNames = new StringBuffer(512);
571:
572: for (int i = 0; i < memberNames.length; i++) {
573: int receivedMemberID = -1;
574: String memberName = memberNames[i];
575: StringUtil.checkGoodName(memberName);
576: try {
577: receivedMemberID = MemberCache.getInstance()
578: .getMemberIDFromMemberName(memberName);
579: } catch (ObjectNotFoundException ex) {
580: isFailed = true;
581: if (missingNames.length() > 0) {
582: missingNames.append(", ");
583: }
584: missingNames.append(memberName);
585: continue;
586: }
587: memberMap.put(new Integer(receivedMemberID), memberName);
588: } // end for
589:
590: if (isFailed) { // the receivers does not exist.
591: String localizedMessage = MVNForumResourceBundle
592: .getString(
593: locale,
594: "mvncore.exception.BadInputException.receivers_are_not_members",
595: new Object[] { missingNames });
596: throw new BadInputException(localizedMessage);
597: }
598: return memberMap;
599: }
600:
601: /**
602: * Check if the online user is Root Admin
603: */
604: public static boolean isRootAdmin(GenericRequest request)
605: throws AuthenticationException, DatabaseException {
606: return (OnlineUserManager.getInstance().getOnlineUser(request)
607: .getMemberID() == MVNForumConstant.MEMBER_ID_OF_ADMIN);
608: }
609:
610: /**
611: * Check if the online user is Root Admin
612: */
613: public static boolean isRootAdmin(HttpServletRequest request)
614: throws AuthenticationException, DatabaseException {
615: return (OnlineUserManager.getInstance().getOnlineUser(request)
616: .getMemberID() == MVNForumConstant.MEMBER_ID_OF_ADMIN);
617: }
618:
619: /**
620: * check if memberID belongs to admin's id
621: */
622: public static boolean isRootAdminID(int memberID) {
623: return (memberID == MVNForumConstant.MEMBER_ID_OF_ADMIN);
624: }
625:
626: /**
627: * Check if request is from a mobile device
628: */
629: public static boolean isRequestFromMobileDevice(
630: GenericRequest request) {
631: if (request.isServletRequest()) {
632: String userAgent = request.getServletRequest().getHeader(
633: "User-Agent").toLowerCase();
634: for (int i = 0; i < KEY_WORDS_OF_MOBILE_DEVICE.length; i++) {
635: if (userAgent.indexOf(KEY_WORDS_OF_MOBILE_DEVICE[i]) != -1) {
636: return true;
637: }
638: }
639: }
640: return false;
641: }
642:
643: public static String getConfirmedEmailKey(int memberID)
644: throws ObjectNotFoundException, DatabaseException {
645: MemberDAO memberDAO = DAOFactory.getMemberDAO();
646: String encryptedPassword = memberDAO.getPassword(memberID);
647: if (encryptedPassword.length() > 16) {
648: return encryptedPassword.substring(0, 16);
649: }
650: if (encryptedPassword.length() < 16) {
651: for (int i = encryptedPassword.length(); i < 16; i++) {
652: encryptedPassword = encryptedPassword + " ";
653: }
654: }
655: return encryptedPassword;
656: }
657:
658: // public static void checkInstance(String className, Class clazz) throws BadInputException {
659: // try {
660: // Class.forName(className);
661: // throw new BadInputException("Class " + className + " is not a implementation of " + clazz);
662: // } catch (ClassNotFoundException e) {
663: // e.printStackTrace();
664: // throw new BadInputException("Cannot load class " + className);
665: // }
666: // }
667:
668: public static Collection getForumsOwnedByMemberName(
669: String memberName) throws DatabaseException {
670: ArrayList result = new ArrayList();
671:
672: Collection allForums = DAOFactory.getForumDAO().getForums();
673: for (Iterator iter = allForums.iterator(); iter.hasNext();) {
674: ForumBean forumBean = (ForumBean) iter.next();
675: String forumOwnerName = forumBean.getForumOwnerName();
676: if (forumOwnerName.equalsIgnoreCase(memberName)) {
677: result.add(forumBean);
678: }
679: }
680:
681: return result;
682: }
683:
684: public static Collection getPrivateForums(MVNForumPermission perms)
685: throws DatabaseException {
686:
687: ArrayList result = new ArrayList();
688:
689: Collection allForums = ForumCache.getInstance().getBeans();
690: for (Iterator iter = allForums.iterator(); iter.hasNext();) {
691: ForumBean forum = (ForumBean) iter.next();
692: int forumId = forum.getForumID();
693: if ((forum.getForumType() == ForumBean.FORUM_TYPE_PRIVATE)
694: && (forum.getForumStatus() != ForumBean.FORUM_STATUS_DISABLED)) {
695: if (perms.canReadPost(forumId)
696: || perms.canDeleteForum(forumId)
697: || perms.canEditForum(forumId)) {
698:
699: result.add(forum);
700: }
701: }
702: }
703:
704: return result;
705: }
706:
707: public static Collection getNewMembersInRecentDays(
708: Timestamp fromDate, Timestamp toDate, String sort,
709: String order) throws IllegalArgumentException,
710: DatabaseException {
711:
712: final int PARTIAL_SIZE = 10;// each loop with size of 10
713:
714: Collection newMembers = new ArrayList();
715:
716: int offset = 0;
717:
718: do {
719: // get partial result
720: Collection members = DAOFactory.getMemberDAO()
721: .getMembers_withSortSupport_limit(offset,
722: PARTIAL_SIZE, sort, order,
723: MemberDAO.ALL_MEMBER_STATUS);
724:
725: if (members.size() == 0) {
726: break;
727: }
728:
729: // process new partial result
730: for (Iterator iterator = members.iterator(); iterator
731: .hasNext();) {
732:
733: MemberBean member = (MemberBean) iterator.next();
734: Timestamp creationDate = member.getMemberCreationDate();
735: if (creationDate.after(fromDate)
736: && creationDate.before(toDate)) {
737: newMembers.add(member);
738: } else {
739: break;
740: }
741: }
742:
743: offset += PARTIAL_SIZE;
744: } while (true);
745:
746: return newMembers;
747: }
748:
749: public static String getStringFromFreeMarkerTemplate(
750: HashMap informationSet, String templateFileName)
751: throws IOException, TemplateException {
752:
753: Configuration config = MVNForumConfig
754: .getFreeMarkerConfiguration();
755: Template template = config.getTemplate(templateFileName);
756:
757: StringWriter resultString = new StringWriter(256);
758: template.process(informationSet, resultString);
759:
760: return resultString.toString();
761: }
762:
763: public static StringBuffer getIndividualPermission(int combinePers,
764: boolean globalPermission) throws BadInputException {
765:
766: StringBuffer indivialPermissions = new StringBuffer();
767: int[] individualForumPermissionArray = null;
768:
769: switch (combinePers) {
770:
771: case MVNForumPermission.PERMISSION_SYSTEM_ADMIN:
772: indivialPermissions
773: .append("This permission includes all individual permissions");
774: break;
775:
776: case MVNForumPermission.PERMISSION_FORUM_ADMIN:
777: if (globalPermission) {
778: individualForumPermissionArray = MVNForumPermission.individualForumAdminPermissionArray;
779: } else {
780: individualForumPermissionArray = MVNForumPermission.individualForumAdminLimitPermissionArray;
781: }
782: break;
783:
784: case MVNForumPermission.PERMISSION_FORUM_MODERATOR:
785: if (globalPermission) {
786: individualForumPermissionArray = MVNForumPermission.individualForumModeratorPermissionArray;
787: } else {
788: individualForumPermissionArray = MVNForumPermission.individualForumModeratorLimitPermissionArray;
789: }
790: break;
791:
792: case MVNForumPermission.PERMISSION_POWER_USER:
793: if (globalPermission) {
794: individualForumPermissionArray = MVNForumPermission.individualPowerUserPermissionArray;
795: } else {
796: individualForumPermissionArray = MVNForumPermission.individualPowerUserLimitPermissionArray;
797: }
798: break;
799:
800: case MVNForumPermission.PERMISSION_NORMAL_USER:
801: if (globalPermission) {
802: individualForumPermissionArray = MVNForumPermission.individualNormalUserPermissionArray;
803: } else {
804: individualForumPermissionArray = MVNForumPermission.individualNormalUserLimitPermissionArray;
805: }
806: break;
807:
808: case MVNForumPermission.PERMISSION_LIMITED_USER:
809: if (globalPermission) {
810: individualForumPermissionArray = MVNForumPermission.individualLimitedUserPermissionArray;
811: } else {
812: individualForumPermissionArray = MVNForumPermission.individualLimitedUserLimitPermissionArray;
813: }
814: break;
815:
816: default:
817: throw new BadInputException("This permission is invalid");
818:
819: } // end switch
820:
821: if (individualForumPermissionArray != null) {
822: indivialPermissions
823: .append("This permission includes the individual permission: <br />");
824: indivialPermissions.append("<ul>");
825: for (int i = 0; i < individualForumPermissionArray.length; i++) {
826: indivialPermissions
827: .append("<li>")
828: .append(
829: AbstractPermission
830: .getDescription(individualForumPermissionArray[i]))
831: .append("</li>");
832: }
833: indivialPermissions.append("</ul>");
834: }
835:
836: return indivialPermissions;
837: }
838:
839: public static String getThreadPriorityIcon(int threadPriority) {
840: String threadPriorityIcon = null;
841: if (threadPriority == ThreadBean.THREAD_PRIORITY_LOW) {
842: threadPriorityIcon = ThreadIconLegend.THREAD_ICON_PRIORITY_LOW;
843: } else if (threadPriority == ThreadBean.THREAD_PRIORITY_NORMAL) {
844: threadPriorityIcon = ThreadIconLegend.THREAD_ICON_PRIORITY_NORMAL;
845: } else if (threadPriority == ThreadBean.THREAD_PRIORITY_HIGH) {
846: threadPriorityIcon = ThreadIconLegend.THREAD_ICON_PRIORITY_HIGH;
847: } else {
848: AssertionUtil.doAssert(false,
849: "Does not support thread priority = "
850: + threadPriority);
851: }
852: return threadPriorityIcon;
853: }
854:
855: public static String getThreadTypeIcon(int threadType) {
856: String threadTypeIcon = "";
857: if (threadType == ThreadBean.THREAD_TYPE_STICKY) {
858: threadTypeIcon = ThreadIconLegend.THREAD_ICON_TYPE_STICKY;
859: } else if (threadType == ThreadBean.THREAD_TYPE_FORUM_ANNOUNCEMENT) {
860: threadTypeIcon = ThreadIconLegend.THREAD_ICON_TYPE_FORUM_ANNOUNCEMENT;
861: } else if (threadType == ThreadBean.THREAD_TYPE_GLOBAL_ANNOUNCEMENT) {
862: threadTypeIcon = ThreadIconLegend.THREAD_ICON_TYPE_GLOBAL_ANNOUNCEMENT;
863: }
864: return threadTypeIcon;
865: }
866:
867: }
|