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 prefs) {
285 String emailFromAddress = PropsValues.MESSAGE_BOARDS_EMAIL_FROM_ADDRESS;
286
287 return prefs.getValue("email-from-address", emailFromAddress);
288 }
289
290 public static String getEmailFromName(PortletPreferences prefs) {
291 String emailFromName = PropsValues.MESSAGE_BOARDS_EMAIL_FROM_NAME;
292
293 return prefs.getValue("email-from-name", emailFromName);
294 }
295
296 public static boolean getEmailHtmlFormat(PortletPreferences prefs) {
297 String emailHtmlFormat = prefs.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 prefs) {
310
311 String emailMessageAddedEnabled = prefs.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(PortletPreferences prefs) {
323 String emailMessageAddedBody = prefs.getValue(
324 "email-message-added-body", StringPool.BLANK);
325
326 if (Validator.isNotNull(emailMessageAddedBody)) {
327 return emailMessageAddedBody;
328 }
329 else {
330 return ContentUtil.get(
331 PropsValues.MESSAGE_BOARDS_EMAIL_MESSAGE_ADDED_BODY);
332 }
333 }
334
335 public static String getEmailMessageAddedSignature(
336 PortletPreferences prefs) {
337
338 String emailMessageAddedSignature = prefs.getValue(
339 "email-message-added-signature", StringPool.BLANK);
340
341 if (Validator.isNotNull(emailMessageAddedSignature)) {
342 return emailMessageAddedSignature;
343 }
344 else {
345 return ContentUtil.get(
346 PropsValues.MESSAGE_BOARDS_EMAIL_MESSAGE_ADDED_SIGNATURE);
347 }
348 }
349
350 public static String getEmailMessageAddedSubjectPrefix(
351 PortletPreferences prefs) {
352
353 String emailMessageAddedSubjectPrefix = prefs.getValue(
354 "email-message-added-subject-prefix", StringPool.BLANK);
355
356 if (Validator.isNotNull(emailMessageAddedSubjectPrefix)) {
357 return emailMessageAddedSubjectPrefix;
358 }
359 else {
360 return ContentUtil.get(
361 PropsValues.MESSAGE_BOARDS_EMAIL_MESSAGE_ADDED_SUBJECT_PREFIX);
362 }
363 }
364
365 public static boolean getEmailMessageUpdatedEnabled(
366 PortletPreferences prefs) {
367
368 String emailMessageUpdatedEnabled = prefs.getValue(
369 "email-message-updated-enabled", StringPool.BLANK);
370
371 if (Validator.isNotNull(emailMessageUpdatedEnabled)) {
372 return GetterUtil.getBoolean(emailMessageUpdatedEnabled);
373 }
374 else {
375 return PropsValues.MESSAGE_BOARDS_EMAIL_MESSAGE_UPDATED_ENABLED;
376 }
377 }
378
379 public static String getEmailMessageUpdatedBody(PortletPreferences prefs) {
380 String emailMessageUpdatedBody = prefs.getValue(
381 "email-message-updated-body", StringPool.BLANK);
382
383 if (Validator.isNotNull(emailMessageUpdatedBody)) {
384 return emailMessageUpdatedBody;
385 }
386 else {
387 return ContentUtil.get(
388 PropsValues.MESSAGE_BOARDS_EMAIL_MESSAGE_UPDATED_BODY);
389 }
390 }
391
392 public static String getEmailMessageUpdatedSignature(
393 PortletPreferences prefs) {
394
395 String emailMessageUpdatedSignature = prefs.getValue(
396 "email-message-updated-signature", StringPool.BLANK);
397
398 if (Validator.isNotNull(emailMessageUpdatedSignature)) {
399 return emailMessageUpdatedSignature;
400 }
401 else {
402 return ContentUtil.get(
403 PropsValues.MESSAGE_BOARDS_EMAIL_MESSAGE_UPDATED_SIGNATURE);
404 }
405 }
406
407 public static String getEmailMessageUpdatedSubjectPrefix(
408 PortletPreferences prefs) {
409
410 String emailMessageUpdatedSubject = prefs.getValue(
411 "email-message-updated-subject-prefix", StringPool.BLANK);
412
413 if (Validator.isNotNull(emailMessageUpdatedSubject)) {
414 return emailMessageUpdatedSubject;
415 }
416 else {
417 return ContentUtil.get(
418 PropsValues.
419 MESSAGE_BOARDS_EMAIL_MESSAGE_UPDATED_SUBJECT_PREFIX);
420 }
421 }
422
423 public static String getMailId(String mx, long categoryId, long messageId) {
424 StringBuilder sb = new StringBuilder();
425
426 sb.append(StringPool.LESS_THAN);
427 sb.append(POP_PORTLET_PREFIX);
428 sb.append(categoryId);
429 sb.append(StringPool.PERIOD);
430 sb.append(messageId);
431 sb.append(StringPool.AT);
432 sb.append(PropsValues.POP_SERVER_SUBDOMAIN);
433 sb.append(StringPool.PERIOD);
434 sb.append(mx);
435 sb.append(StringPool.GREATER_THAN);
436
437 return sb.toString();
438 }
439
440 public static String getMailingListAddress(
441 long categoryId, long messageId, String mx,
442 String defaultMailingListAddress) {
443
444 if (POP_SERVER_SUBDOMAIN_LENGTH <= 0) {
445 return defaultMailingListAddress;
446 }
447
448 StringBuilder sb = new StringBuilder();
449
450 sb.append(POP_PORTLET_PREFIX);
451 sb.append(categoryId);
452 sb.append(StringPool.PERIOD);
453 sb.append(messageId);
454 sb.append(StringPool.AT);
455 sb.append(PropsValues.POP_SERVER_SUBDOMAIN);
456 sb.append(StringPool.PERIOD);
457 sb.append(mx);
458
459 return sb.toString();
460 }
461
462 public static long getMessageId(String mailId) {
463 int x = mailId.indexOf(StringPool.LESS_THAN) + 1;
464 int y = mailId.indexOf(StringPool.AT);
465
466 long messageId = 0;
467
468 if ((x > 0 ) && (y != -1)) {
469 String temp = mailId.substring(x, y);
470
471 int z = temp.lastIndexOf(StringPool.PERIOD);
472
473 if (z != -1) {
474 messageId = GetterUtil.getLong(temp.substring(z + 1));
475 }
476 }
477
478 return messageId;
479 }
480
481 public static long getParentMessageId(Message message) throws Exception {
482 long parentMessageId = -1;
483
484 String parentHeader = getParentMessageIdString(message);
485
486 if (parentHeader != null) {
487 if (_log.isDebugEnabled()) {
488 _log.debug("Parent header " + parentHeader);
489 }
490
491 parentMessageId = getMessageId(parentHeader);
492
493 if (_log.isDebugEnabled()) {
494 _log.debug("Previous message id " + parentMessageId);
495 }
496 }
497
498 return parentMessageId;
499 }
500
501 public static String getParentMessageIdString(Message message)
502 throws Exception {
503
504
509 String parentHeader = null;
510
511 String[] references = message.getHeader("References");
512
513 if ((references != null) && (references.length > 0)) {
514 parentHeader = references[0].substring(
515 references[0].lastIndexOf("<"));
516 }
517
518 if (parentHeader == null) {
519 String[] inReplyToHeaders = message.getHeader("In-Reply-To");
520
521 if ((inReplyToHeaders != null) && (inReplyToHeaders.length > 0)) {
522 parentHeader = inReplyToHeaders[0];
523 }
524 }
525
526 if (parentHeader == null) {
527 parentHeader = _getParentMessageIdFromSubject(message);
528 }
529
530 return parentHeader;
531 }
532
533 public static String getSubjectWithoutMessageId(Message message)
534 throws Exception {
535
536 String subject = message.getSubject();
537
538 String parentMessageId = _getParentMessageIdFromSubject(message);
539
540 if (Validator.isNotNull(parentMessageId)) {
541 int pos = subject.indexOf(parentMessageId);
542
543 if (pos != -1) {
544 subject = subject.substring(0, pos);
545 }
546 }
547
548 return subject;
549 }
550
551 public static String[] getThreadPriority(
552 PortletPreferences prefs, String languageId, double value,
553 ThemeDisplay themeDisplay)
554 throws Exception {
555
556 String[] priorities = LocalizationUtil.getPreferencesValues(
557 prefs, "priorities", languageId);
558
559 String[] priorityPair = _findThreadPriority(
560 value, themeDisplay, priorities);
561
562 if (priorityPair == null) {
563 String defaultLanguageId = LocaleUtil.toLanguageId(
564 LocaleUtil.getDefault());
565
566 priorities = LocalizationUtil.getPreferencesValues(
567 prefs, "priorities", defaultLanguageId);
568
569 priorityPair = _findThreadPriority(value, themeDisplay, priorities);
570 }
571
572 return priorityPair;
573 }
574
575 public static Date getUnbanDate(MBBan ban, int expireInterval) {
576 Date banDate = ban.getCreateDate();
577
578 Calendar cal = Calendar.getInstance();
579
580 cal.setTime(banDate);
581
582 cal.add(Calendar.DATE, expireInterval);
583
584 return cal.getTime();
585 }
586
587 public static String getUserRank(
588 PortletPreferences prefs, String languageId, int posts)
589 throws Exception {
590
591 String rank = StringPool.BLANK;
592
593 String[] ranks = LocalizationUtil.getPreferencesValues(
594 prefs, "ranks", languageId);
595
596 for (int i = 0; i < ranks.length; i++) {
597 String[] kvp = StringUtil.split(ranks[i], StringPool.EQUAL);
598
599 String kvpName = kvp[0];
600 int kvpPosts = GetterUtil.getInteger(kvp[1]);
601
602 if (posts >= kvpPosts) {
603 rank = kvpName;
604 }
605 else {
606 break;
607 }
608 }
609
610 return rank;
611 }
612
613 public static String[] getUserRank(
614 PortletPreferences prefs, String languageId, MBStatsUser statsUser)
615 throws Exception {
616
617 String[] rank = {StringPool.BLANK, StringPool.BLANK};
618
619 int maxPosts = 0;
620
621 Group group = GroupLocalServiceUtil.getGroup(
622 statsUser.getGroupId());
623
624 long companyId = group.getCompanyId();
625
626 String[] ranks = LocalizationUtil.getPreferencesValues(
627 prefs, "ranks", languageId);
628
629 for (int i = 0; i < ranks.length; i++) {
630 String[] kvp = StringUtil.split(ranks[i], StringPool.EQUAL);
631
632 String curRank = kvp[0];
633 String curRankValue = kvp[1];
634
635 String[] curRankValueKvp = StringUtil.split(
636 curRankValue, StringPool.COLON);
637
638 if (curRankValueKvp.length <= 1) {
639 int posts = GetterUtil.getInteger(curRankValue);
640
641 if ((posts <= statsUser.getMessageCount()) &&
642 (posts >= maxPosts)) {
643
644 rank[0] = curRank;
645 maxPosts = posts;
646 }
647
648 }
649 else {
650 String entityType = curRankValueKvp[0];
651 String entityValue = curRankValueKvp[1];
652
653 try {
654 if (_isEntityRank(
655 companyId, statsUser, entityType, entityValue)) {
656
657 rank[1] = curRank;
658
659 break;
660 }
661 }
662 catch (Exception e) {
663 if (_log.isWarnEnabled()) {
664 _log.warn(e);
665 }
666 }
667 }
668 }
669
670 return rank;
671 }
672
673 public static boolean hasMailIdHeader(Message message) throws Exception {
674 String[] messageIds = message.getHeader("Message-ID");
675
676 if (messageIds == null) {
677 return false;
678 }
679
680 for (String messageId : messageIds) {
681 if (messageId.contains(PropsValues.POP_SERVER_SUBDOMAIN)) {
682 return true;
683 }
684 }
685
686 return false;
687 }
688
689 public static boolean isAllowAnonymousPosting(PortletPreferences prefs) {
690 String allowAnonymousPosting = prefs.getValue(
691 "allow-anonymous-posting", StringPool.BLANK);
692
693 if (Validator.isNotNull(allowAnonymousPosting)) {
694 return GetterUtil.getBoolean(allowAnonymousPosting);
695 }
696 else {
697 return PropsValues.MESSAGE_BOARDS_ANONYMOUS_POSTING_ENABLED;
698 }
699 }
700
701 private static String[] _findThreadPriority(
702 double value, ThemeDisplay themeDisplay, String[] priorities) {
703
704 for (int i = 0; i < priorities.length; i++) {
705 String[] priority = StringUtil.split(priorities[i]);
706
707 try {
708 String priorityName = priority[0];
709 String priorityImage = priority[1];
710 double priorityValue = GetterUtil.getDouble(priority[2]);
711
712 if (value == priorityValue) {
713 if (!priorityImage.startsWith(Http.HTTP)) {
714 priorityImage =
715 themeDisplay.getPathThemeImages() + priorityImage;
716 }
717
718 return new String[] {priorityName, priorityImage};
719 }
720 }
721 catch (Exception e) {
722 _log.error("Unable to determine thread priority", e);
723 }
724 }
725
726 return null;
727 }
728
729 private static String _getParentMessageIdFromSubject(Message message)
730 throws Exception {
731
732 String parentMessageId = null;
733
734 String subject = StringUtil.reverse(message.getSubject());
735
736 int pos = subject.indexOf(StringPool.LESS_THAN);
737
738 if (pos != -1) {
739 parentMessageId = StringUtil.reverse(subject.substring(0, pos + 1));
740 }
741
742 return parentMessageId;
743 }
744
745 private static boolean _isEntityRank(
746 long companyId, MBStatsUser statsUser, String entityType,
747 String entityValue)
748 throws Exception {
749
750 long groupId = statsUser.getGroupId();
751 long userId = statsUser.getUserId();
752
753 if (entityType.equals("community-role") ||
754 entityType.equals("organization-role")) {
755
756 Role role = RoleLocalServiceUtil.getRole(companyId, entityValue);
757
758 if (UserGroupRoleLocalServiceUtil.hasUserGroupRole(
759 userId, groupId, role.getRoleId())) {
760
761 return true;
762 }
763 }
764 else if (entityType.equals("organization")) {
765 Organization organization =
766 OrganizationLocalServiceUtil.getOrganization(
767 companyId, entityValue);
768
769 if (OrganizationLocalServiceUtil.hasUserOrganization(
770 userId, organization.getOrganizationId())) {
771
772 return true;
773 }
774 }
775 else if (entityType.equals("regular-role")) {
776 if (RoleLocalServiceUtil.hasUserRole(
777 userId, companyId, entityValue, true)) {
778
779 return true;
780 }
781 }
782 else if (entityType.equals("user-group")) {
783 UserGroup userGroup = UserGroupLocalServiceUtil.getUserGroup(
784 companyId, entityValue);
785
786 if (UserLocalServiceUtil.hasUserGroupUser(
787 userGroup.getUserGroupId(), userId)) {
788
789 return true;
790 }
791 }
792
793 return false;
794 }
795
796 private static Log _log = LogFactoryUtil.getLog(MBUtil.class);
797
798 }