001/*
002 *  Copyright 2017 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.frontedition;
017
018import java.util.ArrayList;
019import java.util.Arrays;
020import java.util.Collection;
021import java.util.Collections;
022import java.util.Comparator;
023import java.util.HashMap;
024import java.util.LinkedHashMap;
025import java.util.List;
026import java.util.Map;
027import java.util.Set;
028import java.util.stream.Collectors;
029
030import javax.jcr.RepositoryException;
031
032import org.apache.avalon.framework.context.Context;
033import org.apache.avalon.framework.context.ContextException;
034import org.apache.avalon.framework.context.Contextualizable;
035import org.apache.avalon.framework.logger.LogEnabled;
036import org.apache.avalon.framework.logger.Logger;
037import org.apache.avalon.framework.service.ServiceException;
038import org.apache.avalon.framework.service.ServiceManager;
039import org.apache.avalon.framework.service.Serviceable;
040import org.apache.cocoon.components.ContextHelper;
041import org.apache.cocoon.environment.Request;
042import org.apache.commons.lang3.ArrayUtils;
043import org.apache.commons.lang3.StringUtils;
044import org.apache.commons.lang3.tuple.Pair;
045import org.w3c.dom.NodeList;
046
047import org.ametys.cms.CmsConstants;
048import org.ametys.cms.content.RootContentHelper;
049import org.ametys.cms.contenttype.AttributeDefinition;
050import org.ametys.cms.contenttype.ContentType;
051import org.ametys.cms.contenttype.ContentTypeExtensionPoint;
052import org.ametys.cms.contenttype.ContentTypesHelper;
053import org.ametys.cms.repository.Content;
054import org.ametys.cms.repository.WorkflowAwareContent;
055import org.ametys.cms.workflow.ContentWorkflowHelper;
056import org.ametys.core.right.RightManager;
057import org.ametys.core.right.RightManager.RightResult;
058import org.ametys.core.ui.ClientSideElement;
059import org.ametys.core.ui.ClientSideElement.Script;
060import org.ametys.core.ui.ClientSideElement.ScriptFile;
061import org.ametys.core.ui.widgets.richtext.RichTextConfiguration;
062import org.ametys.core.ui.widgets.richtext.RichTextConfigurationExtensionPoint;
063import org.ametys.core.util.I18nizableSerializer;
064import org.ametys.core.util.JSONUtils;
065import org.ametys.plugins.core.ui.minimize.HashCache;
066import org.ametys.plugins.explorer.resources.actions.ExplorerResourcesDAO;
067import org.ametys.plugins.repository.AmetysObject;
068import org.ametys.plugins.repository.AmetysObjectIterable;
069import org.ametys.plugins.repository.AmetysObjectResolver;
070import org.ametys.plugins.repository.AmetysRepositoryException;
071import org.ametys.plugins.repository.RepositoryConstants;
072import org.ametys.plugins.repository.UnknownAmetysObjectException;
073import org.ametys.plugins.repository.jcr.DefaultTraversableAmetysObject;
074import org.ametys.plugins.repository.provider.RequestAttributeWorkspaceSelector;
075import org.ametys.plugins.repository.version.VersionableAmetysObject;
076import org.ametys.plugins.workflow.support.WorkflowHelper;
077import org.ametys.plugins.workflow.support.WorkflowProvider;
078import org.ametys.plugins.workflow.support.WorkflowProvider.AmetysObjectWorkflow;
079import org.ametys.runtime.i18n.I18nizableText;
080import org.ametys.runtime.model.ModelItem;
081import org.ametys.runtime.model.ModelItemGroup;
082import org.ametys.runtime.plugin.PluginsManager;
083import org.ametys.web.cache.PageHelper;
084import org.ametys.web.renderingcontext.RenderingContext;
085import org.ametys.web.repository.page.ModifiablePage;
086import org.ametys.web.repository.page.Page;
087import org.ametys.web.repository.page.SitemapElement;
088import org.ametys.web.repository.page.Zone;
089import org.ametys.web.repository.page.ZoneItem;
090import org.ametys.web.repository.site.Site;
091import org.ametys.web.repository.site.SiteManager;
092import org.ametys.web.repository.sitemap.Sitemap;
093import org.ametys.web.transformation.xslt.AmetysXSLTHelper;
094
095import com.opensymphony.workflow.loader.ActionDescriptor;
096import com.opensymphony.workflow.loader.StepDescriptor;
097import com.opensymphony.workflow.loader.WorkflowDescriptor;
098import com.opensymphony.workflow.spi.Step;
099
100/**
101 * Helper for preparing the Ametys Edition
102 */
103public class AmetysFrontEditionHelper implements Serviceable, Contextualizable, LogEnabled
104{
105    /** The right's id from front-edition access */
106    public static final String FRONT_EDITION_RIGHT_ID = "Front_Edition_Access_Right";
107    
108    private static AmetysObjectResolver _ametysObjectResolver;
109    private static HashCache _hashCache;
110    private static RichTextConfigurationExtensionPoint _richTextConfigurationExtensionPoint;
111    private static RightManager _rightManager;
112    private static ContentWorkflowHelper _contentWorkflowHelper;
113    private static PageHelper _pageHelper;
114    private static WorkflowHelper _workflowHelper;
115    private static JSONUtils _jsonUtils;
116    private static SiteManager _siteManager;
117    private static WorkflowProvider _workflowProvider;
118    private static ContentTypesHelper _contentTypesHelper;
119    private static ContentTypeExtensionPoint _contentTypesEP;
120    private static RootContentHelper _rootContentHelper;
121    
122    private static Context _context;
123
124    private static Logger _logger;
125
126    public void service(ServiceManager manager) throws ServiceException
127    {
128        _ametysObjectResolver = (AmetysObjectResolver) manager.lookup(AmetysObjectResolver.ROLE);
129        _siteManager = (SiteManager) manager.lookup(SiteManager.ROLE);
130        _hashCache = (HashCache) manager.lookup(HashCache.ROLE);
131        _richTextConfigurationExtensionPoint = (RichTextConfigurationExtensionPoint) manager.lookup(RichTextConfigurationExtensionPoint.ROLE);
132        _rightManager = (RightManager) manager.lookup(RightManager.ROLE);
133        _contentWorkflowHelper = (ContentWorkflowHelper) manager.lookup(ContentWorkflowHelper.ROLE);
134        _contentTypesHelper = (ContentTypesHelper) manager.lookup(ContentTypesHelper.ROLE);
135        _contentTypesEP = (ContentTypeExtensionPoint) manager.lookup(ContentTypeExtensionPoint.ROLE);
136        _pageHelper = (PageHelper) manager.lookup(PageHelper.ROLE);
137        _workflowHelper = (WorkflowHelper) manager.lookup(WorkflowHelper.ROLE);
138        _jsonUtils = (JSONUtils) manager.lookup(JSONUtils.ROLE);
139        _workflowProvider = (WorkflowProvider) manager.lookup(WorkflowProvider.ROLE);
140        _rootContentHelper = (RootContentHelper) manager.lookup(RootContentHelper.ROLE);
141    }
142    
143    @Override
144    public void contextualize(Context context) throws ContextException
145    {
146        _context = context;
147    }
148    
149    @Override
150    public void enableLogging(Logger logger)
151    {
152        _logger = logger;
153    }
154    
155    /**
156     * Prepare a hashcode for js files
157     * @param locale The language code to use
158     * @param theme The url for the theme
159     * @return The new hashcode to read the minimified concatened file
160     */
161    public static String prepareJSFiles(String locale, String theme)
162    {
163        String themeName = StringUtils.substringAfterLast(theme, "/");
164        
165        Map<String, String> filesInfos = new HashMap<>();
166        filesInfos.put("media", "");
167        filesInfos.put("tag", "script");
168        
169        Map<String, Map<String, String>> files = new LinkedHashMap<>();
170        files.put("/plugins/extjs7/resources/ext-all.js", filesInfos);
171        files.put("/plugins/extjs7/resources/classic/locale/locale-" + locale + ".js", filesInfos);
172        files.put(theme + "/" + themeName + ".js", filesInfos);
173
174        files.put("/plugins/core-ui/resources/js/Ext.fixes." + locale + ".js", filesInfos);
175        files.put("/plugins/core-ui/resources/js/Ext.enhancements." + locale + ".js", filesInfos);
176        
177        files.put("/plugins/core-ui/resources/js/Ametys." + locale + ".js", filesInfos);
178        files.put("/plugins/front-edition/resources/js/Ametys/override/Ametys." + locale + ".js", filesInfos);
179        files.put("/plugins/core-ui/resources/js/Ametys/mask/GlobalLoadMask." + locale + ".js", filesInfos);
180        
181        files.put("/plugins/core-ui/resources/js/Ametys/log/Logger." + locale + ".js", filesInfos);
182        files.put("/plugins/core-ui/resources/js/Ametys/log/Logger/Entry." + locale + ".js", filesInfos);
183        files.put("/plugins/core-ui/resources/js/Ametys/log/LoggerFactory." + locale + ".js", filesInfos);
184        files.put("/plugins/core-ui/resources/js/Ametys/log/ErrorDialog." + locale + ".js", filesInfos);
185        
186        files.put("/plugins/core-ui/resources/js/Ametys/window/DialogBox." + locale + ".js", filesInfos);
187        files.put("/plugins/front-edition/resources/js/Ametys/override/Ametys/window/DialogBox." + locale + ".js", filesInfos);
188        files.put("/plugins/core-ui/resources/js/Ametys/window/MessageBox." + locale + ".js", filesInfos);
189        
190        files.put("/plugins/core-ui/resources/js/Ametys/form/AbstractField." + locale + ".js", filesInfos);
191        files.put("/plugins/core-ui/resources/js/Ametys/form/AbstractFieldsWrapper." + locale + ".js", filesInfos);
192        files.put("/plugins/core-ui/resources/js/Ametys/form/AbstractQueryableComboBox." + locale + ".js", filesInfos);
193        files.put("/plugins/core-ui/resources/js/Ametys/form/AbstractQueryableComboBox/SplitterTracker." + locale + ".js", filesInfos);
194        files.put("/plugins/front-edition/resources/js/Ametys/override/Ametys/form/widget/AbstractQueryableComboBox." + locale + ".js", filesInfos);
195        files.put("/plugins/core-ui/resources/js/Ametys/form/field/DateTime." + locale + ".js", filesInfos);
196        files.put("/plugins/core-ui/resources/js/Ametys/form/field/StringTime." + locale + ".js", filesInfos);
197        files.put("/plugins/core-ui/resources/js/Ametys/form/field/Password." + locale + ".js", filesInfos);
198        files.put("/plugins/core-ui/resources/js/Ametys/form/field/ChangePassword." + locale + ".js", filesInfos);
199        files.put("/plugins/core-ui/resources/js/Ametys/form/field/ReferencedNumberField." + locale + ".js", filesInfos);
200        files.put("/plugins/core-ui/resources/js/Ametys/form/field/RichText." + locale + ".js", filesInfos);
201        files.put("/plugins/cms/resources/js/Ametys/cms/form/field/RichText." + locale + ".js", filesInfos);
202        files.put("/plugins/core-ui/resources/js/Ametys/form/field/RichText/SplitterTracker." + locale + ".js", filesInfos);
203        files.put("/plugins/core-ui/resources/js/Ametys/form/field/TextArea." + locale + ".js", filesInfos);
204        files.put("/plugins/core-ui/resources/js/Ametys/form/field/ColorSelector." + locale + ".js", filesInfos);
205        files.put("/plugins/core-ui/resources/js/Ametys/form/field/SelectUserDirectory." + locale + ".js", filesInfos);
206        files.put("/plugins/core-ui/resources/js/Ametys/form/field/SelectGroupDirectories." + locale + ".js", filesInfos);
207        files.put("/plugins/core-ui/resources/js/Ametys/form/field/Code." + locale + ".js", filesInfos);
208        files.put("/plugins/tiny_mce/resources/js/tinymce.js", filesInfos);
209        files.put("/plugins/codemirror/resources/js/codemirror.js", filesInfos);
210        files.put("/plugins/codemirror/resources/js/addon/edit/matchbrackets.js", filesInfos);
211        files.put("/plugins/codemirror/resources/js/addon/selection/active-line.js", filesInfos);
212        files.put("/plugins/codemirror/resources/js/mode/xml/xml.js", filesInfos);
213        files.put("/plugins/codemirror/resources/js/mode/javascript/javascript.js", filesInfos);
214        files.put("/plugins/codemirror/resources/js/mode/css/css.js", filesInfos);
215        files.put("/plugins/codemirror/resources/js/mode/htmlmixed/htmlmixed.js", filesInfos);
216        
217        files.put("/plugins/core-ui/resources/js/Ametys/data/ServerCaller." + locale + ".js", filesInfos);
218        files.put("/plugins/core-ui/resources/js/Ametys/data/ServerComm." + locale + ".js", filesInfos);
219        files.put("/plugins/front-edition/resources/js/Ametys/override/Ametys/data/ServerComm." + locale + ".js", filesInfos);
220        files.put("/plugins/core-ui/resources/js/Ametys/data/ServerCommProxy." + locale + ".js", filesInfos);
221        files.put("/plugins/core-ui/resources/js/Ametys/data/ServerComm/TimeoutDialog." + locale + ".js", filesInfos);
222
223        files.put("/plugins/core-ui/resources/js/Ametys/form/widget/RichText/RichTextConfigurationBase." + locale + ".js", filesInfos);
224        files.put("/plugins/core-ui/resources/js/Ametys/form/widget/RichText/RichTextConfiguration." + locale + ".js", filesInfos);
225        
226        files.put("/plugins/core-ui/resources/js/Ametys/plugins/coreui/system/devmode/StacktraceHelper." + locale + ".js", filesInfos);
227
228        files.put("/plugins/front-edition/resources/js/front-comm." + locale + ".js", filesInfos);
229        files.put("/plugins/front-edition/resources/js/front-widget." + locale + ".js", filesInfos);
230//        files.put("/plugins/front-edition/resources/js/front-page." + locale + ".js", filesInfos);
231        files.put("/plugins/core-ui/resources/js/Ametys/helper/EnterURL." + locale + ".js", filesInfos);
232        files.put("/plugins/core-ui/resources/js/Ametys/helper/FileUpload." + locale + ".js", filesInfos);
233        files.put("/plugins/web/resources/js/Ametys/web/helper/ChoosePage." + locale + ".js", filesInfos);
234        files.put("/plugins/web/resources/js/Ametys/web/helper/ContextToolbar." + locale + ".js", filesInfos);
235        files.put("/plugins/web/resources/js/Ametys/web/sitemap/SitemapTree." + locale + ".js", filesInfos);
236        files.put("/plugins/web/resources/js/Ametys/web/sitemap/SitemapTree/Page." + locale + ".js", filesInfos);
237        files.put("/plugins/web/resources/js/Ametys/web/sitemap/SitemapTree/Sitemap." + locale + ".js", filesInfos);
238        files.put("/plugins/web/resources/js/Ametys/web/site/SitesTree/Site." + locale + ".js", filesInfos);
239        files.put("/plugins/cms/resources/js/Ametys/cms/editor/LinkHandler." + locale + ".js", filesInfos);
240        files.put("/plugins/cms/resources/js/Ametys/plugins/cms/editor/Links." + locale + ".js", filesInfos);
241        files.put("/plugins/cms/resources/js/Ametys/plugins/cms/editor/Links/LinkHandler." + locale + ".js", filesInfos);
242        files.put("/plugins/web/resources/js/Ametys/plugins/web/editor/Links." + locale + ".js", filesInfos);
243        files.put("/plugins/web/resources/js/Ametys/plugins/web/editor/PageLinkHandler." + locale + ".js", filesInfos);
244        files.put("/plugins/cms/resources/js/Ametys/plugins/cms/editor/Images." + locale + ".js", filesInfos);
245        
246        files.put("/plugins/cms/resources/js/tinymce/basicstyles." + locale + ".js", filesInfos);
247        files.put("/plugins/cms/resources/js/tinymce/lists." + locale + ".js", filesInfos);
248        files.put("/plugins/cms/resources/js/tinymce/links." + locale + ".js", filesInfos);
249        files.put("/plugins/web/resources/js/tinymce/links." + locale + ".js", filesInfos);
250        files.put("/plugins/front-edition/resources/js/tinymce/links." + locale + ".js", filesInfos);
251        files.put("/plugins/cms/resources/js/tinymce/styles." + locale + ".js", filesInfos);
252        files.put("/plugins/cms/resources/js/tinymce/images." + locale + ".js", filesInfos);
253        files.put("/plugins/front-edition/resources/js/tinymce/images." + locale + ".js", filesInfos);
254        
255        if (PluginsManager.getInstance().getPluginNames().contains("inlinemedia"))
256        {
257            
258            files.put("/plugins/inlinemedia/resources/js/Ametys/plugins/inlinemedia/Media." + locale + ".js", filesInfos);
259            files.put("/plugins/inlinemedia/resources/js/Ametys/plugins/inlinemedia/InsertMediaHelper." + locale + ".js", filesInfos);
260            files.put("/plugins/inlinemedia/resources/js/tinymce/images." + locale + ".js", filesInfos);
261        }
262        
263        files.put("/plugins/front-edition/resources/js/tinymce/save." + locale + ".js", filesInfos);
264        
265        //TinyMCE Tables
266        files.put("/plugins/cms/resources/js/tinymce/tables." + locale + ".js", filesInfos);
267        files.put("/plugins/front-edition/resources/js/tinymce/tables." + locale + ".js", filesInfos);
268        files.put("/plugins/cms/resources/js/Ametys/plugins/cms/editor/Tables." + locale + ".js", filesInfos);
269        files.put("/plugins/cms/resources/js/Ametys/plugins/cms/editor/BasicActions." + locale + ".js", filesInfos);
270        //TinyMCE Images
271        files.put("/plugins/cms/resources/js/Ametys/cms/uihelper/ChooseResource." + locale + ".js", filesInfos);
272        files.put("/plugins/explorer/resources/js/Ametys/explorer/tree/ExplorerTree." + locale + ".js", filesInfos);
273        files.put("/plugins/explorer/resources/js/Ametys/explorer/tree/ExplorerTree/NodeEntry." + locale + ".js", filesInfos);
274        files.put("/plugins/explorer/resources/js/Ametys/explorer/Resource." + locale + ".js", filesInfos);
275        files.put("/plugins/explorer/resources/js/Ametys/explorer/ExplorerNodeDAO." + locale + ".js", filesInfos);
276        files.put("/plugins/explorer/resources/js/Ametys/explorer/ExplorerNode." + locale + ".js", filesInfos);
277        files.put("/plugins/web/resources/js/Ametys/plugins/web/explorer/ExplorerNode." + locale + ".js", filesInfos);
278        files.put("/plugins/cms/resources/js/Ametys/cms/attach/AttachmentsExplorerTree." + locale + ".js", filesInfos);
279        files.put("/plugins/cms/resources/js/Ametys/cms/uihelper/ChooseAttachmentFile." + locale + ".js", filesInfos);
280        files.put("/plugins/front-edition/resources/js/Ametys/override/Ametys/cms/uihelper/ChooseAttachmentFile." + locale + ".js", filesInfos);
281        files.put("/plugins/explorer/resources/js/Ametys/explorer/resources/actions/FileActions." + locale + ".js", filesInfos);
282        files.put("/plugins/explorer/resources/js/Ametys/explorer/resources/helper/ResourceUpload." + locale + ".js", filesInfos);
283        files.put("/plugins/core-ui/resources/js/Ametys/file/AbstractFileExplorerTree/FileNode." + locale + ".js", filesInfos);
284        files.put("/plugins/core-ui/resources/js/Ametys/file/AbstractFileExplorerTree." + locale + ".js", filesInfos);
285
286        //Empty Message class
287        files.put("/plugins/core-ui/resources/js/Ametys/message/Message." + locale + ".js", filesInfos);
288        files.put("/plugins/core-ui/resources/js/Ametys/message/MessageTarget." + locale + ".js", filesInfos);
289        files.put("/plugins/core-ui/resources/js/Ametys/message/MessageTargetFactory." + locale + ".js", filesInfos);
290        files.put("/plugins/core-ui/resources/js/Ametys/message/factory/DefaultMessageTargetFactory." + locale + ".js", filesInfos);
291        files.put("/plugins/front-edition/resources/js/Ametys/message/MessageTargetHelper." + locale + ".js", filesInfos);
292        //add page
293        files.put("/plugins/web/resources/js/Ametys/plugins/web/page/AddPageWizard." + locale + ".js", filesInfos);
294        files.put("/plugins/front-edition/resources/js/Ametys/override/Ametys/plugins/web/page/AddPageWizard." + locale + ".js", filesInfos);
295        files.put("/plugins/web/resources/js/Ametys/web/sitemap/SitemapDAO." + locale + ".js", filesInfos);
296        files.put("/plugins/web/resources/js/Ametys/web/sitemap/Sitemap." + locale + ".js", filesInfos);
297        files.put("/plugins/web/resources/js/Ametys/web/page/PageDAO." + locale + ".js", filesInfos);
298        files.put("/plugins/front-edition/resources/js/Ametys/override/Ametys/web/page/PageDAO." + locale + ".js", filesInfos);
299        files.put("/plugins/web/resources/js/Ametys/plugins/web/page/AddPageWizard/Card." + locale + ".js", filesInfos);
300        files.put("/plugins/web/resources/js/Ametys/plugins/web/page/AddPageWizard/CreatePageCard." + locale + ".js", filesInfos);
301        files.put("/plugins/web/resources/js/Ametys/plugins/web/page/AddPageWizard/PageContentCard." + locale + ".js", filesInfos);
302        files.put("/plugins/web/resources/js/Ametys/plugins/web/page/AddPageWizard/ContentPropertiesCard." + locale + ".js", filesInfos);
303        files.put("/plugins/core-ui/resources/js/Ametys/form/Widget." + locale + ".js", filesInfos);
304        files.put("/plugins/core-ui/resources/js/Ametys/form/ConfigurableFormPanel." + locale + ".js", filesInfos);
305        files.put("/plugins/front-edition/resources/js/Ametys/userprefs/UserPrefsDAO." + locale + ".js", filesInfos);
306        files.put("/plugins/core-ui/resources/js/Ametys/form/ConfigurableFormPanel/Repeater." + locale + ".js", filesInfos);
307        files.put("/plugins/core-ui/resources/js/Ametys/form/ConfigurableFormPanel/FieldCheckersManager." + locale + ".js", filesInfos);
308        files.put("/plugins/front-edition/resources/js/Ametys/message/MessageBus." + locale + ".js", filesInfos);
309        files.put("/plugins/core-ui/resources/js/Ametys/form/WidgetManager." + locale + ".js", filesInfos);
310        files.put("/plugins/core-ui/resources/js/Ametys/form/widget/DefaultWidgets." + locale + ".js", filesInfos);
311        files.put("/plugins/core-ui/resources/js/Ametys/form/widget/Date." + locale + ".js", filesInfos);
312        files.put("/plugins/core-ui/resources/js/Ametys/form/widget/DateTime." + locale + ".js", filesInfos);
313        files.put("/plugins/front-edition/resources/js/Ametys/override/Ametys/form/WidgetManager." + locale + ".js", filesInfos);
314        
315        files.put("/plugins/cms/resources/js/Ametys/cms/content/ContentDAO." + locale + ".js", filesInfos);
316        files.put("/plugins/web/resources/js/Ametys/web/content/ContentDAO." + locale + ".js", filesInfos);
317        files.put("/plugins/front-edition/resources/js/Ametys/override/Ametys/cms/content/ContentDAO." + locale + ".js", filesInfos);
318        files.put("/plugins/cms/resources/js/Ametys/cms/content/Content." + locale + ".js", filesInfos);
319        files.put("/plugins/core-ui/resources/js/Ametys/navhistory/HistoryDAO." + locale + ".js", filesInfos);
320        files.put("/plugins/core-ui/resources/js/Ametys/window/MessageBox." + locale + ".js", filesInfos);
321        files.put("/plugins/front-edition/resources/js/Ametys/tool/ToolsManager." + locale + ".js", filesInfos);
322
323        files.put("/plugins/cms/resources/js/Ametys/cms/form/widget/RichText." + locale + ".js", filesInfos);
324        files.put("/plugins/front-edition/resources/js/Ametys/override/Ametys/cms/form/widget/SelectContent/ContentEntry." + locale + ".js", filesInfos);
325        files.put("/plugins/cms/resources/js/Ametys/cms/form/widget/SelectContent." + locale + ".js", filesInfos);
326        files.put("/plugins/front-edition/resources/js/Ametys/override/Ametys/cms/form/widget/SelectContent." + locale + ".js", filesInfos);
327        files.put("/plugins/cms/resources/js/Ametys/cms/form/widget/SelectReferenceTableContent." + locale + ".js", filesInfos);
328        files.put("/plugins/front-edition/resources/js/Ametys/override/Ametys/cms/form/widget/SelectReferenceTableContent." + locale + ".js", filesInfos);
329        files.put("/plugins/web/resources/js/Ametys/plugins/web/page/AddPageWizard/PageTypeCard." + locale + ".js", filesInfos);
330        files.put("/plugins/front-edition/resources/js/Ametys/override/Ametys/plugins/web/page/AddPageWizard/PageTypeCard." + locale + ".js", filesInfos);
331        files.put("/plugins/web/resources/js/Ametys/web/form/widget/SelectPage." + locale + ".js", filesInfos);
332        files.put("/plugins/front-edition/resources/js/Ametys/override/Ametys/web/form/widget/SelectPage." + locale + ".js", filesInfos);
333        files.put("/plugins/web/resources/js/Ametys/web/form/widget/SelectSite." + locale + ".js", filesInfos);
334        files.put("/plugins/web/resources/js/Ametys/web/helper/ChooseSite." + locale + ".js", filesInfos);
335        files.put("/plugins/web/resources/js/Ametys/web/site/SitesTree." + locale + ".js", filesInfos);
336        files.put("/plugins/web/resources/js/Ametys/web/site/SitesTree/Site." + locale + ".js", filesInfos);
337        files.put("/plugins/web/resources/js/Ametys/web/helper/ContextToolbar." + locale + ".js", filesInfos);
338        files.put("/plugins/web/resources/js/Ametys/web/site/SitesTree/Site." + locale + ".js", filesInfos);
339        files.put("/plugins/web/resources/js/Ametys/web/form/widget/SelectPage/PageEntry." + locale + ".js", filesInfos);
340        files.put("/plugins/web/resources/js/Ametys/plugins/web/page/AddPageWizard/TagsCard." + locale + ".js", filesInfos);
341        files.put("/plugins/web/resources/js/Ametys/plugins/web/page/AddPageWizard/TagsCardLite." + locale + ".js", filesInfos);
342        files.put("/plugins/web/resources/js/Ametys/web/page/Page." + locale + ".js", filesInfos);
343        files.put("/plugins/cms/resources/js/Ametys/plugins/cms/tag/TagsTreePanel." + locale + ".js", filesInfos);
344        files.put("/plugins/cms/resources/js/Ametys/plugins/cms/tag/TagsTreePanel/TagNode." + locale + ".js", filesInfos);
345
346        //delete page
347        files.put("/plugins/web/resources/js/Ametys/plugins/web/sitemap/SitemapActions." + locale + ".js", filesInfos);
348
349        //page tags
350        files.put("/plugins/web/resources/js/Ametys/plugins/web/tag/AffectTagAction." + locale + ".js", filesInfos);
351        files.put("/plugins/cms/resources/js/Ametys/cms/uihelper/ChooseTagHelper." + locale + ".js", filesInfos);
352        files.put("/plugins/cms/resources/js/Ametys/cms/uihelper/ChooseTag." + locale + ".js", filesInfos);
353        files.put("/plugins/web/resources/js/Ametys/web/helper/ChooseTag." + locale + ".js", filesInfos);
354        files.put("/plugins/cms/resources/js/Ametys/plugins/cms/tag/TagActions." + locale + ".js", filesInfos);
355        files.put("/plugins/web/resources/js/Ametys/plugins/web/tag/TagsTreePanel." + locale + ".js", filesInfos);
356        
357        // scheduled publication
358        files.put("/plugins/web/resources/js/Ametys/plugins/web/page/SchedulePublication." + locale + ".js", filesInfos);
359        files.put("/plugins/front-edition/resources/js/Ametys/override/Ametys/plugins/web/page/SchedulePublication." + locale + ".js", filesInfos);
360
361        // ping
362        files.put("/plugins/core-ui/resources/js/Ametys/plugins/coreui/system/StartTimeChecker." + locale + ".js", filesInfos);
363
364        // actions on content
365        files.put("/plugins/cms/resources/js/Ametys/cms/uihelper/EditContent." + locale + ".js", filesInfos);
366        files.put("/plugins/web/resources/js/Ametys/plugins/web/zone/ZoneActions." + locale + ".js", filesInfos);
367        files.put("/plugins/web/resources/js/Ametys/plugins/web/zone/ZoneDAO." + locale + ".js", filesInfos);
368
369        // file widget (+cropping for image filter)
370        files.put("/plugins/core-ui/resources/js/Ametys/form/widget/File." + locale + ".js", filesInfos);
371        files.put("/plugins/front-edition/resources/js/Ametys/override/Ametys/form/widget/File." + locale + ".js", filesInfos);
372        files.put("/plugins/core-ui/resources/js/Ametys/form/widget/File/FileSource." + locale + ".js", filesInfos);
373        files.put("/plugins/core-ui/resources/js/Ametys/form/widget/File/External." + locale + ".js", filesInfos);
374        files.put("/plugins/cms/resources/js/Ametys/cms/form/widget/File/Resource." + locale + ".js", filesInfos);
375        files.put("/plugins/core-ui/resources/js/Ametys/helper/crop/CropDialog." + locale + ".js", filesInfos);
376        files.put("/plugins/core-ui/resources/js/Jcrop/jquery.Jcrop." + locale + ".js", filesInfos);
377        files.put("/plugins/core-ui/resources/js/Ametys/form/widget/Image." + locale + ".js", filesInfos);
378        files.put("/plugins/front-edition/resources/js/Ametys/override/Ametys/form/widget/Image." + locale + ".js", filesInfos);
379        
380        // Let's add all richtextconfiguration files
381        _addRichTextConfigurationFiles(files, filesInfos, locale, true);
382
383        return _hashCache.createHash(files, locale);
384    }
385
386    /**
387     * Prepare a hashcode for css files
388     * @param locale The language code to use
389     * @param theme The url for the theme
390     * @return The new hashcode to read the minimified concatened file
391     */
392    public static String prepareCSSFiles(String locale, String theme)
393    {
394        Map<String, String> filesInfos = new HashMap<>();
395        filesInfos.put("media", "");
396        filesInfos.put("tag", "link");
397        
398        Map<String, Map<String, String>> files = new LinkedHashMap<>();
399        String themeName = StringUtils.substringAfterLast(theme, "/");
400        files.put(theme + "/" + themeName + "-all.css", filesInfos); 
401        files.put("/plugins/front-edition/resources/css/theme-ametys-base-light.css", filesInfos);
402        files.put("/plugins/core-ui/resources/font/ametys/AmetysIcon.css", filesInfos);
403        files.put("/plugins/core-ui/resources/css/Ametys/form/image.css", filesInfos);
404        files.put("/plugins/core-ui/resources/css/Jcrop/jquery.Jcrop.css", filesInfos);
405        files.put("/plugins/web/resources/css/pages/addpage.css", filesInfos);
406        files.put("/plugins/cms/resources/css/selectcontent.css", filesInfos);
407        files.put("/plugins/codemirror/resources/css/codemirror.css", filesInfos);
408        files.put("/plugins/codemirror/resources/js/addon/hint/show-hint.css", filesInfos);
409        
410        // Let's add all richtextconfiguration files
411        _addRichTextConfigurationFiles(files, filesInfos, locale, false);
412        
413        return _hashCache.createHash(files, locale);
414    }
415
416    private static List<ScriptFile> _getRichTextConfigurationFiles(boolean scripts, Map<String, Object> contextParameters)
417    {
418        List<ScriptFile> files = new ArrayList<>();
419        
420        for (String richTextConfigurationId : _richTextConfigurationExtensionPoint.getExtensionsIds())
421        {
422            RichTextConfiguration richTextConfiguration = _richTextConfigurationExtensionPoint.getExtension(richTextConfigurationId);
423            for (String category : richTextConfiguration.getCategories())
424            {
425                Set<ClientSideElement> convertors = richTextConfiguration.getConvertors(category, contextParameters);
426                if (convertors != null)
427                {
428                    for (ClientSideElement convertor : convertors)
429                    {
430                        List<Script> scriptsToAdd = convertor.getScripts(Collections.EMPTY_MAP);
431                        if (scriptsToAdd != null)
432                        {
433                            for (Script script : scriptsToAdd)
434                            {
435                                List<ScriptFile> scriptFiles = scripts ? script.getScriptFiles() : script.getCSSFiles();
436                                if (scriptFiles != null)
437                                {
438                                    files.addAll(scriptFiles);
439                                }
440                            }
441                        }
442                    }
443                }
444
445                Set<ClientSideElement> validators = richTextConfiguration.getValidators(category, contextParameters);
446                if (validators != null)
447                {
448                    for (ClientSideElement validator : validators)
449                    {
450                        List<Script> scriptsToAdd = validator.getScripts(Collections.EMPTY_MAP);
451                        if (scriptsToAdd != null)
452                        {
453                            for (Script script : scriptsToAdd)
454                            {
455                                List<ScriptFile> scriptFiles = scripts ? script.getScriptFiles() : script.getCSSFiles();
456                                if (scriptFiles != null)
457                                {
458                                    files.addAll(scriptFiles);
459                                }
460                            }
461                        }
462                    }
463                }
464            }
465        }
466
467        return files;
468    }
469
470    private static void _addRichTextConfigurationFiles(Map<String, Map<String, String>> files, Map<String, String> filesInfos, String locale, boolean scripts)
471    {
472        Map<String, Object> contextParameters = new HashMap<>();
473        contextParameters.put("siteName", AmetysXSLTHelper.site());
474        
475        List<ScriptFile> richTextConfigurationFiles = _getRichTextConfigurationFiles(scripts, contextParameters);
476        for (ScriptFile file : richTextConfigurationFiles)
477        {
478            String uri = null;
479            if (file.isLangSpecific())
480            {
481                if (file.getLangPaths().containsKey(locale))
482                {
483                    uri = file.getLangPaths().get(locale);
484                }
485                else if (file.getLangPaths().containsKey(file.getDefaultLang()))
486                {
487                    uri = file.getLangPaths().get(file.getDefaultLang());
488                }
489            }
490            else
491            {
492                uri = file.getPath();
493            }
494            
495            if (uri != null)
496            {
497                files.put(uri, filesInfos);
498            }
499        }
500    }
501    /**
502     * Check if we can display the front edition button for a specific right
503     * Checks :
504     * * Rendering context == front
505     * * Edition mode
506     * * Front_Edition_Access_Right on current page
507     * * RightId available  on object
508     * @param rightId right to check (can be null)
509     * @param objectId id of page/content to check. Can be null or empty to get the current page
510     * @return true if all is OK, false if at least one is false
511     * @deprecated Use the version with three arguments
512     */
513    @Deprecated
514    public static boolean hasFrontEditionRight(String rightId, String objectId)
515    {
516        return hasFrontEditionRight(rightId, objectId, true);
517    }
518    /**
519     * Check if we can display the front edition button for a specific right
520     * Checks :
521     * * Rendering context == front
522     * * Edition mode
523     * * Front_Edition_Access_Right on current page
524     * * RightId available on object
525     * @param rightId right to check (can be null)
526     * @param objectId id of page/content to check. Can be null or empty to get the current page
527     * @param editionModeOnly Check if the user is in edition mode
528     * @return true if all is OK, false if at least one is false
529     */
530    public static boolean hasFrontEditionRight(String rightId, String objectId, boolean editionModeOnly)
531    {
532        String aoId = objectId;
533        if (StringUtils.isEmpty(aoId))
534        {
535            aoId = AmetysXSLTHelper.pageId();
536        }
537        
538        if (StringUtils.isEmpty(aoId)                                 // No page or content to check
539            || !RenderingContext.FRONT.toString().equals(AmetysXSLTHelper.renderingContext())     // We are no on front
540            || editionModeOnly && !AmetysXSLTHelper.isEditionMode()   // Not in edition mode
541            || !hasFrontEditionRight())                                 // The user has the front edition right on current page
542        {
543            
544            return false;
545        }
546        
547        Request request = ContextHelper.getRequest(_context);
548        
549        // Retrieve the current workspace.
550        String currentWsp = RequestAttributeWorkspaceSelector.getForcedWorkspace(request);
551        
552        try
553        {
554            // Force default workspace (rights have to be checked on default workspace)
555            // The target objectId can be a node page, available of front only when a first subpage will be created
556            RequestAttributeWorkspaceSelector.setForcedWorkspace(request, RepositoryConstants.DEFAULT_WORKSPACE);
557            
558            if (StringUtils.contains(aoId, ";"))
559            {
560                String[] pageIds = StringUtils.split(aoId, ";");
561                for (String pid : pageIds)
562                {
563                    if (_rightManager.currentUserHasRight(rightId, _ametysObjectResolver.resolveById(pid)) == RightResult.RIGHT_ALLOW)   // Check right on page (If this page does not exists an exception will be thrown... this is fine)
564                    {
565                        return true;
566                    }
567                    // else check the next one
568                }
569                return false; // No right inside the list
570            }
571            else
572            {
573                return StringUtils.isEmpty(rightId) // There is no right to check OR the user has the right
574                    || _rightManager.currentUserHasRight(rightId, _ametysObjectResolver.resolveById(aoId)) == RightResult.RIGHT_ALLOW;   // Check right on page (If this page does not exists an exception will be thrown... this is fine)
575            }
576        }
577        finally
578        {
579            // Restore workspace
580            RequestAttributeWorkspaceSelector.setForcedWorkspace(request, currentWsp);
581        }
582    }
583    
584    /**
585     * Check if current user has right on Ametys object for front edition
586     * Checks :
587     * * Rendering context == front
588     * * Edition mode
589     * * Front_Edition_Access_Right on current page
590     * * RightId available on object
591     * @param rightId right to check (can be null)
592     * @param ao The ametys object check. Cannot be null
593     * @param editionModeOnly Check if the user is in edition mode
594     * @return true if all is OK, false if at least one is false
595     */
596    public static boolean hasFrontEditionRight(String rightId, AmetysObject ao, boolean editionModeOnly)
597    {
598        if (!RenderingContext.FRONT.toString().equals(AmetysXSLTHelper.renderingContext())     // We are no on front
599            || editionModeOnly && !AmetysXSLTHelper.isEditionMode()   // Not in edition mode
600            || !hasFrontEditionRight())                                 // The user has the front edition right on current page
601        {
602            return false;
603        }
604        
605        Request request = ContextHelper.getRequest(_context);
606        
607        // Retrieve the current workspace.
608        String currentWsp = RequestAttributeWorkspaceSelector.getForcedWorkspace(request);
609        
610        try
611        {
612            // Force default workspace (rights have to be checked on default workspace)
613            // The target objectId can be a node page, available of front only when a first subpage will be created
614            RequestAttributeWorkspaceSelector.setForcedWorkspace(request, RepositoryConstants.DEFAULT_WORKSPACE);
615            
616            return StringUtils.isEmpty(rightId) // There is no right to check OR the user has the right
617                    || _rightManager.currentUserHasRight(rightId, ao) == RightResult.RIGHT_ALLOW;   // Check right on page (If this page does not exists an exception will be thrown... this is fine)
618        }
619        finally
620        {
621            // Restore workspace
622            RequestAttributeWorkspaceSelector.setForcedWorkspace(request, currentWsp);
623        }
624    }
625    
626    /**
627     * Check if the current user has the Front_Edition_Access_Right right
628     * @return true if right granted
629     */
630    public static boolean hasFrontEditionRight()
631    {
632        Request request = ContextHelper.getRequest(_context);
633        
634        // Retrieve the current workspace.
635        String currentWsp = RequestAttributeWorkspaceSelector.getForcedWorkspace(request);
636        
637        try
638        {
639            // Force default workspace (rights have to be checked on default workspace)
640            RequestAttributeWorkspaceSelector.setForcedWorkspace(request, RepositoryConstants.DEFAULT_WORKSPACE);
641            
642            String pageId = AmetysXSLTHelper.pageId();
643            if (StringUtils.isNotEmpty(pageId))
644            {
645                Page page = _ametysObjectResolver.resolveById(pageId);
646                return _rightManager.currentUserHasRight(FRONT_EDITION_RIGHT_ID, page) == RightResult.RIGHT_ALLOW;
647            }
648            
649            String lang = AmetysXSLTHelper.lang();
650            if (StringUtils.isEmpty(lang))
651            {
652                lang = (String) request.getAttribute("lang");
653            }
654            String siteName = AmetysXSLTHelper.site();
655            
656            if (StringUtils.isNotEmpty(siteName) && StringUtils.isNoneEmpty(lang))
657            {
658                Site site = _siteManager.getSite(siteName);
659                Sitemap sitemap = site.getSitemap(lang);
660                return _rightManager.currentUserHasRight(FRONT_EDITION_RIGHT_ID, sitemap) == RightResult.RIGHT_ALLOW;
661            }
662            
663            return false;
664        }
665        finally
666        {
667            // Restore workspace
668            RequestAttributeWorkspaceSelector.setForcedWorkspace(request, currentWsp);
669        }
670        
671        
672    }
673    /**
674     * Check if the current workflow action is available on this content
675     * @param actionId action to check
676     * @param contentId content to check
677     * @param checkEditionMode check also if we are in edition mode
678     * @return true if right is granted
679     */
680    public static boolean hasWorkflowRight(int actionId, String contentId, boolean checkEditionMode)
681    {
682        List<Integer> actionIds = new ArrayList<>();
683        actionIds.add(actionId);
684        return hasWorkflowRight(actionIds, contentId, checkEditionMode);
685    }
686    /**
687     * Check if a list of workflow actions are available on this content
688     * @param actionIds list of action ids
689     * @param contentId id of the content to check
690     * @param checkEditionMode check also if we are in edition mode
691     * @return true if all actions are available
692     */
693    public static boolean hasWorkflowRight(List<Integer> actionIds, String contentId, boolean checkEditionMode)
694    {
695        Content content = _ametysObjectResolver.resolveById(contentId);
696        return hasWorkflowRight(actionIds, content, checkEditionMode);
697    }
698    /**
699     * Check if a list of workflow actions are available on this content
700     * @param actionIds list of action ids
701     * @param content content to check
702     * @param checkEditionMode check also if we are in edition mode
703     * @return true if all actions are available
704     */
705    public static boolean hasWorkflowRight(List<Integer> actionIds, Content content, boolean checkEditionMode)
706    {
707        if (checkEditionMode)
708        {
709            boolean editionModeOk = AmetysXSLTHelper.isEditionMode();
710            if (!editionModeOk)
711            {
712                return false;
713            }
714        }
715        boolean result = false;
716        if (content instanceof WorkflowAwareContent)
717        {
718            WorkflowAwareContent wcontent = (WorkflowAwareContent) content;
719            int[] availableActions = _contentWorkflowHelper.getAvailableActions(wcontent);
720            for (int actionId : actionIds)
721            {
722                result = result || ArrayUtils.contains(availableActions, actionId);
723                if (result)
724                {
725                    break;
726                }
727            }
728        }
729        return result;
730    }
731    
732    /**
733     * Get the toolbar configuration for page: retrieve the user rights, the parent and page position
734     * @param pageId The page id
735     * @param addContentsConfigAsJson The items configuration for adding contents as JSON string
736     * @param editionModeOnly true to check edition mode
737     * @return the user's rights, parent and page position
738     * @throws UnknownAmetysObjectException if content is unknown
739     * @throws AmetysRepositoryException if an error occurred
740     * @throws RepositoryException if an error occurred 
741     */
742    public static String getPageToolbarConfig(String pageId, String addContentsConfigAsJson, boolean editionModeOnly) throws UnknownAmetysObjectException, AmetysRepositoryException, RepositoryException
743    {
744        Map<String, Object> result = new HashMap<>();
745        
746        Page page = _ametysObjectResolver.resolveById(pageId);
747        SitemapElement parent = page.getParent();
748        long position = _getPagePosition(page);
749        
750        List<Object> addContentsConfig = _jsonUtils.convertJsonToList(addContentsConfigAsJson);
751        
752        @SuppressWarnings("unchecked")
753        Set<Object> allowedContentTypes = addContentsConfig.stream()
754            .filter(Map.class::isInstance)
755            .filter(cfg -> _hasContentCreationRight((Map) cfg))
756            .map(cfg -> (String) ((Map) cfg).get("contentType"))
757            .collect(Collectors.toSet());
758        result.put("allowedContentTypes", allowedContentTypes);
759        
760        result.put("title", page.getTitle());
761        result.put("parentId", parent.getId());
762        result.put("position", position);
763
764        // Get the active status for each action depending on user's rights, page position, FO edition mode, ...
765        result.put("actionStatus", _getActionStatusOnPage(page, position, parent.getChildrenPages().getSize(), editionModeOnly));
766        
767        return _jsonUtils.convertObjectToJson(result);
768    }
769    
770    private static boolean _hasContentCreationRight(Map<String, Object> config)
771    {
772        if (config.containsKey("contentType"))
773        {
774            String cTypeId = (String) config.get("contentType");
775            
776            ContentType contentType = _contentTypesEP.getExtension(cTypeId);
777            if (contentType == null)
778            {
779                _logger.warn("Unknown content type '" + cTypeId + "'");
780                return false;
781            }
782            
783            String right = contentType.getRight();
784            if (StringUtils.isEmpty(right))
785            {
786                return true;
787            }
788            
789            return _rightManager.currentUserHasRight(right, "/cms") == RightResult.RIGHT_ALLOW || _rightManager.currentUserHasRight(right, _rootContentHelper.getRootContent()) == RightResult.RIGHT_ALLOW;
790        }
791        else
792        {
793            _logger.warn("Configuration to add content is invalid: missing 'contentType'. It will be ignored");
794            return false;
795        }
796    }
797    
798    private static long _getPagePosition(Page page) throws AmetysRepositoryException
799    {
800        SitemapElement parent = page.getParent();
801        AmetysObjectIterable< ? extends Page> children = parent.getChildrenPages();
802        
803        long count = 1;
804        for (Page child : children)
805        {
806            if (child.getId().equals(page.getId()))
807            {
808                return count;
809            }
810            count++;
811        }
812        
813        // Not found
814        return -1;
815    }
816    
817    private static Map<String, Boolean> _getActionStatusOnPage(Page page, long position, long size, boolean editionModeOnly) throws UnknownAmetysObjectException, AmetysRepositoryException
818    {
819        Map<String, Boolean> rights = new HashMap<>();
820        
821        if (page instanceof ModifiablePage)
822        {
823            rights.put("add-content", hasFrontEditionRight("Web_Rights_Page_AddContent", page, editionModeOnly));
824            rights.put("add-page", hasFrontEditionRight("Web_Rights_Page_Create", page, editionModeOnly));
825            rights.put("tag", hasFrontEditionRight("Web_Rights_Page_Tag", page, editionModeOnly));
826            rights.put("rename", hasFrontEditionRight("Web_Rights_Page_Rename", page, editionModeOnly));
827            rights.put("schedule-publication", hasFrontEditionRight("Web_Rights_Page_Schedule", page, editionModeOnly));
828            rights.put("delete", hasFrontEditionRight("Web_Rights_Page_Delete", page, editionModeOnly));
829            
830            boolean canMove = hasFrontEditionRight("Web_Rights_Page_Create", page.getParent().getId(), editionModeOnly);
831            boolean moveUp = canMove && position > 1;
832            boolean moveDown = canMove && position < size;
833            
834            rights.put("move-up", moveUp);
835            rights.put("move-down", moveDown);
836            rights.put("move", moveDown || moveUp);
837        }
838        
839        return rights;
840    }
841    
842    /**
843     * Get the toolbar configuration for content: retrieve user rights, available workflow actions, content current step and status history
844     * @param contentId The content id
845     * @param zoneItemId The zone item id
846     * @param restrictedActions The actions ids to retrieve. Set to null or empty to get all available workflow actions with no restriction
847     * @param jsonStepConfig The step configuration
848     * @param locale the locale for translation
849     * @param editionModeOnly true to check edition mode
850     * @return the user's rights, available workflow actions and content current step
851     * @throws UnknownAmetysObjectException if content is unknown
852     * @throws AmetysRepositoryException if an error occurred
853     * @throws RepositoryException if an error occurred 
854     */
855    public static String getContentToolbarConfig(String contentId, String zoneItemId, String restrictedActions, String jsonStepConfig, String locale, boolean editionModeOnly) throws UnknownAmetysObjectException, AmetysRepositoryException, RepositoryException
856    {
857        Map<String, Object> result = new HashMap<>();
858        
859        Content content = _ametysObjectResolver.resolveById(contentId);
860
861        // Get the active status of each action depending on user rights, FO mode, content's position, ...
862        result.put("actionStatus", _getActionStatusOnContent(content, zoneItemId, editionModeOnly));
863        
864        if (content instanceof WorkflowAwareContent)
865        {
866            WorkflowDescriptor workflowDescriptor = _getWorkflowDescriptor((WorkflowAwareContent) content);
867            
868            WorkflowAwareContent wcontent = (WorkflowAwareContent) content;
869            
870            Map<String, Object> step = new HashMap<>();
871            long currentStepId = wcontent.getCurrentStepId();
872            
873            // Current step
874            StepDescriptor stepDescriptor = _getStepDescriptor(workflowDescriptor, currentStepId);
875            step.put("id", currentStepId);
876            String name = stepDescriptor.getName();
877            step.put("label", new I18nizableText(StringUtils.substringBefore(name, ":"), StringUtils.substringAfter(name, ":")));
878            result.put("step", step);
879            
880            Map<String, Object> stepConfig = StringUtils.isEmpty(jsonStepConfig) ? null : _jsonUtils.convertJsonToMap(jsonStepConfig);
881            result.put("statusHistory", _getStatusHistory(wcontent, currentStepId, stepConfig, workflowDescriptor));
882            
883            List<Integer> availableActions = Arrays.stream(_contentWorkflowHelper.getAvailableActions(wcontent)).boxed().collect(Collectors.toList());
884            result.put("availableWorkflowActions", availableActions);
885            
886            if (!editionModeOnly || AmetysXSLTHelper.isEditionMode())
887            {
888                List<Object> restrictedActionsAsList = StringUtils.isEmpty(restrictedActions) ? null : _jsonUtils.convertJsonToList(restrictedActions);
889                
890                List<Object> restrictedActionIds = restrictedActionsAsList == null ? null : restrictedActionsAsList.stream()
891                    .map(o -> o instanceof Map ? ((Map) o).get("id") : o)
892                    .collect(Collectors.toList());
893                
894                @SuppressWarnings("unchecked")
895                Map<Object, Map<String, Object>> workflowActions = availableActions.stream()
896                    .filter(actionId -> restrictedActionIds == null || restrictedActionIds.contains(actionId))
897                    .map(actionId -> {
898                        Map<String, Object> wa = new HashMap<>();
899                        
900                        _addDefaultWorkflowActionProperties(wa, workflowDescriptor, actionId);
901                        
902                        if (restrictedActionIds != null && restrictedActionsAsList != null && restrictedActionIds.contains(actionId))
903                        {
904                            for (Object object : restrictedActionsAsList)
905                            {
906                                if (object instanceof Map && ((Map) object).get("id") == actionId)
907                                {
908                                    // get or override properties from map sent by client side
909                                    wa.putAll((Map<String, Object>) object);
910                                    break;
911                                }
912                            }
913                            
914                        }
915                        return Pair.of(actionId, wa);
916                    })
917                    .collect(Collectors.toMap(Pair::getLeft, Pair::getRight));
918                
919                result.put("workflowActions", workflowActions);
920            }
921        }
922        
923        Request request = ContextHelper.getRequest(_context);
924        try
925        {
926            request.setAttribute(I18nizableSerializer.REQUEST_ATTR_LOCALE, locale);
927            return _jsonUtils.convertObjectToJson(result);
928        }
929        finally
930        {
931            request.removeAttribute(I18nizableSerializer.REQUEST_ATTR_LOCALE);
932        }
933    }
934    
935    private static Map<String, Boolean> _getActionStatusOnContent(Content content, String zoneItemId, boolean editionModeOnly) throws UnknownAmetysObjectException, AmetysRepositoryException
936    {
937        Map<String, Boolean> rights = new HashMap<>();
938        
939        ZoneItem zoneItem = _ametysObjectResolver.resolveById(zoneItemId);
940        Zone zone = zoneItem.getZone();
941        SitemapElement sitemapElement = zone.getSitemapElement();
942        
943        rights.put("tag", hasFrontEditionRight("CMS_Rights_Content_Tag", content, editionModeOnly));
944        rights.put("remove", sitemapElement instanceof ModifiablePage && hasFrontEditionRight("Web_Rights_Page_DeleteZoneItem", sitemapElement, editionModeOnly));
945        rights.put("delete", hasFrontEditionRight("CMS_Rights_DeleteContent", content, editionModeOnly));
946        
947        boolean moveUp = false;
948        boolean moveDown = false;
949        
950        long position = getZoneItemPosition(zoneItem);
951        long size = getZoneSize(zone);
952        
953        if (position != -1 && sitemapElement instanceof ModifiablePage && hasFrontEditionRight("Web_Rights_Page_OrganizeZoneItem", sitemapElement, editionModeOnly))
954        {
955            if (position > 0) 
956            {
957                moveUp = true;
958            }
959            
960            if (position + 1 < size)
961            {
962                moveDown = true;
963            }
964        }
965        rights.put("move-up", moveUp);
966        rights.put("move-down", moveDown);
967        rights.put("move", moveDown || moveUp);
968        
969        return rights;
970    }
971    
972    private static Map<Integer, Map<String, Object>> _getStatusHistory(WorkflowAwareContent content, long currentStepId, Map<String, Object> stepsConfig, WorkflowDescriptor workflowDescriptor)
973    {
974        List<Step> historyStatus = new ArrayList<>();
975            
976        if (stepsConfig.containsKey(String.valueOf(currentStepId)))
977        {
978            AmetysObjectWorkflow workflow = _workflowProvider.getAmetysObjectWorkflow(content);
979            
980            long workflowId = content.getWorkflowId();
981            List<Step> historySteps = workflow.getHistorySteps(workflowId);
982
983            // Sort by start date descendant 
984            Collections.sort(historySteps, new Comparator<Step>()
985            {
986                public int compare(Step s1, Step s2)
987                {
988                    return -s1.getStartDate().compareTo(s2.getStartDate());
989                }
990            });
991            
992            @SuppressWarnings("unchecked")
993            Map<String, Object> currentStepCfg = (Map<String, Object>) stepsConfig.get(String.valueOf(currentStepId));
994            String currentStepType = currentStepCfg != null ? (String) currentStepCfg.get("type") : null;
995            
996            boolean stop = false;
997            for (Step step : historySteps)
998            {
999                if (stop)
1000                {
1001                    break;
1002                }
1003
1004                long stepId = step.getStepId();
1005                @SuppressWarnings("unchecked")
1006                Map<String, Object> stepCfg = (Map<String, Object>) stepsConfig.get(String.valueOf(stepId));
1007                String stepType = stepCfg != null ? (String) stepCfg.get("type") : null;
1008                
1009                stop = "positive".equals(currentStepType) && !"positive".equals(stepType) 
1010                        || ("negative".equals(currentStepType) || "neutral".equals(currentStepType)) && !"negative".equals(stepType)
1011                        || currentStepId == stepId;
1012                
1013                if (!stop)
1014                {
1015                    historyStatus.add(step);
1016                }
1017            }
1018        }
1019        
1020        Map<Integer, Map<String, Object>> jsonHistoryStatus = new LinkedHashMap<>();
1021        for (Step step : historyStatus)
1022        {
1023            if (!jsonHistoryStatus.containsKey(step.getStepId()))
1024            {
1025                StepDescriptor stepDescriptor = _getStepDescriptor(workflowDescriptor, step.getStepId());
1026                String name = stepDescriptor.getName();
1027                I18nizableText label = new I18nizableText(StringUtils.substringBefore(name, ":"), StringUtils.substringAfter(name, ":"));
1028                jsonHistoryStatus.put(step.getStepId(), Map.of("label", label));
1029            }
1030        }
1031        
1032        return jsonHistoryStatus;
1033    }
1034    
1035    private static void _addDefaultWorkflowActionProperties(Map<String, Object> wa, WorkflowDescriptor workflowDescriptor, int actionId)
1036    {
1037        // Add workflow action label
1038        ActionDescriptor wAction = workflowDescriptor.getAction(actionId);
1039        String name = wAction.getName();
1040        wa.put("label", new I18nizableText(StringUtils.substringBefore(name, ":"), StringUtils.substringAfter(name, ":")));
1041        
1042        // Default workflow icon
1043        switch (actionId)
1044        {
1045            case 3:
1046                wa.put("icon", "fas fa-hand-point-up"); // Propose
1047                break;
1048            case 4:
1049                wa.put("icon", "fas fa-check"); // Validate
1050                break;
1051            case 7:
1052                wa.put("icon", "fas fa-times"); // Refuse
1053                break;  
1054            case 10:
1055                wa.put("icon", "fas fa-ban"); // Unpublish
1056                break;  
1057            default:
1058                break;
1059        }
1060    }
1061    
1062    private static WorkflowDescriptor _getWorkflowDescriptor(WorkflowAwareContent content)
1063    {
1064        long workflowId = content.getWorkflowId();
1065        
1066        AmetysObjectWorkflow workflow = _workflowProvider.getAmetysObjectWorkflow(content);
1067        
1068        String workflowName = workflow.getWorkflowName(workflowId);
1069        return workflow.getWorkflowDescriptor(workflowName);
1070    }
1071    
1072    private static StepDescriptor _getStepDescriptor(WorkflowDescriptor workflowDescriptor, long stepId)
1073    {
1074        if (workflowDescriptor != null)
1075        {
1076            StepDescriptor stepDescriptor = workflowDescriptor.getStep((int) stepId);
1077            if (stepDescriptor != null)
1078            {
1079                return stepDescriptor;
1080            }
1081        }
1082        
1083        return null;
1084    }
1085    
1086    /**
1087     * Get a string representing a json map of the contentIds with true/false if they can/can't be modified 
1088     * @param actionId action to check
1089     * @param inputPageId page (can be null)
1090     * @param checkEditionMode check also if we are in edition mode
1091     * @return {contentId : true/false, ....}
1092     */
1093    public static String getModifiableContents(int actionId, String inputPageId, boolean checkEditionMode)
1094    {
1095        Map<String, Object> jsonObject = new HashMap<>();
1096        String pageId = inputPageId;
1097        if (StringUtils.isEmpty(inputPageId))
1098        {
1099            pageId = AmetysXSLTHelper.pageId();
1100        }
1101        
1102        if (!StringUtils.isEmpty(pageId))
1103        {
1104            AmetysObject resolveById = _ametysObjectResolver.resolveById(pageId);
1105            if (resolveById instanceof Page)
1106            {
1107                Page page = (Page) resolveById;
1108                List<Content> contents = _pageHelper.getAllContents(page);
1109                for (Content content : contents)
1110                {
1111                    Map<String, Object> contentInfo = new HashMap<>();
1112                    contentInfo.put("unmodifiableAttributes", AmetysFrontEditionHelper.getUnmodifiableAttributes(content, List.of(actionId), checkEditionMode));
1113                    contentInfo.put("rights", AmetysFrontEditionHelper.getRightsForContent(content));
1114                    
1115                    jsonObject.put(content.getId(), contentInfo);
1116                }
1117            }
1118        }
1119
1120        return _jsonUtils.convertObjectToJson(jsonObject);
1121    }
1122    
1123    /**
1124     * Get path of unmodifiable attributes. Check if content can be modified and the restrictions on attributes
1125     * @param content the content
1126     * @param actionIds the workflow action ids to check
1127     * @param checkEditionMode to check edition mode
1128     * @return the list with the path of unmodifiable attributes (regarding of restrictions) or null if the content cannot be modified
1129     */
1130    public static List<String> getUnmodifiableAttributes(Content content, List<Integer> actionIds, boolean checkEditionMode)
1131    {
1132        try
1133        {
1134            boolean hasWorkflowRight = hasWorkflowRight(actionIds, content, checkEditionMode);
1135            if (!hasWorkflowRight)
1136            {
1137                // content is not editable
1138                return null;
1139            }
1140            
1141            Collection<? extends ModelItem> modelItems = _contentTypesHelper.getModelItems(content.getTypes());
1142            List<AttributeDefinition> attributes = _getAttributeDefinitionsRecursively(modelItems);
1143            return attributes.stream()
1144                .filter(mi -> !mi.canWrite(content))
1145                .map(mi -> mi.getPath())
1146                .collect(Collectors.toList());
1147        }
1148        catch (IllegalArgumentException e)
1149        {
1150            _logger.error("Fail to get restricted model items for content " + content.getId(), e);
1151            return List.of();
1152        }
1153    }
1154    
1155    /**
1156     * Get a map of chosen rights for a content
1157     * @param content the content
1158     * @return the chosen rights for a content
1159     */
1160    public static Map<String, Object> getRightsForContent(Content content)
1161    {
1162        Map<String, Object> rights = new HashMap<>();
1163        rights.put("hasAddFileRight", _rightManager.currentUserHasRight(ExplorerResourcesDAO.RIGHTS_RESOURCE_ADD, content) == RightResult.RIGHT_ALLOW);
1164        return rights;
1165    }
1166    
1167    private static List<AttributeDefinition> _getAttributeDefinitionsRecursively(Collection<? extends ModelItem> modelItems)
1168    {
1169        List<AttributeDefinition> attributeDefs = new ArrayList<>();
1170        
1171        for (ModelItem modelItem : modelItems)
1172        {
1173            if (modelItem instanceof AttributeDefinition)
1174            {
1175                attributeDefs.add((AttributeDefinition) modelItem);
1176            }
1177            else if (modelItem instanceof ModelItemGroup)
1178            {
1179                attributeDefs.addAll(_getAttributeDefinitionsRecursively(((ModelItemGroup) modelItem).getModelItems()));
1180            }
1181        }
1182        
1183        return attributeDefs;
1184    }
1185    
1186    /**
1187     * Get the name of a workflow action
1188     * @param workflowName workflow name
1189     * @param actionId action id in the workflow
1190     * @return name of the workflow action
1191     */
1192    public static String getWorkflowName(String workflowName, int actionId)
1193    {
1194        String workflowNameKey = _workflowHelper.getActionName(workflowName, actionId);
1195        String translatedName = org.ametys.core.util.AmetysXSLTHelper.translate(workflowNameKey);
1196        return translatedName;
1197    }
1198    /**
1199     * Get the status (validated/draft) of all contents in a page
1200     * @param pageId id of the page to check
1201     * @return "" if not a page, "draft" if all contents are drafts, "validated" if all contents are validated, and "mixed" if there are both
1202     */
1203    public static String getPageStatus(String pageId)
1204    {
1205        boolean hasDraft = false;
1206        boolean hasValidated = false;
1207        AmetysObject resolveById = _ametysObjectResolver.resolveById(pageId);
1208        if (resolveById instanceof Page)
1209        {
1210            Page page = (Page) resolveById;
1211            List<Content> contents = _pageHelper.getAllContents(page);
1212            for (Content content : contents)
1213            {
1214                if (isContentLive(content))
1215                {
1216                    hasValidated = true;
1217                }
1218                else
1219                {
1220                    hasDraft = true;
1221                }
1222            }
1223            String result = "none";
1224            if (hasDraft && !hasValidated)
1225            {
1226                result = "draft";
1227            }
1228            else if (!hasDraft && hasValidated)
1229            {
1230                result = "validated";
1231            }
1232            else if (hasDraft && hasValidated)
1233            {
1234                result = "mixed";
1235            }
1236            return result;
1237        }
1238        else
1239        {
1240            return "";
1241        }
1242    }
1243
1244    /**
1245     * Get the workflow step id of a content
1246     * @param contentId id of the content
1247     * @return the step Id
1248     */
1249    public static long getContentWorkflowId(String contentId)
1250    {
1251        AmetysObject resolvedById = _ametysObjectResolver.resolveById(contentId);
1252        if (resolvedById instanceof Content)
1253        {
1254            Content content = (Content) resolvedById;
1255            return getContentWorkflowId(content);
1256        }
1257        else
1258        {
1259            return 0;
1260        }
1261    }
1262    /**
1263     * Get the workflow step id of a content
1264     * @param content content
1265     * @return the step Id
1266     */
1267    public static long getContentWorkflowId(Content content)
1268    {
1269        WorkflowAwareContent wContent = (WorkflowAwareContent) content;
1270        return wContent.getCurrentStepId();
1271    }
1272
1273    /**
1274     * check if a content is published ot not
1275     * @param contentId id of the content
1276     * @return "validated" or "draft", "" if not found
1277     */
1278    public static String getContentStatus(String contentId)
1279    {
1280        AmetysObject resolvedById = _ametysObjectResolver.resolveById(contentId);
1281        if (resolvedById instanceof Content)
1282        {
1283            Content content = (Content) resolvedById;
1284            return getContentStatus(content);
1285        }
1286        else
1287        {
1288            return "";
1289        }
1290    }
1291    /**
1292     * check if a content is published ot not
1293     * @param content content
1294     * @return "validated" or "draft"
1295     */
1296    public static String getContentStatus(Content content)
1297    {
1298        return isContentLive(content) ? "validated" : "draft";
1299    }
1300    /**
1301     * check if a content is published ot not
1302     * @param contentId id of the content
1303     * @return true if validated
1304     */
1305    public static boolean isContentLive(String contentId)
1306    {
1307        AmetysObject resolvedById = _ametysObjectResolver.resolveById(contentId);
1308        if (resolvedById instanceof Content)
1309        {
1310            Content content = (Content) resolvedById;
1311            return isContentLive(content);
1312        }
1313        else
1314        {
1315            return false;
1316        }
1317    }
1318    /**
1319     * check if a content is published ot not
1320     * @param content content
1321     * @return true if validated
1322     */
1323    public static boolean isContentLive(Content content)
1324    {
1325        return Arrays.asList(((VersionableAmetysObject) content).getLabels()).contains(CmsConstants.LIVE_LABEL);
1326    }
1327    /**
1328     * Get the position of this zoneItem in the zone, or -1 if not found
1329     * @param zoneItemId zoneitem to search
1330     * @return zero based position, -1 if not found
1331     * @throws UnknownAmetysObjectException If zone item is not found
1332     * @throws AmetysRepositoryException If an error occurred
1333     */
1334    public static long getZoneItemPosition(String zoneItemId) throws UnknownAmetysObjectException, AmetysRepositoryException
1335    {
1336        ZoneItem zoneItem = _ametysObjectResolver.resolveById(zoneItemId);
1337        return getZoneItemPosition(zoneItem);
1338    }
1339    
1340    /**
1341     * Get the position of this zoneItem in its parent zone, or -1 if not found
1342     * @param zoneItem zoneitem
1343     * @return zero based position, -1 if not found
1344     */
1345    public static long getZoneItemPosition(ZoneItem zoneItem)
1346    {
1347        AmetysObject parent = zoneItem.getParent();
1348        if (parent instanceof DefaultTraversableAmetysObject)
1349        {
1350            return ((DefaultTraversableAmetysObject) parent).getChildPosition(zoneItem);
1351        }
1352        return -1; // virtual page
1353    }
1354    
1355    /**
1356     * Return the size of a zone
1357     * @param zoneName zone name
1358     * @param pageId page Id
1359     * @return size of the zone (-1 if not found)
1360     */
1361    public static long getZoneSize(String zoneName, String pageId)
1362    {
1363        Page page = _ametysObjectResolver.resolveById(pageId);
1364        Zone zone = page.getZone(zoneName);
1365        return getZoneSize(zone);
1366    }
1367    
1368    /**
1369     * Return the size of a zone
1370     * @param zone the zone
1371     * @return size of the zone or -1 is zone is null
1372     */
1373    public static long getZoneSize(Zone zone)
1374    {
1375        if (zone != null)
1376        {
1377            return zone.getZoneItems().getSize();
1378        }
1379        return -1;
1380    }
1381    /**
1382     * Test if a page is modifiable
1383     * @param pageId id of the page to check
1384     * @return true if the page is modifiable, false otherwise
1385     */
1386    public static boolean isPageModifiable(String pageId)
1387    {
1388        try
1389        {
1390            AmetysObject resolveById = _ametysObjectResolver.resolveById(pageId);
1391            return resolveById instanceof ModifiablePage;
1392        }
1393        catch (AmetysRepositoryException e)
1394        {
1395            // Nothing, this is not a page
1396        }
1397        
1398        return false;
1399    }
1400    
1401    /**
1402     * Returns the ids of the pages tagged with the specified tag in default workspace
1403     * @param tag The tag id
1404     * @return Array of pages ids
1405     */
1406    public static NodeList findPagesIdsByTagInDefaultWorkspace(String tag)
1407    {
1408        return findPagesIdsByTagInDefaultWorkspace(tag, false);
1409    }
1410    
1411    /**
1412     * Returns the ids of the pages tagged with the specified tag  in default workspace
1413     * @param tag The tag id
1414     * @param checkReadAccess true to return only pages with read access for current user
1415     * @return Array of pages ids
1416     */
1417    public static NodeList findPagesIdsByTagInDefaultWorkspace(String tag, boolean checkReadAccess)
1418    {
1419        Request request = ContextHelper.getRequest(_context);
1420        
1421        // Retrieve the current workspace.
1422        String currentWsp = RequestAttributeWorkspaceSelector.getForcedWorkspace(request);
1423        
1424        try
1425        {
1426            // Force default workspace
1427            // The tagged page can be a node page, available of front only when a first subpage will be created
1428            RequestAttributeWorkspaceSelector.setForcedWorkspace(request, RepositoryConstants.DEFAULT_WORKSPACE);
1429            return AmetysXSLTHelper.findPagesIdsByTag(tag, checkReadAccess);
1430        }
1431        finally
1432        {
1433         // Restore workspace
1434            RequestAttributeWorkspaceSelector.setForcedWorkspace(request, currentWsp);
1435        }
1436    }
1437    /**
1438     * Returns the ids of the pages tagged with the specified tag in default workspace
1439     * @param sitename The site id
1440     * @param lang The language code
1441     * @param tag The tag id
1442     * @return Array of pages ids
1443     */
1444    public static NodeList findPagesIdsByTagInDefaultWorkspace(String sitename, String lang, String tag)
1445    {
1446        return findPagesIdsByTagInDefaultWorkspace(sitename, lang, tag, false);
1447    }
1448    
1449    /**
1450     * Returns the ids of the pages tagged with the specified tag in default workspace
1451     * @param sitename The site id
1452     * @param lang The language code
1453     * @param tag The tag id
1454     * @param checkReadAccess true to return only pages with read access for current user
1455     * @return Array of pages ids
1456     */
1457    public static NodeList findPagesIdsByTagInDefaultWorkspace(String sitename, String lang, String tag, boolean checkReadAccess)
1458    {
1459        Request request = ContextHelper.getRequest(_context);
1460        
1461        // Retrieve the current workspace.
1462        String currentWsp = RequestAttributeWorkspaceSelector.getForcedWorkspace(request);
1463        
1464        try
1465        {
1466            // Force default workspace
1467            // The tagged page can be a node page, available of front only when a first subpage will be created
1468            RequestAttributeWorkspaceSelector.setForcedWorkspace(request, RepositoryConstants.DEFAULT_WORKSPACE);
1469            return AmetysXSLTHelper.findPagesIdsByTag(sitename, lang, tag, checkReadAccess);
1470        }
1471        finally
1472        {
1473         // Restore workspace
1474            RequestAttributeWorkspaceSelector.setForcedWorkspace(request, currentWsp);
1475        }
1476    }
1477}