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