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