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.ugc.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.ugc.observation.ObservationConstants;
044import org.ametys.plugins.ugc.page.UGCPageHandler;
045import org.ametys.plugins.ugc.page.VirtualUGCPageFactory;
046import org.ametys.runtime.i18n.I18nizableTextParameter;
047import org.ametys.runtime.i18n.I18nizableText;
048import org.ametys.web.clientsideelement.AbstractPageClientSideElement;
049import org.ametys.web.repository.page.ModifiablePage;
050import org.ametys.web.repository.page.Page;
051
052/**
053 * Client side element for a controller which set/remove the root page of a ugc.
054 */
055public class SetUGCRootClientSideElement extends AbstractPageClientSideElement
056{
057    /** Observer manager. */
058    protected ObservationManager _observationManager;
059    /** The extension point for content types */
060    protected ContentTypeExtensionPoint _contentTypeEP;
061    /** The UGC page handler */
062    protected UGCPageHandler _ugcPageHandler;
063
064    @Override
065    public void service(ServiceManager smanager) throws ServiceException
066    {
067        super.service(smanager);
068        _observationManager = (ObservationManager) smanager.lookup(ObservationManager.ROLE);
069        _contentTypeEP = (ContentTypeExtensionPoint) smanager.lookup(ContentTypeExtensionPoint.ROLE);
070        _ugcPageHandler = (UGCPageHandler) smanager.lookup(UGCPageHandler.ROLE);
071        
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 (_isUGCRootPage((JCRAmetysObject) page))
091            {
092                List<String> i18nParameters = new ArrayList<>();
093                i18nParameters.add(page.getTitle());
094    
095                I18nizableText ed = (I18nizableText) parameters.get("ugc-page-description");
096                I18nizableText msg = new I18nizableText(ed.getCatalogue(), ed.getKey(), i18nParameters);
097                result.put("ugc-page-title", msg);
098                
099                ed = (I18nizableText) parameters.get("remove-ugc-page-description");
100                msg = new I18nizableText(ed.getCatalogue(), ed.getKey(), i18nParameters);
101                result.put("remove-ugc-page-title", msg);
102                
103                String contentTypeId = page.getValue(UGCPageHandler.CONTENT_TYPE_DATA_NAME, StringUtils.EMPTY);
104                if (StringUtils.isNotEmpty(contentTypeId))
105                {
106                    I18nizableText contentTypeText = _contentTypeEP.hasExtension(contentTypeId) ? _contentTypeEP.getExtension(contentTypeId).getLabel() : new I18nizableText(contentTypeId);
107                    
108                    Map<String, I18nizableTextParameter> contentTypeI18nParameters = new HashMap<>();
109                    contentTypeI18nParameters.put("0", contentTypeText);
110                    
111                    ed = (I18nizableText) parameters.get("contenttype-ugc-page-description");
112                    msg = new I18nizableText(ed.getCatalogue(), ed.getKey(), contentTypeI18nParameters);
113                    result.put("contenttype-ugc-page-description", msg);
114                }
115                
116                result.put("ugc-page-id", new I18nizableText(page.getId()));
117            }
118            else if (!_ugcPageHandler.getUGCRootPages(page.getSiteName(), page.getSitemapName()).isEmpty())
119            {
120                I18nizableText ed = (I18nizableText) parameters.get("ugc-page-already-exist");
121                I18nizableText msg = new I18nizableText(ed.getCatalogue(), ed.getKey());
122                result.put("ugc-page-already-exist", msg);
123            }
124            else
125            {
126                List<String> i18nParameters = new ArrayList<>();
127                i18nParameters.add(page.getTitle());
128    
129                I18nizableText ed = (I18nizableText) parameters.get("add-ugc-page-description");
130                I18nizableText msg = new I18nizableText(ed.getCatalogue(), ed.getKey(), i18nParameters);
131                
132                result.put("add-ugc-page-id", new I18nizableText(page.getId()));
133                result.put("add-ugc-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    /**
152     * Sets the given page as the root of a ugc
153     * @param pageId The id of the page
154     * @param contentTypeId The id of the content type
155     * @param attributePath The classification attribute path
156     * @return A result map
157     * @throws RepositoryException if a repository error occurred
158     */
159    @Callable
160    public Map<String, Object> setUGCRoot(String pageId, String contentTypeId, String attributePath) throws RepositoryException
161    {
162        Map<String, Object> result = new HashMap<>();
163        
164        ContentType contentType = _contentTypeEP.getExtension(contentTypeId);
165        if (contentType == null)
166        {
167            result.put("error", "wrong-content-type");
168            return result;
169        }
170        else if (StringUtils.isNotBlank(attributePath))
171        {
172            if (!contentType.hasModelItem(attributePath))
173            {
174                result.put("error", "wrong-metadata");
175                return result;
176            }
177        }
178        
179        Page page = _resolver.resolveById(pageId);
180        Page currentUGCPage = _ugcPageHandler.getUGCRootPage(page.getSiteName(), page.getSitemapName(), contentTypeId);
181        
182        Map<String, Object> eventParams = new HashMap<>();
183        eventParams.put(org.ametys.web.ObservationConstants.ARGS_PAGE, page);
184        
185        if (currentUGCPage != null && currentUGCPage.getId().equals(pageId))
186        {
187            // Unindex pages for all workspaces before the properties changed 
188            _observationManager.notify(new Event(ObservationConstants.EVENT_UGC_ROOT_UPDATING, _currentUserProvider.getUser(), eventParams));
189            
190            _updateUGCRootProperty(page, contentTypeId, attributePath);
191        }
192        else
193        {
194            _addUGCRootProperty(page, contentTypeId, attributePath);
195        }
196        
197        // Live synchronization
198        _notifyPageUpdated(page);
199        
200        // Indexation
201        _observationManager.notify(new Event(ObservationConstants.EVENT_UGC_ROOT_UPDATED, _currentUserProvider.getUser(), eventParams));
202        return result;
203    }
204    
205    /**
206     * Remove the ugc root status to the given page
207     * @param pageId The id of the page
208     * @return A result map
209     * @throws RepositoryException if a repository error occured
210     */
211    @Callable
212    public Map<String, Object> removeUGCRoot(String pageId) throws RepositoryException
213    {
214        Map<String, Object> result = new HashMap<>();
215        
216        Page page = _resolver.resolveById(pageId);
217        
218        if (page instanceof JCRAmetysObject)
219        {
220            if (!_isUGCRootPage((JCRAmetysObject) page))
221            {
222                result.put("error", "no-root");
223                return result;
224            }
225            
226            Map<String, Object> eventParams = new HashMap<>();
227            eventParams.put(org.ametys.web.ObservationConstants.ARGS_PAGE, page);
228            
229            // Unindex pages for all workspaces before the properties were removed 
230            _observationManager.notify(new Event(ObservationConstants.EVENT_UGC_ROOT_DELETING, _currentUserProvider.getUser(), eventParams));
231            
232            _removeUGCRootProperty(page);
233            
234            _notifyPageUpdated(page);
235            
236            // After live synchronization
237            _observationManager.notify(new Event(ObservationConstants.EVENT_UGC_ROOT_DELETED, _currentUserProvider.getUser(), eventParams));
238        }
239        else
240        {
241            result.put("error", "no-root");
242        }
243        return result;
244    }
245    
246    /**
247     * Gets information about ugc root status on the given.
248     * @param pageId The id of the page
249     * @return information about ugc root status on the given.
250     */
251    @Callable
252    public Map<String, Object> getRootPageInfo(String pageId)
253    {
254        Map<String, Object> result = new HashMap<>();
255        
256        Page page = _resolver.resolveById(pageId);
257        Set<Page> currentUGCPages = _ugcPageHandler.getUGCRootPages(page.getSiteName(), page.getSitemapName());
258        
259        if (currentUGCPages.contains(page))
260        {
261            result.put("isRoot", true);
262            result.put("contentType", page.getValue(UGCPageHandler.CONTENT_TYPE_DATA_NAME));
263            result.put("metadata", page.getValue(UGCPageHandler.CLASSIFICATION_ATTRIBUTE_DATA_NAME));
264        }
265        else
266        {
267            result.put("isRoot", false);
268        }
269        
270        return result;
271    }
272    
273    private void _addUGCRootProperty(Page page, String contentType, String metadata) throws RepositoryException
274    {
275        if (page instanceof JCRAmetysObject)
276        {
277            JCRAmetysObject jcrPage = (JCRAmetysObject) page;
278            Node node = jcrPage.getNode();
279            
280            List<Value> values = new ArrayList<>();
281            if (node.hasProperty(AmetysObjectResolver.VIRTUAL_PROPERTY))
282            {
283                values.addAll(Arrays.asList(node.getProperty(AmetysObjectResolver.VIRTUAL_PROPERTY).getValues()));
284            }
285            
286            StringValue virtualUGCPageFactoryClassName = new StringValue(VirtualUGCPageFactory.class.getName());
287            if (!values.contains(virtualUGCPageFactoryClassName))
288            {
289                values.add(virtualUGCPageFactoryClassName);
290            }
291            
292            node.setProperty(AmetysObjectResolver.VIRTUAL_PROPERTY, values.toArray(new Value[values.size()]));
293
294            // Set the ugc root property
295            if (page instanceof ModifiablePage)
296            {
297                ((ModifiablePage) page).setValue(UGCPageHandler.CONTENT_TYPE_DATA_NAME, contentType);
298                ((ModifiablePage) page).setValue(UGCPageHandler.CLASSIFICATION_ATTRIBUTE_DATA_NAME, metadata);
299            }
300            
301            jcrPage.saveChanges();
302        }
303    }
304    
305    private void _updateUGCRootProperty(Page page, String contentType, String metadata)
306    {
307        if (page instanceof ModifiablePage)
308        {
309            ModifiablePage modifiablePage = (ModifiablePage) page;
310            
311            // Set the ugc root property
312            modifiablePage.setValue(UGCPageHandler.CONTENT_TYPE_DATA_NAME, contentType);
313            modifiablePage.setValue(UGCPageHandler.CLASSIFICATION_ATTRIBUTE_DATA_NAME, metadata);
314            
315            modifiablePage.saveChanges();
316        }
317    }
318    
319    private void _removeUGCRootProperty(Page page) throws RepositoryException
320    {
321        if (page instanceof JCRAmetysObject)
322        {
323            JCRAmetysObject jcrPage = (JCRAmetysObject) page;
324            Node node = jcrPage.getNode();
325            
326            if (node.hasProperty(AmetysObjectResolver.VIRTUAL_PROPERTY))
327            {
328                List<Value> values = new ArrayList<>(Arrays.asList(node.getProperty(AmetysObjectResolver.VIRTUAL_PROPERTY).getValues()));
329                int index = values.stream()
330                        .map(LambdaUtils.wrap(Value::getString))
331                        .collect(Collectors.toList())
332                        .indexOf(VirtualUGCPageFactory.class.getName());
333                if (index != -1)
334                {
335                    values.remove(index);
336                    node.setProperty(AmetysObjectResolver.VIRTUAL_PROPERTY, values.toArray(new Value[values.size()]));
337                }
338
339                // Remove the ugc root property
340                if (page instanceof ModifiablePage)
341                {
342                    ModifiablePage modifiablePage = (ModifiablePage) page;
343                    if (modifiablePage.hasValue(UGCPageHandler.CONTENT_TYPE_DATA_NAME))
344                    {
345                        modifiablePage.removeValue(UGCPageHandler.CONTENT_TYPE_DATA_NAME);
346                    }
347                    if (modifiablePage.hasValue(UGCPageHandler.CLASSIFICATION_ATTRIBUTE_DATA_NAME))
348                    {
349                        modifiablePage.removeValue(UGCPageHandler.CLASSIFICATION_ATTRIBUTE_DATA_NAME);
350                    }
351                }
352                
353                jcrPage.saveChanges();
354            }
355        }
356    }
357    
358    private boolean _isUGCRootPage (JCRAmetysObject jcrPage)
359    {
360        try
361        {
362            Node node = jcrPage.getNode();
363            
364            if (node.hasProperty(AmetysObjectResolver.VIRTUAL_PROPERTY))
365            {
366                List<Value> values = Arrays.asList(node.getProperty(AmetysObjectResolver.VIRTUAL_PROPERTY).getValues());
367                
368                return values.stream()
369                        .map(LambdaUtils.wrap(Value::getString))
370                        .anyMatch(v -> VirtualUGCPageFactory.class.getName().equals(v));
371            }
372            else
373            {
374                return false;
375            }
376        }
377        catch (RepositoryException e)
378        {
379            return false;
380        }
381    }
382    
383    private void _notifyPageUpdated(Page page)
384    {
385        Map<String, Object> eventParams = new HashMap<>();
386        eventParams.put(org.ametys.web.ObservationConstants.ARGS_PAGE, page);
387        _observationManager.notify(new Event(org.ametys.web.ObservationConstants.EVENT_PAGE_UPDATED, _currentUserProvider.getUser(), eventParams));
388    }
389}