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.userdirectory.signup;
017
018import java.util.Map;
019
020import org.apache.avalon.framework.configuration.Configuration;
021import org.apache.avalon.framework.configuration.ConfigurationException;
022import org.apache.avalon.framework.context.Context;
023import org.apache.avalon.framework.context.ContextException;
024import org.apache.avalon.framework.service.ServiceException;
025import org.apache.avalon.framework.service.ServiceManager;
026import org.apache.cocoon.components.ContextHelper;
027import org.apache.cocoon.environment.Request;
028import org.apache.commons.lang.StringUtils;
029
030import org.ametys.cms.contenttype.ContentType;
031import org.ametys.cms.contenttype.ContentTypeExtensionPoint;
032import org.ametys.cms.workflow.EditContentFunction;
033import org.ametys.core.user.User;
034import org.ametys.core.util.JSONUtils;
035import org.ametys.plugins.core.user.UserHelper;
036import org.ametys.plugins.repository.AmetysRepositoryException;
037import org.ametys.runtime.i18n.I18nizableText;
038import org.ametys.web.WebConstants;
039import org.ametys.web.content.FOContentCreationHelper;
040import org.ametys.web.repository.page.ZoneItem;
041import org.ametys.web.usermanagement.UserManagementException;
042
043import com.google.common.collect.Multimap;
044import com.opensymphony.workflow.WorkflowException;
045
046/**
047 * This component overrides {@link org.ametys.web.usermanagement.UserSignupManager} to add the creation of a user content on signup.
048 */
049public class UserSignupManager extends org.ametys.web.usermanagement.UserSignupManager
050{
051    /** The default workflow action id for initializing user content */
052    protected int _initWorkflowActionId;
053    /** The default workflow name user content */
054    protected String _workflowName;
055    
056    private Context _context;
057    private ContentTypeExtensionPoint _contentTypeEP;
058    private FOContentCreationHelper _foHelper;
059    private UserHelper _userHelper;
060    private JSONUtils _jsonUtils;
061
062    @Override
063    public void contextualize(Context context) throws ContextException
064    {
065        super.contextualize(context);
066        _context = context;
067    }
068    
069    @Override
070    public void service(ServiceManager serviceManager) throws ServiceException
071    {
072        super.service(serviceManager);
073        _contentTypeEP = (ContentTypeExtensionPoint) serviceManager.lookup(ContentTypeExtensionPoint.ROLE);
074        _foHelper = (FOContentCreationHelper) serviceManager.lookup(FOContentCreationHelper.ROLE);
075        _userHelper = (UserHelper) serviceManager.lookup(UserHelper.ROLE);
076        _jsonUtils = (JSONUtils) serviceManager.lookup(JSONUtils.ROLE);
077    }
078    
079    @Override
080    public void configure(Configuration configuration) throws ConfigurationException
081    {
082        super.configure(configuration);
083        
084        _initWorkflowActionId = Integer.valueOf(configuration.getChild("user-init-action-id").getValue());
085        _workflowName = configuration.getChild("user-workflow-name").getValue();
086    }
087    
088    /**
089     * Get the request
090     * @return the request
091     */
092    protected Request _getRequest()
093    {
094        return ContextHelper.getRequest(_context);
095    }
096    
097    @Override
098    public void validationBeforeSignup(Multimap<String, I18nizableText> errors)
099    {
100        Request request = _getRequest();
101        
102        ZoneItem zoneItem = (ZoneItem) request.getAttribute(WebConstants.REQUEST_ATTR_ZONEITEM);
103        if (zoneItem != null)
104        {
105            String userContentTypeId = zoneItem.getServiceParameters().getValue("user-content-type");
106            if (StringUtils.isNotBlank(userContentTypeId))
107            {
108                ContentType userContentType = _contentTypeEP.getExtension(userContentTypeId);
109                if (userContentType != null)
110                {
111                    Map<String, Object> userValues = _foHelper.getAndValidateFormValues(request, userContentType, "signup", errors);
112                    if (errors.isEmpty())
113                    {
114                        request.setAttribute(UserSignupManager.class.getName() + "$userValues", userValues);
115                    }
116                }
117            }
118        }
119    }
120    
121    @Override
122    public void additionalSignupOperations(User createdUser, Multimap<String, I18nizableText> errors) throws UserManagementException
123    {
124        super.additionalSignupOperations(createdUser, errors);
125        
126        Request request = _getRequest();
127        
128        String siteName = (String) request.getAttribute(WebConstants.REQUEST_ATTR_SITE_NAME);
129        String language = (String) request.getAttribute(WebConstants.REQUEST_ATTR_SITEMAP_NAME);
130        ZoneItem zoneItem = (ZoneItem) request.getAttribute(WebConstants.REQUEST_ATTR_ZONEITEM);
131        
132        if (zoneItem != null)
133        {
134            String userContentTypeId = zoneItem.getServiceParameters().getValue("user-content-type");
135            if (StringUtils.isNotBlank(userContentTypeId))
136            {
137                ContentType userContentType = _contentTypeEP.getExtension(userContentTypeId);
138                if (userContentType != null)
139                {
140                    // Create the user content type linked to this user
141                    @SuppressWarnings("unchecked")
142                    Map<String, Object> userValues = (Map<String, Object>) request.getAttribute(UserSignupManager.class.getName() + "$userValues");
143                    
144                    // Add link to created user
145                    userValues.put(EditContentFunction.FORM_ELEMENTS_PREFIX + "user", _jsonUtils.convertObjectToJson(_userHelper.user2json(createdUser.getIdentity())));
146                        
147                    if (errors.isEmpty())
148                    {
149                        try
150                        {
151                            _foHelper.createAndEditContent(_initWorkflowActionId, userContentType.getId(), siteName, createdUser.getFullName(), createdUser.getFullName(), language, userValues, _workflowName, null);
152                        }
153                        catch (AmetysRepositoryException | WorkflowException e)
154                        {
155                            getLogger().error("Unable to create the user content for user '{}' after sign up", createdUser, e);
156                            errors.put("global", new I18nizableText("PLUGINS_USER_DIRECTORY_SIGNUP_SERVICE_CREATE_CONTENT_ERROR"));
157                        }
158                    }
159                }
160            }
161        }
162    }
163    
164}