001/*
002 *  Copyright 2016 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 */
016
017package org.ametys.plugins.workspaces.project.helper;
018
019import java.time.ZonedDateTime;
020import java.util.HashMap;
021import java.util.List;
022import java.util.Map;
023
024import org.apache.avalon.framework.context.Context;
025import org.apache.avalon.framework.context.ContextException;
026import org.apache.avalon.framework.context.Contextualizable;
027import org.apache.avalon.framework.logger.LogEnabled;
028import org.apache.avalon.framework.logger.Logger;
029import org.apache.avalon.framework.service.ServiceException;
030import org.apache.avalon.framework.service.ServiceManager;
031import org.apache.avalon.framework.service.Serviceable;
032import org.apache.cocoon.components.ContextHelper;
033import org.apache.cocoon.environment.Request;
034import org.apache.commons.lang3.StringUtils;
035import org.w3c.dom.Node;
036
037import org.ametys.core.util.DateUtils;
038import org.ametys.core.util.dom.MapElement;
039import org.ametys.plugins.workspaces.categories.Category;
040import org.ametys.plugins.workspaces.categories.CategoryColorsComponent;
041import org.ametys.plugins.workspaces.categories.CategoryProviderExtensionPoint;
042import org.ametys.plugins.workspaces.members.ProjectInvitationHelper;
043import org.ametys.plugins.workspaces.project.ProjectManager;
044import org.ametys.plugins.workspaces.project.objects.Project;
045import org.ametys.web.cocoon.I18nUtils;
046import org.ametys.web.repository.site.Site;
047import org.ametys.web.repository.site.SiteManager;
048
049/**
050 * Helper component to be used from XSL stylesheets to get info related to projects.
051 */
052public class ProjectXsltHelper implements Serviceable, Contextualizable, LogEnabled
053{
054    private static Logger _logger;
055    private static Context _context;
056    private static SiteManager _siteManager;
057    private static ProjectManager _projectManager;
058    private static CategoryProviderExtensionPoint _categoryProviderEP;
059    private static CategoryColorsComponent _categoryColorsComponent;
060    private static I18nUtils _i18nUtils;
061    private static ProjectInvitationHelper _projectInvitationHelper;
062
063    
064    @Override
065    public void contextualize(Context context) throws ContextException
066    {
067        _context = context;
068    }
069    
070    @Override
071    public void enableLogging(Logger logger)
072    {
073        _logger = logger;
074    }
075    
076    @Override
077    public void service(ServiceManager manager) throws ServiceException
078    {
079        _siteManager = (SiteManager) manager.lookup(SiteManager.ROLE);
080        _projectManager = (ProjectManager) manager.lookup(ProjectManager.ROLE);
081        _categoryProviderEP = (CategoryProviderExtensionPoint) manager.lookup(CategoryProviderExtensionPoint.ROLE);
082        _categoryColorsComponent = (CategoryColorsComponent) manager.lookup(CategoryColorsComponent.ROLE);
083        _i18nUtils = (I18nUtils) manager.lookup(org.ametys.core.util.I18nUtils.ROLE);
084        _projectInvitationHelper = (ProjectInvitationHelper) manager.lookup(ProjectInvitationHelper.ROLE);
085    }
086    
087    /**
088     * Returns the current project
089     * @return the current project
090     */
091    public static String project()
092    {
093        Project project = null;
094        
095        Request request = ContextHelper.getRequest(_context);
096        String siteName = (String) request.getAttribute("site");
097        
098        if (StringUtils.isNotEmpty(siteName) && _siteManager.hasSite(siteName))
099        {
100            Site site = _siteManager.getSite(siteName);
101            List<Project> projects = _projectManager.getProjectsForSite(site);
102            
103            project = !projects.isEmpty() ? projects.get(0) : null;
104        }
105        
106        if (project == null && _logger.isWarnEnabled())
107        {
108            String warnMsg = String.format("No project was found for site '%s'.", siteName);
109            _logger.warn(warnMsg);
110        }
111        
112        return project != null ? project.getName() : null;
113    }
114    
115    /**
116     * Returns the title of the current project
117     * @return the title of the current project
118     */
119    public static String projectTitle()
120    {
121        return projectTitle(project());
122    }
123    
124    /**
125     * Returns the title of the given project
126     * @param projectName The project to consider
127     * @return the title of the given project or empty otherwise
128     */
129    public static String projectTitle(String projectName)
130    {
131        String title = "";
132        
133        Project project = _projectManager.getProject(projectName);
134        if (project != null)
135        {
136            title = project.getTitle();
137        }
138        
139        return title;
140    }
141    
142    /**
143     * Returns the description of the current project
144     * @return the description of the current project
145     */
146    public static String projectDescription()
147    {
148        return projectDescription(project());
149    }
150    
151    /**
152     * Returns the description of the given project
153     * @param projectName The project to consider
154     * @return the description of the given project or empty otherwise
155     */
156    public static String projectDescription(String projectName)
157    {
158        String title = "";
159        
160        Project project = _projectManager.getProject(projectName);
161        if (project != null)
162        {
163            title = project.getDescription();
164        }
165        
166        return title;
167    }
168    
169    /**
170     * Returns the creation date of the current project
171     * @return the creation date of the current project at the ISO format or empty otherwise
172     */
173    public static String projectCreationDate()
174    {
175        return projectCreationDate(project());
176    }
177    
178    /**
179     * Returns the creation date of the given project
180     * @param projectName The project to consider
181     * @return the creation date of the given project at the ISO format or empty otherwise
182     */
183    public static String projectCreationDate(String projectName)
184    {
185        String creationDate = "";
186        
187        Project project = _projectManager.getProject(projectName);
188        if (project != null)
189        {
190            ZonedDateTime date = project.getCreationDate();
191            creationDate = date.format(DateUtils.getISODateTimeFormatter());
192        }
193        
194        return creationDate;
195    }
196    
197    /**
198     * Return the color associated to the first category associated to the current project
199     * @return the hexa code color or the default color if no color is associated to the first category or if not category is associated.
200     * &lt;color&gt;
201     *     &lt;main&gt;#FFFFFF&lt;/main&gt;
202     *     &lt;text&gt;#000000&lt;/text&gt;
203     * &lt;/color&gt;
204     */
205    public static MapElement projectCategoryColor()
206    {
207        return projectCategoryColor(project());
208    }
209    
210    /**
211     * Return the color associated to the first category associated to the given project
212     * @param projectName The project to consider
213     * @return the hexa code color or the default color if no color is associated to the first category or if not category is associated
214     * &lt;color&gt;
215     *     &lt;main&gt;#FFFFFF&lt;/main&gt;
216     *     &lt;text&gt;#000000&lt;/text&gt;
217     * &lt;/color&gt;
218     */
219    public static MapElement projectCategoryColor(String projectName)
220    {
221        String index = null;
222        
223        Project project = _projectManager.getProject(projectName);
224        Category category = _getFirstCategory(project);
225        if (category != null)
226        {
227            index = category.getColor();
228        }
229        
230        if (StringUtils.isBlank(index))
231        {
232            index = _categoryColorsComponent.getDefaultKey();
233        }
234        
235        Map<String, String> color = _categoryColorsComponent.getColors().get(index);
236        return new MapElement("color", color);
237    }
238    
239    private static Category _getFirstCategory(Project project)
240    {
241        if (project != null)
242        {
243            for (String categoryId : project.getCategories())
244            {
245                Category category = _categoryProviderEP.getTag(categoryId, null);
246                if (category != null)
247                {
248                    return category;
249                }
250            }
251        }
252        return null;
253    }
254    
255    
256    /**
257     * Return the color associated to the first category associated to the current project
258     * @return the hexa code color or the default color if no color is associated to the first category or if not category is associated
259     */
260    public static String projectCategoryLabel()
261    {
262        return projectCategoryLabel(project());
263    }
264    
265    /**
266     * Return the color associated to the first category associated to the given project
267     * @param projectName The project to consider
268     * @return the label or empty if no category
269     */
270    public static String projectCategoryLabel(String projectName)
271    {
272        Project project = _projectManager.getProject(projectName);
273        Category category = _getFirstCategory(project);
274        if (category != null)
275        {
276            Request request = ContextHelper.getRequest(_context);
277            String language = (String) request.getAttribute("sitemapLanguage");
278            
279            return _i18nUtils.translate(category.getTitle(), language);
280        }
281        return null; 
282    }
283    
284    /**
285     * True if the resource comes from workspaces
286     * @param resourceId the resource id
287     * @return true if the resource comes from workspaces
288     */
289    public static boolean isResourceFromWorkspace(String resourceId)
290    {
291        return _projectManager.getParentProject(resourceId) != null;
292    }
293    
294    /**
295     * Get the site of a project's resource
296     * @param projectResourceId The resource id
297     * @return The site &lt;site id="site://xxx" name="siteName"&gt;&lt;title&gt;Site's titleX&lt;/title&gt;&lt;url&gt;http://...&lt;/url&gt;/site&gt;
298     */
299    public static Node resourceSite(String projectResourceId)
300    {
301        Project project = _projectManager.getParentProject(projectResourceId);
302        if (project != null)
303        {
304            Site site = project.getSites().iterator().next();
305            
306            Map<String, String> attributes = new HashMap<>();
307            attributes.put("name", site.getName());
308            attributes.put("id", site.getId());
309            
310            Map<String, String> values = new HashMap<>();
311            values.put("title", site.getTitle());
312            values.put("url", site.getUrl());
313            
314            return new MapElement("site", attributes, values);
315        }
316        
317        return null;
318    }
319    
320    /**
321     * Check if the current user is allowed to invite users, and if the invitations are correctly configured
322     * @param projectName The project name
323     * @param lang The project language
324     * @return True if users can be invited
325     */
326    public static boolean canInviteUsersToProject(String projectName, String lang)
327    {
328        Map<String, Object> invitationConfiguration = _projectInvitationHelper.getInvitationConfiguration(projectName, lang);
329        return (boolean) invitationConfiguration.getOrDefault("allowed", false);
330    }
331}