1
22
23 package com.liferay.portlet.messageboards.util;
24
25 import com.liferay.portal.kernel.language.LanguageUtil;
26 import com.liferay.portal.kernel.portlet.LiferayWindowState;
27 import com.liferay.portal.kernel.util.GetterUtil;
28 import com.liferay.portal.kernel.util.Http;
29 import com.liferay.portal.kernel.util.LocaleUtil;
30 import com.liferay.portal.kernel.util.ParamUtil;
31 import com.liferay.portal.kernel.util.StringPool;
32 import com.liferay.portal.kernel.util.StringUtil;
33 import com.liferay.portal.kernel.util.Validator;
34 import com.liferay.portal.model.Group;
35 import com.liferay.portal.model.Organization;
36 import com.liferay.portal.model.Role;
37 import com.liferay.portal.model.UserGroup;
38 import com.liferay.portal.service.GroupLocalServiceUtil;
39 import com.liferay.portal.service.OrganizationLocalServiceUtil;
40 import com.liferay.portal.service.RoleLocalServiceUtil;
41 import com.liferay.portal.service.UserGroupLocalServiceUtil;
42 import com.liferay.portal.service.UserGroupRoleLocalServiceUtil;
43 import com.liferay.portal.service.UserLocalServiceUtil;
44 import com.liferay.portal.theme.ThemeDisplay;
45 import com.liferay.portal.util.ContentUtil;
46 import com.liferay.portal.util.PropsValues;
47 import com.liferay.portlet.messageboards.model.MBBan;
48 import com.liferay.portlet.messageboards.model.MBCategory;
49 import com.liferay.portlet.messageboards.model.MBMessage;
50 import com.liferay.portlet.messageboards.model.MBStatsUser;
51 import com.liferay.portlet.messageboards.model.impl.MBCategoryImpl;
52 import com.liferay.portlet.messageboards.service.MBCategoryLocalServiceUtil;
53 import com.liferay.portlet.messageboards.service.MBMessageLocalServiceUtil;
54 import com.liferay.util.LocalizationUtil;
55 import com.liferay.util.mail.JavaMailUtil;
56
57 import java.io.InputStream;
58
59 import java.util.Calendar;
60 import java.util.Date;
61
62 import javax.mail.BodyPart;
63 import javax.mail.Message;
64 import javax.mail.Part;
65 import javax.mail.internet.MimeMessage;
66 import javax.mail.internet.MimeMultipart;
67
68 import javax.portlet.PortletPreferences;
69 import javax.portlet.PortletURL;
70 import javax.portlet.RenderRequest;
71 import javax.portlet.RenderResponse;
72
73 import javax.servlet.jsp.PageContext;
74
75 import org.apache.commons.logging.Log;
76 import org.apache.commons.logging.LogFactory;
77
78
84 public class MBUtil {
85
86 public static final String POP_PORTLET_PREFIX = "mb.";
87
88 public static final int POP_SERVER_SUBDOMAIN_LENGTH =
89 PropsValues.POP_SERVER_SUBDOMAIN.length();
90
91 public static void collectMultipartContent(
92 MimeMultipart multipart, MBMailMessage collector)
93 throws Exception {
94
95 for (int i = 0; i < multipart.getCount(); i++) {
96 BodyPart part = multipart.getBodyPart(i);
97
98 collectPartContent(part, collector);
99 }
100 }
101
102 public static void collectPartContent(Part part, MBMailMessage collector)
103 throws Exception {
104
105 Object partContent = part.getContent();
106
107 String contentType = part.getContentType().toLowerCase();
108
109 if ((part.getDisposition() != null) &&
110 (part.getDisposition().equalsIgnoreCase(MimeMessage.ATTACHMENT))) {
111
112 if (_log.isDebugEnabled()) {
113 _log.debug("Processing attachment");
114 }
115
116 byte[] bytes = null;
117
118 if (partContent instanceof String) {
119 bytes = ((String)partContent).getBytes();
120 }
121 else if (partContent instanceof InputStream) {
122 bytes = JavaMailUtil.getBytes(part);
123 }
124
125 collector.addFile(part.getFileName(), bytes);
126 }
127 else {
128 if (partContent instanceof MimeMultipart) {
129 collectMultipartContent((MimeMultipart)partContent, collector);
130 }
131 else if (partContent instanceof String) {
132 if (contentType.startsWith("text/html")) {
133 collector.setHtmlBody((String)partContent);
134 }
135 else {
136 collector.setPlainBody((String)partContent);
137 }
138 }
139 }
140 }
141
142 public static String getBreadcrumbs(
143 long categoryId, long messageId, PageContext pageContext,
144 RenderRequest renderRequest, RenderResponse renderResponse)
145 throws Exception {
146
147 if (messageId > 0) {
148 MBMessage message = MBMessageLocalServiceUtil.getMessage(messageId);
149
150 return getBreadcrumbs(
151 null, message, pageContext, renderRequest, renderResponse);
152 }
153 else {
154 MBCategory category = null;
155
156 try {
157 if ((categoryId > 0) &&
158 (categoryId != MBCategoryImpl.DEFAULT_PARENT_CATEGORY_ID)) {
159
160 category = MBCategoryLocalServiceUtil.getCategory(
161 categoryId);
162 }
163 }
164 catch (Exception e) {
165 _log.error("Unable to retrieve category " + categoryId, e);
166 }
167
168 return getBreadcrumbs(
169 category, null, pageContext, renderRequest, renderResponse);
170 }
171 }
172
173 public static String getBreadcrumbs(
174 MBCategory category, MBMessage message, PageContext pageContext,
175 RenderRequest renderRequest, RenderResponse renderResponse)
176 throws Exception {
177
178 String strutsAction = ParamUtil.getString(
179 renderRequest, "struts_action");
180
181 boolean selectCategory = strutsAction.equals(
182 "/message_boards/select_category");
183
184 if ((message != null) && (category == null)) {
185 category = message.getCategory();
186 }
187
188 PortletURL categoriesURL = renderResponse.createRenderURL();
189
190 if (selectCategory) {
191 categoriesURL.setWindowState(LiferayWindowState.POP_UP);
192
193 categoriesURL.setParameter(
194 "struts_action", "/message_boards/select_category");
195 }
196 else {
197
199 categoriesURL.setParameter("struts_action", "/message_boards/view");
200 categoriesURL.setParameter(
201 "categoryId",
202 String.valueOf(MBCategoryImpl.DEFAULT_PARENT_CATEGORY_ID));
203 }
204
205 String categoriesLink =
206 "<a href=\"" + categoriesURL.toString() + "\">" +
207 LanguageUtil.get(pageContext, "categories") + "</a>";
208
209 if (category == null) {
210 return "<span class=\"first last\">" + categoriesLink + "</span>";
211 }
212
213 String breadcrumbs = StringPool.BLANK;
214
215 for (int i = 0;; i++) {
216 category = category.toEscapedModel();
217
218 PortletURL portletURL = renderResponse.createRenderURL();
219
220 if (selectCategory) {
221 portletURL.setWindowState(LiferayWindowState.POP_UP);
222
223 portletURL.setParameter(
224 "struts_action", "/message_boards/select_category");
225 portletURL.setParameter(
226 "categoryId", String.valueOf(category.getCategoryId()));
227 }
228 else {
229
231 portletURL.setParameter(
232 "struts_action", "/message_boards/view");
233 portletURL.setParameter(
234 "categoryId", String.valueOf(category.getCategoryId()));
235 }
236
237 String categoryLink =
238 "<a href=\"" + portletURL.toString() + "\">" +
239 category.getName() + "</a>";
240
241 if (i == 0) {
242 if (message != null) {
243 breadcrumbs += categoryLink;
244 }
245 else {
246 breadcrumbs =
247 "<span class=\"last\">" + categoryLink + "</span>";
248 }
249 }
250 else {
251 breadcrumbs = categoryLink + " » " + breadcrumbs;
252 }
253
254 if (category.isRoot()) {
255 break;
256 }
257
258 category = MBCategoryLocalServiceUtil.getCategory(
259 category.getParentCategoryId());
260 }
261
262 breadcrumbs =
263 "<span class=\"first\">" + categoriesLink + " » </span>" +
264 breadcrumbs;
265
266 if (message != null) {
267 message = message.toEscapedModel();
268
269 PortletURL messageURL = renderResponse.createRenderURL();
270
271
273 messageURL.setParameter(
274 "struts_action", "/message_boards/view_message");
275 messageURL.setParameter(
276 "messageId", String.valueOf(message.getMessageId()));
277
278 String messageLink =
279 "<span class=\"last\"><a href=\"" + messageURL.toString() +
280 "\">" + message.getSubject() + "</a></span>";
281
282 breadcrumbs = breadcrumbs + " » " + messageLink;
283 }
284
285 return breadcrumbs;
286 }
287
288 public static String getEmailFromAddress(PortletPreferences prefs) {
289 String emailFromAddress = PropsValues.MESSAGE_BOARDS_EMAIL_FROM_ADDRESS;
290
291 return prefs.getValue("email-from-address", emailFromAddress);
292 }
293
294 public static String getEmailFromName(PortletPreferences prefs) {
295 String emailFromName = PropsValues.MESSAGE_BOARDS_EMAIL_FROM_NAME;
296
297 return prefs.getValue("email-from-name", emailFromName);
298 }
299
300 public static boolean getEmailHtmlFormat(PortletPreferences prefs) {
301 String emailHtmlFormat = prefs.getValue(
302 "email-html-format", StringPool.BLANK);
303
304 if (Validator.isNotNull(emailHtmlFormat)) {
305 return GetterUtil.getBoolean(emailHtmlFormat);
306 }
307 else {
308 return PropsValues.MESSAGE_BOARDS_EMAIL_HTML_FORMAT;
309 }
310 }
311
312 public static boolean getEmailMessageAddedEnabled(
313 PortletPreferences prefs) {
314
315 String emailMessageAddedEnabled = prefs.getValue(
316 "email-message-added-enabled", StringPool.BLANK);
317
318 if (Validator.isNotNull(emailMessageAddedEnabled)) {
319 return GetterUtil.getBoolean(emailMessageAddedEnabled);
320 }
321 else {
322 return PropsValues.MESSAGE_BOARDS_EMAIL_MESSAGE_ADDED_ENABLED;
323 }
324 }
325
326 public static String getEmailMessageAddedBody(PortletPreferences prefs) {
327 String emailMessageAddedBody = prefs.getValue(
328 "email-message-added-body", StringPool.BLANK);
329
330 if (Validator.isNotNull(emailMessageAddedBody)) {
331 return emailMessageAddedBody;
332 }
333 else {
334 return ContentUtil.get(
335 PropsValues.MESSAGE_BOARDS_EMAIL_MESSAGE_ADDED_BODY);
336 }
337 }
338
339 public static String getEmailMessageAddedSignature(
340 PortletPreferences prefs) {
341
342 String emailMessageAddedSignature = prefs.getValue(
343 "email-message-added-signature", StringPool.BLANK);
344
345 if (Validator.isNotNull(emailMessageAddedSignature)) {
346 return emailMessageAddedSignature;
347 }
348 else {
349 return ContentUtil.get(
350 PropsValues.MESSAGE_BOARDS_EMAIL_MESSAGE_ADDED_SIGNATURE);
351 }
352 }
353
354 public static String getEmailMessageAddedSubjectPrefix(
355 PortletPreferences prefs) {
356
357 String emailMessageAddedSubjectPrefix = prefs.getValue(
358 "email-message-added-subject-prefix", StringPool.BLANK);
359
360 if (Validator.isNotNull(emailMessageAddedSubjectPrefix)) {
361 return emailMessageAddedSubjectPrefix;
362 }
363 else {
364 return ContentUtil.get(
365 PropsValues.MESSAGE_BOARDS_EMAIL_MESSAGE_ADDED_SUBJECT_PREFIX);
366 }
367 }
368
369 public static boolean getEmailMessageUpdatedEnabled(
370 PortletPreferences prefs) {
371
372 String emailMessageUpdatedEnabled = prefs.getValue(
373 "email-message-updated-enabled", StringPool.BLANK);
374
375 if (Validator.isNotNull(emailMessageUpdatedEnabled)) {
376 return GetterUtil.getBoolean(emailMessageUpdatedEnabled);
377 }
378 else {
379 return PropsValues.MESSAGE_BOARDS_EMAIL_MESSAGE_UPDATED_ENABLED;
380 }
381 }
382
383 public static String getEmailMessageUpdatedBody(PortletPreferences prefs) {
384 String emailMessageUpdatedBody = prefs.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 prefs) {
398
399 String emailMessageUpdatedSignature = prefs.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 prefs) {
413
414 String emailMessageUpdatedSubject = prefs.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 prefs, String languageId, double value,
557 ThemeDisplay themeDisplay)
558 throws Exception {
559
560 String[] priorities = LocalizationUtil.getPreferencesValues(
561 prefs, "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 prefs, "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 prefs, String languageId, int posts)
593 throws Exception {
594
595 String rank = StringPool.BLANK;
596
597 String[] ranks = LocalizationUtil.getPreferencesValues(
598 prefs, "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 prefs, String languageId, MBStatsUser statsUser)
619 throws Exception {
620
621 String rank = StringPool.BLANK;
622
623 int maxPosts = 0;
624
625 Group group = GroupLocalServiceUtil.getGroup(
626 statsUser.getGroupId());
627
628 long companyId = group.getCompanyId();
629
630 String[] ranks = LocalizationUtil.getPreferencesValues(
631 prefs, "ranks", languageId);
632
633 for (int i = 0; i < ranks.length; i++) {
634 String[] kvp = StringUtil.split(ranks[i], StringPool.EQUAL);
635
636 String curRank = kvp[0];
637 String curRankValue = kvp[1];
638
639 String[] curRankValueKvp = StringUtil.split(
640 curRankValue, StringPool.COLON);
641
642 if (curRankValueKvp.length <= 1) {
643 int posts = GetterUtil.getInteger(curRankValue);
644
645 if ((posts <= statsUser.getMessageCount()) &&
646 (posts > maxPosts)) {
647
648 rank = curRank;
649 maxPosts = posts;
650 }
651
652 continue;
653 }
654
655 String entityType = curRankValueKvp[0];
656 String entityValue = curRankValueKvp[1];
657
658 try {
659 if (_isEntityRank(
660 companyId, statsUser, entityType, entityValue)) {
661
662 return curRank;
663 }
664 }
665 catch (Exception e) {
666 if (_log.isWarnEnabled()) {
667 _log.warn(e);
668 }
669 }
670 }
671
672 return rank;
673 }
674
675 public static boolean hasMailIdHeader(Message message) throws Exception {
676 String[] messageIds = message.getHeader("Message-ID");
677
678 if (messageIds == null) {
679 return false;
680 }
681
682 for (String messageId : messageIds) {
683 if (messageId.contains(PropsValues.POP_SERVER_SUBDOMAIN)) {
684 return true;
685 }
686 }
687
688 return false;
689 }
690
691 public static boolean isAllowAnonymousPosting(PortletPreferences prefs) {
692 String allowAnonymousPosting = prefs.getValue(
693 "allow-anonymous-posting", StringPool.BLANK);
694
695 if (Validator.isNotNull(allowAnonymousPosting)) {
696 return GetterUtil.getBoolean(allowAnonymousPosting);
697 }
698 else {
699 return PropsValues.MESSAGE_BOARDS_ANONYMOUS_POSTING_ENABLED;
700 }
701 }
702
703 private static String[] _findThreadPriority(
704 double value, ThemeDisplay themeDisplay, String[] priorities) {
705
706 for (int i = 0; i < priorities.length; i++) {
707 String[] priority = StringUtil.split(priorities[i]);
708
709 try {
710 String priorityName = priority[0];
711 String priorityImage = priority[1];
712 double priorityValue = GetterUtil.getDouble(priority[2]);
713
714 if (value == priorityValue) {
715 if (!priorityImage.startsWith(Http.HTTP)) {
716 priorityImage =
717 themeDisplay.getPathThemeImages() + priorityImage;
718 }
719
720 return new String[] {priorityName, priorityImage};
721 }
722 }
723 catch (Exception e) {
724 _log.error("Unable to determine thread priority", e);
725 }
726 }
727
728 return null;
729 }
730
731 private static String _getParentMessageIdFromSubject(Message message)
732 throws Exception {
733
734 String parentMessageId = null;
735
736 String subject = StringUtil.reverse(message.getSubject());
737
738 int pos = subject.indexOf(StringPool.LESS_THAN);
739
740 if (pos != -1) {
741 parentMessageId = StringUtil.reverse(subject.substring(0, pos + 1));
742 }
743
744 return parentMessageId;
745 }
746
747 private static boolean _isEntityRank(
748 long companyId, MBStatsUser statsUser, String entityType,
749 String entityValue)
750 throws Exception {
751
752 long groupId = statsUser.getGroupId();
753 long userId = statsUser.getUserId();
754
755 if (entityType.equals("community-role") ||
756 entityType.equals("organization-role")) {
757
758 Role role = RoleLocalServiceUtil.getRole(companyId, entityValue);
759
760 if (UserGroupRoleLocalServiceUtil.hasUserGroupRole(
761 userId, groupId, role.getRoleId())) {
762
763 return true;
764 }
765 }
766 else if (entityType.equals("organization")) {
767 Organization organization =
768 OrganizationLocalServiceUtil.getOrganization(
769 companyId, entityValue);
770
771 if (OrganizationLocalServiceUtil.hasUserOrganization(
772 userId, organization.getOrganizationId())) {
773
774 return true;
775 }
776 }
777 else if (entityType.equals("regular-role")) {
778 if (RoleLocalServiceUtil.hasUserRole(
779 userId, companyId, entityValue, true)) {
780
781 return true;
782 }
783 }
784 else if (entityType.equals("user-group")) {
785 UserGroup userGroup = UserGroupLocalServiceUtil.getUserGroup(
786 companyId, entityValue);
787
788 if (UserLocalServiceUtil.hasUserGroupUser(
789 userGroup.getUserGroupId(), userId)) {
790
791 return true;
792 }
793 }
794
795 return false;
796 }
797
798 private static Log _log = LogFactory.getLog(MBUtil.class);
799
800 }