1
14
15 package com.liferay.portlet.messageboards.util;
16
17 import com.liferay.portal.kernel.log.Log;
18 import com.liferay.portal.kernel.log.LogFactoryUtil;
19 import com.liferay.portal.kernel.portlet.LiferayWindowState;
20 import com.liferay.portal.kernel.util.GetterUtil;
21 import com.liferay.portal.kernel.util.Http;
22 import com.liferay.portal.kernel.util.LocaleUtil;
23 import com.liferay.portal.kernel.util.ParamUtil;
24 import com.liferay.portal.kernel.util.StringBundler;
25 import com.liferay.portal.kernel.util.StringPool;
26 import com.liferay.portal.kernel.util.StringUtil;
27 import com.liferay.portal.kernel.util.Validator;
28 import com.liferay.portal.model.Group;
29 import com.liferay.portal.model.Organization;
30 import com.liferay.portal.model.Role;
31 import com.liferay.portal.model.UserGroup;
32 import com.liferay.portal.service.GroupLocalServiceUtil;
33 import com.liferay.portal.service.OrganizationLocalServiceUtil;
34 import com.liferay.portal.service.RoleLocalServiceUtil;
35 import com.liferay.portal.service.UserGroupLocalServiceUtil;
36 import com.liferay.portal.service.UserGroupRoleLocalServiceUtil;
37 import com.liferay.portal.service.UserLocalServiceUtil;
38 import com.liferay.portal.theme.ThemeDisplay;
39 import com.liferay.portal.util.ContentUtil;
40 import com.liferay.portal.util.PortalUtil;
41 import com.liferay.portal.util.PropsValues;
42 import com.liferay.portal.util.WebKeys;
43 import com.liferay.portlet.messageboards.model.MBBan;
44 import com.liferay.portlet.messageboards.model.MBCategory;
45 import com.liferay.portlet.messageboards.model.MBMailingList;
46 import com.liferay.portlet.messageboards.model.MBMessage;
47 import com.liferay.portlet.messageboards.model.MBStatsUser;
48 import com.liferay.portlet.messageboards.service.MBCategoryLocalServiceUtil;
49 import com.liferay.portlet.messageboards.service.MBMailingListLocalServiceUtil;
50 import com.liferay.util.LocalizationUtil;
51 import com.liferay.util.mail.JavaMailUtil;
52
53 import java.io.InputStream;
54
55 import java.util.Calendar;
56 import java.util.Collections;
57 import java.util.Date;
58 import java.util.List;
59
60 import javax.mail.BodyPart;
61 import javax.mail.Message;
62 import javax.mail.Part;
63 import javax.mail.internet.MimeMessage;
64 import javax.mail.internet.MimeMultipart;
65
66 import javax.portlet.PortletPreferences;
67 import javax.portlet.PortletURL;
68 import javax.portlet.RenderResponse;
69
70 import javax.servlet.http.HttpServletRequest;
71
72
77 public class MBUtil {
78
79 public static final String POP_PORTLET_PREFIX = "mb.";
80
81 public static final int POP_SERVER_SUBDOMAIN_LENGTH =
82 PropsValues.POP_SERVER_SUBDOMAIN.length();
83
84 public static void addPortletBreadcrumbEntries(
85 long categoryId, HttpServletRequest request,
86 RenderResponse renderResponse)
87 throws Exception {
88
89 MBCategory category = MBCategoryLocalServiceUtil.getCategory(
90 categoryId);
91
92 addPortletBreadcrumbEntries(category, request, renderResponse);
93 }
94
95 public static void addPortletBreadcrumbEntries(
96 MBCategory category, HttpServletRequest request,
97 RenderResponse renderResponse)
98 throws Exception {
99
100 String strutsAction = ParamUtil.getString(
101 request, "struts_action");
102
103 boolean selectCategory = strutsAction.equals(
104 "/message_boards/select_category");
105
106 PortletURL portletURL = renderResponse.createRenderURL();
107
108 if (selectCategory) {
109 ThemeDisplay themeDisplay = (ThemeDisplay)request.getAttribute(
110 WebKeys.THEME_DISPLAY);
111
112 portletURL.setWindowState(LiferayWindowState.POP_UP);
113
114 portletURL.setParameter(
115 "struts_action", "/message_boards/select_category");
116
117 PortalUtil.addPortletBreadcrumbEntry(
118 request, themeDisplay.translate("categories"),
119 portletURL.toString());
120 }
121 else {
122 portletURL.setParameter("struts_action", "/message_boards/view");
123 portletURL.setParameter("tabs1", "categories");
124 }
125
126 List<MBCategory> ancestorCategories = category.getAncestors();
127
128 Collections.reverse(ancestorCategories);
129
130 for (MBCategory curCategory : ancestorCategories) {
131 portletURL.setParameter(
132 "mbCategoryId", String.valueOf(curCategory.getCategoryId()));
133
134 PortalUtil.addPortletBreadcrumbEntry(
135 request, curCategory.getName(), portletURL.toString());
136 }
137
138 portletURL.setParameter(
139 "mbCategoryId", String.valueOf(category.getCategoryId()));
140
141 PortalUtil.addPortletBreadcrumbEntry(
142 request, category.getName(), portletURL.toString());
143 }
144
145 public static void addPortletBreadcrumbEntries(
146 MBMessage message, HttpServletRequest request,
147 RenderResponse renderResponse)
148 throws Exception {
149
150 MBCategory category = message.getCategory();
151
152 addPortletBreadcrumbEntries(category, request, renderResponse);
153
154 PortletURL portletURL = renderResponse.createRenderURL();
155
156 portletURL.setParameter(
157 "struts_action", "/message_boards/view_message");
158 portletURL.setParameter("tabs1", "categories");
159 portletURL.setParameter(
160 "messageId", String.valueOf(message.getMessageId()));
161
162 PortalUtil.addPortletBreadcrumbEntry(
163 request, message.getSubject(), portletURL.toString());
164 }
165
166 public static void collectMultipartContent(
167 MimeMultipart multipart, MBMailMessage collector)
168 throws Exception {
169
170 for (int i = 0; i < multipart.getCount(); i++) {
171 BodyPart part = multipart.getBodyPart(i);
172
173 collectPartContent(part, collector);
174 }
175 }
176
177 public static void collectPartContent(Part part, MBMailMessage collector)
178 throws Exception {
179
180 Object partContent = part.getContent();
181
182 String contentType = part.getContentType().toLowerCase();
183
184 if ((part.getDisposition() != null) &&
185 (part.getDisposition().equalsIgnoreCase(MimeMessage.ATTACHMENT))) {
186
187 if (_log.isDebugEnabled()) {
188 _log.debug("Processing attachment");
189 }
190
191 byte[] bytes = null;
192
193 if (partContent instanceof String) {
194 bytes = ((String)partContent).getBytes();
195 }
196 else if (partContent instanceof InputStream) {
197 bytes = JavaMailUtil.getBytes(part);
198 }
199
200 collector.addFile(part.getFileName(), bytes);
201 }
202 else {
203 if (partContent instanceof MimeMultipart) {
204 collectMultipartContent((MimeMultipart)partContent, collector);
205 }
206 else if (partContent instanceof String) {
207 if (contentType.startsWith("text/html")) {
208 collector.setHtmlBody((String)partContent);
209 }
210 else {
211 collector.setPlainBody((String)partContent);
212 }
213 }
214 }
215 }
216
217 public static String getEmailFromAddress(PortletPreferences preferences) {
218 String emailFromAddress = PropsValues.MESSAGE_BOARDS_EMAIL_FROM_ADDRESS;
219
220 return preferences.getValue("email-from-address", emailFromAddress);
221 }
222
223 public static String getEmailFromName(PortletPreferences preferences) {
224 String emailFromName = PropsValues.MESSAGE_BOARDS_EMAIL_FROM_NAME;
225
226 return preferences.getValue("email-from-name", emailFromName);
227 }
228
229 public static boolean getEmailHtmlFormat(PortletPreferences preferences) {
230 String emailHtmlFormat = preferences.getValue(
231 "email-html-format", StringPool.BLANK);
232
233 if (Validator.isNotNull(emailHtmlFormat)) {
234 return GetterUtil.getBoolean(emailHtmlFormat);
235 }
236 else {
237 return PropsValues.MESSAGE_BOARDS_EMAIL_HTML_FORMAT;
238 }
239 }
240
241 public static String getEmailMessageAddedBody(
242 PortletPreferences preferences) {
243
244 String emailMessageAddedBody = preferences.getValue(
245 "email-message-added-body", StringPool.BLANK);
246
247 if (Validator.isNotNull(emailMessageAddedBody)) {
248 return emailMessageAddedBody;
249 }
250 else {
251 return ContentUtil.get(
252 PropsValues.MESSAGE_BOARDS_EMAIL_MESSAGE_ADDED_BODY);
253 }
254 }
255
256 public static boolean getEmailMessageAddedEnabled(
257 PortletPreferences preferences) {
258
259 String emailMessageAddedEnabled = preferences.getValue(
260 "email-message-added-enabled", StringPool.BLANK);
261
262 if (Validator.isNotNull(emailMessageAddedEnabled)) {
263 return GetterUtil.getBoolean(emailMessageAddedEnabled);
264 }
265 else {
266 return PropsValues.MESSAGE_BOARDS_EMAIL_MESSAGE_ADDED_ENABLED;
267 }
268 }
269
270 public static String getEmailMessageAddedSignature(
271 PortletPreferences preferences) {
272
273 String emailMessageAddedSignature = preferences.getValue(
274 "email-message-added-signature", StringPool.BLANK);
275
276 if (Validator.isNotNull(emailMessageAddedSignature)) {
277 return emailMessageAddedSignature;
278 }
279 else {
280 return ContentUtil.get(
281 PropsValues.MESSAGE_BOARDS_EMAIL_MESSAGE_ADDED_SIGNATURE);
282 }
283 }
284
285 public static String getEmailMessageAddedSubjectPrefix(
286 PortletPreferences preferences) {
287
288 String emailMessageAddedSubjectPrefix = preferences.getValue(
289 "email-message-added-subject-prefix", StringPool.BLANK);
290
291 if (Validator.isNotNull(emailMessageAddedSubjectPrefix)) {
292 return emailMessageAddedSubjectPrefix;
293 }
294 else {
295 return ContentUtil.get(
296 PropsValues.MESSAGE_BOARDS_EMAIL_MESSAGE_ADDED_SUBJECT_PREFIX);
297 }
298 }
299
300 public static String getEmailMessageUpdatedBody(
301 PortletPreferences preferences) {
302
303 String emailMessageUpdatedBody = preferences.getValue(
304 "email-message-updated-body", StringPool.BLANK);
305
306 if (Validator.isNotNull(emailMessageUpdatedBody)) {
307 return emailMessageUpdatedBody;
308 }
309 else {
310 return ContentUtil.get(
311 PropsValues.MESSAGE_BOARDS_EMAIL_MESSAGE_UPDATED_BODY);
312 }
313 }
314
315 public static boolean getEmailMessageUpdatedEnabled(
316 PortletPreferences preferences) {
317
318 String emailMessageUpdatedEnabled = preferences.getValue(
319 "email-message-updated-enabled", StringPool.BLANK);
320
321 if (Validator.isNotNull(emailMessageUpdatedEnabled)) {
322 return GetterUtil.getBoolean(emailMessageUpdatedEnabled);
323 }
324 else {
325 return PropsValues.MESSAGE_BOARDS_EMAIL_MESSAGE_UPDATED_ENABLED;
326 }
327 }
328
329 public static String getEmailMessageUpdatedSignature(
330 PortletPreferences preferences) {
331
332 String emailMessageUpdatedSignature = preferences.getValue(
333 "email-message-updated-signature", StringPool.BLANK);
334
335 if (Validator.isNotNull(emailMessageUpdatedSignature)) {
336 return emailMessageUpdatedSignature;
337 }
338 else {
339 return ContentUtil.get(
340 PropsValues.MESSAGE_BOARDS_EMAIL_MESSAGE_UPDATED_SIGNATURE);
341 }
342 }
343
344 public static String getEmailMessageUpdatedSubjectPrefix(
345 PortletPreferences preferences) {
346
347 String emailMessageUpdatedSubject = preferences.getValue(
348 "email-message-updated-subject-prefix", StringPool.BLANK);
349
350 if (Validator.isNotNull(emailMessageUpdatedSubject)) {
351 return emailMessageUpdatedSubject;
352 }
353 else {
354 return ContentUtil.get(
355 PropsValues.
356 MESSAGE_BOARDS_EMAIL_MESSAGE_UPDATED_SUBJECT_PREFIX);
357 }
358 }
359
360 public static String getMailId(String mx, long categoryId, long messageId) {
361 StringBundler sb = new StringBundler(10);
362
363 sb.append(StringPool.LESS_THAN);
364 sb.append(POP_PORTLET_PREFIX);
365 sb.append(categoryId);
366 sb.append(StringPool.PERIOD);
367 sb.append(messageId);
368 sb.append(StringPool.AT);
369
370 if (Validator.isNotNull(PropsValues.POP_SERVER_SUBDOMAIN)) {
371 sb.append(PropsValues.POP_SERVER_SUBDOMAIN);
372 sb.append(StringPool.PERIOD);
373 }
374
375 sb.append(mx);
376 sb.append(StringPool.GREATER_THAN);
377
378 return sb.toString();
379 }
380
381 public static String getMailingListAddress(
382 long groupId, long categoryId, long messageId, String mx,
383 String defaultMailingListAddress) {
384
385 if (POP_SERVER_SUBDOMAIN_LENGTH <= 0) {
386 String mailingListAddress = defaultMailingListAddress;
387
388 try {
389 MBMailingList mailingList =
390 MBMailingListLocalServiceUtil.getCategoryMailingList(
391 groupId, categoryId);
392
393 if (mailingList.isActive()) {
394 mailingListAddress = mailingList.getEmailAddress();
395 }
396 }
397 catch (Exception e) {
398 }
399
400 return mailingListAddress;
401 }
402
403 StringBundler sb = new StringBundler(8);
404
405 sb.append(POP_PORTLET_PREFIX);
406 sb.append(categoryId);
407 sb.append(StringPool.PERIOD);
408 sb.append(messageId);
409 sb.append(StringPool.AT);
410 sb.append(PropsValues.POP_SERVER_SUBDOMAIN);
411 sb.append(StringPool.PERIOD);
412 sb.append(mx);
413
414 return sb.toString();
415 }
416
417 public static long getMessageId(String mailId) {
418 int x = mailId.indexOf(StringPool.LESS_THAN) + 1;
419 int y = mailId.indexOf(StringPool.AT);
420
421 long messageId = 0;
422
423 if ((x > 0 ) && (y != -1)) {
424 String temp = mailId.substring(x, y);
425
426 int z = temp.lastIndexOf(StringPool.PERIOD);
427
428 if (z != -1) {
429 messageId = GetterUtil.getLong(temp.substring(z + 1));
430 }
431 }
432
433 return messageId;
434 }
435
436 public static long getParentMessageId(Message message) throws Exception {
437 long parentMessageId = -1;
438
439 String parentHeader = getParentMessageIdString(message);
440
441 if (parentHeader != null) {
442 if (_log.isDebugEnabled()) {
443 _log.debug("Parent header " + parentHeader);
444 }
445
446 parentMessageId = getMessageId(parentHeader);
447
448 if (_log.isDebugEnabled()) {
449 _log.debug("Previous message id " + parentMessageId);
450 }
451 }
452
453 return parentMessageId;
454 }
455
456 public static String getParentMessageIdString(Message message)
457 throws Exception {
458
459
464 String parentHeader = null;
465
466 String[] references = message.getHeader("References");
467
468 if ((references != null) && (references.length > 0)) {
469 String reference = references[0];
470
471 int x = reference.lastIndexOf("<mb.");
472
473 if (x > -1) {
474 int y = reference.indexOf(">", x);
475
476 parentHeader = reference.substring(x, y);
477 }
478 }
479
480 if (parentHeader == null) {
481 String[] inReplyToHeaders = message.getHeader("In-Reply-To");
482
483 if ((inReplyToHeaders != null) && (inReplyToHeaders.length > 0)) {
484 parentHeader = inReplyToHeaders[0];
485 }
486 }
487
488 if (Validator.isNull(parentHeader) ||
489 !parentHeader.startsWith(POP_PORTLET_PREFIX, 1)) {
490
491 parentHeader = _getParentMessageIdFromSubject(message);
492 }
493
494 return parentHeader;
495 }
496
497 public static String getSubjectWithoutMessageId(Message message)
498 throws Exception {
499
500 String subject = message.getSubject();
501
502 String parentMessageId = _getParentMessageIdFromSubject(message);
503
504 if (Validator.isNotNull(parentMessageId)) {
505 int pos = subject.indexOf(parentMessageId);
506
507 if (pos != -1) {
508 subject = subject.substring(0, pos);
509 }
510 }
511
512 return subject;
513 }
514
515 public static String[] getThreadPriority(
516 PortletPreferences preferences, String languageId, double value,
517 ThemeDisplay themeDisplay)
518 throws Exception {
519
520 String[] priorities = LocalizationUtil.getPreferencesValues(
521 preferences, "priorities", languageId);
522
523 String[] priorityPair = _findThreadPriority(
524 value, themeDisplay, priorities);
525
526 if (priorityPair == null) {
527 String defaultLanguageId = LocaleUtil.toLanguageId(
528 LocaleUtil.getDefault());
529
530 priorities = LocalizationUtil.getPreferencesValues(
531 preferences, "priorities", defaultLanguageId);
532
533 priorityPair = _findThreadPriority(value, themeDisplay, priorities);
534 }
535
536 return priorityPair;
537 }
538
539 public static Date getUnbanDate(MBBan ban, int expireInterval) {
540 Date banDate = ban.getCreateDate();
541
542 Calendar cal = Calendar.getInstance();
543
544 cal.setTime(banDate);
545
546 cal.add(Calendar.DATE, expireInterval);
547
548 return cal.getTime();
549 }
550
551 public static String getUserRank(
552 PortletPreferences preferences, String languageId, int posts)
553 throws Exception {
554
555 String rank = StringPool.BLANK;
556
557 String[] ranks = LocalizationUtil.getPreferencesValues(
558 preferences, "ranks", languageId);
559
560 for (int i = 0; i < ranks.length; i++) {
561 String[] kvp = StringUtil.split(ranks[i], StringPool.EQUAL);
562
563 String kvpName = kvp[0];
564 int kvpPosts = GetterUtil.getInteger(kvp[1]);
565
566 if (posts >= kvpPosts) {
567 rank = kvpName;
568 }
569 else {
570 break;
571 }
572 }
573
574 return rank;
575 }
576
577 public static String[] getUserRank(
578 PortletPreferences preferences, String languageId,
579 MBStatsUser statsUser)
580 throws Exception {
581
582 String[] rank = {StringPool.BLANK, StringPool.BLANK};
583
584 int maxPosts = 0;
585
586 Group group = GroupLocalServiceUtil.getGroup(
587 statsUser.getGroupId());
588
589 long companyId = group.getCompanyId();
590
591 String[] ranks = LocalizationUtil.getPreferencesValues(
592 preferences, "ranks", languageId);
593
594 for (int i = 0; i < ranks.length; i++) {
595 String[] kvp = StringUtil.split(ranks[i], StringPool.EQUAL);
596
597 String curRank = kvp[0];
598 String curRankValue = kvp[1];
599
600 String[] curRankValueKvp = StringUtil.split(
601 curRankValue, StringPool.COLON);
602
603 if (curRankValueKvp.length <= 1) {
604 int posts = GetterUtil.getInteger(curRankValue);
605
606 if ((posts <= statsUser.getMessageCount()) &&
607 (posts >= maxPosts)) {
608
609 rank[0] = curRank;
610 maxPosts = posts;
611 }
612
613 }
614 else {
615 String entityType = curRankValueKvp[0];
616 String entityValue = curRankValueKvp[1];
617
618 try {
619 if (_isEntityRank(
620 companyId, statsUser, entityType, entityValue)) {
621
622 rank[1] = curRank;
623
624 break;
625 }
626 }
627 catch (Exception e) {
628 if (_log.isWarnEnabled()) {
629 _log.warn(e);
630 }
631 }
632 }
633 }
634
635 return rank;
636 }
637
638 public static boolean hasMailIdHeader(Message message) throws Exception {
639 String[] messageIds = message.getHeader("Message-ID");
640
641 if (messageIds == null) {
642 return false;
643 }
644
645 for (String messageId : messageIds) {
646 if (Validator.isNotNull(PropsValues.POP_SERVER_SUBDOMAIN) &&
647 messageId.contains(PropsValues.POP_SERVER_SUBDOMAIN)) {
648
649 return true;
650 }
651 }
652
653 return false;
654 }
655
656 public static boolean isAllowAnonymousPosting(
657 PortletPreferences preferences) {
658
659 String allowAnonymousPosting = preferences.getValue(
660 "allow-anonymous-posting", StringPool.BLANK);
661
662 if (Validator.isNotNull(allowAnonymousPosting)) {
663 return GetterUtil.getBoolean(allowAnonymousPosting);
664 }
665 else {
666 return PropsValues.MESSAGE_BOARDS_ANONYMOUS_POSTING_ENABLED;
667 }
668 }
669
670 private static String[] _findThreadPriority(
671 double value, ThemeDisplay themeDisplay, String[] priorities) {
672
673 for (int i = 0; i < priorities.length; i++) {
674 String[] priority = StringUtil.split(priorities[i]);
675
676 try {
677 String priorityName = priority[0];
678 String priorityImage = priority[1];
679 double priorityValue = GetterUtil.getDouble(priority[2]);
680
681 if (value == priorityValue) {
682 if (!priorityImage.startsWith(Http.HTTP)) {
683 priorityImage =
684 themeDisplay.getPathThemeImages() + priorityImage;
685 }
686
687 return new String[] {priorityName, priorityImage};
688 }
689 }
690 catch (Exception e) {
691 _log.error("Unable to determine thread priority", e);
692 }
693 }
694
695 return null;
696 }
697
698 private static String _getParentMessageIdFromSubject(Message message)
699 throws Exception {
700
701 String parentMessageId = null;
702
703 String subject = StringUtil.reverse(message.getSubject());
704
705 int pos = subject.indexOf(StringPool.LESS_THAN);
706
707 if (pos != -1) {
708 parentMessageId = StringUtil.reverse(subject.substring(0, pos + 1));
709 }
710
711 return parentMessageId;
712 }
713
714 private static boolean _isEntityRank(
715 long companyId, MBStatsUser statsUser, String entityType,
716 String entityValue)
717 throws Exception {
718
719 long groupId = statsUser.getGroupId();
720 long userId = statsUser.getUserId();
721
722 if (entityType.equals("community-role") ||
723 entityType.equals("organization-role")) {
724
725 Role role = RoleLocalServiceUtil.getRole(companyId, entityValue);
726
727 if (UserGroupRoleLocalServiceUtil.hasUserGroupRole(
728 userId, groupId, role.getRoleId(), true)) {
729
730 return true;
731 }
732 }
733 else if (entityType.equals("organization")) {
734 Organization organization =
735 OrganizationLocalServiceUtil.getOrganization(
736 companyId, entityValue);
737
738 if (OrganizationLocalServiceUtil.hasUserOrganization(
739 userId, organization.getOrganizationId(), false, true,
740 false)) {
741
742 return true;
743 }
744 }
745 else if (entityType.equals("regular-role")) {
746 if (RoleLocalServiceUtil.hasUserRole(
747 userId, companyId, entityValue, true)) {
748
749 return true;
750 }
751 }
752 else if (entityType.equals("user-group")) {
753 UserGroup userGroup = UserGroupLocalServiceUtil.getUserGroup(
754 companyId, entityValue);
755
756 if (UserLocalServiceUtil.hasUserGroupUser(
757 userGroup.getUserGroupId(), userId)) {
758
759 return true;
760 }
761 }
762
763 return false;
764 }
765
766 private static Log _log = LogFactoryUtil.getLog(MBUtil.class);
767
768 }