001/*
002 *  Copyright 2021 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.forms.dao;
017
018import java.time.LocalDate;
019import java.time.ZonedDateTime;
020import java.util.ArrayList;
021import java.util.HashMap;
022import java.util.List;
023import java.util.Map;
024import java.util.Optional;
025import java.util.Set;
026import java.util.stream.Collectors;
027
028import javax.jcr.Node;
029import javax.jcr.Repository;
030import javax.jcr.RepositoryException;
031
032import org.apache.avalon.framework.component.Component;
033import org.apache.avalon.framework.service.ServiceException;
034import org.apache.avalon.framework.service.ServiceManager;
035import org.apache.avalon.framework.service.Serviceable;
036import org.apache.commons.lang.StringUtils;
037
038import org.ametys.core.observation.Event;
039import org.ametys.core.observation.ObservationManager;
040import org.ametys.core.right.RightManager;
041import org.ametys.core.right.RightManager.RightResult;
042import org.ametys.core.ui.Callable;
043import org.ametys.core.user.CurrentUserProvider;
044import org.ametys.core.user.UserIdentity;
045import org.ametys.core.util.DateUtils;
046import org.ametys.core.util.I18nUtils;
047import org.ametys.plugins.core.user.UserHelper;
048import org.ametys.plugins.forms.FormEvents;
049import org.ametys.plugins.forms.helper.ScheduleOpeningHelper;
050import org.ametys.plugins.forms.repository.CopyFormUpdater;
051import org.ametys.plugins.forms.repository.CopyFormUpdaterExtensionPoint;
052import org.ametys.plugins.forms.repository.Form;
053import org.ametys.plugins.forms.repository.FormDirectory;
054import org.ametys.plugins.forms.repository.FormEntry;
055import org.ametys.plugins.forms.repository.FormFactory;
056import org.ametys.plugins.forms.repository.FormQuestion;
057import org.ametys.plugins.repository.AmetysObject;
058import org.ametys.plugins.repository.AmetysObjectIterable;
059import org.ametys.plugins.repository.AmetysObjectResolver;
060import org.ametys.plugins.repository.ModifiableAmetysObject;
061import org.ametys.plugins.repository.UnknownAmetysObjectException;
062import org.ametys.plugins.repository.jcr.NameHelper;
063import org.ametys.plugins.repository.provider.AbstractRepository;
064import org.ametys.plugins.workflow.support.WorkflowHelper;
065import org.ametys.runtime.i18n.I18nizableText;
066import org.ametys.runtime.model.ElementDefinition;
067import org.ametys.runtime.plugin.component.AbstractLogEnabled;
068import org.ametys.web.parameters.view.ViewParametersManager;
069import org.ametys.web.repository.page.ModifiableZoneItem;
070import org.ametys.web.repository.page.Page;
071import org.ametys.web.repository.page.SitemapElement;
072import org.ametys.web.repository.page.ZoneDAO;
073import org.ametys.web.repository.page.ZoneItem;
074import org.ametys.web.repository.site.SiteManager;
075import org.ametys.web.service.Service;
076import org.ametys.web.service.ServiceExtensionPoint;
077
078/**
079 * The form DAO
080 */
081public class FormDAO extends AbstractLogEnabled implements Serviceable, Component
082{
083    /** The Avalon role */
084    public static final String ROLE = FormDAO.class.getName();
085    /** The right id to handle forms */
086    public static final String HANDLE_FORMS_RIGHT_ID = "Plugins_Forms_Right_Handle";
087
088    private static final String __FORM_NAME_PREFIX = "form-";
089    
090    /** The Ametys object resolver */
091    protected AmetysObjectResolver _resolver;
092    /** The current user provider */
093    protected CurrentUserProvider _userProvider;
094    /** I18n Utils */
095    protected I18nUtils _i18nUtils;
096    /** The form directory DAO */
097    protected FormDirectoryDAO _formDirectoryDAO;
098    /** The form page DAO */
099    protected FormPageDAO _formPageDAO;
100    /** The form entry DAO */
101    protected FormEntryDAO _formEntryDAO;
102    /** The user helper */
103    protected UserHelper _userHelper;
104    /** The JCR repository. */
105    protected Repository _repository;
106    /** The right manager */
107    protected RightManager _rightManager;
108    /** The service extension point */
109    protected ServiceExtensionPoint _serviceEP;
110    /** The zone DAO */
111    protected ZoneDAO _zoneDAO;
112    /** The schedule opening helper */
113    protected ScheduleOpeningHelper _scheduleOpeningHelper;
114    /** The workflow helper */
115    protected WorkflowHelper _workflowHelper;
116    /** The site manager */
117    protected SiteManager _siteManager;
118    /** Observer manager. */
119    protected ObservationManager _observationManager;
120    /** The current user provider. */
121    protected CurrentUserProvider _currentUserProvider;
122    
123    /** The copy form updater extension point */
124    protected CopyFormUpdaterExtensionPoint _copyFormEP;
125    
126    public void service(ServiceManager manager) throws ServiceException
127    {
128        _resolver = (AmetysObjectResolver) manager.lookup(AmetysObjectResolver.ROLE);
129        _userProvider = (CurrentUserProvider) manager.lookup(CurrentUserProvider.ROLE);
130        _userHelper = (UserHelper) manager.lookup(UserHelper.ROLE);
131        _i18nUtils = (I18nUtils) manager.lookup(I18nUtils.ROLE);
132        _formDirectoryDAO = (FormDirectoryDAO) manager.lookup(FormDirectoryDAO.ROLE);
133        _formPageDAO = (FormPageDAO) manager.lookup(FormPageDAO.ROLE);
134        _formEntryDAO = (FormEntryDAO) manager.lookup(FormEntryDAO.ROLE);
135        _repository = (Repository) manager.lookup(AbstractRepository.ROLE);
136        _rightManager = (RightManager) manager.lookup(RightManager.ROLE);
137        _serviceEP = (ServiceExtensionPoint) manager.lookup(ServiceExtensionPoint.ROLE);
138        _zoneDAO = (ZoneDAO) manager.lookup(ZoneDAO.ROLE);
139        _scheduleOpeningHelper = (ScheduleOpeningHelper) manager.lookup(ScheduleOpeningHelper.ROLE);
140        _workflowHelper = (WorkflowHelper) manager.lookup(WorkflowHelper.ROLE);
141        _siteManager = (SiteManager) manager.lookup(SiteManager.ROLE);
142        _observationManager = (ObservationManager) manager.lookup(ObservationManager.ROLE);
143        _currentUserProvider = (CurrentUserProvider) manager.lookup(CurrentUserProvider.ROLE);
144        _copyFormEP = (CopyFormUpdaterExtensionPoint) manager.lookup(CopyFormUpdaterExtensionPoint.ROLE);
145    }
146
147    /**
148     * Check if a user have read rights on a form
149     * @param userIdentity the user
150     * @param form the form
151     * @return true if the user have read rights on a form
152     */
153    public boolean hasReadRightOnForm(UserIdentity userIdentity, Form form)
154    {
155        return _rightManager.hasReadAccess(userIdentity, form);
156    }
157    
158    /**
159     * Check if a user have write rights on a form element
160     * @param userIdentity the user
161     * @param formElement the form element
162     * @return true if the user have write rights on a form element
163     */
164    public boolean hasWriteRightOnForm(UserIdentity userIdentity, AmetysObject formElement)
165    {
166        return _rightManager.hasRight(userIdentity, HANDLE_FORMS_RIGHT_ID, formElement) == RightResult.RIGHT_ALLOW;
167    }
168    
169    /**
170     * Check if a user have write rights on a form
171     * @param userIdentity the user
172     * @param form the form
173     * @return true if the user have write rights on a form
174     */
175    public boolean hasRightAffectationRightOnForm(UserIdentity userIdentity, Form form)
176    {
177        return hasWriteRightOnForm(userIdentity, form) || _rightManager.hasRight(userIdentity, "Runtime_Rights_Rights_Handle", "/cms") == RightResult.RIGHT_ALLOW;
178    }
179    
180    /**
181     * Check rights for a form element as ametys object
182     * @param formElement the form element as ametys object
183     */
184    public void checkHandleFormRight(AmetysObject formElement)
185    {
186        UserIdentity user = _userProvider.getUser();
187        if (!hasWriteRightOnForm(user, formElement))
188        {
189            throw new IllegalAccessError("User '" + user + "' tried to handle forms without convenient right [" + HANDLE_FORMS_RIGHT_ID + "]");
190        }
191    }
192    
193    /**
194     * Get all forms from a site
195     * @param siteName the site name
196     * @return the list of form
197     */
198    public List<Form> getForms(String siteName)
199    {
200        String xpathQuery = "//element(" + siteName + ", ametys:site)//element(*, ametys:form)";
201        return _resolver.query(xpathQuery)
202            .stream()
203            .filter(Form.class::isInstance)
204            .map(Form.class::cast)
205            .collect(Collectors.toList());
206    }
207    
208    /**
209     * Get the form properties
210     * @param formId The form's id
211     * @param full <code>true</code> to get full information on form
212     * @param withRights <code>true</code> to have rights in the properties
213     * @return The form properties
214     */
215    @Callable
216    public Map<String, Object> getFormProperties (String formId, boolean full, boolean withRights)
217    {
218        try
219        {
220            Form form = _resolver.resolveById(formId);
221            return getFormProperties(form, full, true);
222        }
223        catch (UnknownAmetysObjectException e)
224        {
225            getLogger().warn("Can't find form with id: {}. It probably has just been deleted", formId, e);
226            Map<String, Object> infos = new HashMap<>();
227            infos.put("id", formId);
228            return infos;
229        }
230    }
231    
232    /**
233     * Get the form properties
234     * @param form The form
235     * @param full <code>true</code> to get full information on form
236     * @param withRights <code>true</code> to have rights in the properties
237     * @return The form properties
238     */
239    public Map<String, Object> getFormProperties (Form form, boolean full, boolean withRights)
240    {
241        Map<String, Object> infos = new HashMap<>();
242        
243        List<FormEntry> entries = form.getEntries();
244        List<SitemapElement> pages = getFormPage(form.getId(), form.getSiteName());
245        String workflowName = form.getWorkflowName();
246
247        infos.put("type", "root");
248        infos.put("isForm", true);
249        infos.put("author", _userHelper.user2json(form.getAuthor(), true)); 
250        infos.put("contributor", _userHelper.user2json(form.getContributor())); 
251        infos.put("lastModificationDate", DateUtils.zonedDateTimeToString(form.getLastModificationDate()));
252        infos.put("creationDate", DateUtils.zonedDateTimeToString(form.getCreationDate()));
253        infos.put("entriesAmount", entries.size());
254        infos.put("lastEntry", _getLastSubmissionDate(entries));
255        infos.put("workflowLabel", StringUtils.isNotBlank(workflowName) ? _workflowHelper.getWorkflowLabel(workflowName) : new I18nizableText("plugin.forms", "PLUGINS_FORMS_FORMS_EDITOR_WORKFLOW_NO_WORKFLOW"));
256        
257        /** Use in the bus message */
258        infos.put("id", form.getId());
259        infos.put("name", form.getName());
260        infos.put("title", form.getTitle());
261        infos.put("fullPath", getFormFullPath(form.getId()));
262        infos.put("pages", _getPagesInfos(pages));
263        infos.put("hasChildren", form.getPages().size() > 0);
264        infos.put("workflowName", workflowName);
265        
266        infos.put("isConfigured", isFormConfigured(form));
267        
268        UserIdentity currentUser = _userProvider.getUser();
269        if (withRights)
270        {
271            Set<String> userRights = _getUserRights(form);
272            infos.put("rights", userRights);
273            infos.put("canEditRight", userRights.contains(HANDLE_FORMS_RIGHT_ID) || _rightManager.hasRight(currentUser, "Runtime_Rights_Rights_Handle", "/cms") == RightResult.RIGHT_ALLOW);
274        }
275        else
276        {
277            boolean canWrite = hasWriteRightOnForm(currentUser, form);
278            infos.put("canWrite", canWrite);
279            infos.put("canEditRight", canWrite || _rightManager.hasRight(currentUser, "Runtime_Rights_Rights_Handle", "/cms") == RightResult.RIGHT_ALLOW);
280            infos.put("canRead", hasReadRightOnForm(currentUser, form));
281        }
282        
283        if (full)
284        {
285            infos.put("isPublished", !pages.isEmpty());
286            infos.put("hasEntries", form.hasEntries());
287            infos.put("nbEntries", form.getActiveEntries().size());
288            
289            FormDirectory formDirectoriesRoot = _formDirectoryDAO.getFormDirectoriesRootNode(form.getSiteName());
290            String parentId = form.getParent().getId().equals(formDirectoriesRoot.getId()) ? FormDirectoryDAO.ROOT_FORM_DIRECTORY_ID : form.getParent().getId();
291            infos.put("parentId", parentId);
292            
293            infos.put("isLimitedToOneEntryByUser", form.isLimitedToOneEntryByUser());
294            infos.put("isEntriesLimited", form.isEntriesLimited());
295            Optional<Long> maxEntries = form.getMaxEntries();
296            if (maxEntries.isPresent())
297            {
298                infos.put("maxEntries", maxEntries.get());
299            }
300            infos.put("isQueueEnabled", form.isQueueEnabled());
301            Optional<Long> queueSize = form.getQueueSize();
302            if (queueSize.isPresent())
303            {
304                infos.put("queueSize", queueSize.get());
305            }
306            
307            LocalDate startDate = form.getStartDate();
308            LocalDate endDate = form.getEndDate();
309            if (startDate != null || endDate != null)
310            {
311                infos.put("scheduleStatus", _scheduleOpeningHelper.getStatus(form));
312                if (startDate != null)
313                {
314                    infos.put("startDate", DateUtils.localDateToString(startDate));
315                }
316                if (endDate != null)
317                {
318                    infos.put("endDate", DateUtils.localDateToString(endDate));
319                }
320            }
321
322            infos.put("receiptAcknowledgement", form.hasValue(Form.RECEIPT_SENDER));
323            infos.put("isAnonymous", _rightManager.hasAnonymousReadAccess(form));
324        }
325        
326        return infos;
327    }
328    
329    /**
330     * Get the form title
331     * @param formId the form id
332     * @return the form title
333     */
334    @Callable
335    public String getFormTitle(String formId)
336    {
337        Form form = _resolver.resolveById(formId);
338        return form.getTitle();
339    }
340    
341    /**
342     * Get the form full path
343     * @param formId the form id
344     * @return the form full path
345     */
346    @Callable
347    public String getFormFullPath(String formId)
348    {
349        Form form = _resolver.resolveById(formId);
350        
351        String separator = " > ";
352        String fullPath = form.getTitle();
353        
354        FormDirectory parent = form.getParent();
355        if (!_formDirectoryDAO.isRoot(parent))
356        {
357            fullPath = _formDirectoryDAO.getFormDirectoryPath(parent, separator) + separator + fullPath;
358        }
359        
360        return fullPath;
361    }
362    
363    /**
364     * Get user rights for the given form
365     * @param form the form
366     * @return the set of rights
367     */
368    protected Set<String> _getUserRights (Form form)
369    {
370        UserIdentity user = _userProvider.getUser();
371        return _rightManager.getUserRights(user, form);
372    }
373    
374    /**
375     * Creates a {@link Form}.
376     * @param siteName The site name
377     * @param parentId The id of the parent.
378     * @param name  name The desired name for the new {@link Form}
379     * @return The id of the created form
380     * @throws Exception if an error occurs during the form creation process
381     */
382    @Callable
383    public Map<String, String> createForm (String siteName, String parentId, String name) throws Exception
384    {
385        Map<String, String> result = new HashMap<>();
386        
387        FormDirectory parentDirectory = _formDirectoryDAO.getFormDirectory(siteName, parentId);
388        _formDirectoryDAO.checkHandleFormDirectoriesRight(parentDirectory);
389        
390        String uniqueName = _findUniqueName(parentDirectory, name);
391        Form form = parentDirectory.createChild(uniqueName, FormFactory.FORM_NODETYPE);
392        
393        form.setTitle(name);
394        form.setAuthor(_userProvider.getUser());
395        form.setCreationDate(ZonedDateTime.now());
396        form.setLastModificationDate(ZonedDateTime.now());
397        
398        parentDirectory.saveChanges();
399        String formId = form.getId();
400        
401        _formPageDAO.createPage(formId, _i18nUtils.translate(new I18nizableText("plugin.forms", "PLUGINS_FORMS_CREATE_PAGE_DEFAULT_NAME")));
402        
403        result.put("id", formId);
404        result.put("name", form.getTitle());
405        
406        return result;
407    }
408    
409    private String _findUniqueName(FormDirectory parent, String name)
410    {
411        String legalName;
412        try
413        {
414            legalName = NameHelper.filterName(name);
415        }
416        catch (IllegalArgumentException e)
417        {
418            legalName = NameHelper.filterName(__FORM_NAME_PREFIX + name);
419        }
420        
421        // Find unique name from legal name
422        String uniqueName = legalName;
423        int index = 2;
424        while (parent.hasChild(uniqueName))
425        {
426            uniqueName = legalName + "-" + (index++);
427        }
428        
429        return uniqueName;
430    }
431    
432    /**
433     * Rename a {@link Form}
434     * @param id The id of the form 
435     * @param newName The new name for the form
436     * @return A result map
437     */
438    @Callable
439    public Map<String, String> renameForm (String id, String newName)
440    {
441        Map<String, String> results = new HashMap<>();
442        
443        Form form = _resolver.resolveById(id);
444        checkHandleFormRight(form);
445        
446        String uniqueName = _findUniqueName(form.getParent(), newName);
447        Node node = form.getNode();
448        try
449        {
450            form.setTitle(newName);
451            form.setContributor(_userProvider.getUser());
452            form.setLastModificationDate(ZonedDateTime.now());
453            
454            node.getSession().move(node.getPath(), node.getParent().getPath() + '/' + uniqueName);
455            node.getSession().save();
456            
457            results.put("newName", form.getTitle());
458        }
459        catch (RepositoryException e)
460        {
461            getLogger().warn("Form renaming failed.", e);
462            results.put("message", "cannot-rename");
463        }
464        
465        results.put("id", id);
466        return results;
467    }
468    
469    /**
470     * Copies and pastes a form.
471     * @param formDirectoryId The id of the form directory target of the copy
472     * @param formId The id of the form to copy
473     * @return The results
474     */
475    @Callable
476    public Map<String, String> copyForm(String formDirectoryId, String formId)
477    {
478        Map<String, String> result = new HashMap<>();
479        
480        Form originalForm = _resolver.resolveById(formId);
481        FormDirectory parentFormDirectory = _resolver.resolveById(formDirectoryId);
482        _formDirectoryDAO.checkHandleFormDirectoriesRight(parentFormDirectory);
483        
484        String uniqueName = _findUniqueName(parentFormDirectory, originalForm.getTitle());
485        
486        Form cForm = originalForm.copyTo(parentFormDirectory, uniqueName);
487        originalForm.copyTo(cForm);
488        
489        String copyTitle = _i18nUtils.translate(new I18nizableText("plugin.forms", "PLUGIN_FORMS_TREE_COPY_NAME_PREFIX")) + originalForm.getTitle();
490        cForm.setTitle(copyTitle);
491        cForm.setAuthor(_userProvider.getUser());
492        cForm.setCreationDate(ZonedDateTime.now());
493        cForm.setLastModificationDate(ZonedDateTime.now());
494        
495        for (String epId : _copyFormEP.getExtensionsIds())
496        {
497            CopyFormUpdater copyFormUpdater = _copyFormEP.getExtension(epId);
498            copyFormUpdater.updateForm(originalForm, cForm);
499        }
500        
501        result.put("id", cForm.getId());
502        
503        return result;
504    }
505    
506    /**
507     * Deletes a {@link Form}.
508     * @param id The id of the form to delete
509     * @return The id of the form 
510     */
511    @Callable
512    public Map<String, String> deleteForm (String id)
513    {
514        Map<String, String> result = new HashMap<>();
515        
516        Form form = _resolver.resolveById(id);
517        checkHandleFormRight(form);
518        
519        List<SitemapElement> pages = getFormPage(form.getId(), form.getSiteName());
520        if (!pages.isEmpty())
521        {
522            throw new IllegalAccessError("Can't delete form ('" + form.getId() + "') which contains pages");
523        }
524
525        ModifiableAmetysObject parent = form.getParent();
526        form.remove();
527        parent.saveChanges();
528        
529        result.put("id", id);
530        return result;
531    }
532    
533    /**
534     * Moves a {@link Form}
535     * @param siteName name of the site
536     * @param id The id of the form
537     * @param newParentId The id of the new parent directory of the form. 
538     * @return A result map
539     */
540    @Callable
541    public Map<String, Object> moveForm(String siteName, String id, String newParentId)
542    {
543        Map<String, Object> results = new HashMap<>();
544        Form form = _resolver.resolveById(id);
545        FormDirectory directory = _formDirectoryDAO.getFormDirectory(siteName, newParentId);
546        
547        if (hasWriteRightOnForm(_userProvider.getUser(), form) && _formDirectoryDAO.hasWriteRightOnFormDirectory(_userProvider.getUser(), directory))
548        {
549            _formDirectoryDAO.move(form, siteName, newParentId, results);
550        }
551        else
552        {
553            results.put("message", "not-allowed");
554        }
555
556        results.put("id", form.getId());
557        return results;
558    }
559    
560    /**
561     * Change workflow of a {@link Form}
562     * @param formId The id of the form 
563     * @param workflowName The name of new workflow
564     * @return A result map
565     */
566    @Callable
567    public Map<String, String> setWorkflow (String formId, String workflowName)
568    {
569        Map<String, String> results = new HashMap<>();
570        
571        Form form = _resolver.resolveById(formId);
572        checkHandleFormRight(form);
573        
574        form.setWorkflowName(workflowName);
575        form.setContributor(_userProvider.getUser());
576        form.setLastModificationDate(ZonedDateTime.now());
577        
578        form.saveChanges();
579        
580        results.put("id", formId);
581
582        Map<String, Object> eventParams = new HashMap<>();
583        eventParams.put("form", form);
584        _observationManager.notify(new Event(FormEvents.FORM_MODIFIED, _currentUserProvider.getUser(), eventParams));
585        
586        return results;
587    }
588
589    /**
590     * Get the submission date of the last entry to the form
591     * @param entries A list of form entry
592     * @return the date of the last submission
593     */
594    protected ZonedDateTime _getLastSubmissionDate(List<FormEntry> entries)
595    {
596        ZonedDateTime lastSubmissionDate = null;
597        if (!entries.isEmpty())
598        {
599            lastSubmissionDate = entries.get(0).getSubmitDate();
600            for (FormEntry entry : entries)
601            {
602                ZonedDateTime submitDate = entry.getSubmitDate();
603                if (lastSubmissionDate.isBefore(submitDate))
604                {
605                    lastSubmissionDate = submitDate;
606                }
607            }
608        }
609        return lastSubmissionDate;
610    }
611
612    /**
613     * Get all zone items which contains the form
614     * @param formId the form id
615     * @param siteName the site name
616     * @return the zone items
617     */
618    public AmetysObjectIterable<ModifiableZoneItem> getFormZoneItems(String formId, String siteName)
619    {
620        String xpathQuery = "//element(" + siteName + ", ametys:site)//element(*, ametys:zoneItem)[@ametys-internal:service = 'org.ametys.forms.service.Display' and ametys:service_parameters/@ametys:formId = '" + formId + "']";
621        return _resolver.query(xpathQuery);
622    }
623    
624    /**
625     * Get the locale to use for a given form
626     * @param form the form
627     * @return the locale to use
628     */
629    public String getFormLocale(Form form)
630    {
631        List<SitemapElement> zoneItems = getFormPage(form.getId(), form.getSiteName());
632        
633        return zoneItems.stream()
634                .findFirst()
635                .get()
636                .getSitemapName();
637    }
638    
639    /**
640     * Get all the page where the form is published
641     * @param formId the form id
642     * @param siteName the site name
643     * @return the list of page
644     */
645    public List<SitemapElement> getFormPage(String formId, String siteName)
646    {
647        AmetysObjectIterable<ModifiableZoneItem> zoneItems = getFormZoneItems(formId, siteName);
648        
649        return zoneItems.stream()
650                .map(z -> z.getZone().getSitemapElement())
651                .collect(Collectors.toList());
652    }
653    
654    /**
655     * Get the page names
656     * @param pages the list of page
657     * @return the list of page name
658     */
659    protected List<Map<String, Object>> _getPagesInfos(List<SitemapElement> pages)
660    {
661        List<Map<String, Object>> pagesInfos = new ArrayList<>();
662        for (SitemapElement sitemapElement : pages)
663        {
664            Map<String, Object> info = new HashMap<>();
665            info.put("id", sitemapElement.getId());
666            info.put("title", sitemapElement.getTitle());
667            info.put("isPage", sitemapElement instanceof Page);
668            
669            pagesInfos.add(info);
670        }
671        
672        return pagesInfos;
673    }
674    
675    /**
676     * Get all the view available for the form display service
677     * @param formId the form identifier
678     * @param siteName the site name
679     * @param language the language
680     * @return the views as json
681     * @throws Exception if an error occurred
682     */
683    @Callable
684    public List<Map<String, Object>> getFormDisplayViews(String formId, String siteName, String language) throws Exception
685    {
686        List<Map<String, Object>> jsonifiedViews = new ArrayList<>();
687    
688        Service service = _serviceEP.getExtension("org.ametys.forms.service.Display");
689        ElementDefinition viewElementDefinition = (ElementDefinition) service.getParameters().getOrDefault(ViewParametersManager.SERVICE_VIEW_DEFAULT_MODEL_ITEM_NAME, null);
690        
691        String xpathQuery = "//element(" + siteName + ", ametys:site)/ametys-internal:sitemaps/" + language
692                + "//element(*, ametys:zoneItem)[@ametys-internal:service = 'org.ametys.forms.service.Display' and ametys:service_parameters/@ametys:formId = '" + formId + "']";
693        AmetysObjectIterable<ModifiableZoneItem> zoneItems = _resolver.query(xpathQuery);
694        
695        Optional<Object> existedServiceView = zoneItems.stream()
696            .map(ZoneItem::getServiceParameters)
697            .map(sp -> sp.getValue(ViewParametersManager.SERVICE_VIEW_DEFAULT_MODEL_ITEM_NAME))
698            .findFirst();
699        
700        Map<String, I18nizableText> typedEntries = viewElementDefinition.getEnumerator().getTypedEntries();
701        for (String id : typedEntries.keySet())
702        {
703            Map<String, Object> viewAsJson = new HashMap<>();
704            viewAsJson.put("id", id);
705            viewAsJson.put("label", typedEntries.get(id));
706            
707            Boolean isServiceView = existedServiceView.map(s -> s.equals(id)).orElse(false);
708            if (isServiceView || existedServiceView.isEmpty() && id.equals(viewElementDefinition.getDefaultValue()))
709            {
710                viewAsJson.put("isDefault", true);
711            }
712            
713            jsonifiedViews.add(viewAsJson);
714        }
715        
716        return jsonifiedViews;
717    }
718    
719    /**
720     * <code>true</code> if the form is well configured
721     * @param form the form
722     * @return <code>true</code> if the form is well configured
723     */
724    public boolean isFormConfigured(Form form)
725    {
726        List<FormQuestion> questions = form.getQuestions();
727        return !questions.isEmpty() && !questions.stream().anyMatch(q -> !q.getType().isQuestionConfigured(q));
728    }
729    
730    /**
731     * Get the dashboard URI
732     * @param siteName the site name
733     * @return the dashboard URI
734     */
735    public String getDashboardUri(String siteName)
736    {
737        String xpathQuery = "//element(" + siteName + ", ametys:site)//element(*, ametys:zoneItem)[@ametys-internal:service = 'org.ametys.plugins.forms.workflow.service.dashboard']";
738        AmetysObjectIterable<ModifiableZoneItem> zoneItems = _resolver.query(xpathQuery);
739        
740        Optional<Page> dashboardPage = zoneItems.stream()
741                .map(z -> z.getZone().getSitemapElement())
742                .filter(Page.class::isInstance)
743                .map(Page.class::cast)
744                .findAny();
745        
746        if (dashboardPage.isPresent())
747        {
748            Page page = dashboardPage.get();
749            String pagePath = page.getSitemap().getName() + "/" + page.getPathInSitemap() + ".html";
750            
751            String url = _siteManager.getSite(siteName).getUrl();
752            return url + "/" + pagePath;
753        }
754        
755        return StringUtils.EMPTY;
756    }
757    
758    /**
759     * Get the admin dashboard URI
760     * @param siteName the site name
761     * @return the admin dashboard URI
762     */
763    public String getAdminDashboardUri(String siteName)
764    {
765        String xpathQuery = "//element(" + siteName + ", ametys:site)//element(*, ametys:zoneItem)[@ametys-internal:service = 'org.ametys.plugins.forms.workflow.service.admin.dashboard']";
766        AmetysObjectIterable<ModifiableZoneItem> zoneItems = _resolver.query(xpathQuery);
767        
768        Optional<Page> dashboardPage = zoneItems.stream()
769                .map(z -> z.getZone().getSitemapElement())
770                .filter(Page.class::isInstance)
771                .map(Page.class::cast)
772                .findAny();
773        
774        if (dashboardPage.isPresent())
775        {
776            Page page = dashboardPage.get();
777            String pagePath = page.getSitemap().getName() + "/" + page.getPathInSitemap() + ".html";
778            
779            String url = _siteManager.getSite(siteName).getUrl();
780            return url + "/" + pagePath;
781        }
782        
783        return StringUtils.EMPTY;
784    }
785}