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