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