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.jcr.Repository;
026import javax.jcr.RepositoryException;
027import javax.jcr.Session;
028import javax.mail.MessagingException;
029
030import org.apache.avalon.framework.service.ServiceException;
031import org.apache.avalon.framework.service.ServiceManager;
032import org.apache.commons.lang.StringUtils;
033
034import org.ametys.core.group.Group;
035import org.ametys.core.group.GroupIdentity;
036import org.ametys.core.group.GroupManager;
037import org.ametys.core.ui.Callable;
038import org.ametys.core.ui.ClientSideElement;
039import org.ametys.core.user.User;
040import org.ametys.core.user.UserIdentity;
041import org.ametys.core.user.UserManager;
042import org.ametys.core.util.I18nUtils;
043import org.ametys.core.util.mail.SendMailHelper;
044import org.ametys.runtime.config.Config;
045import org.ametys.runtime.i18n.I18nizableText;
046import org.ametys.web.WebConstants;
047import org.ametys.web.repository.page.Page;
048import org.ametys.web.repository.site.Site;
049import org.ametys.web.site.SiteConfigurationExtensionPoint;
050import org.ametys.web.skin.Skin;
051import org.ametys.web.skin.SkinsManager;
052
053/**
054 * This {@link ClientSideElement} creates a button that will be enabled if page and its hierarchy is valid.
055 *
056 */
057public class LivePageClientSideElement extends AbstractPageClientSideElement
058{
059    /** The {@link UserManager} */
060    private UserManager _userManager;
061    
062    /** The {@link UserManager} for front-end users */
063    private UserManager _foUsersManager;
064    
065    /** The {@link GroupManager} for front-end groups */
066    private GroupManager _foGroupsManager;
067    
068    /** The {@link SiteConfigurationExtensionPoint} */
069    private SiteConfigurationExtensionPoint _siteConfiguration;
070    
071    /** The {@link I18nUtils} */
072    private I18nUtils _i18nUtils;
073
074    /** The {@link SkinsManager}*/
075    private SkinsManager _skinManager;
076    
077    /** The repository */
078    private Repository _repository;
079    
080    @Override
081    public void service(ServiceManager smanager) throws ServiceException
082    {
083        super.service(smanager);
084        _userManager = (UserManager) smanager.lookup(UserManager.ROLE);
085        _foUsersManager = (UserManager) smanager.lookup(UserManager.ROLE);
086        _foGroupsManager = (GroupManager) smanager.lookup(GroupManager.ROLE);
087        _siteConfiguration = (SiteConfigurationExtensionPoint) smanager.lookup(SiteConfigurationExtensionPoint.ROLE);
088        _i18nUtils = (I18nUtils) smanager.lookup(I18nUtils.ROLE);
089        _skinManager = (SkinsManager) smanager.lookup(SkinsManager.ROLE);
090        _repository = (Repository) smanager.lookup(Repository.class.getName());
091    }
092    
093    /**
094     * Get the live status of given pages
095     * @param pageIds The page id
096     * @return the result
097     */
098    @SuppressWarnings("unchecked")
099    @Callable
100    public Map<String, Object> getStatus (List<String> pageIds)
101    {
102        Map<String, Object> results = new HashMap<>();
103        
104        results.put("invalid-pages", new ArrayList<Map<String, Object>>());
105        results.put("invalid-hierarchy", new ArrayList<Map<String, Object>>());
106        results.put("allright-pages", new ArrayList<Map<String, Object>>());
107        results.put("noright-pages", new ArrayList<Map<String, Object>>());
108        
109        Session liveSession = null;
110        try
111        {
112            liveSession = _repository.login(WebConstants.LIVE_WORKSPACE);
113            
114            for (String pageId : pageIds)
115            {
116                Page page = _resolver.resolveById(pageId);
117                Skin skin = _skinManager.getSkin(page.getSite().getSkinId());
118
119                boolean error = false;
120
121                // Has right ?
122                if (!hasRight(page))
123                {
124                    Map<String, Object> pageParams = getPageDefaultParameters(page);
125                    pageParams.put("description", getNoRightPageDescription(page));
126                    
127                    List<Map<String, Object>> noRightsPages = (List<Map<String, Object>>) results.get("noright-pages");
128                    noRightsPages.add(pageParams);
129
130                    error = true;
131                }
132                
133                // Is page valid ?
134                boolean validPage = _synchronizeComponent.isPageValid(page, skin);
135                if (!validPage)
136                {
137                    Map<String, Object> pageParams = getPageDefaultParameters(page);
138                    pageParams.put("description", _getInvalidPageDescription(page));
139                    
140                    List<Map<String, Object>> invalidPages = (List<Map<String, Object>>) results.get("invalid-pages");
141                    invalidPages.add(pageParams);
142
143                    error = true;
144                }
145                // Is hierarchy valid ?
146                else if (validPage && !_synchronizeComponent.isHierarchyValid(page, liveSession))
147                {
148                    Map<String, Object> pageParams = getPageDefaultParameters(page);
149                    pageParams.put("description", _getInvalidHierarchyDescription(page));
150                    
151                    List<Map<String, Object>> invalidHierarchy = (List<Map<String, Object>>) results.get("invalid-hierarchy");
152                    invalidHierarchy.add(pageParams);
153
154                    error = true;
155                }
156
157                // All right
158                if (!error)
159                {
160                    Map<String, Object> pageParams = getPageDefaultParameters(page);
161                    pageParams.put("description", getAllRightPageDescription(page));
162
163                    List<Map<String, Object>> allrightPages = (List<Map<String, Object>>) results.get("allright-pages");
164                    allrightPages.add(pageParams);
165                }
166               
167            }
168            
169            return results;
170        }
171        catch (RepositoryException e)
172        {
173            throw new RuntimeException("Unable to check live workspace", e);
174        }
175        finally
176        {
177            if (liveSession != null)
178            {
179                liveSession.logout();
180            }
181        }
182        
183    }
184    
185    /**
186     * Send a notification for online pages.
187     * @param pageIds the ids of the pages
188     * @param users the users that will be notified
189     * @param groups the groups that will be notified
190     * @param comment the comment of the notifier 
191     * @return true 
192     */
193    @Callable
194    public boolean sendOnlineNotification(List<String> pageIds, List<Map<String, String>> users, List<Map<String, String>> groups, String comment)
195    { 
196        UserIdentity userIdentity = _currentUserProvider.getUser();
197        User notifier = _userManager.getUser(userIdentity.getPopulationId(), userIdentity.getLogin());
198        
199        List<UserIdentity> userIdentities = new ArrayList<>();
200        for (Map<String, String> user : users)
201        {
202            String login = user.get("login");
203            String populationId = user.get("populationId");
204            userIdentities.add(new UserIdentity(login, populationId));
205        }
206        List<GroupIdentity> groupIdentities = new ArrayList<>();
207        for (Map<String, String> group : groups)
208        {
209            String id = group.get("groupId");
210            String groupDirectory = group.get("groupDirectory");
211            groupIdentities.add(new GroupIdentity(id, groupDirectory));
212        }
213        Set<User> distinctUsers = _getDistinctUsers (userIdentities, groupIdentities);
214        
215        for (String pageId : pageIds)
216        {
217            Page page = _resolver.resolveById(pageId);
218            
219            String from = _getSender(notifier, page);
220            String subject = _getSubject (notifier, page);
221            
222            for (User user : distinctUsers)
223            {
224                if (StringUtils.isNotEmpty(user.getEmail()))
225                {
226                    try
227                    {
228                        String body = _getBody(notifier, user, page, comment);
229                        SendMailHelper.sendMail(subject, null, body, user.getEmail(), from);
230                    }
231                    catch (MessagingException e) 
232                    {
233                        getLogger().error("Unable to send mail to user " + user.getEmail(), e);
234                    }
235                }
236            }
237        }
238        
239        return true;
240    }
241    
242    /**
243     * Get i18n description for invalid page
244     * @param page The page
245     * @return The {@link I18nizableText} description
246     */
247    private I18nizableText _getInvalidPageDescription (Page page)
248    {
249        List<String> i18nParameters = new ArrayList<>();
250        i18nParameters.add(page.getTitle());
251        
252        I18nizableText ed = (I18nizableText) this._script.getParameters().get("invalid-page-description");
253        return  new I18nizableText(ed.getCatalogue(), ed.getKey(), i18nParameters);
254    }
255    
256    /**
257     * Get i18n description for invalid hierarchy
258     * @param page The page
259     * @return The {@link I18nizableText} description
260     */
261    private I18nizableText _getInvalidHierarchyDescription (Page page)
262    {
263        List<String> i18nParameters = new ArrayList<>();
264        i18nParameters.add(page.getTitle());
265        
266        I18nizableText ed = (I18nizableText) this._script.getParameters().get("invalid-hierarchy-description");
267        return  new I18nizableText(ed.getCatalogue(), ed.getKey(), i18nParameters);
268    }
269    
270    /**
271     * Get the email sender
272     * @param sender The user responsible for the action
273     * @param page The published page
274     * @return The sender
275     */
276    private String _getSender (User sender, Page page)
277    {
278        if (sender != null && sender.getEmail() != null)
279        {
280            return sender.getFullName() + " <" + sender.getEmail() + ">";
281        }
282        
283        String from = _siteConfiguration.getValueAsString(page.getSiteName(), "site-mail-from");
284        if (StringUtils.isBlank(from))
285        {
286            from = Config.getInstance().getValueAsString("smtp.mail.from");
287        }
288        return from;
289    }
290    
291    /**
292     * Get the email subject
293     * @param sender The user responsible for the notification
294     * @param page The published page
295     * @return The email subject
296     */
297    private String _getSubject (User sender, Page page)
298    {
299        Site site = page.getSite();
300        
301        Map<String, I18nizableText> subjectI18nParameters = new HashMap<>();
302        subjectI18nParameters.put("user", new I18nizableText(sender.getFullName()));
303        subjectI18nParameters.put("siteTitle", new I18nizableText(site.getTitle()));
304        subjectI18nParameters.put("pageTitle", new I18nizableText(page.getTitle()));
305        
306        I18nizableText msg = new I18nizableText("plugin.web", "PLUGINS_WEB_PAGE_NOTIFY_ONLINE_PUBLICATION_MAIL_SUBJECT", subjectI18nParameters);
307        
308        return _i18nUtils.translate(msg, page.getSitemapName());
309    }
310    
311    /**
312     * Get the email body
313     * @param sender The user responsible for the notification
314     * @param user The recipient of the notification
315     * @param page The published page
316     * @param comment The user's comment. Can be empty or null.
317     * @return The email body
318     */
319    private String _getBody (User sender, User user, Page page, String comment)
320    {
321        Site site = page.getSite();
322        
323        Map<String, I18nizableText> bodyI18nParameters = new HashMap<>();
324        bodyI18nParameters.put("sender", new I18nizableText(sender.getFullName()));
325        bodyI18nParameters.put("user", new I18nizableText(user.getFullName()));
326        bodyI18nParameters.put("siteTitle", new I18nizableText(site.getTitle()));
327        bodyI18nParameters.put("siteUrl", new I18nizableText(site.getUrl()));
328        bodyI18nParameters.put("pageTitle", new I18nizableText(page.getTitle()));
329        bodyI18nParameters.put("pageUrl", new I18nizableText(site.getUrl() + "/" + page.getSitemap().getName() + "/" + page.getPathInSitemap() + ".html"));
330
331        I18nizableText msg = null;
332        if (StringUtils.isNotEmpty(comment))
333        {
334            bodyI18nParameters.put("comment", new I18nizableText(comment));
335            msg = new I18nizableText("plugin.web", "PLUGINS_WEB_PAGE_NOTIFY_ONLINE_PUBLICATION_MAIL_BODY_WITH_COMMENT", bodyI18nParameters);
336        }
337        else
338        {
339            msg = new I18nizableText("plugin.web", "PLUGINS_WEB_PAGE_NOTIFY_ONLINE_PUBLICATION_MAIL_BODY", bodyI18nParameters);
340        }
341        
342        return _i18nUtils.translate(msg, page.getSitemapName());
343    }
344    
345    private Set<User> _getDistinctUsers (List<UserIdentity> userIdentities, List<GroupIdentity> groupIdentities)
346    {
347        Set<User> users = new HashSet<>();
348        
349        for (UserIdentity userIdentity : userIdentities)
350        {
351            if (userIdentity != null && StringUtils.isNotEmpty(userIdentity.getLogin()) && StringUtils.isNotEmpty(userIdentity.getPopulationId()))
352            {
353                User user = _foUsersManager.getUser(userIdentity.getPopulationId(), userIdentity.getLogin());
354                if (user != null)
355                {
356                    users.add(user);
357                }
358            }
359        }
360        
361        for (GroupIdentity groupIdentity : groupIdentities)
362        {
363            if (groupIdentity != null && StringUtils.isNotEmpty(groupIdentity.getId()) && StringUtils.isNotEmpty(groupIdentity.getDirectoryId()))
364            {
365                Group group = _foGroupsManager.getGroup(groupIdentity.getDirectoryId(), groupIdentity.getId());
366                if (group != null)
367                {
368                    Set<UserIdentity> groupUsers = group.getUsers();
369                    for (UserIdentity userIdentity : groupUsers)
370                    {
371                        User user = _foUsersManager.getUser(userIdentity.getPopulationId(), userIdentity.getLogin());
372                        if (user != null)
373                        {
374                            users.add(user);
375                        }
376                    }
377                }
378            }
379        }
380        
381        return users;
382    }
383}