1   /**
2    * Copyright (c) 2000-2008 Liferay, Inc. All rights reserved.
3    *
4    * Permission is hereby granted, free of charge, to any person obtaining a copy
5    * of this software and associated documentation files (the "Software"), to deal
6    * in the Software without restriction, including without limitation the rights
7    * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8    * copies of the Software, and to permit persons to whom the Software is
9    * furnished to do so, subject to the following conditions:
10   *
11   * The above copyright notice and this permission notice shall be included in
12   * all copies or substantial portions of the Software.
13   *
14   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20   * SOFTWARE.
21   */
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.LocaleUtil;
29  import com.liferay.portal.kernel.util.StringMaker;
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.PropsUtil;
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.Http;
55  import com.liferay.util.LocalizationUtil;
56  
57  import java.io.IOException;
58  
59  import java.util.Calendar;
60  import java.util.Date;
61  
62  import javax.portlet.PortletPreferences;
63  import javax.portlet.PortletURL;
64  import javax.portlet.RenderRequest;
65  import javax.portlet.RenderResponse;
66  import javax.portlet.WindowState;
67  
68  import javax.servlet.jsp.PageContext;
69  
70  import org.apache.commons.logging.Log;
71  import org.apache.commons.logging.LogFactory;
72  
73  /**
74   * <a href="MBUtil.java.html"><b><i>View Source</i></b></a>
75   *
76   * @author Brian Wing Shun Chan
77   *
78   */
79  public class MBUtil {
80  
81      public static final String POP_PORTLET_PREFIX = "mb.";
82  
83      public static String getBreadcrumbs(
84              long categoryId, long messageId, PageContext pageContext,
85              RenderRequest req, RenderResponse res)
86          throws Exception {
87  
88          if (messageId > 0) {
89              MBMessage message = MBMessageLocalServiceUtil.getMessage(messageId);
90  
91              return getBreadcrumbs(null, message, pageContext, req, res);
92          }
93          else {
94              MBCategory category = null;
95  
96              try {
97                  if ((categoryId > 0) &&
98                      (categoryId != MBCategoryImpl.DEFAULT_PARENT_CATEGORY_ID)) {
99  
100                     category = MBCategoryLocalServiceUtil.getCategory(
101                         categoryId);
102                 }
103             }
104             catch (Exception e) {
105             }
106 
107             return getBreadcrumbs(category, null, pageContext, req, res);
108         }
109     }
110 
111     public static String getBreadcrumbs(
112             MBCategory category, MBMessage message, PageContext pageContext,
113             RenderRequest req, RenderResponse res)
114         throws Exception {
115 
116         if ((message != null) && (category == null)) {
117             category = message.getCategory();
118         }
119 
120         PortletURL categoriesURL = res.createRenderURL();
121 
122         WindowState windowState = req.getWindowState();
123 
124         if (windowState.equals(LiferayWindowState.POP_UP)) {
125             categoriesURL.setWindowState(LiferayWindowState.POP_UP);
126 
127             categoriesURL.setParameter(
128                 "struts_action", "/message_boards/select_category");
129         }
130         else {
131             categoriesURL.setWindowState(WindowState.MAXIMIZED);
132 
133             categoriesURL.setParameter("struts_action", "/message_boards/view");
134             categoriesURL.setParameter(
135                 "categoryId",
136                 String.valueOf(MBCategoryImpl.DEFAULT_PARENT_CATEGORY_ID));
137         }
138 
139         String categoriesLink =
140             "<a href=\"" + categoriesURL.toString() + "\">" +
141                 LanguageUtil.get(pageContext, "categories") + "</a>";
142 
143         if (category == null) {
144             return categoriesLink;
145         }
146 
147         String breadcrumbs = StringPool.BLANK;
148 
149         if (category != null) {
150             for (int i = 0;; i++) {
151                 category = category.toEscapedModel();
152 
153                 PortletURL portletURL = res.createRenderURL();
154 
155                 if (windowState.equals(LiferayWindowState.POP_UP)) {
156                     portletURL.setWindowState(LiferayWindowState.POP_UP);
157 
158                     portletURL.setParameter(
159                         "struts_action", "/message_boards/select_category");
160                     portletURL.setParameter(
161                         "categoryId", String.valueOf(category.getCategoryId()));
162                 }
163                 else {
164                     portletURL.setWindowState(WindowState.MAXIMIZED);
165 
166                     portletURL.setParameter(
167                         "struts_action", "/message_boards/view");
168                     portletURL.setParameter(
169                         "categoryId", String.valueOf(category.getCategoryId()));
170                 }
171 
172                 String categoryLink =
173                     "<a href=\"" + portletURL.toString() + "\">" +
174                         category.getName() + "</a>";
175 
176                 if (i == 0) {
177                     breadcrumbs = categoryLink;
178                 }
179                 else {
180                     breadcrumbs = categoryLink + " &raquo; " + breadcrumbs;
181                 }
182 
183                 if (category.isRoot()) {
184                     break;
185                 }
186 
187                 category = MBCategoryLocalServiceUtil.getCategory(
188                     category.getParentCategoryId());
189             }
190         }
191 
192         breadcrumbs = categoriesLink + " &raquo; " + breadcrumbs;
193 
194         if (message != null) {
195             message = message.toEscapedModel();
196 
197             PortletURL messageURL = res.createRenderURL();
198 
199             messageURL.setWindowState(WindowState.MAXIMIZED);
200 
201             messageURL.setParameter(
202                 "struts_action", "/message_boards/view_message");
203             messageURL.setParameter(
204                 "messageId", String.valueOf(message.getMessageId()));
205 
206             String messageLink =
207                 "<a href=\"" + messageURL.toString() + "\">" +
208                     message.getSubject() + "</a>";
209 
210             breadcrumbs = breadcrumbs + " &raquo; " + messageLink;
211         }
212 
213         return breadcrumbs;
214     }
215 
216     public static String getEmailFromAddress(PortletPreferences prefs) {
217         String emailFromAddress = PropsUtil.get(
218             PropsUtil.MESSAGE_BOARDS_EMAIL_FROM_ADDRESS);
219 
220         return prefs.getValue("email-from-address", emailFromAddress);
221     }
222 
223     public static String getEmailFromName(PortletPreferences prefs) {
224         String emailFromName = PropsUtil.get(
225             PropsUtil.MESSAGE_BOARDS_EMAIL_FROM_NAME);
226 
227         return prefs.getValue("email-from-name", emailFromName);
228     }
229 
230     public static boolean getEmailMessageAddedEnabled(
231         PortletPreferences prefs) {
232 
233         String emailMessageAddedEnabled = prefs.getValue(
234             "email-message-added-enabled", StringPool.BLANK);
235 
236         if (Validator.isNotNull(emailMessageAddedEnabled)) {
237             return GetterUtil.getBoolean(emailMessageAddedEnabled);
238         }
239         else {
240             return GetterUtil.getBoolean(PropsUtil.get(
241                 PropsUtil.MESSAGE_BOARDS_EMAIL_MESSAGE_ADDED_ENABLED));
242         }
243     }
244 
245     public static String getEmailMessageAddedBody(PortletPreferences prefs)
246         throws IOException {
247 
248         String emailMessageAddedBody = prefs.getValue(
249             "email-message-added-body", StringPool.BLANK);
250 
251         if (Validator.isNotNull(emailMessageAddedBody)) {
252             return emailMessageAddedBody;
253         }
254         else {
255             return ContentUtil.get(PropsUtil.get(
256                 PropsUtil.MESSAGE_BOARDS_EMAIL_MESSAGE_ADDED_BODY));
257         }
258     }
259 
260     public static String getEmailMessageAddedSignature(PortletPreferences prefs)
261         throws IOException {
262 
263         String emailMessageAddedSignature = prefs.getValue(
264             "email-message-added-signature", StringPool.BLANK);
265 
266         if (Validator.isNotNull(emailMessageAddedSignature)) {
267             return emailMessageAddedSignature;
268         }
269         else {
270             return ContentUtil.get(PropsUtil.get(
271                 PropsUtil.MESSAGE_BOARDS_EMAIL_MESSAGE_ADDED_SIGNATURE));
272         }
273     }
274 
275     public static String getEmailMessageAddedSubjectPrefix(
276             PortletPreferences prefs)
277         throws IOException {
278 
279         String emailMessageAddedSubjectPrefix = prefs.getValue(
280             "email-message-added-subject-prefix", StringPool.BLANK);
281 
282         if (Validator.isNotNull(emailMessageAddedSubjectPrefix)) {
283             return emailMessageAddedSubjectPrefix;
284         }
285         else {
286             return ContentUtil.get(PropsUtil.get(
287                 PropsUtil.MESSAGE_BOARDS_EMAIL_MESSAGE_ADDED_SUBJECT_PREFIX));
288         }
289     }
290 
291     public static boolean getEmailMessageUpdatedEnabled(
292         PortletPreferences prefs) {
293 
294         String emailMessageUpdatedEnabled = prefs.getValue(
295             "email-message-updated-enabled", StringPool.BLANK);
296 
297         if (Validator.isNotNull(emailMessageUpdatedEnabled)) {
298             return GetterUtil.getBoolean(emailMessageUpdatedEnabled);
299         }
300         else {
301             return GetterUtil.getBoolean(PropsUtil.get(
302                 PropsUtil.MESSAGE_BOARDS_EMAIL_MESSAGE_UPDATED_ENABLED));
303         }
304     }
305 
306     public static String getEmailMessageUpdatedBody(PortletPreferences prefs)
307         throws IOException {
308 
309         String emailMessageUpdatedBody = prefs.getValue(
310             "email-message-updated-body", StringPool.BLANK);
311 
312         if (Validator.isNotNull(emailMessageUpdatedBody)) {
313             return emailMessageUpdatedBody;
314         }
315         else {
316             return ContentUtil.get(PropsUtil.get(
317                 PropsUtil.MESSAGE_BOARDS_EMAIL_MESSAGE_UPDATED_BODY));
318         }
319     }
320 
321     public static String getEmailMessageUpdatedSignature(
322             PortletPreferences prefs)
323         throws IOException {
324 
325         String emailMessageUpdatedSignature = prefs.getValue(
326             "email-message-updated-signature", StringPool.BLANK);
327 
328         if (Validator.isNotNull(emailMessageUpdatedSignature)) {
329             return emailMessageUpdatedSignature;
330         }
331         else {
332             return ContentUtil.get(PropsUtil.get(
333                 PropsUtil.MESSAGE_BOARDS_EMAIL_MESSAGE_UPDATED_SIGNATURE));
334         }
335     }
336 
337     public static String getEmailMessageUpdatedSubjectPrefix(
338             PortletPreferences prefs)
339         throws IOException {
340 
341         String emailMessageUpdatedSubject = prefs.getValue(
342             "email-message-updated-subject-prefix", StringPool.BLANK);
343 
344         if (Validator.isNotNull(emailMessageUpdatedSubject)) {
345             return emailMessageUpdatedSubject;
346         }
347         else {
348             return ContentUtil.get(PropsUtil.get(
349                 PropsUtil.MESSAGE_BOARDS_EMAIL_MESSAGE_UPDATED_SUBJECT_PREFIX));
350         }
351     }
352 
353     public static String getMailId(String mx, long categoryId, long messageId) {
354         StringMaker sm = new StringMaker();
355 
356         sm.append(StringPool.LESS_THAN);
357         sm.append(POP_PORTLET_PREFIX);
358         sm.append(categoryId);
359         sm.append(StringPool.PERIOD);
360         sm.append(messageId);
361         sm.append(StringPool.AT);
362         sm.append(PropsValues.POP_SERVER_SUBDOMAIN);
363         sm.append(StringPool.PERIOD);
364         sm.append(mx);
365         sm.append(StringPool.GREATER_THAN);
366 
367         return sm.toString();
368     }
369 
370     public static String getMailingListAddress(
371         long categoryId, long messageId, String mx) {
372 
373         StringMaker sm = new StringMaker();
374 
375         sm.append(POP_PORTLET_PREFIX);
376         sm.append(categoryId);
377         sm.append(StringPool.PERIOD);
378         sm.append(messageId);
379         sm.append(StringPool.AT);
380         sm.append(PropsValues.POP_SERVER_SUBDOMAIN);
381         sm.append(StringPool.PERIOD);
382         sm.append(mx);
383 
384         return sm.toString();
385     }
386 
387     public static long getMessageId(String mailId) {
388         int x = mailId.indexOf(StringPool.LESS_THAN) + 1;
389         int y = mailId.indexOf(StringPool.AT);
390 
391         long messageId = 0;
392 
393         if ((x > 0 ) && (y != -1)) {
394             String temp = mailId.substring(x, y);
395 
396             int z = temp.indexOf(StringPool.PERIOD);
397 
398             if (z != -1) {
399                 messageId = GetterUtil.getLong(temp.substring(z));
400             }
401         }
402 
403         return messageId;
404     }
405 
406     public static String[] getThreadPriority(
407             PortletPreferences prefs, String languageId, double value,
408             ThemeDisplay themeDisplay)
409         throws Exception {
410 
411         String[] priorities = LocalizationUtil.getPrefsValues(
412             prefs, "priorities", languageId);
413 
414         String[] priorityPair = _findThreadPriority(
415             value, themeDisplay, priorities);
416 
417         if (priorityPair == null) {
418             String defaultLanguageId = LocaleUtil.toLanguageId(
419                 LocaleUtil.getDefault());
420 
421             priorities = LocalizationUtil.getPrefsValues(
422                 prefs, "priorities", defaultLanguageId);
423 
424             priorityPair = _findThreadPriority(value, themeDisplay, priorities);
425         }
426 
427         return priorityPair;
428     }
429 
430     public static Date getUnbanDate(MBBan ban, int expireInterval) {
431         Date banDate = ban.getCreateDate();
432 
433         Calendar cal = Calendar.getInstance();
434 
435         cal.setTime(banDate);
436 
437         cal.add(Calendar.DATE, expireInterval);
438 
439         return cal.getTime();
440     }
441 
442     public static String getUserRank(
443             PortletPreferences prefs, String languageId, int posts)
444         throws Exception {
445 
446         String rank = StringPool.BLANK;
447 
448         String[] ranks = LocalizationUtil.getPrefsValues(
449             prefs, "ranks", languageId);
450 
451         for (int i = 0; i < ranks.length; i++) {
452             String[] kvp = StringUtil.split(ranks[i], StringPool.EQUAL);
453 
454             String kvpName = kvp[0];
455             int kvpPosts = GetterUtil.getInteger(kvp[1]);
456 
457             if (posts >= kvpPosts) {
458                 rank = kvpName;
459             }
460             else {
461                 break;
462             }
463         }
464 
465         return rank;
466     }
467 
468     public static String getUserRank(
469             PortletPreferences prefs, String languageId, MBStatsUser statsUser)
470         throws Exception {
471 
472         String rank = StringPool.BLANK;
473 
474         Group group = GroupLocalServiceUtil.getGroup(
475             statsUser.getGroupId());
476 
477         long companyId = group.getCompanyId();
478 
479         String[] ranks = LocalizationUtil.getPrefsValues(
480             prefs, "ranks", languageId);
481 
482         for (int i = 0; i < ranks.length; i++) {
483             String[] kvp = StringUtil.split(ranks[i], StringPool.EQUAL);
484 
485             String curRank = kvp[0];
486             String curRankValue = kvp[1];
487 
488             String[] curRankValueKvp = StringUtil.split(
489                 curRankValue, StringPool.COLON);
490 
491             if (curRankValueKvp.length <= 1) {
492                 int kvpPosts = GetterUtil.getInteger(curRankValue);
493 
494                 if (statsUser.getMessageCount() >= kvpPosts) {
495                     rank = curRank;
496                 }
497 
498                 continue;
499             }
500 
501             String entityType = curRankValueKvp[0];
502             String entityValue = curRankValueKvp[1];
503 
504             try {
505                 if (_isEntityRank(
506                         companyId, statsUser, entityType, entityValue)) {
507 
508                     return curRank;
509                 }
510             }
511             catch (Exception e) {
512                 if (_log.isWarnEnabled()) {
513                     _log.warn(e);
514                 }
515             }
516         }
517 
518         return rank;
519     }
520 
521     public static boolean isAllowAnonymousPosting(PortletPreferences prefs) {
522         String allowAnonymousPosting = prefs.getValue(
523             "allow-anonymous-posting", StringPool.BLANK);
524 
525         if (Validator.isNotNull(allowAnonymousPosting)) {
526             return GetterUtil.getBoolean(allowAnonymousPosting);
527         }
528         else {
529             return PropsValues.MESSAGE_BOARDS_ANONYMOUS_POSTING_ENABLED;
530         }
531     }
532 
533     private static String[] _findThreadPriority(
534         double value, ThemeDisplay themeDisplay, String[] priorities) {
535 
536         for (int i = 0; i < priorities.length; i++) {
537             String[] priority = StringUtil.split(priorities[i]);
538 
539             try {
540                 String priorityName = priority[0];
541                 String priorityImage = priority[1];
542                 double priorityValue = GetterUtil.getDouble(priority[2]);
543 
544                 if (value == priorityValue) {
545                     if (!priorityImage.startsWith(Http.HTTP)) {
546                         priorityImage =
547                             themeDisplay.getPathThemeImages() + priorityImage;
548                     }
549 
550                     return new String[] {priorityName, priorityImage};
551                 }
552             }
553             catch (Exception e) {
554             }
555         }
556 
557         return null;
558     }
559 
560     private static boolean _isEntityRank(
561             long companyId, MBStatsUser statsUser, String entityType,
562             String entityValue)
563         throws Exception {
564 
565         long groupId = statsUser.getGroupId();
566         long userId = statsUser.getUserId();
567 
568         if (entityType.equals("community-role") ||
569             entityType.equals("organization-role")) {
570 
571             Role role = RoleLocalServiceUtil.getRole(companyId, entityValue);
572 
573             if (UserGroupRoleLocalServiceUtil.hasUserGroupRole(
574                     userId, groupId, role.getRoleId())) {
575 
576                 return true;
577             }
578         }
579         else if (entityType.equals("organization")) {
580             Organization organization =
581                 OrganizationLocalServiceUtil.getOrganization(
582                     companyId, entityValue);
583 
584             if (OrganizationLocalServiceUtil.hasUserOrganization(
585                     userId, organization.getOrganizationId())) {
586 
587                 return true;
588             }
589         }
590         else if (entityType.equals("regular-role")) {
591             if (RoleLocalServiceUtil.hasUserRole(
592                     userId, companyId, entityValue, true)) {
593 
594                 return true;
595             }
596         }
597         else if (entityType.equals("user-group")) {
598             UserGroup userGroup = UserGroupLocalServiceUtil.getUserGroup(
599                 companyId, entityValue);
600 
601             if (UserLocalServiceUtil.hasUserGroupUser(
602                     userGroup.getUserGroupId(), userId)) {
603 
604                 return true;
605             }
606         }
607 
608         return false;
609     }
610 
611     private static Log _log = LogFactory.getLog(MBUtil.class);
612 
613 }