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