001/*
002 *  Copyright 2018 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.plugins.workspaces.wall;
017
018import java.io.IOException;
019import java.io.InputStream;
020import java.util.Collections;
021import java.util.HashMap;
022import java.util.List;
023import java.util.Map;
024import java.util.Set;
025import java.util.concurrent.ExecutionException;
026import java.util.stream.Collectors;
027
028import javax.jcr.RepositoryException;
029
030import org.apache.avalon.framework.component.Component;
031import org.apache.avalon.framework.service.ServiceException;
032import org.apache.avalon.framework.service.ServiceManager;
033import org.apache.avalon.framework.service.Serviceable;
034import org.apache.cocoon.servlet.multipart.Part;
035import org.apache.commons.lang3.StringUtils;
036import org.apache.commons.lang3.tuple.Pair;
037import org.apache.excalibur.xml.sax.SAXParser;
038import org.apache.solr.client.solrj.SolrServerException;
039import org.xml.sax.InputSource;
040
041import org.ametys.cms.ObservationConstants;
042import org.ametys.cms.content.RichTextHandler;
043import org.ametys.cms.content.indexing.solr.SolrIndexer;
044import org.ametys.cms.contenttype.ContentType;
045import org.ametys.cms.contenttype.ContentTypeExtensionPoint;
046import org.ametys.cms.data.Binary;
047import org.ametys.cms.data.RichText;
048import org.ametys.cms.data.type.ResourceElementTypeHelper;
049import org.ametys.cms.indexing.IndexingObserver;
050import org.ametys.cms.repository.Content;
051import org.ametys.cms.repository.ContentDAO;
052import org.ametys.cms.repository.ContentDAO.TagMode;
053import org.ametys.cms.repository.comment.ui.CommentsAndReportsTreeComponent;
054import org.ametys.cms.rights.ContentRightAssignmentContext;
055import org.ametys.core.observation.Event;
056import org.ametys.core.observation.ObservationManager;
057import org.ametys.core.observation.ObservationManager.ObserverFuture;
058import org.ametys.core.right.RightManager;
059import org.ametys.core.ui.Callable;
060import org.ametys.core.ui.mail.StandardMailBodyHelper;
061import org.ametys.core.ui.mail.StandardMailBodyHelper.MailBodyBuilder;
062import org.ametys.core.upload.Upload;
063import org.ametys.core.upload.UploadManager;
064import org.ametys.core.user.CurrentUserProvider;
065import org.ametys.core.user.User;
066import org.ametys.core.user.UserIdentity;
067import org.ametys.core.user.UserManager;
068import org.ametys.core.util.I18nUtils;
069import org.ametys.core.util.language.UserLanguagesManager;
070import org.ametys.core.util.mail.SendMailHelper;
071import org.ametys.plugins.explorer.resources.ResourceCollection;
072import org.ametys.plugins.repository.AmetysObjectResolver;
073import org.ametys.plugins.repository.AmetysRepositoryException;
074import org.ametys.plugins.workspaces.WorkspacesConstants;
075import org.ametys.plugins.workspaces.WorkspacesHelper;
076import org.ametys.plugins.workspaces.project.ProjectManager;
077import org.ametys.plugins.workspaces.project.modules.WorkspaceModule;
078import org.ametys.plugins.workspaces.project.modules.WorkspaceModuleExtensionPoint;
079import org.ametys.plugins.workspaces.project.objects.Project;
080import org.ametys.plugins.workspaces.project.rights.ProjectRightHelper;
081import org.ametys.runtime.authentication.AccessDeniedException;
082import org.ametys.runtime.config.Config;
083import org.ametys.runtime.i18n.I18nizableText;
084import org.ametys.runtime.i18n.I18nizableTextParameter;
085import org.ametys.runtime.plugin.component.AbstractLogEnabled;
086import org.ametys.web.content.FOContentCreationHelper;
087import org.ametys.web.repository.site.Site;
088import org.ametys.web.repository.site.SiteManager;
089
090import com.opensymphony.workflow.WorkflowException;
091
092import jakarta.mail.MessagingException;
093
094/**
095 * Helper for wall contents
096 *
097 */
098public class WallContentManager extends AbstractLogEnabled implements Component, Serviceable
099{
100    /** The Avalon role */
101    public static final String ROLE = WallContentManager.class.getName();
102    /** The tag for pin */
103    public static final String WALL_CONTENT_PIN_TAG = "WORKSPACES_CONTENT_PINNED";
104    
105    private static final int __INITIAL_WORKFLOW_ACTION_ID = 1111;
106    private static final String __WORKFLOW_NAME = "wall-content";
107    
108    private FOContentCreationHelper _foContentHelper;
109    private ContentTypeExtensionPoint _cTypeEP;
110    private I18nUtils _i18nUtils;
111    private ContentDAO _contentDAO;
112    private ObservationManager _observationManager;
113    private RightManager _rightManager;
114    private AmetysObjectResolver _resolver;
115    private UserManager _userManager;
116    private CurrentUserProvider _currentUserProvider;
117    private ProjectManager _projectManager;
118    private SiteManager _siteManager;
119    private ServiceManager _smanager;
120    private UploadManager _uploadManager;
121    private SolrIndexer _solrIndexer;
122    private WorkspaceModuleExtensionPoint _moduleEP;
123    private CommentsAndReportsTreeComponent _commentAndReportCmp;
124    private ProjectRightHelper _projectRightHelper;
125    private UserLanguagesManager _userLanguagesManager;
126    private WorkspacesHelper _workspaceHelper;
127    
128    public void service(ServiceManager manager) throws ServiceException
129    {
130        _smanager = manager;
131        _foContentHelper = (FOContentCreationHelper) manager.lookup(FOContentCreationHelper.ROLE);
132        _cTypeEP = (ContentTypeExtensionPoint) manager.lookup(ContentTypeExtensionPoint.ROLE);
133        _i18nUtils = (I18nUtils) manager.lookup(I18nUtils.ROLE);
134        _contentDAO = (ContentDAO) manager.lookup(ContentDAO.ROLE);
135        _observationManager = (ObservationManager) manager.lookup(ObservationManager.ROLE);
136        _rightManager = (RightManager) manager.lookup(RightManager.ROLE);
137        _resolver = (AmetysObjectResolver) manager.lookup(AmetysObjectResolver.ROLE);
138        _userManager = (UserManager) manager.lookup(UserManager.ROLE);
139        _currentUserProvider = (CurrentUserProvider) manager.lookup(CurrentUserProvider.ROLE);
140        _projectManager = (ProjectManager) manager.lookup(ProjectManager.ROLE);
141        _siteManager = (SiteManager) manager.lookup(SiteManager.ROLE);
142        _uploadManager = (UploadManager) manager.lookup(UploadManager.ROLE);
143        _solrIndexer = (SolrIndexer) manager.lookup(SolrIndexer.ROLE);
144        _moduleEP = (WorkspaceModuleExtensionPoint) manager.lookup(WorkspaceModuleExtensionPoint.ROLE);
145        _commentAndReportCmp = (CommentsAndReportsTreeComponent) manager.lookup(CommentsAndReportsTreeComponent.ROLE);
146        _projectRightHelper = (ProjectRightHelper) manager.lookup(ProjectRightHelper.ROLE);
147        _userLanguagesManager = (UserLanguagesManager) manager.lookup(UserLanguagesManager.ROLE);
148        _workspaceHelper = (WorkspacesHelper) manager.lookup(WorkspacesHelper.ROLE);
149    }
150    
151    /**
152     * Create and publish a new wall content
153     * @param text the text
154     * @param part the file part for illustration. Can be null.
155     * @param siteName the site name
156     * @param lang the language
157     * @return the results
158     */
159    @Callable(rights = Callable.CHECKED_BY_IMPLEMENTATION)
160    public Map<String, Object> publishContent(String text, Part part, String siteName, String lang)
161    {
162        Map<String, Object> results = new HashMap<>();
163
164        try
165        {
166            if (!_projectRightHelper.hasReadAccess())
167            {
168                throw new AccessDeniedException("User '" + _currentUserProvider.getUser() + "' tried to publish wall content on non authorized project");
169            }
170            
171            ContentType cType = _cTypeEP.getExtension(WorkspacesConstants.WALL_CONTENT_CONTENT_TYPE_ID);
172            
173            String contentTitle = _i18nUtils.translate(cType.getDefaultTitle(), lang);
174            
175            Map<String, Object> userValues = new HashMap<>();
176            userValues.put(Content.ATTRIBUTE_TITLE, contentTitle);
177            userValues.put("content", text);
178            userValues.put("comment", true); // active comments
179            
180            if (part != null)
181            {
182                try (InputStream is = part.getInputStream())
183                {
184                    Upload upload = _uploadManager.storeUpload(_currentUserProvider.getUser(), part.getFileName(), is);
185                    Binary fileValue = ResourceElementTypeHelper.binaryFromUpload(upload);
186                    
187                    userValues.put("illustration", Map.of("image", fileValue));
188                }
189                catch (IOException e)
190                {
191                    getLogger().error("Failed to store uploaded wall content illustration", e);
192                }
193            }
194            
195            try
196            {
197                results = _foContentHelper.createAndEditContent(__INITIAL_WORKFLOW_ACTION_ID, WorkspacesConstants.WALL_CONTENT_CONTENT_TYPE_ID, siteName, contentTitle, contentTitle, lang, userValues, __WORKFLOW_NAME, null);
198                
199                Content content = (Content) results.get(Content.class.getName());
200                _notifyContentCreation(content);
201                
202                // remove Content from result
203                results.remove(Content.class.getName());
204                
205                results.put("success", true);
206            }
207            finally
208            {
209                _commitAllChanges();
210            }
211        }
212        catch (AmetysRepositoryException | WorkflowException e)
213        {
214            results.put("success", false);
215            getLogger().error("Failed to create wall content for site {} and language {}", siteName, lang, e);
216        }
217        return results;
218    }
219    
220    /**
221     * Commit all changes in solr
222     */
223    protected void _commitAllChanges()
224    {
225        // Before trying to commit, be sure all the async observers of the current request are finished
226        List<ObserverFuture> futuresForRequest = _observationManager.getFuturesForRequest();
227        for (ObserverFuture observerFuture : futuresForRequest)
228        {
229            if (observerFuture.traits().contains(IndexingObserver.INDEXING_OBSERVER))
230            {
231                try
232                {
233                    observerFuture.future().get();
234                }
235                catch (ExecutionException | InterruptedException e)
236                {
237                    getLogger().info("An exception occured when calling #get() on Future result of an observer." , e);
238                }
239            }
240        }
241        
242        // Force commit all uncommited changes
243        try
244        {
245            _solrIndexer.commit();
246        }
247        catch (IOException | SolrServerException e)
248        {
249            getLogger().error("Impossible to commit changes", e);
250        }
251    }
252    
253    private void _notifyContentCreation(Content content)
254    {
255        Map<String, Object> eventParams = new HashMap<>();
256        eventParams.put(ObservationConstants.ARGS_CONTENT, content);
257        eventParams.put(ObservationConstants.ARGS_CONTENT_ID, content.getId());
258        
259        _observationManager.notify(new Event(org.ametys.plugins.workspaces.ObservationConstants.EVENT_WALLCONTENT_ADDED, content.getCreator(), eventParams));
260    }
261    
262    /**
263     * Pin a wall content
264     * @param contentId the content id
265     * @param contextualParameters the contextual parameters
266     * @return the result
267     */
268    @Callable (rights = Callable.CHECKED_BY_IMPLEMENTATION)
269    public Map<String, Object> pinContent(String contentId, Map<String, Object> contextualParameters)
270    {
271        if (!_projectRightHelper.hasRightOnModule("Plugins_Workspaces_Right_Pin_WallContent", WallContentModule.WALLCONTENT_MODULE_ID))
272        {
273            throw new AccessDeniedException("User '" + _currentUserProvider.getUser() + "' tried to pin content '" + contentId + "' without convenient right.");
274        }
275        
276        return _pinOrUnpinContent(contentId, contextualParameters, TagMode.INSERT);
277    }
278    
279    /**
280     * Unpin a wall content
281     * @param contentId the content id
282     * @param contextualParameters the contextual parameters
283     * @return the result
284     */
285    @Callable (rights = Callable.CHECKED_BY_IMPLEMENTATION)
286    public Map<String, Object> unpinContent(String contentId, Map<String, Object> contextualParameters)
287    {
288        if (!_projectRightHelper.hasRightOnModule("Plugins_Workspaces_Right_Pin_WallContent", WallContentModule.WALLCONTENT_MODULE_ID))
289        {
290            throw new AccessDeniedException("User '" + _currentUserProvider.getUser() + "' tried to unpin content '" + contentId + "' without convenient right.");
291        }
292        
293        return _pinOrUnpinContent(contentId, contextualParameters, TagMode.REMOVE);
294    }
295    
296    private Map<String, Object> _pinOrUnpinContent(String contentId,  Map<String, Object> contextualParameters, TagMode mode)
297    {
298        try
299        {
300            Map<String, Object> result = _contentDAO.tag(Collections.singletonList(contentId), Collections.singletonList(WALL_CONTENT_PIN_TAG), mode, contextualParameters, true);
301            return result;
302        }
303        finally
304        {
305            _commitAllChanges();
306        }
307    }
308    
309    /**
310     * Report content to webmasters (user with report notification right on wall contents)
311     * @param siteName the current site name
312     * @param contentId the id of content to report
313     * @return true if the content was successfully reported
314     */
315    @Callable (rights = Callable.READ_ACCESS, paramIndex = 1, rightContext = ContentRightAssignmentContext.ID)
316    public boolean reportContent(String siteName, String contentId)
317    {
318        Content content = _resolver.resolveById(contentId);
319        User reporter = _userManager.getUser(_currentUserProvider.getUser());
320        Site site = _siteManager.getSite(siteName);
321        
322        // Add the report to the content
323        _contentDAO.report(content);
324        
325        // Send a mail to the allowed users
326        List<Project> projects = _projectManager.getProjectsForSite(site);
327        if (!projects.isEmpty())
328        {
329            Project project = projects.get(0);
330            
331            Map<String, List<String>> recipientsByLanguage = _getReportsRecipientsByLanguage(project);
332            if (!recipientsByLanguage.isEmpty())
333            {
334                Map<String, I18nizableTextParameter> i18nParams = new HashMap<>();
335                i18nParams.put("projectTitle", new I18nizableText(project.getTitle()));
336                i18nParams.put("siteTitle", new I18nizableText(site.getTitle()));
337                
338                I18nizableText i18nSubject = new I18nizableText("plugin.workspaces", "PLUGINS_WORKSPACES_WALL_CONTENT_REPORTED_SUBJECT", i18nParams);
339                
340                i18nParams.put("projectUrl", new I18nizableText(site.getUrl()));
341                i18nParams.put("reporter", new I18nizableText(reporter.getFullName()));
342                i18nParams.put("content", new I18nizableText(getExcerpt(content, 200)));
343                
344                String from = site.getValue("site-mail-from");
345                
346                MailBodyBuilder bodyBuilder = StandardMailBodyHelper.newHTMLBody()
347                        .withTitle(i18nSubject)
348                        .withMessage(new I18nizableText("plugin.workspaces", "PLUGINS_WORKSPACES_WALL_CONTENT_REPORTED_BODY", i18nParams))
349                        .withDetails(new I18nizableText("plugin.workspaces", "PLUGINS_WORKSPACES_WALL_CONTENT_REPORTED_BODY_EXTRACT"), getExcerpt(content, 200), false)
350                        .withLink(site.getUrl(), new I18nizableText("plugin.workspaces", "PROJECT_MAIL_NOTIFICATION_BODY_DEFAULT_BUTTON_TEXT"));
351                
352                for (String userLanguage : recipientsByLanguage.keySet())
353                {
354                    try
355                    {
356                        List<String> emails = recipientsByLanguage.get(userLanguage);
357                        String subject = _i18nUtils.translate(i18nSubject, userLanguage);
358                        
359                        String htmlBody = bodyBuilder.withLanguage(userLanguage).build();
360                        
361                        SendMailHelper.newMail()
362                            .withSubject(subject)
363                            .withHTMLBody(htmlBody)
364                            .withSender(from)
365                            .withRecipients(emails)
366                            .sendMail();
367                    }
368                    catch (MessagingException | IOException e)
369                    {
370                        getLogger().warn("Could not send a notification mail to {}", recipientsByLanguage.get(userLanguage), e);
371                    }
372                }
373
374                return true;
375            }
376        }
377        
378        return false;
379    }
380    
381    /**
382     * Get the excerpt of content
383     * @param content the content
384     * @param maxLength the max length for content excerpt
385     * @return the excerpt
386     */
387    public String getExcerpt(Content content, int maxLength)
388    {
389        if (content.hasValue("content"))
390        {
391            RichText richText = content.getValue("content");
392            SAXParser saxParser = null;
393            try (InputStream is = richText.getInputStream())
394            {
395                RichTextHandler txtHandler = new RichTextHandler(maxLength);
396                saxParser = (SAXParser) _smanager.lookup(SAXParser.ROLE);
397                saxParser.parse(new InputSource(is), txtHandler);
398                
399                return txtHandler.getValue();
400            }
401            catch (Exception e)
402            {
403                getLogger().error("Cannot extract excerpt from content {}", content.getId(), e);
404            }
405            finally
406            {
407                _smanager.release(saxParser);
408            }
409        }
410     
411        return "";
412    }
413    
414    /**
415     * Retrieves the list of recipients for reports notification sending
416     * @param project the current project
417     * @return the list of recipients for reports notification sending
418     */
419    protected Map<String, List<String>> _getReportsRecipientsByLanguage(Project project)
420    {
421        WorkspaceModule module = _moduleEP.getModule(WallContentModule.WALLCONTENT_MODULE_ID);
422        ResourceCollection moduleRoot = module.getModuleRoot(project, false);
423        
424        Set<UserIdentity> users = _rightManager.getAllowedUsers("Plugins_Workspaces_Right_ReportNotification_WallContent", moduleRoot).resolveAllowedUsers(Config.getInstance().getValue("runtime.mail.massive.sending"));
425        
426        String defaultLanguage = _workspaceHelper.getLang(project, _userLanguagesManager.getDefaultLanguage());
427        
428        return users.stream()
429                .map(_userManager::getUser)
430                .filter(user -> user != null)
431                .map(user -> Pair.of(user, user.getEmail()))
432                .filter(p -> StringUtils.isNotBlank(p.getRight()))
433                .collect(Collectors.groupingBy(
434                        p -> {
435                            return StringUtils.defaultIfBlank(p.getLeft().getLanguage(), defaultLanguage);
436                        },
437                        Collectors.mapping(
438                                Pair::getRight,
439                                Collectors.toList()
440                        )
441                    )
442                );
443    }
444    
445    /**
446     * Add or remove a reaction on a content
447     * @param contentId The content id
448     * @param reactionName the reaction name (ex: LIKE)
449     * @param remove true to remove the reaction, false to add reaction
450     * @return the result with the current actors of this reaction
451     */
452    @Callable (rights = Callable.CHECKED_BY_IMPLEMENTATION)
453    public Map<String, Object> react(String contentId, String reactionName, boolean remove)
454    {
455        return _contentDAO.react(contentId, reactionName, remove);
456    }
457    
458    /**
459     * Retrieves the comments and reports of the contents of the given type
460     * Manages only contents that have at least one report (on itself or on a comment)
461     * @param contentTypeId the content type identifier
462     * @return the comments and reports of the contents
463     * @throws RepositoryException if an error occurs while retrieving contents from the repository
464     */
465    @Callable (rights = Callable.CHECKED_BY_IMPLEMENTATION)
466    public Map getCommentsAndReportsFromContentTypeId(String contentTypeId) throws RepositoryException
467    {
468        return _commentAndReportCmp.getCommentsAndReportsFromContentTypeId(contentTypeId, "Plugins_Workspaces_Right_See_Reports_WallContent");
469    }
470    
471}