001/*
002 *  Copyright 2016 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.clientsideelement;
017
018import java.util.ArrayList;
019import java.util.Arrays;
020import java.util.HashMap;
021import java.util.List;
022import java.util.Map;
023import java.util.Set;
024import java.util.stream.Collectors;
025
026import javax.jcr.Node;
027import javax.jcr.RepositoryException;
028import javax.jcr.Value;
029
030import org.apache.avalon.framework.service.ServiceException;
031import org.apache.avalon.framework.service.ServiceManager;
032import org.apache.commons.lang3.StringUtils;
033import org.apache.jackrabbit.value.StringValue;
034
035import org.ametys.cms.contenttype.ContentType;
036import org.ametys.cms.contenttype.ContentTypeExtensionPoint;
037import org.ametys.core.observation.Event;
038import org.ametys.core.observation.ObservationManager;
039import org.ametys.core.ui.Callable;
040import org.ametys.core.util.LambdaUtils;
041import org.ametys.plugins.repository.AmetysObjectResolver;
042import org.ametys.plugins.repository.jcr.JCRAmetysObject;
043import org.ametys.plugins.repository.metadata.CompositeMetadata;
044import org.ametys.plugins.repository.metadata.ModifiableCompositeMetadata;
045import org.ametys.plugins.userdirectory.UserDirectoryPageHandler;
046import org.ametys.plugins.userdirectory.observation.ObservationConstants;
047import org.ametys.plugins.userdirectory.page.VirtualUserDirectoryPageFactory;
048import org.ametys.runtime.i18n.I18nizableText;
049import org.ametys.web.clientsideelement.AbstractPageClientSideElement;
050import org.ametys.web.repository.page.ModifiablePage;
051import org.ametys.web.repository.page.Page;
052
053/**
054 * Client side element for a controller wich set/remove the root page of a user directory.
055 */
056public class SetUserDirectoryRootClientSideElement extends AbstractPageClientSideElement
057{
058    /** Observer manager. */
059    protected ObservationManager _observationManager;
060    /** The extension point for content types */
061    protected ContentTypeExtensionPoint _contentTypeEP;
062    /** The User Directory page handler */
063    protected UserDirectoryPageHandler _userDirectoryPageHandler;
064
065    @Override
066    public void service(ServiceManager smanager) throws ServiceException
067    {
068        super.service(smanager);
069        _observationManager = (ObservationManager) smanager.lookup(ObservationManager.ROLE);
070        _contentTypeEP = (ContentTypeExtensionPoint) smanager.lookup(ContentTypeExtensionPoint.ROLE);
071        _userDirectoryPageHandler = (UserDirectoryPageHandler) smanager.lookup(UserDirectoryPageHandler.ROLE);
072    }
073    
074    /**
075     * Gets the status of the given page
076     * @param pageId The page id
077     * @return the status of the given page
078     */
079    @Callable
080    public Map<String, Object> getStatus(String pageId)
081    {
082        Map<String, Object> result = new HashMap<>();
083        
084        Map<String, Object> parameters = this._script.getParameters();
085        
086        Page page = _resolver.resolveById(pageId);
087
088        if (page instanceof JCRAmetysObject)
089        {
090            if (_isUserDirectoryRootPage((JCRAmetysObject) page))
091            {
092                List<String> i18nParameters = new ArrayList<>();
093                i18nParameters.add(page.getTitle());
094    
095                I18nizableText ed = (I18nizableText) parameters.get("user-directory-page-description");
096                I18nizableText msg = new I18nizableText(ed.getCatalogue(), ed.getKey(), i18nParameters);
097                result.put("user-directory-page-title", msg);
098                
099                ed = (I18nizableText) parameters.get("remove-user-directory-page-description");
100                msg = new I18nizableText(ed.getCatalogue(), ed.getKey(), i18nParameters);
101                result.put("remove-user-directory-page-title", msg);
102                
103                String contentTypeId = page.getMetadataHolder().getString(UserDirectoryPageHandler.CONTENT_TYPE_METADATA_NAME, "");
104                
105                if (StringUtils.isNotEmpty(contentTypeId))
106                {
107                    I18nizableText contentTypeText = _contentTypeEP.hasExtension(contentTypeId) ? _contentTypeEP.getExtension(contentTypeId).getLabel() : new I18nizableText(contentTypeId);
108                    
109                    Map<String, I18nizableText> contentTypeI18nParameters = new HashMap<>();
110                    contentTypeI18nParameters.put("0", contentTypeText);
111                    
112                    ed = (I18nizableText) parameters.get("contenttype-user-directory-page-description");
113                    msg = new I18nizableText(ed.getCatalogue(), ed.getKey(), contentTypeI18nParameters);
114                    result.put("contenttype-user-directory-page-description", msg);
115                }
116                
117                result.put("user-directory-page-id", new I18nizableText(page.getId()));
118                
119                I18nizableText defaultDirectoryDeep = (I18nizableText) parameters.get("default-depth");
120                long depthMetadata = page.getMetadataHolder().getLong(UserDirectoryPageHandler.DEPTH_METADATA_NAME, -1);
121                I18nizableText depth = depthMetadata == -1 ? defaultDirectoryDeep : new I18nizableText(String.valueOf(depthMetadata));
122                result.put("depth", depth);
123            }
124            else
125            {
126                List<String> i18nParameters = new ArrayList<>();
127                i18nParameters.add(page.getTitle());
128    
129                I18nizableText ed = (I18nizableText) parameters.get("add-user-directory-page-description");
130                I18nizableText msg = new I18nizableText(ed.getCatalogue(), ed.getKey(), i18nParameters);
131                
132                result.put("add-user-directory-page-id", new I18nizableText(page.getId()));
133                result.put("add-user-directory-page-title", msg);
134            }
135        }
136        else
137        {
138            List<String> noJcrI18nParameters = new ArrayList<>();
139            noJcrI18nParameters.add(page.getTitle());
140
141            I18nizableText ed = (I18nizableText) parameters.get("no-jcr-page-description");
142            I18nizableText msg = new I18nizableText(ed.getCatalogue(), ed.getKey(), noJcrI18nParameters);
143            
144            result.put("no-jcr-page-id", new I18nizableText(page.getId()));
145            result.put("no-jcr-page-title", msg);
146        }
147        
148        return result;
149    }
150    
151    private boolean _isUserDirectoryRootPage (JCRAmetysObject jcrPage)
152    {
153        try
154        {
155            Node node = jcrPage.getNode();
156            
157            if (node.hasProperty(AmetysObjectResolver.VIRTUAL_PROPERTY))
158            {
159                List<Value> values = Arrays.asList(node.getProperty(AmetysObjectResolver.VIRTUAL_PROPERTY).getValues());
160                
161                return values.stream()
162                        .map(LambdaUtils.wrap(Value::getString))
163                        .anyMatch(v -> VirtualUserDirectoryPageFactory.class.getName().equals(v));
164            }
165            else
166            {
167                return false;
168            }
169        }
170        catch (RepositoryException e)
171        {
172            return false;
173        }
174    }
175    
176    /**
177     * Gets the content types which can build a user directory
178     * @param pageId The id of the page being edited
179     * @return the content types which can build a user directory
180     */
181    @Callable
182    public List<Map<String, Object>> getSupportedContentTypes(String pageId)
183    {
184        List<Map<String, Object>> result = new ArrayList<>();
185        Page page = _resolver.resolveById(pageId);
186        
187        for (String contentTypeId : _contentTypeEP.getSubTypes(UserDirectoryPageHandler.ABSTRACT_USER_CONTENT_TYPE))
188        {
189            ContentType contentType = _contentTypeEP.getExtension(contentTypeId);
190            Page userDirectoryRootPage = _userDirectoryPageHandler.getUserDirectoryRootPage(page.getSiteName(), page.getSitemapName(), contentTypeId);
191            if (!contentType.isAbstract() && (userDirectoryRootPage == null || userDirectoryRootPage.equals(page)))
192            {
193                // The content type is not already a root of a user directory or is the root of the currently edited page
194                Map<String, Object> entry = new HashMap<>();
195                entry.put("value", contentType.getId());
196                entry.put("text", contentType.getLabel());
197                result.add(entry);
198            }
199        }
200        
201        return result;
202    }
203    
204    /**
205     * Sets the given page as the root of a user directory
206     * @param pageId The id of the page
207     * @param contentType The id of the content type
208     * @param metadata The 
209     * @param depth The depth of the tree structure
210     * @return A result map
211     * @throws RepositoryException if a repository error occured
212     */
213    @Callable
214    public Map<String, Object> setUserDirectoryRoot(String pageId, String contentType, String metadata, int depth) throws RepositoryException
215    {
216        Map<String, Object> result = new HashMap<>();
217        if (!_contentTypeEP.isDescendant(contentType, UserDirectoryPageHandler.ABSTRACT_USER_CONTENT_TYPE))
218        {
219            result.put("error", "invalid-content-type");
220            return result;
221        }
222        
223        Page page = _resolver.resolveById(pageId);
224        Set<Page> currentUserDirectoryPages = _userDirectoryPageHandler.getUserDirectoryRootPages(page.getSiteName(), page.getSitemapName());
225        
226        Map<String, Object> eventParams = new HashMap<>();
227        eventParams.put(org.ametys.web.ObservationConstants.ARGS_PAGE, page);
228        
229        if (currentUserDirectoryPages.contains(page))
230        {
231            // Unindex pages for all workspaces before the properties changed 
232            _observationManager.notify(new Event(ObservationConstants.EVENT_USER_DIRECTORY_ROOT_UPDATING, _currentUserProvider.getUser(), eventParams));
233            
234            _updateUserDirectoryRootProperty(page, contentType, metadata, depth);
235        }
236        else
237        {
238            _addUserDirectoryRootProperty(page, contentType, metadata, depth);
239        }
240        
241        _userDirectoryPageHandler.clearCache(page);
242        
243        // Live synchronization
244        _notifyPageUpdated(page);
245        
246        // Indexation
247        _observationManager.notify(new Event(ObservationConstants.EVENT_USER_DIRECTORY_ROOT_UPDATED, _currentUserProvider.getUser(), eventParams));
248        return result;
249    }
250    
251    /**
252     * Remove the user directory root status to the given page
253     * @param pageId The id of the page
254     * @return A result map
255     * @throws RepositoryException if a repository error occured
256     */
257    @Callable
258    public Map<String, Object> removeUserDirectoryRoot(String pageId) throws RepositoryException
259    {
260        Map<String, Object> result = new HashMap<>();
261        
262        Page page = _resolver.resolveById(pageId);
263        
264        if (page instanceof JCRAmetysObject)
265        {
266            if (!_isUserDirectoryRootPage((JCRAmetysObject) page))
267            {
268                result.put("error", "no-root");
269                return result;
270            }
271            
272            Map<String, Object> eventParams = new HashMap<>();
273            eventParams.put(org.ametys.web.ObservationConstants.ARGS_PAGE, page);
274            
275            // Unindex pages for all workspaces before the properties were removed 
276            _observationManager.notify(new Event(ObservationConstants.EVENT_USER_DIRECTORY_ROOT_DELETING, _currentUserProvider.getUser(), eventParams));
277            
278            _userDirectoryPageHandler.clearCache(page);
279            _removeUserDirectoryRootProperty(page);
280            
281            _notifyPageUpdated(page);
282            
283            // After live synchronization
284            _observationManager.notify(new Event(ObservationConstants.EVENT_USER_DIRECTORY_ROOT_DELETED, _currentUserProvider.getUser(), eventParams));
285        }
286        else
287        {
288            result.put("error", "no-root");
289        }
290        return result;
291    }
292    
293    /**
294     * Gets information about user directory root status on the given.
295     * @param pageId The id of the page
296     * @return information about user directory root status on the given.
297     */
298    @Callable
299    public Map<String, Object> getRootPageInfo(String pageId)
300    {
301        Map<String, Object> result = new HashMap<>();
302        
303        Page page = _resolver.resolveById(pageId);
304        Set<Page> currentUserDirectoryPages = _userDirectoryPageHandler.getUserDirectoryRootPages(page.getSiteName(), page.getSitemapName());
305        
306        if (currentUserDirectoryPages.contains(page))
307        {
308            result.put("isRoot", true);
309            CompositeMetadata pageMeta = page.getMetadataHolder();
310            result.put("contentType", pageMeta.getString(UserDirectoryPageHandler.CONTENT_TYPE_METADATA_NAME));
311            result.put("metadata", pageMeta.getString(UserDirectoryPageHandler.CLASSIFICATION_METADATA_METADATA_NAME));
312            result.put("depth", pageMeta.getString(UserDirectoryPageHandler.DEPTH_METADATA_NAME));
313        }
314        else
315        {
316            result.put("isRoot", false);
317        }
318        
319        return result;
320    }
321    
322    private void _addUserDirectoryRootProperty(Page page, String contentType, String metadata, int depth) throws RepositoryException
323    {
324        if (page instanceof JCRAmetysObject)
325        {
326            JCRAmetysObject jcrPage = (JCRAmetysObject) page;
327            Node node = jcrPage.getNode();
328            
329            List<Value> values = new ArrayList<>();
330            if (node.hasProperty(AmetysObjectResolver.VIRTUAL_PROPERTY))
331            {
332                values.addAll(Arrays.asList(node.getProperty(AmetysObjectResolver.VIRTUAL_PROPERTY).getValues()));
333            }
334            
335            String virtualUserDirectoryPageFactoryClassName = VirtualUserDirectoryPageFactory.class.getName();
336            if (!values.contains(virtualUserDirectoryPageFactoryClassName))
337            {
338                values.add(new StringValue(virtualUserDirectoryPageFactoryClassName));
339            }
340            
341            node.setProperty(AmetysObjectResolver.VIRTUAL_PROPERTY, values.toArray(new Value[values.size()]));
342
343            // Set the user directory root property
344            ModifiableCompositeMetadata pageMeta = jcrPage.getMetadataHolder();
345            pageMeta.setMetadata(UserDirectoryPageHandler.CONTENT_TYPE_METADATA_NAME, contentType);
346            pageMeta.setMetadata(UserDirectoryPageHandler.CLASSIFICATION_METADATA_METADATA_NAME, metadata);
347            pageMeta.setMetadata(UserDirectoryPageHandler.DEPTH_METADATA_NAME, depth);
348            
349            jcrPage.saveChanges();
350        }
351    }
352    
353    private void _updateUserDirectoryRootProperty(Page page, String contentType, String metadata, int depth)
354    {
355        if (page instanceof ModifiablePage)
356        {
357            ModifiablePage modifiablePage = (ModifiablePage) page;
358            ModifiableCompositeMetadata pageMeta = modifiablePage.getMetadataHolder();
359            
360            // Set the user directory root property
361            pageMeta.setMetadata(UserDirectoryPageHandler.CONTENT_TYPE_METADATA_NAME, contentType);
362            pageMeta.setMetadata(UserDirectoryPageHandler.CLASSIFICATION_METADATA_METADATA_NAME, metadata);
363            pageMeta.setMetadata(UserDirectoryPageHandler.DEPTH_METADATA_NAME, depth);
364            
365            modifiablePage.saveChanges();
366        }
367    }
368    
369    private void _removeUserDirectoryRootProperty(Page page) throws RepositoryException
370    {
371        if (page instanceof JCRAmetysObject)
372        {
373            JCRAmetysObject jcrPage = (JCRAmetysObject) page;
374            Node node = jcrPage.getNode();
375            
376            if (node.hasProperty(AmetysObjectResolver.VIRTUAL_PROPERTY))
377            {
378                List<Value> values = new ArrayList<>(Arrays.asList(node.getProperty(AmetysObjectResolver.VIRTUAL_PROPERTY).getValues()));
379                int index = values.stream()
380                        .map(LambdaUtils.wrap(Value::getString))
381                        .collect(Collectors.toList())
382                        .indexOf(VirtualUserDirectoryPageFactory.class.getName());
383                if (index != -1)
384                {
385                    values.remove(index);
386                    node.setProperty(AmetysObjectResolver.VIRTUAL_PROPERTY, values.toArray(new Value[values.size()]));
387                }
388
389                // Remove the user directory root property
390                ModifiableCompositeMetadata pageMeta = jcrPage.getMetadataHolder();
391                if (pageMeta.hasMetadata(UserDirectoryPageHandler.CONTENT_TYPE_METADATA_NAME))
392                {
393                    pageMeta.removeMetadata(UserDirectoryPageHandler.CONTENT_TYPE_METADATA_NAME);
394                }
395                if (pageMeta.hasMetadata(UserDirectoryPageHandler.CLASSIFICATION_METADATA_METADATA_NAME))
396                {
397                    pageMeta.removeMetadata(UserDirectoryPageHandler.CLASSIFICATION_METADATA_METADATA_NAME);
398                }
399                if (pageMeta.hasMetadata(UserDirectoryPageHandler.DEPTH_METADATA_NAME))
400                {
401                    pageMeta.removeMetadata(UserDirectoryPageHandler.DEPTH_METADATA_NAME);
402                }
403                
404                jcrPage.saveChanges();
405            }
406        }
407    }
408    
409    private void _notifyPageUpdated(Page page)
410    {
411        Map<String, Object> eventParams = new HashMap<>();
412        eventParams.put(org.ametys.web.ObservationConstants.ARGS_PAGE, page);
413        _observationManager.notify(new Event(org.ametys.web.ObservationConstants.EVENT_PAGE_UPDATED, _currentUserProvider.getUser(), eventParams));
414    }
415}