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.members;
017
018import java.io.IOException;
019import java.util.Iterator;
020import java.util.List;
021import java.util.Locale;
022import java.util.Set;
023
024import org.apache.avalon.framework.service.ServiceException;
025import org.apache.avalon.framework.service.ServiceManager;
026import org.apache.cocoon.ProcessingException;
027import org.apache.cocoon.environment.ObjectModelHelper;
028import org.apache.cocoon.environment.Request;
029import org.apache.cocoon.generation.ServiceableGenerator;
030import org.apache.cocoon.xml.AttributesImpl;
031import org.apache.cocoon.xml.XMLUtils;
032import org.apache.commons.lang.StringUtils;
033import org.apache.commons.lang3.ArrayUtils;
034import org.xml.sax.SAXException;
035
036import org.ametys.cms.contenttype.ContentType;
037import org.ametys.cms.contenttype.ContentTypeExtensionPoint;
038import org.ametys.cms.repository.Content;
039import org.ametys.core.group.GroupManager;
040import org.ametys.core.right.RightManager;
041import org.ametys.core.user.User;
042import org.ametys.core.user.UserIdentity;
043import org.ametys.plugins.core.user.UserHelper;
044import org.ametys.plugins.repository.AmetysRepositoryException;
045import org.ametys.plugins.repository.data.holder.ModelAwareDataHolder;
046import org.ametys.plugins.userdirectory.UserDirectoryHelper;
047import org.ametys.plugins.workspaces.members.JCRProjectMember.MemberType;
048import org.ametys.plugins.workspaces.members.ProjectMemberManager.ProjectMember;
049import org.ametys.plugins.workspaces.project.ProjectManager;
050import org.ametys.plugins.workspaces.project.objects.Project;
051import org.ametys.runtime.config.Config;
052import org.ametys.runtime.model.View;
053import org.ametys.runtime.model.type.DataContext;
054import org.ametys.web.WebConstants;
055import org.ametys.web.repository.page.Page;
056import org.ametys.web.repository.page.ZoneItem;
057import org.ametys.web.usermanagement.UserSignUpConfiguration;
058
059/**
060 * Generator used sax project member
061 */
062public class ProjectMembersGenerator extends ServiceableGenerator
063{
064    /** The project manager component */
065    protected ProjectManager _projectManager;
066    
067    /** The project member manager */
068    protected ProjectMemberManager _projectMemberManager;
069    
070    /** The user helper */
071    protected UserHelper _userHelper;
072    
073    /** The user directory helper */
074    protected UserDirectoryHelper _userDirectoryHelper;
075    
076    /** The content type extension point */
077    protected ContentTypeExtensionPoint _cTypeEP;
078    
079    /** The group manager */
080    protected GroupManager _groupManager;
081
082    /** The sign up configuration */
083    protected UserSignUpConfiguration _signupConfig;
084
085    /** The right manager */
086    protected RightManager _rightManager;
087
088    @Override
089    public void service(ServiceManager serviceManager) throws ServiceException
090    {
091        _projectManager = (ProjectManager) serviceManager.lookup(ProjectManager.ROLE);
092        _projectMemberManager = (ProjectMemberManager) serviceManager.lookup(ProjectMemberManager.ROLE);
093        _userHelper = (UserHelper) serviceManager.lookup(UserHelper.ROLE);
094        _userDirectoryHelper = (UserDirectoryHelper) serviceManager.lookup(UserDirectoryHelper.ROLE);
095        _cTypeEP = (ContentTypeExtensionPoint) serviceManager.lookup(ContentTypeExtensionPoint.ROLE);
096        _groupManager = (GroupManager) serviceManager.lookup(GroupManager.ROLE);
097        _signupConfig = (UserSignUpConfiguration) serviceManager.lookup(UserSignUpConfiguration.ROLE);
098        _rightManager = (RightManager) serviceManager.lookup(RightManager.ROLE);
099    }
100
101    @Override
102    public void generate() throws IOException, SAXException, ProcessingException
103    {
104        Request request = ObjectModelHelper.getRequest(objectModel);
105        
106        Page page = (Page) request.getAttribute(WebConstants.REQUEST_ATTR_PAGE);
107        String lang = page.getSitemapName();
108        
109        ZoneItem zoneItem = (ZoneItem) request.getAttribute(WebConstants.REQUEST_ATTR_ZONEITEM);
110        ModelAwareDataHolder serviceParameters2018 = zoneItem.getServiceParameters();
111        
112        long maxNbMembers = serviceParameters2018.getValue("nbMembers", false, -1L);
113        boolean expandGroup = serviceParameters2018.getValue("expandGroup", false, false);
114        
115        contentHandler.startDocument();
116        
117        List<Project> projects = _projectManager.getProjectsForSite(page.getSite());
118        Project project = projects.isEmpty() ? null : projects.get(0);
119        
120        if (project == null)
121        {
122            throw new IllegalArgumentException("There is no project for site " + page.getSiteName());
123        }
124        
125        try
126        {
127            Set<ProjectMember> members = _projectMemberManager.getProjectMembers(project, expandGroup);
128            
129            AttributesImpl attrs = new AttributesImpl();
130            attrs.addCDATAAttribute("nbMembers", String.valueOf(members.size()));
131            
132            String memberPageId = _getMembersPageId(project);
133            if (memberPageId != null)
134            {
135                attrs.addCDATAAttribute("memberPageId", memberPageId);
136            }
137            
138            String siteName = Config.getInstance().getValue("workspaces.member.userdirectory.site.name");
139            if (StringUtils.isNotEmpty(siteName))
140            {
141                attrs.addCDATAAttribute("userDirectorySiteName", siteName);
142            }
143            XMLUtils.startElement(contentHandler, "project", attrs);
144            
145            UserIdentity[] managers = project.getManagers();
146            
147            int count = 0;
148            Iterator<ProjectMember> it = members.iterator();
149            while (it.hasNext() && (maxNbMembers < 1 || count < maxNbMembers))
150            {
151                ProjectMember member = it.next();
152                _saxMember(member, managers, lang);
153                count++;
154            }
155            
156            XMLUtils.endElement(contentHandler, "project");
157        }
158        catch (AmetysRepositoryException e)
159        {
160            throw new ProcessingException("Unable to get project members", e);
161        }
162        
163        contentHandler.endDocument();
164    }
165    
166    /**
167     * Get the id of member page if exists and current user has access
168     * @param project The project
169     * @return the id of member page. Can be null.
170     */
171    protected String _getMembersPageId(Project project)
172    {
173        Set<Page> memberPages = _projectManager.getModulePages(project, MembersWorkspaceModule.MEMBERS_MODULE_ID);
174        
175        if (!memberPages.isEmpty())
176        {
177            Page memberPage = memberPages.iterator().next();
178            
179            if (_rightManager.currentUserHasReadAccess(memberPage))
180            {
181                return memberPage.getId();
182            }
183        }
184        
185        return null;
186    }
187    /**
188     * SAX a member
189     * @param member the member
190     * @param managers the user identities of project's manager
191     * @param lang the current language
192     * @throws SAXException if an error occurred while saxing
193     * @throws AmetysRepositoryException if an error occurred
194     * @throws IOException if failed to sax user content
195     */
196    protected void _saxMember (ProjectMember member, UserIdentity[] managers, String lang) throws SAXException, AmetysRepositoryException, IOException
197    {
198        AttributesImpl attrs = new AttributesImpl();
199        attrs.addCDATAAttribute("manager", String.valueOf(member.isManager()));
200        
201        if (member.isManager())
202        {
203            // Get the position of this manager
204            int position = ArrayUtils.indexOf(managers, member.getUser().getIdentity());
205            attrs.addCDATAAttribute("managerPosition", String.valueOf(position + 1));
206        }
207        
208        attrs.addCDATAAttribute("type", member.getType().name().toLowerCase());
209        
210        XMLUtils.startElement(contentHandler, "member", attrs);
211        
212        XMLUtils.createElement(contentHandler, "title", member.getTitle());
213        XMLUtils.createElement(contentHandler, "sortabletitle", member.getSortableTitle());
214        String role = member.getRole();
215        if (StringUtils.isNotBlank(role))
216        {
217            XMLUtils.createElement(contentHandler, "role", role);
218        }
219        
220        if (member.getType().equals(MemberType.USER))
221        {
222            User user = member.getUser();
223            _saxUser(user, lang);
224        }
225        
226        XMLUtils.endElement(contentHandler, "member");
227    }
228    
229    /**
230     * Sax user
231     * @param user the user 
232     * @param lang the lang
233     * @throws SAXException if an error occurs saxing data
234     * @throws AmetysRepositoryException if an repository error occurs
235     * @throws IOException if an IO exception error occurs
236     */
237    protected void _saxUser(User user, String lang) throws SAXException, AmetysRepositoryException, IOException
238    {
239        XMLUtils.startElement(contentHandler, "user");
240        _userHelper.saxUser(user, contentHandler, "info");
241        Content userContent = _userDirectoryHelper.getUserContent(user.getIdentity(), lang);
242        if (userContent != null)
243        {
244            AttributesImpl contentAttrs = new AttributesImpl();
245            contentAttrs.addCDATAAttribute("id", userContent.getId());
246            XMLUtils.startElement(contentHandler, "content", contentAttrs);
247            ContentType contentType = _cTypeEP.getExtension(UserDirectoryHelper.ABSTRACT_USER_CONTENT_TYPE);
248            View view = contentType.getView("abstract");
249            userContent.dataToSAX(contentHandler, view, DataContext.newInstance().withLocale(new Locale(lang)).withEmptyValues(false));
250            XMLUtils.endElement(contentHandler, "content");
251        }
252        XMLUtils.endElement(contentHandler, "user");
253        
254    }
255}