001    /**
002     * Copyright (c) 2000-2012 Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portlet.messageboards.util;
016    
017    import com.liferay.portal.kernel.exception.PortalException;
018    import com.liferay.portal.kernel.exception.SystemException;
019    import com.liferay.portal.kernel.log.Log;
020    import com.liferay.portal.kernel.log.LogFactoryUtil;
021    import com.liferay.portal.kernel.portlet.LiferayWindowState;
022    import com.liferay.portal.kernel.util.CharPool;
023    import com.liferay.portal.kernel.util.GetterUtil;
024    import com.liferay.portal.kernel.util.Http;
025    import com.liferay.portal.kernel.util.LocaleUtil;
026    import com.liferay.portal.kernel.util.LocalizationUtil;
027    import com.liferay.portal.kernel.util.ParamUtil;
028    import com.liferay.portal.kernel.util.PropsUtil;
029    import com.liferay.portal.kernel.util.StringBundler;
030    import com.liferay.portal.kernel.util.StringPool;
031    import com.liferay.portal.kernel.util.StringUtil;
032    import com.liferay.portal.kernel.util.Validator;
033    import com.liferay.portal.model.Group;
034    import com.liferay.portal.model.Organization;
035    import com.liferay.portal.model.Role;
036    import com.liferay.portal.model.UserGroup;
037    import com.liferay.portal.security.permission.ActionKeys;
038    import com.liferay.portal.security.permission.PermissionChecker;
039    import com.liferay.portal.service.GroupLocalServiceUtil;
040    import com.liferay.portal.service.OrganizationLocalServiceUtil;
041    import com.liferay.portal.service.RoleLocalServiceUtil;
042    import com.liferay.portal.service.UserGroupLocalServiceUtil;
043    import com.liferay.portal.service.UserGroupRoleLocalServiceUtil;
044    import com.liferay.portal.service.UserLocalServiceUtil;
045    import com.liferay.portal.theme.ThemeDisplay;
046    import com.liferay.portal.util.PortalUtil;
047    import com.liferay.portal.util.PropsValues;
048    import com.liferay.portal.util.WebKeys;
049    import com.liferay.portlet.messageboards.model.MBBan;
050    import com.liferay.portlet.messageboards.model.MBCategory;
051    import com.liferay.portlet.messageboards.model.MBCategoryConstants;
052    import com.liferay.portlet.messageboards.model.MBMailingList;
053    import com.liferay.portlet.messageboards.model.MBMessage;
054    import com.liferay.portlet.messageboards.model.MBMessageConstants;
055    import com.liferay.portlet.messageboards.model.MBStatsUser;
056    import com.liferay.portlet.messageboards.service.MBCategoryLocalServiceUtil;
057    import com.liferay.portlet.messageboards.service.MBMailingListLocalServiceUtil;
058    import com.liferay.portlet.messageboards.service.permission.MBMessagePermission;
059    import com.liferay.util.ContentUtil;
060    import com.liferay.util.mail.JavaMailUtil;
061    
062    import java.io.InputStream;
063    
064    import java.util.Calendar;
065    import java.util.Collections;
066    import java.util.Date;
067    import java.util.List;
068    
069    import javax.mail.BodyPart;
070    import javax.mail.Message;
071    import javax.mail.Part;
072    import javax.mail.internet.MimeMessage;
073    import javax.mail.internet.MimeMultipart;
074    
075    import javax.portlet.PortletPreferences;
076    import javax.portlet.PortletRequest;
077    import javax.portlet.PortletURL;
078    import javax.portlet.RenderResponse;
079    
080    import javax.servlet.http.HttpServletRequest;
081    
082    /**
083     * @author Brian Wing Shun Chan
084     */
085    public class MBUtil {
086    
087            public static final String BB_CODE_EDITOR_WYSIWYG_IMPL_KEY =
088                    "editor.wysiwyg.portal-web.docroot.html.portlet.message_boards." +
089                            "edit_message.bb_code.jsp";
090    
091            public static final String MESSAGE_POP_PORTLET_PREFIX = "mb_message.";
092    
093            public static void addPortletBreadcrumbEntries(
094                            long categoryId, HttpServletRequest request,
095                            RenderResponse renderResponse)
096                    throws Exception {
097    
098                    if ((categoryId == MBCategoryConstants.DEFAULT_PARENT_CATEGORY_ID) ||
099                            (categoryId == MBCategoryConstants.DISCUSSION_CATEGORY_ID)) {
100    
101                            return;
102                    }
103    
104                    MBCategory category = MBCategoryLocalServiceUtil.getCategory(
105                            categoryId);
106    
107                    addPortletBreadcrumbEntries(category, request, renderResponse);
108            }
109    
110            public static void addPortletBreadcrumbEntries(
111                            MBCategory category, HttpServletRequest request,
112                            RenderResponse renderResponse)
113                    throws Exception {
114    
115                    String strutsAction = ParamUtil.getString(request, "struts_action");
116    
117                    PortletURL portletURL = renderResponse.createRenderURL();
118    
119                    if (strutsAction.equals("/message_boards/select_category") ||
120                            strutsAction.equals("/message_boards_admin/select_category")) {
121    
122                            ThemeDisplay themeDisplay = (ThemeDisplay)request.getAttribute(
123                                    WebKeys.THEME_DISPLAY);
124    
125                            portletURL.setWindowState(LiferayWindowState.POP_UP);
126    
127                            portletURL.setParameter(
128                                    "struts_action", "/message_boards/select_category");
129    
130                            PortalUtil.addPortletBreadcrumbEntry(
131                                    request, themeDisplay.translate("categories"),
132                                    portletURL.toString());
133                    }
134                    else {
135                            portletURL.setParameter("struts_action", "/message_boards/view");
136                    }
137    
138                    List<MBCategory> ancestorCategories = category.getAncestors();
139    
140                    Collections.reverse(ancestorCategories);
141    
142                    for (MBCategory curCategory : ancestorCategories) {
143                            portletURL.setParameter(
144                                    "mbCategoryId", String.valueOf(curCategory.getCategoryId()));
145    
146                            PortalUtil.addPortletBreadcrumbEntry(
147                                    request, curCategory.getName(), portletURL.toString());
148                    }
149    
150                    portletURL.setParameter(
151                            "mbCategoryId", String.valueOf(category.getCategoryId()));
152    
153                    PortalUtil.addPortletBreadcrumbEntry(
154                            request, category.getName(), portletURL.toString());
155            }
156    
157            public static void addPortletBreadcrumbEntries(
158                            MBMessage message, HttpServletRequest request,
159                            RenderResponse renderResponse)
160                    throws Exception {
161    
162                    if ((message.getCategoryId() ==
163                                    MBCategoryConstants.DEFAULT_PARENT_CATEGORY_ID) ||
164                            (message.getCategoryId() ==
165                                    MBCategoryConstants.DISCUSSION_CATEGORY_ID)) {
166    
167                            return;
168                    }
169    
170                    MBCategory category = message.getCategory();
171    
172                    addPortletBreadcrumbEntries(category, request, renderResponse);
173    
174                    PortletURL portletURL = renderResponse.createRenderURL();
175    
176                    portletURL.setParameter(
177                            "struts_action", "/message_boards/view_message");
178                    portletURL.setParameter(
179                            "messageId", String.valueOf(message.getMessageId()));
180    
181                    PortalUtil.addPortletBreadcrumbEntry(
182                            request, message.getSubject(), portletURL.toString());
183            }
184    
185            public static void collectMultipartContent(
186                            MimeMultipart multipart, MBMailMessage collector)
187                    throws Exception {
188    
189                    for (int i = 0; i < multipart.getCount(); i++) {
190                            BodyPart part = multipart.getBodyPart(i);
191    
192                            collectPartContent(part, collector);
193                    }
194            }
195    
196            public static void collectPartContent(
197                            Part part, MBMailMessage mbMailMessage)
198                    throws Exception {
199    
200                    Object partContent = part.getContent();
201    
202                    String contentType = part.getContentType().toLowerCase();
203    
204                    if ((part.getDisposition() != null) &&
205                            part.getDisposition().equalsIgnoreCase(MimeMessage.ATTACHMENT)) {
206    
207                            if (_log.isDebugEnabled()) {
208                                    _log.debug("Processing attachment");
209                            }
210    
211                            byte[] bytes = null;
212    
213                            if (partContent instanceof String) {
214                                    bytes = ((String)partContent).getBytes();
215                            }
216                            else if (partContent instanceof InputStream) {
217                                    bytes = JavaMailUtil.getBytes(part);
218                            }
219    
220                            mbMailMessage.addBytes(part.getFileName(), bytes);
221                    }
222                    else {
223                            if (partContent instanceof MimeMultipart) {
224                                    MimeMultipart mimeMultipart = (MimeMultipart)partContent;
225    
226                                    collectMultipartContent(mimeMultipart, mbMailMessage);
227                            }
228                            else if (partContent instanceof String) {
229                                    if (contentType.startsWith("text/html")) {
230                                            mbMailMessage.setHtmlBody((String)partContent);
231                                    }
232                                    else {
233                                            mbMailMessage.setPlainBody((String)partContent);
234                                    }
235                            }
236                    }
237            }
238    
239            public static String getAbsolutePath(
240                            PortletRequest portletRequest, long mbCategoryId)
241                    throws PortalException, SystemException {
242    
243                    ThemeDisplay themeDisplay = (ThemeDisplay)portletRequest.getAttribute(
244                            WebKeys.THEME_DISPLAY);
245    
246                    if (mbCategoryId == MBCategoryConstants.DEFAULT_PARENT_CATEGORY_ID) {
247                            return themeDisplay.translate("home");
248                    }
249    
250                    MBCategory mbCategory = MBCategoryLocalServiceUtil.fetchMBCategory(
251                            mbCategoryId);
252    
253                    List<MBCategory> categories = mbCategory.getAncestors();
254    
255                    Collections.reverse(categories);
256    
257                    StringBundler sb = new StringBundler((categories.size() * 3) + 6);
258    
259                    sb.append(themeDisplay.translate("home"));
260                    sb.append(StringPool.SPACE);
261    
262                    for (MBCategory curCategory : categories) {
263                            sb.append(StringPool.RAQUO);
264                            sb.append(StringPool.SPACE);
265                            sb.append(curCategory.getName());
266                    }
267    
268                    sb.append(StringPool.RAQUO);
269                    sb.append(StringPool.SPACE);
270                    sb.append(mbCategory.getName());
271    
272                    return sb.toString();
273            }
274    
275            public static long getCategoryId(
276                    HttpServletRequest request, MBCategory category) {
277    
278                    long categoryId = MBCategoryConstants.DEFAULT_PARENT_CATEGORY_ID;
279    
280                    if (category != null) {
281                            categoryId = category.getCategoryId();
282                    }
283    
284                    categoryId = ParamUtil.getLong(request, "mbCategoryId", categoryId);
285    
286                    return categoryId;
287            }
288    
289            public static long getCategoryId(
290                    HttpServletRequest request, MBMessage message) {
291    
292                    long categoryId = MBCategoryConstants.DEFAULT_PARENT_CATEGORY_ID;
293    
294                    if (message != null) {
295                            categoryId = message.getCategoryId();
296                    }
297    
298                    categoryId = ParamUtil.getLong(request, "mbCategoryId", categoryId);
299    
300                    return categoryId;
301            }
302    
303            public static String getEmailFromAddress(
304                            PortletPreferences preferences, long companyId)
305                    throws SystemException {
306    
307                    return PortalUtil.getEmailFromAddress(
308                            preferences, companyId,
309                            PropsValues.MESSAGE_BOARDS_EMAIL_FROM_ADDRESS);
310            }
311    
312            public static String getEmailFromName(
313                            PortletPreferences preferences, long companyId)
314                    throws SystemException {
315    
316                    return PortalUtil.getEmailFromName(
317                            preferences, companyId, PropsValues.MESSAGE_BOARDS_EMAIL_FROM_NAME);
318            }
319    
320            public static boolean getEmailHtmlFormat(PortletPreferences preferences) {
321                    String emailHtmlFormat = preferences.getValue(
322                            "emailHtmlFormat", StringPool.BLANK);
323    
324                    if (Validator.isNotNull(emailHtmlFormat)) {
325                            return GetterUtil.getBoolean(emailHtmlFormat);
326                    }
327                    else {
328                            return PropsValues.MESSAGE_BOARDS_EMAIL_HTML_FORMAT;
329                    }
330            }
331    
332            public static String getEmailMessageAddedBody(
333                    PortletPreferences preferences) {
334    
335                    String emailMessageAddedBody = preferences.getValue(
336                            "emailMessageAddedBody", StringPool.BLANK);
337    
338                    if (Validator.isNotNull(emailMessageAddedBody)) {
339                            return emailMessageAddedBody;
340                    }
341                    else {
342                            return ContentUtil.get(
343                                    PropsValues.MESSAGE_BOARDS_EMAIL_MESSAGE_ADDED_BODY);
344                    }
345            }
346    
347            public static boolean getEmailMessageAddedEnabled(
348                    PortletPreferences preferences) {
349    
350                    String emailMessageAddedEnabled = preferences.getValue(
351                            "emailMessageAddedEnabled", StringPool.BLANK);
352    
353                    if (Validator.isNotNull(emailMessageAddedEnabled)) {
354                            return GetterUtil.getBoolean(emailMessageAddedEnabled);
355                    }
356                    else {
357                            return PropsValues.MESSAGE_BOARDS_EMAIL_MESSAGE_ADDED_ENABLED;
358                    }
359            }
360    
361            public static String getEmailMessageAddedSignature(
362                    PortletPreferences preferences) {
363    
364                    String emailMessageAddedSignature = preferences.getValue(
365                            "emailMessageAddedSignature", StringPool.BLANK);
366    
367                    if (Validator.isNotNull(emailMessageAddedSignature)) {
368                            return emailMessageAddedSignature;
369                    }
370                    else {
371                            return ContentUtil.get(
372                                    PropsValues.MESSAGE_BOARDS_EMAIL_MESSAGE_ADDED_SIGNATURE);
373                    }
374            }
375    
376            public static String getEmailMessageAddedSubjectPrefix(
377                    PortletPreferences preferences) {
378    
379                    String emailMessageAddedSubjectPrefix = preferences.getValue(
380                            "emailMessageAddedSubjectPrefix", StringPool.BLANK);
381    
382                    if (Validator.isNotNull(emailMessageAddedSubjectPrefix)) {
383                            return emailMessageAddedSubjectPrefix;
384                    }
385                    else {
386                            return ContentUtil.get(
387                                    PropsValues.MESSAGE_BOARDS_EMAIL_MESSAGE_ADDED_SUBJECT_PREFIX);
388                    }
389            }
390    
391            public static String getEmailMessageUpdatedBody(
392                    PortletPreferences preferences) {
393    
394                    String emailMessageUpdatedBody = preferences.getValue(
395                            "emailMessageUpdatedBody", StringPool.BLANK);
396    
397                    if (Validator.isNotNull(emailMessageUpdatedBody)) {
398                            return emailMessageUpdatedBody;
399                    }
400                    else {
401                            return ContentUtil.get(
402                                    PropsValues.MESSAGE_BOARDS_EMAIL_MESSAGE_UPDATED_BODY);
403                    }
404            }
405    
406            public static boolean getEmailMessageUpdatedEnabled(
407                    PortletPreferences preferences) {
408    
409                    String emailMessageUpdatedEnabled = preferences.getValue(
410                            "emailMessageUpdatedEnabled", StringPool.BLANK);
411    
412                    if (Validator.isNotNull(emailMessageUpdatedEnabled)) {
413                            return GetterUtil.getBoolean(emailMessageUpdatedEnabled);
414                    }
415                    else {
416                            return PropsValues.MESSAGE_BOARDS_EMAIL_MESSAGE_UPDATED_ENABLED;
417                    }
418            }
419    
420            public static String getEmailMessageUpdatedSignature(
421                    PortletPreferences preferences) {
422    
423                    String emailMessageUpdatedSignature = preferences.getValue(
424                            "emailMessageUpdatedSignature", StringPool.BLANK);
425    
426                    if (Validator.isNotNull(emailMessageUpdatedSignature)) {
427                            return emailMessageUpdatedSignature;
428                    }
429                    else {
430                            return ContentUtil.get(
431                                    PropsValues.MESSAGE_BOARDS_EMAIL_MESSAGE_UPDATED_SIGNATURE);
432                    }
433            }
434    
435            public static String getEmailMessageUpdatedSubjectPrefix(
436                    PortletPreferences preferences) {
437    
438                    String emailMessageUpdatedSubject = preferences.getValue(
439                            "emailMessageUpdatedSubjectPrefix", StringPool.BLANK);
440    
441                    if (Validator.isNotNull(emailMessageUpdatedSubject)) {
442                            return emailMessageUpdatedSubject;
443                    }
444                    else {
445                            return ContentUtil.get(
446                                    PropsValues.
447                                            MESSAGE_BOARDS_EMAIL_MESSAGE_UPDATED_SUBJECT_PREFIX);
448                    }
449            }
450    
451            public static String getMailingListAddress(
452                    long groupId, long categoryId, long messageId, String mx,
453                    String defaultMailingListAddress) {
454    
455                    if (PropsValues.POP_SERVER_SUBDOMAIN.length() <= 0) {
456                            String mailingListAddress = defaultMailingListAddress;
457    
458                            try {
459                                    MBMailingList mailingList =
460                                            MBMailingListLocalServiceUtil.getCategoryMailingList(
461                                                    groupId, categoryId);
462    
463                                    if (mailingList.isActive()) {
464                                            mailingListAddress = mailingList.getEmailAddress();
465                                    }
466                            }
467                            catch (Exception e) {
468                            }
469    
470                            return mailingListAddress;
471                    }
472    
473                    StringBundler sb = new StringBundler(8);
474    
475                    sb.append(MESSAGE_POP_PORTLET_PREFIX);
476                    sb.append(categoryId);
477                    sb.append(StringPool.PERIOD);
478                    sb.append(messageId);
479                    sb.append(StringPool.AT);
480                    sb.append(PropsValues.POP_SERVER_SUBDOMAIN);
481                    sb.append(StringPool.PERIOD);
482                    sb.append(mx);
483    
484                    return sb.toString();
485            }
486    
487            public static String getMessageFormat(PortletPreferences preferences) {
488                    String messageFormat = preferences.getValue(
489                            "messageFormat", MBMessageConstants.DEFAULT_FORMAT);
490    
491                    String editorImpl = PropsUtil.get(BB_CODE_EDITOR_WYSIWYG_IMPL_KEY);
492    
493                    if (messageFormat.equals("bbcode") &&
494                            !(editorImpl.equals("bbcode") ||
495                              editorImpl.equals("ckeditor_bbcode"))) {
496    
497                            messageFormat = "html";
498                    }
499    
500                    return messageFormat;
501            }
502    
503            public static long getMessageId(String mailId) {
504                    int x = mailId.indexOf(CharPool.LESS_THAN) + 1;
505                    int y = mailId.indexOf(CharPool.AT);
506    
507                    long messageId = 0;
508    
509                    if ((x > 0 ) && (y != -1)) {
510                            String temp = mailId.substring(x, y);
511    
512                            int z = temp.lastIndexOf(CharPool.PERIOD);
513    
514                            if (z != -1) {
515                                    messageId = GetterUtil.getLong(temp.substring(z + 1));
516                            }
517                    }
518    
519                    return messageId;
520            }
521    
522            public static long getParentMessageId(Message message) throws Exception {
523                    long parentMessageId = -1;
524    
525                    String parentHeader = getParentMessageIdString(message);
526    
527                    if (parentHeader != null) {
528                            if (_log.isDebugEnabled()) {
529                                    _log.debug("Parent header " + parentHeader);
530                            }
531    
532                            parentMessageId = getMessageId(parentHeader);
533    
534                            if (_log.isDebugEnabled()) {
535                                    _log.debug("Previous message id " + parentMessageId);
536                            }
537                    }
538    
539                    return parentMessageId;
540            }
541    
542            public static String getParentMessageIdString(Message message)
543                    throws Exception {
544    
545                    // If the previous block failed, try to get the parent message ID from
546                    // the "References" header as explained in
547                    // http://cr.yp.to/immhf/thread.html. Some mail clients such as Yahoo!
548                    // Mail use the "In-Reply-To" header, so we check that as well.
549    
550                    String parentHeader = null;
551    
552                    String[] references = message.getHeader("References");
553    
554                    if ((references != null) && (references.length > 0)) {
555                            String reference = references[0];
556    
557                            int x = reference.lastIndexOf("<mb.");
558    
559                            if (x > -1) {
560                                    int y = reference.indexOf(">", x);
561    
562                                    parentHeader = reference.substring(x, y);
563                            }
564                    }
565    
566                    if (parentHeader == null) {
567                            String[] inReplyToHeaders = message.getHeader("In-Reply-To");
568    
569                            if ((inReplyToHeaders != null) && (inReplyToHeaders.length > 0)) {
570                                    parentHeader = inReplyToHeaders[0];
571                            }
572                    }
573    
574                    if (Validator.isNull(parentHeader) ||
575                            !parentHeader.startsWith(MESSAGE_POP_PORTLET_PREFIX, 1)) {
576    
577                            parentHeader = _getParentMessageIdFromSubject(message);
578                    }
579    
580                    return parentHeader;
581            }
582    
583            public static String getSubjectWithoutMessageId(Message message)
584                    throws Exception {
585    
586                    String subject = message.getSubject();
587    
588                    String parentMessageId = _getParentMessageIdFromSubject(message);
589    
590                    if (Validator.isNotNull(parentMessageId)) {
591                            int pos = subject.indexOf(parentMessageId);
592    
593                            if (pos != -1) {
594                                    subject = subject.substring(0, pos);
595                            }
596                    }
597    
598                    return subject;
599            }
600    
601            public static String[] getThreadPriority(
602                            PortletPreferences preferences, String languageId, double value,
603                            ThemeDisplay themeDisplay)
604                    throws Exception {
605    
606                    String[] priorities = LocalizationUtil.getPreferencesValues(
607                            preferences, "priorities", languageId);
608    
609                    String[] priorityPair = _findThreadPriority(
610                            value, themeDisplay, priorities);
611    
612                    if (priorityPair == null) {
613                            String defaultLanguageId = LocaleUtil.toLanguageId(
614                                    LocaleUtil.getDefault());
615    
616                            priorities = LocalizationUtil.getPreferencesValues(
617                                    preferences, "priorities", defaultLanguageId);
618    
619                            priorityPair = _findThreadPriority(value, themeDisplay, priorities);
620                    }
621    
622                    return priorityPair;
623            }
624    
625            public static Date getUnbanDate(MBBan ban, int expireInterval) {
626                    Date banDate = ban.getCreateDate();
627    
628                    Calendar cal = Calendar.getInstance();
629    
630                    cal.setTime(banDate);
631    
632                    cal.add(Calendar.DATE, expireInterval);
633    
634                    return cal.getTime();
635            }
636    
637            public static String getUserRank(
638                            PortletPreferences preferences, String languageId, int posts)
639                    throws Exception {
640    
641                    String rank = StringPool.BLANK;
642    
643                    String[] ranks = LocalizationUtil.getPreferencesValues(
644                            preferences, "ranks", languageId);
645    
646                    for (int i = 0; i < ranks.length; i++) {
647                            String[] kvp = StringUtil.split(ranks[i], CharPool.EQUAL);
648    
649                            String kvpName = kvp[0];
650                            int kvpPosts = GetterUtil.getInteger(kvp[1]);
651    
652                            if (posts >= kvpPosts) {
653                                    rank = kvpName;
654                            }
655                            else {
656                                    break;
657                            }
658                    }
659    
660                    return rank;
661            }
662    
663            public static String[] getUserRank(
664                            PortletPreferences preferences, String languageId,
665                            MBStatsUser statsUser)
666                    throws Exception {
667    
668                    String[] rank = {StringPool.BLANK, StringPool.BLANK};
669    
670                    int maxPosts = 0;
671    
672                    Group group = GroupLocalServiceUtil.getGroup(statsUser.getGroupId());
673    
674                    long companyId = group.getCompanyId();
675    
676                    String[] ranks = LocalizationUtil.getPreferencesValues(
677                            preferences, "ranks", languageId);
678    
679                    for (int i = 0; i < ranks.length; i++) {
680                            String[] kvp = StringUtil.split(ranks[i], CharPool.EQUAL);
681    
682                            String curRank = kvp[0];
683                            String curRankValue = kvp[1];
684    
685                            String[] curRankValueKvp = StringUtil.split(
686                                    curRankValue, CharPool.COLON);
687    
688                            if (curRankValueKvp.length <= 1) {
689                                    int posts = GetterUtil.getInteger(curRankValue);
690    
691                                    if ((posts <= statsUser.getMessageCount()) &&
692                                            (posts >= maxPosts)) {
693    
694                                            rank[0] = curRank;
695                                            maxPosts = posts;
696                                    }
697    
698                            }
699                            else {
700                                    String entityType = curRankValueKvp[0];
701                                    String entityValue = curRankValueKvp[1];
702    
703                                    try {
704                                            if (_isEntityRank(
705                                                            companyId, statsUser, entityType, entityValue)) {
706    
707                                                    rank[1] = curRank;
708    
709                                                    break;
710                                            }
711                                    }
712                                    catch (Exception e) {
713                                            if (_log.isWarnEnabled()) {
714                                                    _log.warn(e);
715                                            }
716                                    }
717                            }
718                    }
719    
720                    return rank;
721            }
722    
723            public static boolean hasMailIdHeader(Message message) throws Exception {
724                    String[] messageIds = message.getHeader("Message-ID");
725    
726                    if (messageIds == null) {
727                            return false;
728                    }
729    
730                    for (String messageId : messageIds) {
731                            if (Validator.isNotNull(PropsValues.POP_SERVER_SUBDOMAIN) &&
732                                    messageId.contains(PropsValues.POP_SERVER_SUBDOMAIN)) {
733    
734                                    return true;
735                            }
736                    }
737    
738                    return false;
739            }
740    
741            public static boolean isAllowAnonymousPosting(
742                    PortletPreferences preferences) {
743    
744                    return GetterUtil.getBoolean(
745                            preferences.getValue("allowAnonymousPosting", null),
746                            PropsValues.MESSAGE_BOARDS_ANONYMOUS_POSTING_ENABLED);
747            }
748    
749            public static boolean isViewableMessage(
750                            ThemeDisplay themeDisplay, MBMessage message)
751                    throws Exception {
752    
753                    return isViewableMessage(themeDisplay, message, message);
754            }
755    
756            public static boolean isViewableMessage(
757                            ThemeDisplay themeDisplay, MBMessage message,
758                            MBMessage parentMessage)
759                    throws Exception {
760    
761                    PermissionChecker permissionChecker =
762                            themeDisplay.getPermissionChecker();
763    
764                    if (!MBMessagePermission.contains(
765                                    permissionChecker, parentMessage, ActionKeys.VIEW)) {
766    
767                            return false;
768                    }
769    
770                    if ((message.getMessageId() != parentMessage.getMessageId()) &&
771                            !MBMessagePermission.contains(
772                                    permissionChecker, message, ActionKeys.VIEW)) {
773    
774                            return false;
775                    }
776    
777                    if (!message.isApproved() &&
778                            !Validator.equals(message.getUserId(), themeDisplay.getUserId()) &&
779                            !permissionChecker.isGroupAdmin(themeDisplay.getScopeGroupId())) {
780    
781                            return false;
782                    }
783    
784                    return true;
785            }
786    
787            public static String replaceMessageBodyPaths(
788                    ThemeDisplay themeDisplay, String messageBody) {
789    
790                    return StringUtil.replace(
791                            messageBody,
792                            new String[] {
793                                    "@theme_images_path@", "href=\"/", "src=\"/"
794                            },
795                            new String[] {
796                                    themeDisplay.getPathThemeImages(),
797                                    "href=\"" + themeDisplay.getURLPortal() + "/",
798                                    "src=\"" + themeDisplay.getURLPortal() + "/"
799                            });
800            }
801    
802            private static String[] _findThreadPriority(
803                    double value, ThemeDisplay themeDisplay, String[] priorities) {
804    
805                    for (int i = 0; i < priorities.length; i++) {
806                            String[] priority = StringUtil.split(priorities[i]);
807    
808                            try {
809                                    String priorityName = priority[0];
810                                    String priorityImage = priority[1];
811                                    double priorityValue = GetterUtil.getDouble(priority[2]);
812    
813                                    if (value == priorityValue) {
814                                            if (!priorityImage.startsWith(Http.HTTP)) {
815                                                    priorityImage =
816                                                            themeDisplay.getPathThemeImages() + priorityImage;
817                                            }
818    
819                                            return new String[] {priorityName, priorityImage};
820                                    }
821                            }
822                            catch (Exception e) {
823                                    _log.error("Unable to determine thread priority", e);
824                            }
825                    }
826    
827                    return null;
828            }
829    
830            private static String _getParentMessageIdFromSubject(Message message)
831                    throws Exception {
832    
833                    if (message.getSubject() == null) {
834                            return null;
835                    }
836    
837                    String parentMessageId = null;
838    
839                    String subject = StringUtil.reverse(message.getSubject());
840    
841                    int pos = subject.indexOf(CharPool.LESS_THAN);
842    
843                    if (pos != -1) {
844                            parentMessageId = StringUtil.reverse(subject.substring(0, pos + 1));
845                    }
846    
847                    return parentMessageId;
848            }
849    
850            private static boolean _isEntityRank(
851                            long companyId, MBStatsUser statsUser, String entityType,
852                            String entityValue)
853                    throws Exception {
854    
855                    long groupId = statsUser.getGroupId();
856                    long userId = statsUser.getUserId();
857    
858                    if (entityType.equals("organization-role") ||
859                            entityType.equals("site-role")) {
860    
861                            Role role = RoleLocalServiceUtil.getRole(companyId, entityValue);
862    
863                            if (UserGroupRoleLocalServiceUtil.hasUserGroupRole(
864                                            userId, groupId, role.getRoleId(), true)) {
865    
866                                    return true;
867                            }
868                    }
869                    else if (entityType.equals("organization")) {
870                            Organization organization =
871                                    OrganizationLocalServiceUtil.getOrganization(
872                                            companyId, entityValue);
873    
874                            if (OrganizationLocalServiceUtil.hasUserOrganization(
875                                            userId, organization.getOrganizationId(), false, false)) {
876    
877                                    return true;
878                            }
879                    }
880                    else if (entityType.equals("regular-role")) {
881                            if (RoleLocalServiceUtil.hasUserRole(
882                                            userId, companyId, entityValue, true)) {
883    
884                                    return true;
885                            }
886                    }
887                    else if (entityType.equals("user-group")) {
888                            UserGroup userGroup = UserGroupLocalServiceUtil.getUserGroup(
889                                    companyId, entityValue);
890    
891                            if (UserLocalServiceUtil.hasUserGroupUser(
892                                            userGroup.getUserGroupId(), userId)) {
893    
894                                    return true;
895                            }
896                    }
897    
898                    return false;
899            }
900    
901            private static Log _log = LogFactoryUtil.getLog(MBUtil.class);
902    
903    }