001    /**
002     * Copyright (c) 2000-2011 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.portal.util;
016    
017    import com.liferay.mail.model.FileAttachment;
018    import com.liferay.mail.service.MailServiceUtil;
019    import com.liferay.portal.NoSuchUserException;
020    import com.liferay.portal.kernel.exception.PortalException;
021    import com.liferay.portal.kernel.log.Log;
022    import com.liferay.portal.kernel.log.LogFactoryUtil;
023    import com.liferay.portal.kernel.mail.MailMessage;
024    import com.liferay.portal.kernel.mail.SMTPAccount;
025    import com.liferay.portal.kernel.messaging.DestinationNames;
026    import com.liferay.portal.kernel.messaging.MessageBusUtil;
027    import com.liferay.portal.kernel.util.GetterUtil;
028    import com.liferay.portal.kernel.util.HtmlUtil;
029    import com.liferay.portal.kernel.util.LocaleUtil;
030    import com.liferay.portal.kernel.util.ObjectValuePair;
031    import com.liferay.portal.kernel.util.StringPool;
032    import com.liferay.portal.kernel.util.StringUtil;
033    import com.liferay.portal.kernel.util.Validator;
034    import com.liferay.portal.model.Company;
035    import com.liferay.portal.model.Group;
036    import com.liferay.portal.model.Subscription;
037    import com.liferay.portal.model.User;
038    import com.liferay.portal.security.permission.PermissionChecker;
039    import com.liferay.portal.security.permission.PermissionCheckerFactoryUtil;
040    import com.liferay.portal.service.CompanyLocalServiceUtil;
041    import com.liferay.portal.service.GroupLocalServiceUtil;
042    import com.liferay.portal.service.ServiceContext;
043    import com.liferay.portal.service.SubscriptionLocalServiceUtil;
044    import com.liferay.portal.service.UserLocalServiceUtil;
045    import com.liferay.portal.service.permission.SubscriptionPermissionUtil;
046    
047    import java.io.File;
048    import java.io.Serializable;
049    
050    import java.util.ArrayList;
051    import java.util.HashMap;
052    import java.util.HashSet;
053    import java.util.List;
054    import java.util.Locale;
055    import java.util.Map;
056    import java.util.Set;
057    
058    import javax.mail.internet.InternetAddress;
059    
060    /**
061     * @author Brian Wing Shun Chan
062     * @author Mate Thurzo
063     */
064    public class SubscriptionSender implements Serializable {
065    
066            public void addFileAttachment(File file) {
067                    addFileAttachment(file, null);
068            }
069    
070            public void addFileAttachment(File file, String fileName) {
071                    if (file == null) {
072                            return;
073                    }
074    
075                    if (fileAttachments == null) {
076                            fileAttachments = new ArrayList<FileAttachment>();
077                    }
078    
079                    FileAttachment attachment = new FileAttachment(file, fileName);
080    
081                    fileAttachments.add(attachment);
082            }
083    
084            public void addPersistedSubscribers(String className, long classPK) {
085                    ObjectValuePair<String, Long> ovp = new ObjectValuePair<String, Long>(
086                            className, classPK);
087    
088                    _persistestedSubscribersOVPs.add(ovp);
089            }
090    
091            public void addRuntimeSubscribers(String toAddress, String toName) {
092                    ObjectValuePair<String, String> ovp =
093                            new ObjectValuePair<String, String>(
094                                    toAddress, HtmlUtil.escape(toName));
095    
096                    _runtimeSubscribersOVPs.add(ovp);
097            }
098    
099            public void flushNotifications() throws Exception {
100                    initialize();
101    
102                    Thread currentThread = Thread.currentThread();
103    
104                    ClassLoader contextClassLoader = currentThread.getContextClassLoader();
105    
106                    try {
107                            if ((_classLoader != null) &&
108                                    (contextClassLoader != _classLoader)) {
109    
110                                    currentThread.setContextClassLoader(_classLoader);
111                            }
112    
113                            for (ObjectValuePair<String, Long> ovp :
114                                            _persistestedSubscribersOVPs) {
115    
116                                    String className = ovp.getKey();
117                                    long classPK = ovp.getValue();
118    
119                                    List<Subscription> subscriptions =
120                                            SubscriptionLocalServiceUtil.getSubscriptions(
121                                                    companyId, className, classPK);
122    
123                                    for (Subscription subscription : subscriptions) {
124                                            try {
125                                                    notifySubscriber(subscription);
126                                            }
127                                            catch (PortalException pe) {
128                                                    _log.error(
129                                                            "Unable to process subscription: " + subscription);
130    
131                                                    continue;
132                                            }
133                                    }
134    
135                                    if (bulk) {
136                                            Locale locale = LocaleUtil.getDefault();
137    
138                                            InternetAddress to = new InternetAddress(
139                                                    replaceContent(replyToAddress, locale),
140                                                    replaceContent(replyToAddress, locale));
141    
142                                            sendEmail(to, locale);
143                                    }
144                            }
145    
146                            _persistestedSubscribersOVPs.clear();
147    
148                            for (ObjectValuePair<String, String> ovp :
149                                            _runtimeSubscribersOVPs) {
150    
151                                    String toAddress = ovp.getKey();
152                                    String toName = ovp.getValue();
153    
154                                    if (_sentEmailAddresses.contains(toAddress)) {
155                                            if (_log.isDebugEnabled()) {
156                                                    _log.debug(
157                                                            "Do not send a duplicate email to " + toAddress);
158                                            }
159    
160                                            return;
161                                    }
162                                    else {
163                                            if (_log.isDebugEnabled()) {
164                                                    _log.debug(
165                                                            "Add " + toAddress + " to the list of users who " +
166                                                                    "have received an email");
167                                            }
168    
169                                            _sentEmailAddresses.add(toAddress);
170                                    }
171    
172                                    InternetAddress to = new InternetAddress(toAddress, toName);
173    
174                                    sendEmail(to, LocaleUtil.getDefault());
175                            }
176    
177                            _runtimeSubscribersOVPs.clear();
178                    }
179                    finally {
180                            if ((_classLoader != null) &&
181                                    (contextClassLoader != _classLoader)) {
182    
183                                    currentThread.setContextClassLoader(contextClassLoader);
184                            }
185                    }
186            }
187    
188            public void flushNotificationsAsync() {
189                    Thread currentThread = Thread.currentThread();
190    
191                    _classLoader = currentThread.getContextClassLoader();
192    
193                    MessageBusUtil.sendMessage(DestinationNames.SUBSCRIPTION_SENDER, this);
194            }
195    
196            public Object getContextAttribute(String key) {
197                    return _context.get(key);
198            }
199    
200            public void initialize() throws Exception {
201                    if (_initialized) {
202                            return;
203                    }
204    
205                    _initialized = true;
206    
207                    Company company = CompanyLocalServiceUtil.getCompany(companyId);
208    
209                    setContextAttribute("[$COMPANY_ID$]", company.getCompanyId());
210                    setContextAttribute("[$COMPANY_MX$]", company.getMx());
211                    setContextAttribute("[$COMPANY_NAME$]", company.getName());
212                    setContextAttribute("[$PORTAL_URL$]", getPortalURL(company));
213    
214                    if (groupId > 0) {
215                            Group group = GroupLocalServiceUtil.getGroup(groupId);
216    
217                            setContextAttribute("[$SITE_NAME$]", group.getDescriptiveName());
218                    }
219    
220                    if ((userId > 0) && Validator.isNotNull(_contextUserPrefix)) {
221                            setContextAttribute(
222                                    "[$" + _contextUserPrefix + "_USER_ADDRESS$]",
223                                    HtmlUtil.escape(PortalUtil.getUserEmailAddress(userId)));
224                            setContextAttribute(
225                                    "[$" + _contextUserPrefix + "_USER_NAME$]",
226                                    HtmlUtil.escape(
227                                            PortalUtil.getUserName(userId, StringPool.BLANK)));
228                    }
229    
230                    mailId = PortalUtil.getMailId(
231                            company.getMx(), _mailIdPopPortletPrefix, _mailIdIds);
232            }
233    
234            public String getMailId() {
235                    return this.mailId;
236            }
237    
238            public void setBody(String body) {
239                    this.body = body;
240            }
241    
242            public void setBulk(boolean bulk) {
243                    this.bulk = bulk;
244            }
245    
246            public void setCompanyId(long companyId) {
247                    this.companyId = companyId;
248            }
249    
250            public void setContextAttribute(String key, Object value) {
251                    setContextAttribute(key, value, true);
252            }
253    
254            public void setContextAttribute(String key, Object value, boolean escaped) {
255                    if (escaped) {
256                            _context.put(key, HtmlUtil.escape(String.valueOf(value)));
257                    }
258                    else {
259                            _context.put(key, String.valueOf(value));
260                    }
261            }
262    
263            public void setContextAttributes(Object... values) {
264                    for (int i = 0; i < values.length; i += 2) {
265                            setContextAttribute(String.valueOf(values[i]), values[i + 1]);
266                    }
267            }
268    
269            public void setContextUserPrefix(String contextUserPrefix) {
270                    _contextUserPrefix = contextUserPrefix;
271            }
272    
273            public void setFrom(String fromAddress, String fromName) {
274                    this.fromAddress = fromAddress;
275                    this.fromName = fromName;
276            }
277    
278            public void setGroupId(long groupId) {
279                    this.groupId = groupId;
280            }
281    
282            public void setHtmlFormat(boolean htmlFormat) {
283                    this.htmlFormat = htmlFormat;
284            }
285    
286            public void setInReplyTo(String inReplyTo) {
287                    this.inReplyTo = inReplyTo;
288            }
289    
290            public void setLocalizedBodyMap(Map<Locale, String> localizedBodyMap) {
291                    this.localizedBodyMap = localizedBodyMap;
292            }
293    
294            public void setLocalizedSubjectMap(
295                    Map<Locale, String> localizedSubjectMap) {
296    
297                    this.localizedSubjectMap = localizedSubjectMap;
298            }
299    
300            public void setMailId(String popPortletPrefix, Object... ids) {
301                    _mailIdPopPortletPrefix = popPortletPrefix;
302                    _mailIdIds = ids;
303            }
304    
305            public void setPortletId(String portletId) {
306                    this.portletId = portletId;
307            }
308    
309            public void setReplyToAddress(String replyToAddress) {
310                    this.replyToAddress = replyToAddress;
311            }
312    
313            /**
314             * @see {@link
315             *      com.liferay.portal.kernel.search.BaseIndexer#getParentGroupId(long)}
316             */
317            public void setScopeGroupId(long scopeGroupId) {
318                    try {
319                            Group group = GroupLocalServiceUtil.getGroup(scopeGroupId);
320    
321                            if (group.isLayout()) {
322                                    groupId = group.getParentGroupId();
323                            }
324                            else {
325                                    groupId = scopeGroupId;
326                            }
327                    }
328                    catch (Exception e) {
329                    }
330    
331                    this.scopeGroupId = scopeGroupId;
332            }
333    
334            public void setServiceContext(ServiceContext serviceContext) {
335                    this.serviceContext = serviceContext;
336            }
337    
338            public void setSMTPAccount(SMTPAccount smtpAccount) {
339                    this.smtpAccount = smtpAccount;
340            }
341    
342            public void setSubject(String subject) {
343                    this.subject = subject;
344            }
345    
346            public void setUserId(long userId) {
347                    this.userId = userId;
348            }
349    
350            protected void deleteSubscription(Subscription subscription)
351                    throws Exception {
352    
353                    SubscriptionLocalServiceUtil.deleteSubscription(
354                            subscription.getSubscriptionId());
355            }
356    
357            protected String getPortalURL(Company company) throws Exception {
358                    if (serviceContext != null) {
359                            String portalURL = serviceContext.getPortalURL();
360    
361                            if (Validator.isNotNull(portalURL)) {
362                                    return portalURL;
363                            }
364                    }
365    
366                    return company.getPortalURL(groupId);
367            }
368    
369            protected boolean hasPermission(Subscription subscription, User user)
370                    throws Exception {
371    
372                    PermissionChecker permissionChecker =
373                            PermissionCheckerFactoryUtil.create(user, true);
374    
375                    return SubscriptionPermissionUtil.contains(
376                            permissionChecker, subscription.getClassName(),
377                            subscription.getClassPK());
378            }
379    
380            protected void notifySubscriber(Subscription subscription)
381                    throws Exception {
382    
383                    User user = null;
384    
385                    try {
386                            user = UserLocalServiceUtil.getUserById(subscription.getUserId());
387                    }
388                    catch (NoSuchUserException nsue) {
389                            if (_log.isInfoEnabled()) {
390                                    _log.info(
391                                            "Subscription " + subscription.getSubscriptionId() +
392                                                    " is stale and will be deleted");
393                            }
394    
395                            deleteSubscription(subscription);
396    
397                            return;
398                    }
399    
400                    String emailAddress = user.getEmailAddress();
401    
402                    if (_sentEmailAddresses.contains(emailAddress)) {
403                            if (_log.isDebugEnabled()) {
404                                    _log.debug("Do not send a duplicate email to " + emailAddress);
405                            }
406    
407                            return;
408                    }
409                    else {
410                            if (_log.isDebugEnabled()) {
411                                    _log.debug(
412                                            "Add " + emailAddress +
413                                                    " to the list of users who have received an email");
414                            }
415    
416                            _sentEmailAddresses.add(emailAddress);
417                    }
418    
419                    if (!user.isActive()) {
420                            if (_log.isDebugEnabled()) {
421                                    _log.debug("Skip inactive user " + user.getUserId());
422                            }
423    
424                            return;
425                    }
426    
427                    try {
428                            if (!hasPermission(subscription, user)) {
429                                    if (_log.isDebugEnabled()) {
430                                            _log.debug("Skip unauthorized user " + user.getUserId());
431                                    }
432    
433                                    return;
434                            }
435                    }
436                    catch (Exception e) {
437                            _log.error(e, e);
438    
439                            return;
440                    }
441    
442                    if (bulk) {
443                            InternetAddress bulkAddress = new InternetAddress(
444                                    user.getEmailAddress(), user.getFullName());
445    
446                            if (_bulkAddresses == null) {
447                                    _bulkAddresses = new ArrayList<InternetAddress>();
448                            }
449    
450                            _bulkAddresses.add(bulkAddress);
451                    }
452                    else {
453                            try {
454                                    InternetAddress to = new InternetAddress(
455                                            user.getEmailAddress(), user.getFullName());
456    
457                                    sendEmail(to, user.getLocale());
458                            }
459                            catch (Exception e) {
460                                    _log.error(e, e);
461                            }
462                    }
463            }
464    
465            protected void processMailMessage(MailMessage mailMessage, Locale locale)
466                    throws Exception {
467    
468                    InternetAddress from = mailMessage.getFrom();
469                    InternetAddress to = mailMessage.getTo()[0];
470    
471                    String processedSubject = StringUtil.replace(
472                            mailMessage.getSubject(),
473                            new String[] {
474                                    "[$FROM_ADDRESS$]",
475                                    "[$FROM_NAME$]",
476                                    "[$TO_ADDRESS$]",
477                                    "[$TO_NAME$]"
478                            },
479                            new String[] {
480                                    from.getAddress(),
481                                    GetterUtil.getString(from.getPersonal(), from.getAddress()),
482                                    HtmlUtil.escape(to.getAddress()),
483                                    HtmlUtil.escape(
484                                            GetterUtil.getString(to.getPersonal(), to.getAddress()))
485                            });
486    
487                    processedSubject = replaceContent(processedSubject, locale);
488    
489                    mailMessage.setSubject(processedSubject);
490    
491                    String processedBody = StringUtil.replace(
492                            mailMessage.getBody(),
493                            new String[] {
494                                    "[$FROM_ADDRESS$]",
495                                    "[$FROM_NAME$]",
496                                    "[$TO_ADDRESS$]",
497                                    "[$TO_NAME$]"
498                            },
499                            new String[] {
500                                    from.getAddress(),
501                                    GetterUtil.getString(from.getPersonal(), from.getAddress()),
502                                    HtmlUtil.escape(to.getAddress()),
503                                    HtmlUtil.escape(
504                                            GetterUtil.getString(to.getPersonal(), to.getAddress()))
505                            });
506    
507                    processedBody = replaceContent(processedBody, locale);
508    
509                    mailMessage.setBody(processedBody);
510            }
511    
512            protected String replaceContent(String content, Locale locale)
513                    throws Exception {
514    
515                    for (Map.Entry<String, Object> entry : _context.entrySet()) {
516                            String key = entry.getKey();
517                            Object value = entry.getValue();
518    
519                            content = StringUtil.replace(content, key, String.valueOf(value));
520                    }
521    
522                    if (Validator.isNotNull(portletId)) {
523                            String portletName = PortalUtil.getPortletTitle(portletId, locale);
524    
525                            content = StringUtil.replace(
526                                    content, "[$PORTLET_NAME$]", portletName);
527                    }
528    
529                    Company company = CompanyLocalServiceUtil.getCompany(companyId);
530    
531                    content = StringUtil.replace(
532                            content,
533                            new String[] {
534                                    "href=\"/",
535                                    "src=\"/"
536                            },
537                            new String[] {
538                                    "href=\"" + getPortalURL(company) + "/",
539                                    "src=\"" + getPortalURL(company) + "/"
540                            });
541    
542                    return content;
543            }
544    
545            protected void sendEmail(InternetAddress to, Locale locale)
546                    throws Exception {
547    
548                    InternetAddress from = new InternetAddress(
549                            replaceContent(fromAddress, locale),
550                            replaceContent(fromName, locale));
551    
552                    String processedSubject = null;
553    
554                    if (localizedSubjectMap != null) {
555                            String localizedSubject = localizedSubjectMap.get(locale);
556    
557                            if (Validator.isNull(localizedSubject)) {
558                                    Locale defaultLocale = LocaleUtil.getDefault();
559    
560                                    processedSubject = localizedSubjectMap.get(defaultLocale);
561                            }
562                            else {
563                                    processedSubject = localizedSubject;
564                            }
565                    }
566                    else {
567                            processedSubject = this.subject;
568                    }
569    
570                    String processedBody = null;
571    
572                    if (localizedBodyMap != null) {
573                            String localizedBody = localizedBodyMap.get(locale);
574    
575                            if (Validator.isNull(localizedBody)) {
576                                    Locale defaultLocale = LocaleUtil.getDefault();
577    
578                                    processedBody = localizedBodyMap.get(defaultLocale);
579                            }
580                            else {
581                                    processedBody = localizedBody;
582                            }
583                    }
584                    else {
585                            processedBody = this.body;
586                    }
587    
588                    MailMessage mailMessage = new MailMessage(
589                            from, to, processedSubject, processedBody, htmlFormat);
590    
591                    if (fileAttachments != null) {
592                            for (FileAttachment fileAttachment : fileAttachments) {
593                                    mailMessage.addFileAttachment(
594                                            fileAttachment.getFile(), fileAttachment.getFileName());
595                            }
596                    }
597    
598                    if (bulk && (_bulkAddresses != null)) {
599                            mailMessage.setBulkAddresses(
600                                    _bulkAddresses.toArray(
601                                            new InternetAddress[_bulkAddresses.size()]));
602    
603                            _bulkAddresses.clear();
604                    }
605    
606                    if (inReplyTo != null) {
607                            mailMessage.setInReplyTo(inReplyTo);
608                    }
609    
610                    mailMessage.setMessageId(mailId);
611    
612                    if (replyToAddress != null) {
613                            InternetAddress replyTo = new InternetAddress(
614                                    replaceContent(replyToAddress, locale),
615                                    replaceContent(replyToAddress, locale));
616    
617                            mailMessage.setReplyTo(new InternetAddress[] {replyTo});
618                    }
619    
620                    if (smtpAccount != null) {
621                            mailMessage.setSMTPAccount(smtpAccount);
622                    }
623    
624                    processMailMessage(mailMessage, locale);
625    
626                    MailServiceUtil.sendEmail(mailMessage);
627            }
628    
629            protected String body;
630            protected boolean bulk;
631            protected long companyId;
632            protected List<FileAttachment> fileAttachments =
633                    new ArrayList<FileAttachment>();
634            protected String fromAddress;
635            protected String fromName;
636            protected long groupId;
637            protected boolean htmlFormat;
638            protected String inReplyTo;
639            protected Map<Locale, String> localizedBodyMap;
640            protected Map<Locale, String> localizedSubjectMap;
641            protected String mailId;
642            protected String portletId;
643            protected String replyToAddress;
644            protected ServiceContext serviceContext;
645            protected long scopeGroupId;
646            protected SMTPAccount smtpAccount;
647            protected String subject;
648            protected long userId;
649    
650            private static Log _log = LogFactoryUtil.getLog(SubscriptionSender.class);
651    
652            private List<InternetAddress> _bulkAddresses;
653            private ClassLoader _classLoader;
654            private Map<String, Object> _context = new HashMap<String, Object>();
655            private String _contextUserPrefix;
656            private boolean _initialized;
657            private Object[] _mailIdIds;
658            private String _mailIdPopPortletPrefix;
659            private List<ObjectValuePair<String, Long>> _persistestedSubscribersOVPs =
660                    new ArrayList<ObjectValuePair<String, Long>>();
661            private List<ObjectValuePair<String, String>> _runtimeSubscribersOVPs =
662                    new ArrayList<ObjectValuePair<String, String>>();
663            private Set<String> _sentEmailAddresses = new HashSet<String>();
664    
665    }