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
82 public class MBUtil {
83
84 public static final String POP_PORTLET_PREFIX = "mb.";
85
86 public static final int POP_SERVER_SUBDOMAIN_LENGTH =
87 PropsValues.POP_SERVER_SUBDOMAIN.length();
88
89 public static void collectMultipartContent(
90 MimeMultipart multipart, MBMailMessage collector)
91 throws Exception {
92
93 for (int i = 0; i < multipart.getCount(); i++) {
94 BodyPart part = multipart.getBodyPart(i);
95
96 collectPartContent(part, collector);
97 }
98 }
99
100 public static void collectPartContent(Part part, MBMailMessage collector)
101 throws Exception {
102
103 Object partContent = part.getContent();
104
105 String contentType = part.getContentType().toLowerCase();
106
107 if ((part.getDisposition() != null) &&
108 (part.getDisposition().equalsIgnoreCase(MimeMessage.ATTACHMENT))) {
109
110 if (_log.isDebugEnabled()) {
111 _log.debug("Processing attachment");
112 }
113
114 byte[] bytes = null;
115
116 if (partContent instanceof String) {
117 bytes = ((String)partContent).getBytes();
118 }
119 else if (partContent instanceof InputStream) {
120 bytes = JavaMailUtil.getBytes(part);
121 }
122
123 collector.addFile(part.getFileName(), bytes);
124 }
125 else {
126 if (partContent instanceof MimeMultipart) {
127 collectMultipartContent((MimeMultipart)partContent, collector);
128 }
129 else if (partContent instanceof String) {
130 if (contentType.startsWith("text/html")) {
131 collector.setHtmlBody((String)partContent);
132 }
133 else {
134 collector.setPlainBody((String)partContent);
135 }
136 }
137 }
138 }
139
140 public static String getBreadcrumbs(
141 long categoryId, long messageId, PageContext pageContext,
142 RenderRequest renderRequest, RenderResponse renderResponse)
143 throws Exception {
144
145 if (messageId > 0) {
146 MBMessage message = MBMessageLocalServiceUtil.getMessage(messageId);
147
148 return getBreadcrumbs(
149 null, message, pageContext, renderRequest, renderResponse);
150 }
151 else {
152 MBCategory category = null;
153
154 try {
155 if ((categoryId > 0) &&
156 (categoryId != MBCategoryImpl.DEFAULT_PARENT_CATEGORY_ID)) {
157
158 category = MBCategoryLocalServiceUtil.getCategory(
159 categoryId);
160 }
161 }
162 catch (Exception e) {
163 _log.error("Unable to retrieve category " + categoryId, e);
164 }
165
166 return getBreadcrumbs(
167 category, null, pageContext, renderRequest, renderResponse);
168 }
169 }
170
171 public static String getBreadcrumbs(
172 MBCategory category, MBMessage message, PageContext pageContext,
173 RenderRequest renderRequest, RenderResponse renderResponse)
174 throws Exception {
175
176 String strutsAction = ParamUtil.getString(
177 renderRequest, "struts_action");
178
179 boolean selectCategory = strutsAction.equals(
180 "/message_boards/select_category");
181
182 if ((message != null) && (category == null)) {
183 category = message.getCategory();
184 }
185
186 PortletURL categoriesURL = renderResponse.createRenderURL();
187
188 if (selectCategory) {
189 categoriesURL.setWindowState(LiferayWindowState.POP_UP);
190
191 categoriesURL.setParameter(
192 "struts_action", "/message_boards/select_category");
193 }
194 else {
195
197 categoriesURL.setParameter("struts_action", "/message_boards/view");
198 categoriesURL.setParameter(
199 "categoryId",
200 String.valueOf(MBCategoryImpl.DEFAULT_PARENT_CATEGORY_ID));
201 }
202
203 String categoriesLink =
204 "<a href=\"" + categoriesURL.toString() + "\">" +
205 LanguageUtil.get(pageContext, "categories") + "</a>";
206
207 if (category == null) {
208 return "<span class=\"first last\">" + categoriesLink + "</span>";
209 }
210
211 String breadcrumbs = StringPool.BLANK;
212
213 for (int i = 0;; i++) {
214 category = category.toEscapedModel();
215
216 PortletURL portletURL = renderResponse.createRenderURL();
217
218 if (selectCategory) {
219 portletURL.setWindowState(LiferayWindowState.POP_UP);
220
221 portletURL.setParameter(
222 "struts_action", "/message_boards/select_category");
223 portletURL.setParameter(
224 "categoryId", String.valueOf(category.getCategoryId()));
225 }
226 else {
227
229 portletURL.setParameter(
230 "struts_action", "/message_boards/view");
231 portletURL.setParameter(
232 "categoryId", String.valueOf(category.getCategoryId()));
233 }
234
235 String categoryLink =
236 "<a href=\"" + portletURL.toString() + "\">" +
237 category.getName() + "</a>";
238
239 if (i == 0) {
240 if (message != null) {
241 breadcrumbs += categoryLink;
242 }
243 else {
244 breadcrumbs =
245 "<span class=\"last\">" + categoryLink + "</span>";
246 }
247 }
248 else {
249 breadcrumbs = categoryLink + " » " + breadcrumbs;
250 }
251
252 if (category.isRoot()) {
253 break;
254 }
255
256 category = MBCategoryLocalServiceUtil.getCategory(
257 category.getParentCategoryId());
258 }
259
260 breadcrumbs =
261 "<span class=\"first\">" + categoriesLink + " » </span>" +
262 breadcrumbs;
263
264 if (message != null) {
265 message = message.toEscapedModel();
266
267 PortletURL messageURL = renderResponse.createRenderURL();
268
269
271 messageURL.setParameter(
272 "struts_action", "/message_boards/view_message");
273 messageURL.setParameter(
274 "messageId", String.valueOf(message.getMessageId()));
275
276 String messageLink =
277 "<span class=\"last\"><a href=\"" + messageURL.toString() +
278 "\">" + message.getSubject() + "</a></span>";
279
280 breadcrumbs = breadcrumbs + " » " + messageLink;
281 }
282
283 return breadcrumbs;
284 }
285
286 public static String getEmailFromAddress(PortletPreferences prefs) {
287 String emailFromAddress = PropsValues.MESSAGE_BOARDS_EMAIL_FROM_ADDRESS;
288
289 return prefs.getValue("email-from-address", emailFromAddress);
290 }
291
292 public static String getEmailFromName(PortletPreferences prefs) {
293 String emailFromName = PropsValues.MESSAGE_BOARDS_EMAIL_FROM_NAME;
294
295 return prefs.getValue("email-from-name", emailFromName);
296 }
297
298 public static boolean getEmailHtmlFormat(PortletPreferences prefs) {
299 String emailHtmlFormat = prefs.getValue(
300 "email-html-format", StringPool.BLANK);
301
302 if (Validator.isNotNull(emailHtmlFormat)) {
303 return GetterUtil.getBoolean(emailHtmlFormat);
304 }
305 else {
306 return PropsValues.MESSAGE_BOARDS_EMAIL_HTML_FORMAT;
307 }
308 }
309
310 public static boolean getEmailMessageAddedEnabled(
311 PortletPreferences prefs) {
312
313 String emailMessageAddedEnabled = prefs.getValue(
314 "email-message-added-enabled", StringPool.BLANK);
315
316 if (Validator.isNotNull(emailMessageAddedEnabled)) {
317 return GetterUtil.getBoolean(emailMessageAddedEnabled);
318 }
319 else {
320 return PropsValues.MESSAGE_BOARDS_EMAIL_MESSAGE_ADDED_ENABLED;
321 }
322 }
323
324 public static String getEmailMessageAddedBody(PortletPreferences prefs) {
325 String emailMessageAddedBody = prefs.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 prefs) {
339
340 String emailMessageAddedSignature = prefs.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 prefs) {
354
355 String emailMessageAddedSubjectPrefix = prefs.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 prefs) {
369
370 String emailMessageUpdatedEnabled = prefs.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(PortletPreferences prefs) {
382 String emailMessageUpdatedBody = prefs.getValue(
383 "email-message-updated-body", StringPool.BLANK);
384
385 if (Validator.isNotNull(emailMessageUpdatedBody)) {
386 return emailMessageUpdatedBody;
387 }
388 else {
389 return ContentUtil.get(
390 PropsValues.MESSAGE_BOARDS_EMAIL_MESSAGE_UPDATED_BODY);
391 }
392 }
393
394 public static String getEmailMessageUpdatedSignature(
395 PortletPreferences prefs) {
396
397 String emailMessageUpdatedSignature = prefs.getValue(
398 "email-message-updated-signature", StringPool.BLANK);
399
400 if (Validator.isNotNull(emailMessageUpdatedSignature)) {
401 return emailMessageUpdatedSignature;
402 }
403 else {
404 return ContentUtil.get(
405 PropsValues.MESSAGE_BOARDS_EMAIL_MESSAGE_UPDATED_SIGNATURE);
406 }
407 }
408
409 public static String getEmailMessageUpdatedSubjectPrefix(
410 PortletPreferences prefs) {
411
412 String emailMessageUpdatedSubject = prefs.getValue(
413 "email-message-updated-subject-prefix", StringPool.BLANK);
414
415 if (Validator.isNotNull(emailMessageUpdatedSubject)) {
416 return emailMessageUpdatedSubject;
417 }
418 else {
419 return ContentUtil.get(
420 PropsValues.
421 MESSAGE_BOARDS_EMAIL_MESSAGE_UPDATED_SUBJECT_PREFIX);
422 }
423 }
424
425 public static String getMailId(String mx, long categoryId, long messageId) {
426 StringBuilder sb = new StringBuilder();
427
428 sb.append(StringPool.LESS_THAN);
429 sb.append(POP_PORTLET_PREFIX);
430 sb.append(categoryId);
431 sb.append(StringPool.PERIOD);
432 sb.append(messageId);
433 sb.append(StringPool.AT);
434
435 if (Validator.isNotNull(PropsValues.POP_SERVER_SUBDOMAIN)) {
436 sb.append(PropsValues.POP_SERVER_SUBDOMAIN);
437 sb.append(StringPool.PERIOD);
438 }
439
440 sb.append(mx);
441 sb.append(StringPool.GREATER_THAN);
442
443 return sb.toString();
444 }
445
446 public static String getMailingListAddress(
447 long categoryId, long messageId, String mx,
448 String defaultMailingListAddress) {
449
450 if (POP_SERVER_SUBDOMAIN_LENGTH <= 0) {
451 return defaultMailingListAddress;
452 }
453
454 StringBuilder sb = new StringBuilder();
455
456 sb.append(POP_PORTLET_PREFIX);
457 sb.append(categoryId);
458 sb.append(StringPool.PERIOD);
459 sb.append(messageId);
460 sb.append(StringPool.AT);
461 sb.append(PropsValues.POP_SERVER_SUBDOMAIN);
462 sb.append(StringPool.PERIOD);
463 sb.append(mx);
464
465 return sb.toString();
466 }
467
468 public static long getMessageId(String mailId) {
469 int x = mailId.indexOf(StringPool.LESS_THAN) + 1;
470 int y = mailId.indexOf(StringPool.AT);
471
472 long messageId = 0;
473
474 if ((x > 0 ) && (y != -1)) {
475 String temp = mailId.substring(x, y);
476
477 int z = temp.lastIndexOf(StringPool.PERIOD);
478
479 if (z != -1) {
480 messageId = GetterUtil.getLong(temp.substring(z + 1));
481 }
482 }
483
484 return messageId;
485 }
486
487 public static long getParentMessageId(Message message) throws Exception {
488 long parentMessageId = -1;
489
490 String parentHeader = getParentMessageIdString(message);
491
492 if (parentHeader != null) {
493 if (_log.isDebugEnabled()) {
494 _log.debug("Parent header " + parentHeader);
495 }
496
497 parentMessageId = getMessageId(parentHeader);
498
499 if (_log.isDebugEnabled()) {
500 _log.debug("Previous message id " + parentMessageId);
501 }
502 }
503
504 return parentMessageId;
505 }
506
507 public static String getParentMessageIdString(Message message)
508 throws Exception {
509
510
515 String parentHeader = null;
516
517 String[] references = message.getHeader("References");
518
519 if ((references != null) && (references.length > 0)) {
520 parentHeader = references[0].substring(
521 references[0].lastIndexOf("<"));
522 }
523
524 if (parentHeader == null) {
525 String[] inReplyToHeaders = message.getHeader("In-Reply-To");
526
527 if ((inReplyToHeaders != null) && (inReplyToHeaders.length > 0)) {
528 parentHeader = inReplyToHeaders[0];
529 }
530 }
531
532 if (Validator.isNull(parentHeader) ||
533 !parentHeader.startsWith(POP_PORTLET_PREFIX, 1)) {
534
535 parentHeader = _getParentMessageIdFromSubject(message);
536 }
537
538 return parentHeader;
539 }
540
541 public static String getSubjectWithoutMessageId(Message message)
542 throws Exception {
543
544 String subject = message.getSubject();
545
546 String parentMessageId = _getParentMessageIdFromSubject(message);
547
548 if (Validator.isNotNull(parentMessageId)) {
549 int pos = subject.indexOf(parentMessageId);
550
551 if (pos != -1) {
552 subject = subject.substring(0, pos);
553 }
554 }
555
556 return subject;
557 }
558
559 public static String[] getThreadPriority(
560 PortletPreferences prefs, String languageId, double value,
561 ThemeDisplay themeDisplay)
562 throws Exception {
563
564 String[] priorities = LocalizationUtil.getPreferencesValues(
565 prefs, "priorities", languageId);
566
567 String[] priorityPair = _findThreadPriority(
568 value, themeDisplay, priorities);
569
570 if (priorityPair == null) {
571 String defaultLanguageId = LocaleUtil.toLanguageId(
572 LocaleUtil.getDefault());
573
574 priorities = LocalizationUtil.getPreferencesValues(
575 prefs, "priorities", defaultLanguageId);
576
577 priorityPair = _findThreadPriority(value, themeDisplay, priorities);
578 }
579
580 return priorityPair;
581 }
582
583 public static Date getUnbanDate(MBBan ban, int expireInterval) {
584 Date banDate = ban.getCreateDate();
585
586 Calendar cal = Calendar.getInstance();
587
588 cal.setTime(banDate);
589
590 cal.add(Calendar.DATE, expireInterval);
591
592 return cal.getTime();
593 }
594
595 public static String getUserRank(
596 PortletPreferences prefs, String languageId, int posts)
597 throws Exception {
598
599 String rank = StringPool.BLANK;
600
601 String[] ranks = LocalizationUtil.getPreferencesValues(
602 prefs, "ranks", languageId);
603
604 for (int i = 0; i < ranks.length; i++) {
605 String[] kvp = StringUtil.split(ranks[i], StringPool.EQUAL);
606
607 String kvpName = kvp[0];
608 int kvpPosts = GetterUtil.getInteger(kvp[1]);
609
610 if (posts >= kvpPosts) {
611 rank = kvpName;
612 }
613 else {
614 break;
615 }
616 }
617
618 return rank;
619 }
620
621 public static String[] getUserRank(
622 PortletPreferences prefs, String languageId, MBStatsUser statsUser)
623 throws Exception {
624
625 String[] rank = {StringPool.BLANK, 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 prefs, "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[0] = curRank;
653 maxPosts = posts;
654 }
655
656 }
657 else {
658 String entityType = curRankValueKvp[0];
659 String entityValue = curRankValueKvp[1];
660
661 try {
662 if (_isEntityRank(
663 companyId, statsUser, entityType, entityValue)) {
664
665 rank[1] = curRank;
666
667 break;
668 }
669 }
670 catch (Exception e) {
671 if (_log.isWarnEnabled()) {
672 _log.warn(e);
673 }
674 }
675 }
676 }
677
678 return rank;
679 }
680
681 public static boolean hasMailIdHeader(Message message) throws Exception {
682 String[] messageIds = message.getHeader("Message-ID");
683
684 if (messageIds == null) {
685 return false;
686 }
687
688 for (String messageId : messageIds) {
689 if (messageId.contains(PropsValues.POP_SERVER_SUBDOMAIN)) {
690 return true;
691 }
692 }
693
694 return false;
695 }
696
697 public static boolean isAllowAnonymousPosting(PortletPreferences prefs) {
698 String allowAnonymousPosting = prefs.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(), true)) {
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 }