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.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 String getMailId() {
201                    return this.mailId;
202            }
203    
204            public void initialize() throws Exception {
205                    if (_initialized) {
206                            return;
207                    }
208    
209                    _initialized = true;
210    
211                    Company company = CompanyLocalServiceUtil.getCompany(companyId);
212    
213                    setContextAttribute("[$COMPANY_ID$]", company.getCompanyId());
214                    setContextAttribute("[$COMPANY_MX$]", company.getMx());
215                    setContextAttribute("[$COMPANY_NAME$]", company.getName());
216                    setContextAttribute("[$PORTAL_URL$]", getPortalURL(company));
217    
218                    if (groupId > 0) {
219                            Group group = GroupLocalServiceUtil.getGroup(groupId);
220    
221                            setContextAttribute("[$SITE_NAME$]", group.getDescriptiveName());
222                    }
223    
224                    if ((userId > 0) && Validator.isNotNull(_contextUserPrefix)) {
225                            setContextAttribute(
226                                    "[$" + _contextUserPrefix + "_USER_ADDRESS$]",
227                                    HtmlUtil.escape(PortalUtil.getUserEmailAddress(userId)));
228                            setContextAttribute(
229                                    "[$" + _contextUserPrefix + "_USER_NAME$]",
230                                    HtmlUtil.escape(
231                                            PortalUtil.getUserName(userId, StringPool.BLANK)));
232                    }
233    
234                    mailId = PortalUtil.getMailId(
235                            company.getMx(), _mailIdPopPortletPrefix, _mailIdIds);
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);
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$]", "[$FROM_NAME$]", "[$TO_ADDRESS$]",
475                                    "[$TO_NAME$]"
476                            },
477                            new String[] {
478                                    from.getAddress(),
479                                    GetterUtil.getString(from.getPersonal(), from.getAddress()),
480                                    HtmlUtil.escape(to.getAddress()),
481                                    HtmlUtil.escape(
482                                            GetterUtil.getString(to.getPersonal(), to.getAddress()))
483                            });
484    
485                    processedSubject = replaceContent(processedSubject, locale);
486    
487                    mailMessage.setSubject(processedSubject);
488    
489                    String processedBody = StringUtil.replace(
490                            mailMessage.getBody(),
491                            new String[] {
492                                    "[$FROM_ADDRESS$]", "[$FROM_NAME$]", "[$TO_ADDRESS$]",
493                                    "[$TO_NAME$]"
494                            },
495                            new String[] {
496                                    from.getAddress(),
497                                    GetterUtil.getString(from.getPersonal(), from.getAddress()),
498                                    HtmlUtil.escape(to.getAddress()),
499                                    HtmlUtil.escape(
500                                            GetterUtil.getString(to.getPersonal(), to.getAddress()))
501                            });
502    
503                    processedBody = replaceContent(processedBody, locale);
504    
505                    mailMessage.setBody(processedBody);
506            }
507    
508            protected String replaceContent(String content, Locale locale)
509                    throws Exception {
510    
511                    for (Map.Entry<String, Object> entry : _context.entrySet()) {
512                            String key = entry.getKey();
513                            Object value = entry.getValue();
514    
515                            content = StringUtil.replace(content, key, String.valueOf(value));
516                    }
517    
518                    if (Validator.isNotNull(portletId)) {
519                            String portletName = PortalUtil.getPortletTitle(portletId, locale);
520    
521                            content = StringUtil.replace(
522                                    content, "[$PORTLET_NAME$]", portletName);
523                    }
524    
525                    Company company = CompanyLocalServiceUtil.getCompany(companyId);
526    
527                    content = StringUtil.replace(
528                            content,
529                            new String[] {
530                                    "href=\"/",
531                                    "src=\"/"
532                            },
533                            new String[] {
534                                    "href=\"" + getPortalURL(company) + "/",
535                                    "src=\"" + getPortalURL(company) + "/"
536                            });
537    
538                    return content;
539            }
540    
541            protected void sendEmail(InternetAddress to, Locale locale)
542                    throws Exception {
543    
544                    InternetAddress from = new InternetAddress(
545                            replaceContent(fromAddress, locale),
546                            replaceContent(fromName, locale));
547    
548                    String processedSubject = null;
549    
550                    if (localizedSubjectMap != null) {
551                            String localizedSubject = localizedSubjectMap.get(locale);
552    
553                            if (Validator.isNull(localizedSubject)) {
554                                    Locale defaultLocale = LocaleUtil.getDefault();
555    
556                                    processedSubject = localizedSubjectMap.get(defaultLocale);
557                            }
558                            else {
559                                    processedSubject = localizedSubject;
560                            }
561                    }
562                    else {
563                            processedSubject = this.subject;
564                    }
565    
566                    String processedBody = null;
567    
568                    if (localizedBodyMap != null) {
569                            String localizedBody = localizedBodyMap.get(locale);
570    
571                            if (Validator.isNull(localizedBody)) {
572                                    Locale defaultLocale = LocaleUtil.getDefault();
573    
574                                    processedBody = localizedBodyMap.get(defaultLocale);
575                            }
576                            else {
577                                    processedBody = localizedBody;
578                            }
579                    }
580                    else {
581                            processedBody = this.body;
582                    }
583    
584                    MailMessage mailMessage = new MailMessage(
585                            from, to, processedSubject, processedBody, htmlFormat);
586    
587                    if (fileAttachments != null) {
588                            for (FileAttachment fileAttachment : fileAttachments) {
589                                    mailMessage.addFileAttachment(
590                                            fileAttachment.getFile(), fileAttachment.getFileName());
591                            }
592                    }
593    
594                    if (bulk && (_bulkAddresses != null)) {
595                            mailMessage.setBulkAddresses(
596                                    _bulkAddresses.toArray(
597                                            new InternetAddress[_bulkAddresses.size()]));
598    
599                            _bulkAddresses.clear();
600                    }
601    
602                    if (inReplyTo != null) {
603                            mailMessage.setInReplyTo(inReplyTo);
604                    }
605    
606                    mailMessage.setMessageId(mailId);
607    
608                    if (replyToAddress != null) {
609                            InternetAddress replyTo = new InternetAddress(
610                                    replaceContent(replyToAddress, locale),
611                                    replaceContent(replyToAddress, locale));
612    
613                            mailMessage.setReplyTo(new InternetAddress[] {replyTo});
614                    }
615    
616                    if (smtpAccount != null) {
617                            mailMessage.setSMTPAccount(smtpAccount);
618                    }
619    
620                    processMailMessage(mailMessage, locale);
621    
622                    MailServiceUtil.sendEmail(mailMessage);
623            }
624    
625            protected String body;
626            protected boolean bulk;
627            protected long companyId;
628            protected List<FileAttachment> fileAttachments =
629                    new ArrayList<FileAttachment>();
630            protected String fromAddress;
631            protected String fromName;
632            protected long groupId;
633            protected boolean htmlFormat;
634            protected String inReplyTo;
635            protected Map<Locale, String> localizedBodyMap;
636            protected Map<Locale, String> localizedSubjectMap;
637            protected String mailId;
638            protected String portletId;
639            protected String replyToAddress;
640            protected long scopeGroupId;
641            protected ServiceContext serviceContext;
642            protected SMTPAccount smtpAccount;
643            protected String subject;
644            protected long userId;
645    
646            private static Log _log = LogFactoryUtil.getLog(SubscriptionSender.class);
647    
648            private List<InternetAddress> _bulkAddresses;
649            private ClassLoader _classLoader;
650            private Map<String, Object> _context = new HashMap<String, Object>();
651            private String _contextUserPrefix;
652            private boolean _initialized;
653            private Object[] _mailIdIds;
654            private String _mailIdPopPortletPrefix;
655            private List<ObjectValuePair<String, Long>> _persistestedSubscribersOVPs =
656                    new ArrayList<ObjectValuePair<String, Long>>();
657            private List<ObjectValuePair<String, String>> _runtimeSubscribersOVPs =
658                    new ArrayList<ObjectValuePair<String, String>>();
659            private Set<String> _sentEmailAddresses = new HashSet<String>();
660    
661    }