001    /**
002     * Copyright (c) 2000-2013 Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portlet.messageboards.pop;
016    
017    import com.liferay.portal.kernel.log.Log;
018    import com.liferay.portal.kernel.log.LogFactoryUtil;
019    import com.liferay.portal.kernel.pop.MessageListener;
020    import com.liferay.portal.kernel.pop.MessageListenerException;
021    import com.liferay.portal.kernel.util.CharPool;
022    import com.liferay.portal.kernel.util.GetterUtil;
023    import com.liferay.portal.kernel.util.ObjectValuePair;
024    import com.liferay.portal.kernel.util.PrefsPropsUtil;
025    import com.liferay.portal.kernel.util.PropsKeys;
026    import com.liferay.portal.kernel.util.StreamUtil;
027    import com.liferay.portal.kernel.util.StringUtil;
028    import com.liferay.portal.model.Company;
029    import com.liferay.portal.model.User;
030    import com.liferay.portal.security.auth.PrincipalException;
031    import com.liferay.portal.security.permission.PermissionCheckerUtil;
032    import com.liferay.portal.service.CompanyLocalServiceUtil;
033    import com.liferay.portal.service.ServiceContext;
034    import com.liferay.portal.service.UserLocalServiceUtil;
035    import com.liferay.portal.util.PortalUtil;
036    import com.liferay.portal.util.PortletKeys;
037    import com.liferay.portal.util.PropsValues;
038    import com.liferay.portlet.messageboards.NoSuchCategoryException;
039    import com.liferay.portlet.messageboards.NoSuchMessageException;
040    import com.liferay.portlet.messageboards.model.MBCategory;
041    import com.liferay.portlet.messageboards.model.MBCategoryConstants;
042    import com.liferay.portlet.messageboards.model.MBMessage;
043    import com.liferay.portlet.messageboards.model.MBMessageConstants;
044    import com.liferay.portlet.messageboards.service.MBCategoryLocalServiceUtil;
045    import com.liferay.portlet.messageboards.service.MBMessageLocalServiceUtil;
046    import com.liferay.portlet.messageboards.service.MBMessageServiceUtil;
047    import com.liferay.portlet.messageboards.util.MBMailMessage;
048    import com.liferay.portlet.messageboards.util.MBUtil;
049    
050    import java.io.InputStream;
051    
052    import java.util.List;
053    
054    import javax.mail.Message;
055    import javax.mail.MessagingException;
056    
057    import org.apache.commons.lang.time.StopWatch;
058    
059    /**
060     * @author Brian Wing Shun Chan
061     * @author Jorge Ferrer
062     * @author Michael C. Han
063     */
064    public class MessageListenerImpl implements MessageListener {
065    
066            public boolean accept(String from, String recipient, Message message) {
067                    try {
068                            if (isAutoReply(message)) {
069                                    return false;
070                            }
071    
072                            String messageIdString = getMessageIdString(recipient, message);
073    
074                            if ((messageIdString == null) ||
075                                    !messageIdString.startsWith(
076                                            MBUtil.MESSAGE_POP_PORTLET_PREFIX, getOffset())) {
077    
078                                    return false;
079                            }
080    
081                            Company company = getCompany(messageIdString);
082                            long categoryId = getCategoryId(messageIdString);
083    
084                            MBCategory category = MBCategoryLocalServiceUtil.getCategory(
085                                    categoryId);
086    
087                            if ((category.getCompanyId() != company.getCompanyId()) &&
088                                    !category.isRoot()) {
089    
090                                    return false;
091                            }
092    
093                            if (_log.isDebugEnabled()) {
094                                    _log.debug("Check to see if user " + from + " exists");
095                            }
096    
097                            String pop3User = PrefsPropsUtil.getString(
098                                    PropsKeys.MAIL_SESSION_MAIL_POP3_USER,
099                                    PropsValues.MAIL_SESSION_MAIL_POP3_USER);
100    
101                            if (from.equalsIgnoreCase(pop3User)) {
102                                    return false;
103                            }
104    
105                            UserLocalServiceUtil.getUserByEmailAddress(
106                                    company.getCompanyId(), from);
107    
108                            return true;
109                    }
110                    catch (Exception e) {
111                            if (_log.isErrorEnabled()) {
112                                    _log.error("Unable to process message: " + message, e);
113                            }
114    
115                            return false;
116                    }
117            }
118    
119            public void deliver(String from, String recipient, Message message)
120                    throws MessageListenerException {
121    
122                    List<ObjectValuePair<String, InputStream>> inputStreamOVPs = null;
123    
124                    try {
125                            StopWatch stopWatch = null;
126    
127                            if (_log.isDebugEnabled()) {
128                                    stopWatch = new StopWatch();
129    
130                                    stopWatch.start();
131    
132                                    _log.debug("Deliver message from " + from + " to " + recipient);
133                            }
134    
135                            String messageIdString = getMessageIdString(recipient, message);
136    
137                            Company company = getCompany(messageIdString);
138    
139                            if (_log.isDebugEnabled()) {
140                                    _log.debug("Message id " + messageIdString);
141                            }
142    
143                            long groupId = 0;
144                            long categoryId = getCategoryId(messageIdString);
145    
146                            try {
147                                    MBCategory category = MBCategoryLocalServiceUtil.getCategory(
148                                            categoryId);
149    
150                                    groupId = category.getGroupId();
151    
152                                    if (category.isRoot()) {
153                                            long messageId = getMessageId(messageIdString);
154    
155                                            MBMessage threadMessage =
156                                                    MBMessageLocalServiceUtil.fetchMBMessage(messageId);
157    
158                                            if (threadMessage != null) {
159                                                    groupId = threadMessage.getGroupId();
160                                            }
161                                    }
162                            }
163                            catch (NoSuchCategoryException nsce) {
164                                    groupId = categoryId;
165                                    categoryId = MBCategoryConstants.DEFAULT_PARENT_CATEGORY_ID;
166                            }
167    
168                            if (_log.isDebugEnabled()) {
169                                    _log.debug("Group id " + groupId);
170                                    _log.debug("Category id " + categoryId);
171                            }
172    
173                            User user = UserLocalServiceUtil.getUserByEmailAddress(
174                                    company.getCompanyId(), from);
175    
176                            long parentMessageId = getParentMessageId(recipient, message);
177    
178                            if (_log.isDebugEnabled()) {
179                                    _log.debug("Parent message id " + parentMessageId);
180                            }
181    
182                            MBMessage parentMessage = null;
183    
184                            try {
185                                    if (parentMessageId > 0) {
186                                            parentMessage = MBMessageLocalServiceUtil.getMessage(
187                                                    parentMessageId);
188                                    }
189                            }
190                            catch (NoSuchMessageException nsme) {
191    
192                                    // If the parent message does not exist we ignore it and post
193                                    // the message as a new thread.
194    
195                            }
196    
197                            if (_log.isDebugEnabled()) {
198                                    _log.debug("Parent message " + parentMessage);
199                            }
200    
201                            String subject = MBUtil.getSubjectWithoutMessageId(message);
202    
203                            MBMailMessage mbMailMessage = new MBMailMessage();
204    
205                            MBUtil.collectPartContent(message, mbMailMessage);
206    
207                            inputStreamOVPs = mbMailMessage.getInputStreamOVPs();
208    
209                            PermissionCheckerUtil.setThreadValues(user);
210    
211                            ServiceContext serviceContext = new ServiceContext();
212    
213                            serviceContext.setAddGroupPermissions(true);
214                            serviceContext.setAddGuestPermissions(true);
215                            serviceContext.setLayoutFullURL(
216                                    PortalUtil.getLayoutFullURL(
217                                            groupId, PortletKeys.MESSAGE_BOARDS));
218                            serviceContext.setScopeGroupId(groupId);
219    
220                            if (parentMessage == null) {
221                                    MBMessageServiceUtil.addMessage(
222                                            groupId, categoryId, subject, mbMailMessage.getBody(),
223                                            MBMessageConstants.DEFAULT_FORMAT, inputStreamOVPs, false,
224                                            0.0, true, serviceContext);
225                            }
226                            else {
227                                    MBMessageServiceUtil.addMessage(
228                                            parentMessage.getMessageId(), subject,
229                                            mbMailMessage.getBody(), MBMessageConstants.DEFAULT_FORMAT,
230                                            inputStreamOVPs, false, 0.0, true, serviceContext);
231                            }
232    
233                            if (_log.isDebugEnabled()) {
234                                    _log.debug(
235                                            "Delivering message takes " + stopWatch.getTime() + " ms");
236                            }
237                    }
238                    catch (PrincipalException pe) {
239                            if (_log.isDebugEnabled()) {
240                                    _log.debug("Prevented unauthorized post from " + from);
241                            }
242    
243                            throw new MessageListenerException(pe);
244                    }
245                    catch (Exception e) {
246                            _log.error(e, e);
247    
248                            throw new MessageListenerException(e);
249                    }
250                    finally {
251                            if (inputStreamOVPs != null) {
252                                    for (ObjectValuePair<String, InputStream> inputStreamOVP :
253                                                    inputStreamOVPs) {
254    
255                                            InputStream inputStream = inputStreamOVP.getValue();
256    
257                                            StreamUtil.cleanUp(inputStream);
258                                    }
259                            }
260    
261                            PermissionCheckerUtil.setThreadValues(null);
262                    }
263            }
264    
265            public String getId() {
266                    return MessageListenerImpl.class.getName();
267            }
268    
269            protected long getCategoryId(String messageIdString) {
270                    String[] parts = getMessageIdStringParts(messageIdString);
271    
272                    return GetterUtil.getLong(parts[0]);
273            }
274    
275            protected Company getCompany(String messageIdString) throws Exception {
276                    int pos =
277                            messageIdString.indexOf(CharPool.AT) +
278                                    PropsValues.POP_SERVER_SUBDOMAIN.length() + 1;
279    
280                    if (PropsValues.POP_SERVER_SUBDOMAIN.length() > 0) {
281                            pos++;
282                    }
283    
284                    int endPos = messageIdString.indexOf(CharPool.GREATER_THAN, pos);
285    
286                    if (endPos == -1) {
287                            endPos = messageIdString.length();
288                    }
289    
290                    String mx = messageIdString.substring(pos, endPos);
291    
292                    return CompanyLocalServiceUtil.getCompanyByMx(mx);
293            }
294    
295            protected long getMessageId(String messageIdString) {
296                    String[] parts = getMessageIdStringParts(messageIdString);
297    
298                    return GetterUtil.getLong(parts[1]);
299            }
300    
301            protected String getMessageIdString(String recipient, Message message)
302                    throws Exception {
303    
304                    if (PropsValues.POP_SERVER_SUBDOMAIN.length() > 0) {
305                            return recipient;
306                    }
307                    else {
308                            return MBUtil.getParentMessageIdString(message);
309                    }
310            }
311    
312            protected String[] getMessageIdStringParts(String messageIdString) {
313                    int pos = messageIdString.indexOf(CharPool.AT);
314    
315                    String target = messageIdString.substring(
316                            MBUtil.MESSAGE_POP_PORTLET_PREFIX.length() + getOffset(), pos);
317    
318                    return StringUtil.split(target, CharPool.PERIOD);
319            }
320    
321            protected int getOffset() {
322                    if (PropsValues.POP_SERVER_SUBDOMAIN.length() == 0) {
323                            return 1;
324                    }
325    
326                    return 0;
327            }
328    
329            protected long getParentMessageId(String recipient, Message message)
330                    throws Exception {
331    
332                    if (!StringUtil.startsWith(
333                                    recipient, MBUtil.MESSAGE_POP_PORTLET_PREFIX)) {
334    
335                            return MBUtil.getParentMessageId(message);
336                    }
337    
338                    int pos = recipient.indexOf(CharPool.AT);
339    
340                    if (pos < 0) {
341                            return MBUtil.getParentMessageId(message);
342                    }
343    
344                    String target = recipient.substring(
345                            MBUtil.MESSAGE_POP_PORTLET_PREFIX.length(), pos);
346    
347                    String[] parts = StringUtil.split(target, CharPool.PERIOD);
348    
349                    long parentMessageId = 0;
350    
351                    if (parts.length == 2) {
352                            parentMessageId = GetterUtil.getLong(parts[1]);
353                    }
354    
355                    if (parentMessageId > 0) {
356                            return parentMessageId;
357                    }
358    
359                    return MBUtil.getParentMessageId(message);
360            }
361    
362            protected boolean isAutoReply(Message message) throws MessagingException {
363                    String[] autoReply = message.getHeader("X-Autoreply");
364    
365                    if ((autoReply != null) && (autoReply.length > 0)) {
366                            return true;
367                    }
368    
369                    String[] autoReplyFrom = message.getHeader("X-Autoreply-From");
370    
371                    if ((autoReplyFrom != null) && (autoReplyFrom.length > 0)) {
372                            return true;
373                    }
374    
375                    String[] mailAutoReply = message.getHeader("X-Mail-Autoreply");
376    
377                    if ((mailAutoReply != null) && (mailAutoReply.length > 0)) {
378                            return true;
379                    }
380    
381                    return false;
382            }
383    
384            private static Log _log = LogFactoryUtil.getLog(MessageListenerImpl.class);
385    
386    }