001/*
002 *  Copyright 2020 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.web.parameters.view;
017
018import java.util.Collection;
019import java.util.HashMap;
020import java.util.LinkedHashMap;
021import java.util.LinkedList;
022import java.util.List;
023import java.util.Map;
024import java.util.Optional;
025
026import org.apache.avalon.framework.component.Component;
027import org.apache.avalon.framework.service.ServiceException;
028import org.apache.avalon.framework.service.ServiceManager;
029import org.apache.avalon.framework.service.Serviceable;
030import org.apache.commons.lang.StringUtils;
031import org.apache.commons.lang3.RegExUtils;
032import org.apache.jackrabbit.util.Text;
033
034import org.ametys.cms.contenttype.ContentType;
035import org.ametys.cms.contenttype.ContentTypeExtensionPoint;
036import org.ametys.cms.contenttype.ContentTypesHelper;
037import org.ametys.cms.repository.Content;
038import org.ametys.plugins.repository.AmetysObject;
039import org.ametys.plugins.repository.AmetysObjectResolver;
040import org.ametys.plugins.repository.RepositoryConstants;
041import org.ametys.plugins.repository.data.holder.ModelAwareDataHolder;
042import org.ametys.plugins.repository.data.holder.ModifiableModelAwareDataHolder;
043import org.ametys.plugins.repository.data.holder.impl.DefaultModifiableModelAwareDataHolder;
044import org.ametys.plugins.repository.data.repositorydata.impl.JCRRepositoryData;
045import org.ametys.plugins.repository.model.RepeaterDefinition;
046import org.ametys.runtime.config.DisableCondition;
047import org.ametys.runtime.config.DisableCondition.OPERATOR;
048import org.ametys.runtime.config.DisableConditions;
049import org.ametys.runtime.i18n.I18nizableText;
050import org.ametys.runtime.model.ElementDefinition;
051import org.ametys.runtime.model.Enumerator;
052import org.ametys.runtime.model.Model;
053import org.ametys.runtime.model.ModelItem;
054import org.ametys.runtime.model.StaticEnumerator;
055import org.ametys.runtime.model.View;
056import org.ametys.runtime.model.ViewElement;
057import org.ametys.runtime.model.ViewItem;
058import org.ametys.runtime.model.ViewItemContainer;
059import org.ametys.runtime.model.type.ModelItemTypeConstants;
060import org.ametys.runtime.parameter.DefaultValidator;
061import org.ametys.runtime.plugin.component.AbstractLogEnabled;
062import org.ametys.web.parameters.view.GlobalViewParametersManager.ViewParametersType;
063import org.ametys.web.repository.page.ModifiableZoneItem;
064import org.ametys.web.repository.page.Page;
065import org.ametys.web.repository.page.Page.PageType;
066import org.ametys.web.repository.page.Zone;
067import org.ametys.web.repository.page.ZoneItem;
068import org.ametys.web.repository.page.ZoneItem.ZoneType;
069import org.ametys.web.service.Service;
070import org.ametys.web.service.ServiceExtensionPoint;
071import org.ametys.web.skin.Skin;
072import org.ametys.web.skin.SkinTemplate;
073import org.ametys.web.skin.SkinTemplateZone;
074import org.ametys.web.skin.SkinsManager;
075
076/**
077 * Manager for view parameters
078 */
079public class ViewParametersManager extends AbstractLogEnabled implements Component, Serviceable              
080{
081    /** Avalon Role */
082    public static final String ROLE = ViewParametersManager.class.getName();
083    
084    /** 
085     * The name of the model item to disable inheritance for template
086     * This model item is created from scratch, the name doesn't matter
087     * */
088    public static final String TEMPLATE_INHERIT_MODEL_ITEM_NAME = "template-inheritance";              
089    
090    /** 
091     * The name of the model item to disable inheritance for zone
092     * This model item is created from scratch, the name doesn't matter
093     * */
094    public static final String ZONE_INHERIT_MODEL_ITEM_NAME = "zone-inheritance";              
095    
096    /** 
097     * The name of the model item containing the content view parameters 
098     * This model item is created from scratch, the name doesn't matter
099     * */
100    public static final String CONTENT_VIEW_MODEL_ITEM_NAME = "content-views";              
101    
102    /** 
103     * The name of default attribute in the service parameters to set the service view  
104     * Warning : it's a convention to call this parameter 'xslt', but a service can't have several view xsl with different names
105     * */
106    public static final String SERVICE_VIEW_DEFAULT_MODEL_ITEM_NAME = "xslt";  
107    
108    /** The name of the tag containing the template view parameters */
109    public static final String VIEW_PARAMETERS_TEMPLATE_CONF_NAME = "parameters";              
110    
111    /** The name of the tag containing the zone view parameters */
112    public static final String VIEW_PARAMETERS_ZONE_CONF_NAME = "parameters";              
113    
114    /** The name of the parent tag containing the zone item view parameters */
115    public static final String VIEW_PARAMETERS_ZONE_ITEM_PARENT_CONF_NAME = "zone-items";              
116    
117    /** The name of the tag containing the zone item view parameters */
118    public static final String VIEW_PARAMETERS_ZONE_ITEM_CONF_NAME = "parameters";              
119    
120    /** The name of the tag containing the service view parameters */
121    public static final String VIEW_PARAMETERS_SERVICE_CONF_NAME = "parameters";              
122    
123    /** The name of the tag containing the content view parameters */
124    public static final String VIEW_PARAMETERS_CONTENT_CONF_NAME = "parameters";              
125    
126    /** The composite name for view parameters */
127    public static final String VIEW_PARAMETERS_COMPOSITE_NAME = "view_parameters";              
128    
129    /** The composite name for content view parameters */
130    public static final String CONTENT_VIEW_PARAMETERS_COMPOSITE_NAME = "content_view_parameters";              
131    
132    /** The composite name for service view parameters */
133    public static final String SERVICE_VIEW_PARAMETERS_COMPOSITE_NAME = "service_view_parameters";              
134    
135    /** The node type for view parameters */
136    public static final String VIEW_PARAMETERS_NODETYPE = RepositoryConstants.NAMESPACE_PREFIX + ":compositeMetadata";
137    
138    /** The Ametys object resolver */
139    protected AmetysObjectResolver _resolver;
140    
141    /** The skins manager */
142    protected SkinsManager _skinsManager;
143    
144    /** The service view parameters manager */
145    protected ServiceViewParametersManager _serviceViewParametersManager;
146    
147    /** The content view parameters manager */
148    protected ContentViewParametersManager _contentViewParametersManager;
149    
150    /** The global view parameters manager */
151    protected GlobalViewParametersManager _globalViewParametersManager;
152    
153    /** The content types helper */
154    protected ContentTypesHelper _contentTypesHelper;
155    
156    /** The content type extension point */
157    protected ContentTypeExtensionPoint _contentTypeEP;
158    
159    /** The view parameters type extension point */
160    protected ViewParameterTypeExtensionPoint _viewParametersTypeEP;
161    
162    /** The service extension point */
163    protected ServiceExtensionPoint _serviceEP;
164    
165    public void service(ServiceManager manager) throws ServiceException
166    {
167        _resolver = (AmetysObjectResolver) manager.lookup(AmetysObjectResolver.ROLE);
168        _skinsManager = (SkinsManager) manager.lookup(SkinsManager.ROLE);
169        _serviceViewParametersManager = (ServiceViewParametersManager) manager.lookup(ServiceViewParametersManager.ROLE);
170        _contentViewParametersManager = (ContentViewParametersManager) manager.lookup(ContentViewParametersManager.ROLE);
171        _globalViewParametersManager = (GlobalViewParametersManager) manager.lookup(GlobalViewParametersManager.ROLE);
172        _contentTypesHelper = (ContentTypesHelper) manager.lookup(ContentTypesHelper.ROLE);
173        _contentTypeEP = (ContentTypeExtensionPoint) manager.lookup(ContentTypeExtensionPoint.ROLE);
174        _viewParametersTypeEP = (ViewParameterTypeExtensionPoint) manager.lookup(ViewParameterTypeExtensionPoint.ROLE);
175        _serviceEP = (ServiceExtensionPoint) manager.lookup(ServiceExtensionPoint.ROLE);
176    }
177    
178    /**
179     * Get the view parameters holder
180     * @param parentJCRData the parent JCR data
181     * @param viewParametersModel the view parameters model
182     * @return the view parameters holder
183     */
184    public ModifiableModelAwareDataHolder getParametersHolder(JCRRepositoryData parentJCRData, ViewParametersModel viewParametersModel)
185    {
186        JCRRepositoryData viewRepositoryData = _getJCRRepositoryData(parentJCRData, VIEW_PARAMETERS_COMPOSITE_NAME);
187        return new DefaultModifiableModelAwareDataHolder(viewRepositoryData, viewParametersModel);
188    }
189    
190    /**
191     * Get the content view parameters holder
192     * @param parentJCRData the parent JCR data
193     * @param viewName the view name
194     * @param viewParametersModel the view parameters model
195     * @return the view parameters holder
196     */
197    public ModifiableModelAwareDataHolder getContentViewParametersHolder(JCRRepositoryData parentJCRData, String viewName, ViewParametersModel viewParametersModel)
198    {
199        JCRRepositoryData viewParametersRepositoryData = _getJCRRepositoryData(parentJCRData, CONTENT_VIEW_PARAMETERS_COMPOSITE_NAME);
200        JCRRepositoryData viewRepositoryData = _getJCRRepositoryData(viewParametersRepositoryData, viewName);
201        
202        return new DefaultModifiableModelAwareDataHolder(viewRepositoryData, viewParametersModel);
203    }
204    
205    /**
206     * Get the service view parameters holder
207     * @param parentJCRData the parent JCR data
208     * @param viewName the view name
209     * @param viewParametersModel the view parameters model
210     * @return the view parameters holder
211     */
212    public ModifiableModelAwareDataHolder getServiceViewParametersHolder(JCRRepositoryData parentJCRData, String viewName, ViewParametersModel viewParametersModel)
213    {
214        JCRRepositoryData viewParametersRepositoryData = _getJCRRepositoryData(parentJCRData, SERVICE_VIEW_PARAMETERS_COMPOSITE_NAME);
215        JCRRepositoryData xsltRepositoryData = _getJCRRepositoryData(viewParametersRepositoryData, SERVICE_VIEW_DEFAULT_MODEL_ITEM_NAME);
216        JCRRepositoryData viewRepositoryData = _getJCRRepositoryData(xsltRepositoryData, Text.escapeIllegalJcrChars(viewName));
217        
218        return new DefaultModifiableModelAwareDataHolder(viewRepositoryData, viewParametersModel);
219    }
220    
221    private JCRRepositoryData _getJCRRepositoryData(JCRRepositoryData parentJCRData, String jcrName)
222    {
223        JCRRepositoryData jcrData = null;
224        if (parentJCRData.hasValue(jcrName))
225        {
226            jcrData = (JCRRepositoryData) parentJCRData.getRepositoryData(jcrName);
227        }
228        else
229        {
230            jcrData = (JCRRepositoryData) parentJCRData.addRepositoryData(jcrName, VIEW_PARAMETERS_NODETYPE);
231        }
232        
233        return jcrData;
234    }
235    
236    /**
237     * Get the template view parameters model
238     * @param skinId the skin id
239     * @param templateId the template id
240     * @return the view parameters
241     */
242    public Optional<ViewParametersModel> getTemplateViewParametersModel(String skinId, String templateId)
243    {
244        Skin skin = _skinsManager.getSkin(skinId);
245        SkinTemplate skinTemplate = skin.getTemplate(templateId);
246        return skinTemplate != null ? getTemplateViewParametersModel(skinTemplate) : Optional.empty();
247    }
248    
249    /**
250     * Get the template view parameters model
251     * @param skinTemplate the skin template
252     * @return the view parameters
253     */
254    public Optional<ViewParametersModel> getTemplateViewParametersModel(SkinTemplate skinTemplate)
255    {
256        Optional<ViewParametersModel> optionalViewParameters = skinTemplate.getViewParameters();
257        if (optionalViewParameters.isPresent())
258        {
259            ViewParametersModel viewParameters = optionalViewParameters.get();
260            if (viewParameters.isNotEmpty())
261            {
262                ViewParameter<Boolean> inheritCheckboxElement = getInheritCheckboxElement(viewParameters, TEMPLATE_INHERIT_MODEL_ITEM_NAME);
263                viewParameters.addModelItem(inheritCheckboxElement);
264            }
265        }
266        
267        return optionalViewParameters;
268    }
269    
270    /**
271     * Get the zone view parameters model
272     * @param skinId the skin id
273     * @param templateId the template id
274     * @param zoneId the zone id
275     * @return the view parameters
276     */
277    public Optional<ViewParametersModel> getZoneViewParametersModel(String skinId, String templateId, String zoneId)
278    {
279        Skin skin = _skinsManager.getSkin(skinId);
280        SkinTemplate skinTemplate = skin.getTemplate(templateId);
281        if (skinTemplate == null)
282        {
283            return Optional.empty();
284        }
285        
286        SkinTemplateZone skinTemplateZone = skinTemplate.getZone(zoneId);
287        return skinTemplateZone != null ? getZoneViewParametersModel(skinTemplateZone) : Optional.empty();
288    }
289    
290    /**
291     * Get the zone view parameters model
292     * @param skinTemplateZone the skin template zone
293     * @return the view parameters
294     */
295    public Optional<ViewParametersModel> getZoneViewParametersModel(SkinTemplateZone skinTemplateZone)
296    {
297        Optional<ViewParametersModel> optionalViewParameters = skinTemplateZone.getViewParameters();
298        if (optionalViewParameters.isPresent())
299        {
300            ViewParametersModel viewParameters = optionalViewParameters.get();
301            if (viewParameters.isNotEmpty())
302            {
303                ViewParameter<Boolean> inheritCheckboxElement = getInheritCheckboxElement(viewParameters, ZONE_INHERIT_MODEL_ITEM_NAME);
304                viewParameters.addModelItem(inheritCheckboxElement);
305            }
306        }
307        
308        return optionalViewParameters;
309    }
310    
311    /**
312     * Get the zone item view parameters model
313     * @param zoneItem the zone item
314     * @return the view parameters
315     */
316    public Optional<ViewParametersModel> getZoneItemViewParametersModel(ZoneItem zoneItem)
317    {
318        Zone zone = zoneItem.getZone();
319        Page page = zone.getPage();
320        
321        return getZoneItemViewParametersModel(page.getSite().getSkinId(), page.getTemplate(), zone.getName());
322    }
323    
324    /**
325     * Get the zone item view parameters model
326     * @param skinId the skin id
327     * @param templateId the template id
328     * @param zoneName the zone name
329     * @return the view parameters
330     */
331    public Optional<ViewParametersModel> getZoneItemViewParametersModel(String skinId, String templateId, String zoneName)
332    {
333        Skin skin = _skinsManager.getSkin(skinId);
334        SkinTemplate skinTemplate = skin.getTemplate(templateId);
335        if (skinTemplate == null)
336        {
337            return Optional.empty();
338        }
339        
340        SkinTemplateZone skinTemplateZone = skinTemplate.getZone(zoneName);
341        return skinTemplateZone != null ? skinTemplateZone.getZoneItemViewParameters() : Optional.empty();
342    }
343    
344    /**
345     * Get the content view parameters model
346     * @param zoneItem the zone item
347     * @return the view parameters
348     */
349    public Optional<ViewParametersModel> getContentViewParametersModel(ZoneItem zoneItem)
350    {
351        if (zoneItem.getType() == ZoneType.CONTENT)
352        {
353            String viewName = zoneItem.getViewName();
354            Content content = zoneItem.getContent();
355            String skinId = zoneItem.getZone().getPage().getSite().getSkinId();
356            
357            return getContentViewParametersModel(skinId, content, viewName);
358        }
359        else
360        {
361            throw new IllegalArgumentException("Can't get content view parameters model from a none content zone item");
362        }
363    }
364    
365    /**
366     * Get the content view parameters model
367     * @param skinId the skin id
368     * @param content the content
369     * @param viewName the view name
370     * @return the view parameters
371     */
372    public Optional<ViewParametersModel> getContentViewParametersModel(String skinId, Content content, String viewName)
373    {
374        String contentTypeIdForRendering = _contentTypesHelper.getContentTypeIdForRendering(content);
375        return _contentViewParametersManager.getViewParameters(skinId, contentTypeIdForRendering, viewName);
376    }
377    
378    /**
379     * Get all view parameters model for one content
380     * @param skinId the skin id
381     * @param content the content
382     * @return the map of view parameters model (with the view name)
383     */
384    public Map<String, ViewParametersModel> getContentViewParametersModels(String skinId, Content content)
385    {
386        Map<String, ViewParametersModel> viewParametersModels = new HashMap<>();
387        String contentTypeIdForRendering = _contentTypesHelper.getContentTypeIdForRendering(content);
388        ContentType contentType = _contentTypeEP.getExtension(contentTypeIdForRendering);
389        
390        for (String viewName : contentType.getViewNames(false))
391        {
392            Optional<ViewParametersModel> contentViewParameters = getContentViewParametersModel(skinId, content, viewName);
393            if (contentViewParameters.isPresent())
394            {
395                viewParametersModels.put(viewName, contentViewParameters.get());
396            }
397        }
398        return viewParametersModels;
399    }
400    
401    /**
402     * Get a static enumerator with all content view
403     * @param content the content
404     * @return the element definition of the enumerator
405     */
406    public ElementDefinition<String> getContentViewEnumerator(Content content)
407    {
408        ElementDefinition<String> elementDef = new ElementDefinition<>();
409
410        String contentTypeIdForRendering = _contentTypesHelper.getContentTypeIdForRendering(content);
411        ContentType contentType = _contentTypeEP.getExtension(contentTypeIdForRendering);
412        
413        StaticEnumerator<String> enumerator = new StaticEnumerator<>();
414        for (String viewName : contentType.getViewNames(false))
415        {
416            View view = contentType.getView(viewName);
417            enumerator.add(view.getLabel(), viewName);
418        }
419
420        elementDef.setName(CONTENT_VIEW_MODEL_ITEM_NAME);
421        elementDef.setLabel(new I18nizableText("plugin.web", "PLUGINS_WEB_VIEW_PARAMETERS_DIALOG_BOX_CONTENT_VIEW_FIELD_LABEL"));
422        elementDef.setEnumerator(enumerator);
423        elementDef.setType(_viewParametersTypeEP.getExtension(ModelItemTypeConstants.STRING_TYPE_ID));
424        elementDef.setMultiple(false);
425        elementDef.setValidator(new DefaultValidator(null, true));
426        
427        return elementDef;
428    }
429    
430    /**
431     * Copy content view parameters of the source zone item to the destination zone item
432     * @param zoneItemSource the source zone item
433     * @param zoneItemDestination the destination zone item
434     */
435    public void copyContentViewParameters(ModifiableZoneItem zoneItemSource, ModifiableZoneItem zoneItemDestination)
436    {
437        Content content = zoneItemSource.getContent();
438        
439        String contentTypeIdForRendering = _contentTypesHelper.getContentTypeIdForRendering(content);
440        ContentType contentType = _contentTypeEP.getExtension(contentTypeIdForRendering);
441        
442        for (String viewName : contentType.getViewNames(false))
443        {
444            zoneItemSource.getContentViewParametersHolder(viewName).copyTo(zoneItemDestination.getContentViewParametersHolder(viewName));
445        }
446    }
447    
448    /**
449     * Get the service view parameters model
450     * @param zoneItem the zone item
451     * @return the view parameters
452     */
453    public Optional<ViewParametersModel> getServiceViewParametersModel(ZoneItem zoneItem)
454    {
455        if (zoneItem.getType() == ZoneType.SERVICE)
456        {
457            ModelAwareDataHolder serviceParameters = zoneItem.getServiceParameters();
458            if (serviceParameters.hasDefinition(ViewParametersManager.SERVICE_VIEW_DEFAULT_MODEL_ITEM_NAME))
459            {
460                String viewName = serviceParameters.getValue(ViewParametersManager.SERVICE_VIEW_DEFAULT_MODEL_ITEM_NAME);
461                String serviceId = zoneItem.getServiceId();
462                String skinId = zoneItem.getZone().getPage().getSite().getSkinId();
463                
464                return getServiceViewParametersModel(skinId, serviceId, viewName);
465            }
466        }
467        else
468        {
469            throw new IllegalArgumentException("Can't get service view parameters model from a none service zone item");
470        }
471        
472        return Optional.empty();
473    }
474    
475    /**
476     * Get the service view parameters model
477     * @param skinId the skin id
478     * @param serviceId the service id 
479     * @param viewName the view name
480     * @return the view parameters
481     */
482    public Optional<ViewParametersModel> getServiceViewParametersModel(String skinId, String serviceId, String viewName)
483    {
484        return _serviceViewParametersManager.getViewParameters(skinId, serviceId, viewName);
485    }
486    
487    /**
488     * Get all view parameters model for one service
489     * @param skinId the skin id
490     * @param serviceId the service id
491     * @return the map of view parameters model (with the view name)
492     */
493    public Map<String, ViewParametersModel> getServiceViewParametersModels(String skinId, String serviceId)
494    {
495        Map<String, ViewParametersModel> viewParametersModels = new HashMap<>();
496        
497        ElementDefinition<String> serviceViewEnumerator = getServiceViewEnumerator(serviceId);
498        if (serviceViewEnumerator != null)
499        {
500            Enumerator<String> enumerator = serviceViewEnumerator.getEnumerator();
501            try
502            {
503                for (String viewName : enumerator.getTypedEntries().keySet())
504                {
505                    Optional<ViewParametersModel> serviceViewParameters = getServiceViewParametersModel(skinId, serviceId, viewName);
506                    if (serviceViewParameters.isPresent())
507                    {
508                        viewParametersModels.put(viewName, serviceViewParameters.get());
509                    }
510                }
511            }
512            catch (Exception e)
513            {
514                getLogger().error("Can't get view list for service '{}'", serviceId, e);
515            }
516        }
517        
518        return viewParametersModels;
519    }
520    
521    /**
522     * Get a service enumerator with all content view
523     * @param serviceId the service id
524     * @return the element definition of the enumerator
525     */
526    @SuppressWarnings("unchecked")
527    public ElementDefinition<String> getServiceViewEnumerator(String serviceId)
528    {
529        Service service = _serviceEP.getExtension(serviceId);
530        
531        Map<String, ModelItem> parameters = service.getParameters();
532        if (parameters.containsKey(SERVICE_VIEW_DEFAULT_MODEL_ITEM_NAME))
533        {
534            ElementDefinition<String> xsltDefinition = (ElementDefinition<String>) parameters.get(SERVICE_VIEW_DEFAULT_MODEL_ITEM_NAME);
535            return xsltDefinition;
536        }
537        
538        return null;
539    }
540    
541    /**
542     * Copy service view parameters of the source zone item to the destination zone item
543     * @param zoneItemSource the source zone item
544     * @param zoneItemDestination the destination zone item
545     */
546    public void copyServiceViewParameters(ModifiableZoneItem zoneItemSource, ModifiableZoneItem zoneItemDestination)
547    {
548        String serviceId = zoneItemSource.getServiceId();
549        
550        ElementDefinition<String> serviceViewEnumerator = getServiceViewEnumerator(serviceId);
551        if (serviceViewEnumerator != null)
552        {
553            Enumerator<String> enumerator = serviceViewEnumerator.getEnumerator();
554            try
555            {
556                for (String viewName : enumerator.getTypedEntries().keySet())
557                {
558                    zoneItemSource.getServiceViewParametersHolder(viewName).copyTo(zoneItemDestination.getServiceViewParametersHolder(viewName));
559                }
560            }
561            catch (Exception e)
562            {
563                getLogger().error("Can't get view list for service '{}'. So it can't copy the service view parameters", serviceId, e);
564            }
565        }
566    }
567    
568    /**
569     * Normalize the view name (for service view value with /)
570     * @param viewName the view name
571     * @return the normalized view name
572     */
573    public String normalizeViewName(String viewName)
574    {
575        return RegExUtils.replaceAll(viewName, "/", "\\$");
576    }
577    
578    /**
579     * Add model items to the view item container and add prefix to items name
580     * @param modelItems the model items
581     * @param prefix the prefix
582     * @param viewItemContainer the view item container
583     * @return the list of included model items
584     */
585    public List<ModelItem> includeModelItems(Collection<? extends ModelItem> modelItems, String prefix, ViewItemContainer viewItemContainer)
586    {
587        List<ModelItem> copiedModelItems = new LinkedList<>();
588        for (ModelItem modelItem : modelItems)
589        {
590            if (modelItem instanceof ElementDefinition)
591            {
592                @SuppressWarnings("unchecked")
593                ElementDefinition modelItemCopy = new ElementDefinition((ElementDefinition) modelItem);
594                modelItemCopy.setDisableConditions(null);
595                modelItemCopy.setName(prefix + modelItem.getName());
596                
597                ViewElement viewElement = new ViewElement();
598                viewElement.setDefinition(modelItemCopy);
599                viewItemContainer.addViewItem(viewElement);
600                
601                copiedModelItems.add(modelItemCopy);
602            }
603        }
604        
605        return copiedModelItems;
606    }
607    
608    /**
609     * Set the a disable condition to all model items. These model items will show if the value of the element (elementName) equal the condition value (conditionValue)
610     * @param elementName the element name
611     * @param conditionValue the condition value
612     * @param modelItems the list of model items
613     */
614    public void setDisableConditions(String elementName, String conditionValue, Collection< ? extends ModelItem> modelItems)
615    {
616        for (ModelItem modelItem : modelItems)
617        {
618            if (modelItem instanceof ElementDefinition)
619            {
620                DisableConditions disableConditions = new DisableConditions();
621                DisableCondition condition = new DisableCondition(elementName, OPERATOR.NEQ, conditionValue);
622                disableConditions.getConditions().add(condition);
623                ((ElementDefinition) modelItem).setDisableConditions(disableConditions);
624            }
625            else if (modelItem instanceof RepeaterDefinition)
626            {
627                // Actually we don't handle repeater
628            }
629        }
630    }
631    
632    /**
633     * Get a check box to override inherit parameters
634     * @param model the model of the element
635     * @param name the name of the check box
636     * @return the element definition of the enumerator
637     */
638    public ViewParameter<Boolean> getInheritCheckboxElement(Model model, String name)
639    {
640        ViewParameter<Boolean> elementDef = new ViewParameter<>();
641
642        elementDef.setName(name);
643        elementDef.setLabel(new I18nizableText("plugin.web", "PLUGINS_WEB_VIEW_PARAMETERS_INHERITANCE_CHECKBOX_LABEL"));
644        elementDef.setDescription(new I18nizableText("plugin.web", "PLUGINS_WEB_VIEW_PARAMETERS_INHERITANCE_CHECKBOX_DESC"));
645        elementDef.setType(_viewParametersTypeEP.getExtension(ModelItemTypeConstants.BOOLEAN_TYPE_ID));
646        elementDef.setMultiple(false);
647        elementDef.setDefaultValue(false);
648        elementDef.setModel(model);
649        elementDef.setInheritances(null);
650        
651        return elementDef;
652    }
653    
654    /**
655     * Get the global view parameters for the given type and add the view parameters to it
656     * @param skinId the skin id
657     * @param type the type
658     * @param viewParameters the view parameters
659     * @return the new view parameters (with global view parameters)
660     */
661    public Optional<ViewParametersModel> addGlobalViewParameters(String skinId, ViewParametersType type, Optional<ViewParametersModel> viewParameters)
662    {
663        Optional<ViewParametersModel> globalViewParameters = _globalViewParametersManager.getViewParameters(skinId, type);
664        if (globalViewParameters.isEmpty() || !globalViewParameters.get().isNotEmpty())
665        {
666            return viewParameters;
667        }
668        
669        if (viewParameters.isEmpty())
670        {
671            return globalViewParameters;
672        }
673
674        ViewParametersModel newViewParameters = new ViewParametersModel(viewParameters.get().getId(), new View(), new LinkedHashMap<>());
675        View newView = newViewParameters.getView();
676        
677        // Add global view parameters
678        _addViewItems(globalViewParameters.get().getView(), newView);
679        _addParameters(globalViewParameters.get().getModelItems(), newViewParameters);
680        
681        // Add view parameters
682        _addViewItems(viewParameters.get().getView(), newView);
683        _addParameters(viewParameters.get().getModelItems(), newViewParameters);
684        
685        return Optional.ofNullable(newViewParameters);
686    }
687    
688    /**
689     * Get the parameter holder with the effective parameter path for a view parameter of a template, taking into account the inheritance.
690     * The parameter path can be different in case of inheritance. 
691     * @param page the page
692     * @param parameterPath the initial parameter path.
693     * @return the {@link ViewParameterHolder} for this page and parameter
694     */
695    public Optional<ViewParameterHolder> getTemplateViewParameterHolderWithInheritance(Page page, String parameterPath)
696    {
697        Optional<ViewParametersModel> viewParametersModelOptional = getTemplateViewParametersModel(page.getSite().getSkinId(), page.getTemplate());
698        if (viewParametersModelOptional.isEmpty())
699        {
700            // No view parameters model
701            return Optional.empty();
702        }
703        
704        ViewParametersModel viewParametersModel = viewParametersModelOptional.get();
705        if (!viewParametersModel.hasModelItem(parameterPath))
706        {
707            // The parameter path doesn't exist in the model
708            return Optional.empty();
709        }
710        
711        ModelItem modelItem = viewParametersModel.getModelItem(parameterPath);
712        return getTemplateViewParameterHolderWithInheritance(page, modelItem);
713    }
714    
715    /**
716     * Get the parameter holder with the effective parameter path for a view parameter of a template, taking into account the inheritance.
717     * The parameter path can be different in case of inheritance. 
718     * @param page the page
719     * @param modelItem the model item of parameter
720     * @return the {@link ViewParameterHolder} for this page and parameter
721     */
722    public Optional<ViewParameterHolder> getTemplateViewParameterHolderWithInheritance(Page page, ModelItem modelItem)
723    {
724        ModelAwareDataHolder dataHolder = page.getTemplateParametersHolder();
725        
726        if (!(modelItem instanceof ViewParameter))
727        {
728            return _getViewParamaterHolder(dataHolder, modelItem.getPath());
729        }
730        
731        ViewParameter viewParameter = (ViewParameter) modelItem; 
732        
733        boolean overrideInherit = dataHolder != null ? dataHolder.getValue(ViewParametersManager.TEMPLATE_INHERIT_MODEL_ITEM_NAME, false, false) : false;
734        if (!viewParameter.hasInheritances() || overrideInherit)
735        {
736            // The param has no inheritance or the override inherit param is checked, so just take the value
737            return _getViewParamaterHolder(dataHolder, modelItem.getPath());
738        }
739        else if (viewParameter.hasInheritances())
740        {
741            return _getTemplateViewParameterHolderWithInheritance(page, viewParameter, modelItem.getPath());
742        }
743        
744        // No value found
745        return Optional.empty();
746    }
747    
748    /**
749     * Get the parameter holder with the effective parameter path for a view parameter of a template, taking into account the inheritance.
750     * The parameter path can be different in case of inheritance. 
751     * @param page the page
752     * @param viewParameter the view parameter
753     * @param parameterPath the parameter path.
754     * @return the {@link ViewParameterHolder} for this page and parameter
755     */
756    protected Optional<ViewParameterHolder> _getTemplateViewParameterHolderWithInheritance(Page page, ViewParameter viewParameter, String parameterPath)
757    {
758        AmetysObject parent = page.getParent();
759        if (!(parent instanceof Page))
760        {
761            // No parent page
762            return Optional.empty();
763        }
764        
765        Page parentPage = (Page) parent;
766        if (parentPage.getType() != PageType.CONTAINER)
767        {
768            // Just ignore blank page or page with redirection
769            return _getTemplateViewParameterHolderWithInheritance(parentPage, viewParameter, parameterPath);
770        }
771        
772        // Parameter has defined inheritance
773        String parentTemplate = parentPage.getTemplate();
774        Map<String, String> inheritances = viewParameter.getInheritances();
775        boolean isTemplateMatch = false;
776        for (String template : inheritances.keySet())
777        {
778            // All template match || The parent page match
779            if (template == null || parentTemplate.equals(template))
780            {
781                String context = inheritances.get(template);
782                if (context != null) // if null, it means the template is excluded from inheritance 
783                {
784                    isTemplateMatch = true;
785                    String inheritModelItemPath = "*".equals(context) ? viewParameter.getName() : context;
786                    Optional<ViewParameterHolder> templateParameterHolder = getTemplateViewParameterHolderWithInheritance(parentPage, inheritModelItemPath);
787                    if (templateParameterHolder.isPresent())
788                    {
789                        return templateParameterHolder;
790                    }
791                }
792            }
793        }
794        
795        if (!isTemplateMatch)
796        {
797            // No template match inheritance, so just take the holder and the path
798            return _getViewParamaterHolder(page.getTemplateParametersHolder(), parameterPath);
799            
800        }
801        
802        return Optional.empty();
803    }
804    
805    /**
806     * Get the parameter holder with the effective parameter path for a view parameter of a zone, taking into account the inheritance.
807     * The parameter path can be different in case of inheritance. 
808     * @param page the page
809     * @param zone the zone
810     * @param parameterPath the initial parameter path.
811     * @return the {@link ViewParameterHolder} for this page, zone and parameter
812     */
813    public Optional<ViewParameterHolder> getZoneViewParameterHolderWithInheritance(Page page, Zone zone, String parameterPath)
814    {
815        Optional<ViewParametersModel> viewParametersModelOptional = getZoneViewParametersModel(page.getSite().getSkinId(), page.getTemplate(), zone.getName());
816        if (viewParametersModelOptional.isEmpty())
817        {
818            // No view parameters model
819            return Optional.empty();
820        }
821        
822        ViewParametersModel viewParametersModel = viewParametersModelOptional.get();
823        if (!viewParametersModel.hasModelItem(parameterPath))
824        {
825            // The parameter path doesn't exist in the model
826            return Optional.empty();
827        }
828        
829        ModelItem modelItem = viewParametersModel.getModelItem(parameterPath);
830        return getZoneViewParameterHolderWithInheritance(page, zone, modelItem);
831    }
832    
833    /**
834     * Get the parameter holder with the effective parameter path for a view parameter of a zone, taking into account the inheritance.
835     * The parameter path can be different in case of inheritance. 
836     * @param page the page
837     * @param zone the zone
838     * @param modelItem the model item of the parameter
839     * @return the {@link ViewParameterHolder} for this page, zone and parameter
840     */
841    public Optional<ViewParameterHolder> getZoneViewParameterHolderWithInheritance(Page page, Zone zone, ModelItem modelItem)
842    {
843        ModelAwareDataHolder dataHolder = zone.getZoneParametersHolder();
844        
845        if (!(modelItem instanceof ViewParameter))
846        {
847            return _getViewParamaterHolder(dataHolder, modelItem.getPath());
848        }
849        
850        ViewParameter viewParameter = (ViewParameter) modelItem; 
851        boolean overrideInherit = dataHolder != null ? dataHolder.getValue(ViewParametersManager.ZONE_INHERIT_MODEL_ITEM_NAME, false, false) : false;
852        if (!viewParameter.hasInheritances() || overrideInherit)
853        {
854            // The param has no inheritance or the override inherit param is checked, so just take the value
855            return _getViewParamaterHolder(dataHolder, modelItem.getPath());
856        }
857        else if (viewParameter.hasInheritances())
858        {
859            return _getZoneViewParameterHolderWithInheritance(page, zone, viewParameter, modelItem.getPath());
860        }
861            
862        // No value found
863        return Optional.empty();
864    }
865    
866    /**
867     * Get the parameter holder with the effective parameter path for a view parameter of a zone, taking into account the inheritance.
868     * The parameter path can be different in case of inheritance. 
869     * @param page the page
870     * @param zone the zone
871     * @param viewParameter the view parameter
872     * @param parameterPath the parameter path.
873     * @return the {@link ViewParameterHolder} for this page, zone and parameter
874     */
875    protected Optional<ViewParameterHolder> _getZoneViewParameterHolderWithInheritance(Page page, Zone zone, ViewParameter viewParameter, String parameterPath)
876    {
877        AmetysObject parent = page.getParent();
878        if (!(parent instanceof Page))
879        {
880            // No parent page
881            return Optional.empty();
882        }
883        
884        Page parentPage = (Page) parent;
885        if (parentPage.getType() != PageType.CONTAINER)
886        {
887            // Just ignore blank page or page with redirection
888            return _getZoneViewParameterHolderWithInheritance(parentPage, zone, viewParameter, parameterPath);
889        }
890        
891        // Parameter has defined inheritance
892        String parentTemplate = parentPage.getTemplate();
893        Map<String, String> inheritances = viewParameter.getInheritances();
894        boolean isTemplateMatch = false;
895        for (String template : inheritances.keySet())
896        {
897            // All template match || The parent page match
898            if (template == null || parentTemplate.equals(template))
899            {
900                String context = inheritances.get(template);
901                if (context != null) // if null, it means the template is excluded from inheritance 
902                {
903                    isTemplateMatch = true;
904                    
905                    String inheritModelItemPath = viewParameter.getName();
906                    String zoneName = zone.getName();
907                    if (!"*".equals(context))
908                    {
909                        zoneName = StringUtils.substringBefore(context, "->");
910                        inheritModelItemPath = StringUtils.substringAfter(context, "->");
911                    }
912                    
913                    if (parentPage.hasZone(zoneName))
914                    {
915                        Optional<ViewParameterHolder> zoneParameterHolder = getZoneViewParameterHolderWithInheritance(parentPage, parentPage.getZone(zoneName), inheritModelItemPath);
916                        if (zoneParameterHolder.isPresent())
917                        {
918                            return zoneParameterHolder;
919                        }
920                    }
921                }
922            }
923        }
924        
925        if (!isTemplateMatch)
926        {
927            // No template match inheritance, so just take the holder and the path
928            return _getViewParamaterHolder(zone.getZoneParametersHolder(), parameterPath);
929        }
930        
931        return Optional.empty();
932    }
933    
934    /**
935     * Get content view parameters holder from the zone item
936     * @param zoneItem the zone item
937     * @return the data holder
938     */
939    public Optional<ModelAwareDataHolder> getContentViewParametersHolder(ZoneItem zoneItem)
940    {
941        if (zoneItem.getType() == ZoneType.CONTENT)
942        {
943            String viewName = zoneItem.getViewName();
944            return Optional.ofNullable(zoneItem.getContentViewParametersHolder(viewName));
945        }
946        else
947        {
948            throw new IllegalArgumentException("Zone item with id '" + zoneItem.getId() + " is not of the expected type 'content' to get the content view parameters");
949        }
950    }
951    
952    /**
953     * Get service view parameters holder from the zone item
954     * @param zoneItem the zone item
955     * @return the data holder
956     */
957    public Optional<ModelAwareDataHolder> getServiceViewParametersHolder(ZoneItem zoneItem)
958    {
959        ModelAwareDataHolder dataHolder = null;
960        if (zoneItem.getType() == ZoneType.SERVICE)
961        {
962            ModelAwareDataHolder serviceParameters = zoneItem.getServiceParameters();
963            if (serviceParameters.hasDefinition(ViewParametersManager.SERVICE_VIEW_DEFAULT_MODEL_ITEM_NAME))
964            {
965                String viewName = serviceParameters.getValue(ViewParametersManager.SERVICE_VIEW_DEFAULT_MODEL_ITEM_NAME);
966                dataHolder = zoneItem.getServiceViewParametersHolder(viewName);
967            }
968        }
969        else
970        {
971            throw new IllegalArgumentException("Zone item with id '" + zoneItem.getId() + " is not of the expected type 'service' to get the service view parameters");
972        }
973        
974        return Optional.ofNullable(dataHolder);
975    }
976    
977    /**
978     * Get the template parameter value
979     * @param <T> type of the value to retrieve
980     * @param page the page
981     * @param parameterPath the parameter path
982     * @return the template parameter value. Can be null.
983     */
984    public <T extends Object> T getTemplateParameterValue(Page page, String parameterPath)
985    {
986        Optional<ViewParameterHolder> templateViewParameterHolder = getTemplateViewParameterHolderWithInheritance(page, parameterPath);
987        return templateViewParameterHolder.isPresent() ? templateViewParameterHolder.get().getValue() : null;
988    }
989    
990    /**
991     * Get the zone parameter value
992     * @param <T> type of the value to retrieve
993     * @param page the page
994     * @param zone the zone
995     * @param parameterPath the parameter path
996     * @return the zone parameter value. Can be null.
997     */
998    public <T extends Object> T getZoneParameterValue(Page page, Zone zone, String parameterPath)
999    {
1000        Optional<ViewParameterHolder> zoneViewParameterHolder = getZoneViewParameterHolderWithInheritance(page, zone, parameterPath);
1001        return zoneViewParameterHolder.isPresent() ? zoneViewParameterHolder.get().getValue() : null;
1002    }
1003    
1004    /**
1005     * Get the zone item parameter value
1006     * @param <T> type of the value to retrieve
1007     * @param zoneItem the zone item
1008     * @param parameterPath the parameter path
1009     * @return the zone item parameter value. Can be null.
1010     */
1011    public <T extends Object> T getZoneItemParameterValue(ZoneItem zoneItem, String parameterPath)
1012    {
1013        ModelAwareDataHolder zoneItemParametersHolder = zoneItem.getZoneItemParametersHolder();
1014        return zoneItemParametersHolder != null ? zoneItemParametersHolder.getValue(parameterPath) : null;
1015    }
1016    
1017    /**
1018     * Get the content parameter value
1019     * @param <T> type of the value to retrieve
1020     * @param zoneItem the zone item
1021     * @param viewName the content view name
1022     * @param parameterPath the parameter path
1023     * @return the content parameter value. Can be null.
1024     */
1025    public <T extends Object> T getContentParameterValue(ZoneItem zoneItem, String viewName, String parameterPath)
1026    {
1027        ModelAwareDataHolder contentParametersHolder = zoneItem.getContentViewParametersHolder(viewName);
1028        return contentParametersHolder != null ? contentParametersHolder.getValue(parameterPath) : null;
1029    }
1030    
1031    /**
1032     * Get the service parameter value
1033     * @param <T> type of the value to retrieve
1034     * @param zoneItem the zone item
1035     * @param viewName the service view name
1036     * @param parameterPath the parameter path
1037     * @return the service parameter value. Can be null.
1038     */
1039    public <T extends Object> T getServiceParameterValue(ZoneItem zoneItem, String viewName, String parameterPath)
1040    {
1041        ModelAwareDataHolder serviceParametersHolder = zoneItem.getServiceViewParametersHolder(viewName);
1042        return serviceParametersHolder != null ? serviceParametersHolder.getValue(parameterPath) : null;
1043    }
1044    
1045    private void _addViewItems(View sourceView, View destView) 
1046    {
1047        for (ViewItem viewItem : sourceView.getViewItems())
1048        {
1049            if (!destView.hasModelViewItem(viewItem.getName()))
1050            {
1051                destView.addViewItem(viewItem);
1052            }
1053        }
1054    }
1055    
1056    private void _addParameters(Collection<? extends ModelItem> modelItems, ViewParametersModel viewParametersModel) 
1057    {
1058        for (ModelItem item : modelItems)
1059        {
1060            viewParametersModel.addModelItem(item);
1061        }
1062    }
1063    
1064    private Optional<ViewParameterHolder> _getViewParamaterHolder(ModelAwareDataHolder dataHolder, String parameterPath)
1065    {
1066        if (dataHolder == null)
1067        {
1068            // No holder, return null
1069            return Optional.empty();
1070        }
1071        
1072        if (!dataHolder.hasDefinition(parameterPath))
1073        {
1074            getLogger().warn("The attribute '{}' is not defined by the model", parameterPath);
1075            return Optional.empty();
1076        }
1077        
1078        if (!dataHolder.hasValue(parameterPath))
1079        {
1080            // No value, return null
1081            return Optional.empty();
1082        }
1083        
1084        return Optional.of(new ViewParameterHolder(dataHolder, parameterPath));
1085    }
1086    
1087    /**
1088     * Object representing the data holder of the parameter with the path of the parameter in this holder   
1089     */
1090    public static class ViewParameterHolder
1091    {
1092        private ModelAwareDataHolder _dataHolder;
1093        private String _parameterPath;
1094        
1095        /**
1096         * Constructor for view parameter holder
1097         * @param dataHolder the holder containing the parameter
1098         * @param parameterPath the path of the parameter in the holder
1099         */
1100        public ViewParameterHolder(ModelAwareDataHolder dataHolder, String parameterPath)
1101        {
1102            this._dataHolder = dataHolder;
1103            this._parameterPath = parameterPath;
1104        }
1105        
1106        /**
1107         * Get the holder containing the parameter
1108         * @return the holder containing the parameter
1109         */
1110        public ModelAwareDataHolder getDataHolder()
1111        {
1112            return this._dataHolder;
1113        }
1114        
1115        /**
1116         * Get the path of the parameter in the holder
1117         * @return the path of the parameter in the holder
1118         */
1119        public String getPath()
1120        {
1121            return this._parameterPath;
1122        }
1123        
1124        /**
1125         * Get the parameter value
1126         * @param <T> type of the value to retrieve
1127         * @return the parameter value
1128         */
1129        public <T extends Object> T getValue()
1130        {
1131            return this._dataHolder.getValue(this._parameterPath);
1132        }
1133    }
1134}