001/*
002 *  Copyright 2015 Anyware Services
003 *
004 *  Licensed under the Apache License, Version 2.0 (the "License");
005 *  you may not use this file except in compliance with the License.
006 *  You may obtain a copy of the License at
007 *
008 *      http://www.apache.org/licenses/LICENSE-2.0
009 *
010 *  Unless required by applicable law or agreed to in writing, software
011 *  distributed under the License is distributed on an "AS IS" BASIS,
012 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 *  See the License for the specific language governing permissions and
014 *  limitations under the License.
015 */
016package org.ametys.web.clientsideelement;
017
018import java.util.ArrayList;
019import java.util.HashMap;
020import java.util.HashSet;
021import java.util.List;
022import java.util.Map;
023import java.util.Set;
024
025import javax.mail.MessagingException;
026
027import org.apache.avalon.framework.service.ServiceException;
028import org.apache.avalon.framework.service.ServiceManager;
029import org.apache.commons.lang.StringUtils;
030
031import org.ametys.core.group.Group;
032import org.ametys.core.group.GroupIdentity;
033import org.ametys.core.group.GroupManager;
034import org.ametys.core.ui.Callable;
035import org.ametys.core.ui.ClientSideElement;
036import org.ametys.core.user.User;
037import org.ametys.core.user.UserIdentity;
038import org.ametys.core.user.UserManager;
039import org.ametys.core.util.I18nUtils;
040import org.ametys.core.util.mail.SendMailHelper;
041import org.ametys.plugins.core.user.UserHelper;
042import org.ametys.runtime.config.Config;
043import org.ametys.runtime.i18n.I18nizableText;
044import org.ametys.web.repository.page.Page;
045import org.ametys.web.repository.site.Site;
046
047/**
048 * This {@link ClientSideElement} creates a button that will be enabled if page and its hierarchy is valid.
049 *
050 */
051public class LivePageClientSideElement extends AbstractPageClientSideElement
052{
053    /** The {@link UserManager} */
054    private UserManager _userManager;
055    
056    /** The {@link UserManager} for front-end users */
057    private UserManager _foUsersManager;
058    
059    /** The {@link GroupManager} for front-end groups */
060    private GroupManager _foGroupsManager;
061    
062    /** The {@link I18nUtils} */
063    private I18nUtils _i18nUtils;
064    
065    private UserHelper _userHelper;
066    
067    @Override
068    public void service(ServiceManager smanager) throws ServiceException
069    {
070        super.service(smanager);
071        _userManager = (UserManager) smanager.lookup(UserManager.ROLE);
072        _foUsersManager = (UserManager) smanager.lookup(UserManager.ROLE);
073        _foGroupsManager = (GroupManager) smanager.lookup(GroupManager.ROLE);
074        _i18nUtils = (I18nUtils) smanager.lookup(I18nUtils.ROLE);
075        _userHelper = (UserHelper) smanager.lookup(UserHelper.ROLE);
076    }
077    
078    /**
079     * Send a notification for online pages.
080     * @param pageIds the ids of the pages
081     * @param users the users that will be notified
082     * @param groups the groups that will be notified
083     * @param comment the comment of the notifier 
084     * @return true 
085     */
086    @Callable
087    public boolean sendOnlineNotification(List<String> pageIds, List<Map<String, String>> users, List<Map<String, String>> groups, String comment)
088    { 
089        UserIdentity userIdentity = _currentUserProvider.getUser();
090        User notifier = _userManager.getUser(userIdentity.getPopulationId(), userIdentity.getLogin());
091        
092        List<UserIdentity> userIdentities = new ArrayList<>();
093        for (Map<String, String> user : users)
094        {
095            UserIdentity ui = _userHelper.json2userIdentity(user);
096            if (ui != null)
097            {
098                userIdentities.add(ui);
099            }
100        }
101        List<GroupIdentity> groupIdentities = new ArrayList<>();
102        for (Map<String, String> group : groups)
103        {
104            String id = group.get("groupId");
105            String groupDirectory = group.get("groupDirectory");
106            groupIdentities.add(new GroupIdentity(id, groupDirectory));
107        }
108        Set<User> distinctUsers = _getDistinctUsers (userIdentities, groupIdentities);
109        
110        for (String pageId : pageIds)
111        {
112            Page page = _resolver.resolveById(pageId);
113            
114            String from = _getSender(notifier, page);
115            String subject = _getSubject (notifier, page);
116            
117            for (User user : distinctUsers)
118            {
119                if (StringUtils.isNotEmpty(user.getEmail()))
120                {
121                    try
122                    {
123                        String body = _getBody(notifier, user, page, comment);
124                        SendMailHelper.sendMail(subject, null, body, user.getEmail(), from);
125                    }
126                    catch (MessagingException e) 
127                    {
128                        getLogger().error("Unable to send mail to user " + user.getEmail(), e);
129                    }
130                }
131            }
132        }
133        
134        return true;
135    }
136
137    /**
138     * Get the email sender
139     * @param sender The user responsible for the action
140     * @param page The published page
141     * @return The sender
142     */
143    private String _getSender (User sender, Page page)
144    {
145        if (sender != null && sender.getEmail() != null)
146        {
147            return sender.getFullName() + " <" + sender.getEmail() + ">";
148        }
149        
150        Site site = page.getSite();
151        String defaultFromValue = Config.getInstance().getValue("smtp.mail.from");
152        return site.getValue("site-mail-from", false, defaultFromValue);
153    }
154    
155    /**
156     * Get the email subject
157     * @param sender The user responsible for the notification
158     * @param page The published page
159     * @return The email subject
160     */
161    private String _getSubject (User sender, Page page)
162    {
163        Site site = page.getSite();
164        
165        Map<String, I18nizableText> subjectI18nParameters = new HashMap<>();
166        subjectI18nParameters.put("user", new I18nizableText(sender.getFullName()));
167        subjectI18nParameters.put("siteTitle", new I18nizableText(site.getTitle()));
168        subjectI18nParameters.put("pageTitle", new I18nizableText(page.getTitle()));
169        
170        I18nizableText msg = new I18nizableText("plugin.web", "PLUGINS_WEB_PAGE_NOTIFY_ONLINE_PUBLICATION_MAIL_SUBJECT", subjectI18nParameters);
171        
172        return _i18nUtils.translate(msg, page.getSitemapName());
173    }
174    
175    /**
176     * Get the email body
177     * @param sender The user responsible for the notification
178     * @param user The recipient of the notification
179     * @param page The published page
180     * @param comment The user's comment. Can be empty or null.
181     * @return The email body
182     */
183    private String _getBody (User sender, User user, Page page, String comment)
184    {
185        Site site = page.getSite();
186        
187        Map<String, I18nizableText> bodyI18nParameters = new HashMap<>();
188        bodyI18nParameters.put("sender", new I18nizableText(sender.getFullName()));
189        bodyI18nParameters.put("user", new I18nizableText(user.getFullName()));
190        bodyI18nParameters.put("siteTitle", new I18nizableText(site.getTitle()));
191        bodyI18nParameters.put("siteUrl", new I18nizableText(site.getUrl()));
192        bodyI18nParameters.put("pageTitle", new I18nizableText(page.getTitle()));
193        bodyI18nParameters.put("pageUrl", new I18nizableText(site.getUrl() + "/" + page.getSitemap().getName() + "/" + page.getPathInSitemap() + ".html"));
194
195        I18nizableText msg = null;
196        if (StringUtils.isNotEmpty(comment))
197        {
198            bodyI18nParameters.put("comment", new I18nizableText(comment));
199            msg = new I18nizableText("plugin.web", "PLUGINS_WEB_PAGE_NOTIFY_ONLINE_PUBLICATION_MAIL_BODY_WITH_COMMENT", bodyI18nParameters);
200        }
201        else
202        {
203            msg = new I18nizableText("plugin.web", "PLUGINS_WEB_PAGE_NOTIFY_ONLINE_PUBLICATION_MAIL_BODY", bodyI18nParameters);
204        }
205        
206        return _i18nUtils.translate(msg, page.getSitemapName());
207    }
208    
209    private Set<User> _getDistinctUsers (List<UserIdentity> userIdentities, List<GroupIdentity> groupIdentities)
210    {
211        Set<User> users = new HashSet<>();
212        
213        for (UserIdentity userIdentity : userIdentities)
214        {
215            if (userIdentity != null && StringUtils.isNotEmpty(userIdentity.getLogin()) && StringUtils.isNotEmpty(userIdentity.getPopulationId()))
216            {
217                User user = _foUsersManager.getUser(userIdentity.getPopulationId(), userIdentity.getLogin());
218                if (user != null)
219                {
220                    users.add(user);
221                }
222            }
223        }
224        
225        for (GroupIdentity groupIdentity : groupIdentities)
226        {
227            if (groupIdentity != null && StringUtils.isNotEmpty(groupIdentity.getId()) && StringUtils.isNotEmpty(groupIdentity.getDirectoryId()))
228            {
229                Group group = _foGroupsManager.getGroup(groupIdentity.getDirectoryId(), groupIdentity.getId());
230                if (group != null)
231                {
232                    Set<UserIdentity> groupUsers = group.getUsers();
233                    for (UserIdentity userIdentity : groupUsers)
234                    {
235                        User user = _foUsersManager.getUser(userIdentity.getPopulationId(), userIdentity.getLogin());
236                        if (user != null)
237                        {
238                            users.add(user);
239                        }
240                    }
241                }
242            }
243        }
244        
245        return users;
246    }
247}