001/* 002 * Copyright 2020 Anyware Services 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package org.ametys.plugins.workspaces.project; 017 018import java.time.ZonedDateTime; 019import java.util.ArrayList; 020import java.util.Arrays; 021import java.util.Collection; 022import java.util.Collections; 023import java.util.HashMap; 024import java.util.HashSet; 025import java.util.LinkedHashSet; 026import java.util.List; 027import java.util.Map; 028import java.util.Objects; 029import java.util.Optional; 030import java.util.Set; 031import java.util.function.Predicate; 032import java.util.regex.Pattern; 033import java.util.stream.Collectors; 034import java.util.stream.Stream; 035import java.util.stream.StreamSupport; 036 037import javax.jcr.Node; 038import javax.jcr.PathNotFoundException; 039import javax.jcr.RepositoryException; 040import javax.jcr.Session; 041import javax.jcr.Value; 042 043import org.apache.avalon.framework.activity.Initializable; 044import org.apache.avalon.framework.component.Component; 045import org.apache.avalon.framework.context.Context; 046import org.apache.avalon.framework.context.ContextException; 047import org.apache.avalon.framework.context.Contextualizable; 048import org.apache.avalon.framework.logger.AbstractLogEnabled; 049import org.apache.avalon.framework.service.ServiceException; 050import org.apache.avalon.framework.service.ServiceManager; 051import org.apache.avalon.framework.service.Serviceable; 052import org.apache.cocoon.components.ContextHelper; 053import org.apache.cocoon.environment.Request; 054import org.apache.commons.collections.CollectionUtils; 055import org.apache.commons.lang3.ArrayUtils; 056import org.apache.commons.lang3.StringUtils; 057import org.apache.commons.lang3.tuple.Pair; 058 059import org.ametys.cms.fo.ForceDefaultRepositoryWorkspaceCallableDecorator; 060import org.ametys.cms.tag.Tag; 061import org.ametys.core.cache.AbstractCacheManager; 062import org.ametys.core.cache.AbstractCacheManager.CacheType; 063import org.ametys.core.cache.Cache; 064import org.ametys.core.cache.CacheException; 065import org.ametys.core.group.GroupDirectoryContextHelper; 066import org.ametys.core.group.GroupIdentity; 067import org.ametys.core.observation.Event; 068import org.ametys.core.observation.ObservationManager; 069import org.ametys.core.observation.Observer; 070import org.ametys.core.right.RightManager; 071import org.ametys.core.right.RightManager.RightResult; 072import org.ametys.core.ui.Callable; 073import org.ametys.core.user.CurrentUserProvider; 074import org.ametys.core.user.UserIdentity; 075import org.ametys.core.user.population.PopulationContextHelper; 076import org.ametys.core.util.I18nUtils; 077import org.ametys.core.util.LambdaUtils; 078import org.ametys.plugins.core.impl.cache.AbstractCacheKey; 079import org.ametys.plugins.core.search.UserAndGroupSearchManager; 080import org.ametys.plugins.core.user.UserHelper; 081import org.ametys.plugins.explorer.ExplorerNode; 082import org.ametys.plugins.explorer.resources.ModifiableResourceCollection; 083import org.ametys.plugins.repository.AmetysObject; 084import org.ametys.plugins.repository.AmetysObjectIterable; 085import org.ametys.plugins.repository.AmetysObjectResolver; 086import org.ametys.plugins.repository.AmetysRepositoryException; 087import org.ametys.plugins.repository.CollectionIterable; 088import org.ametys.plugins.repository.ModifiableAmetysObject; 089import org.ametys.plugins.repository.ModifiableTraversableAmetysObject; 090import org.ametys.plugins.repository.RepositoryConstants; 091import org.ametys.plugins.repository.UnknownAmetysObjectException; 092import org.ametys.plugins.repository.jcr.JCRAmetysObject; 093import org.ametys.plugins.repository.provider.AbstractRepository; 094import org.ametys.plugins.repository.provider.JackrabbitRepository; 095import org.ametys.plugins.repository.provider.WorkspaceSelector; 096import org.ametys.plugins.repository.query.QueryHelper; 097import org.ametys.plugins.repository.query.expression.Expression; 098import org.ametys.plugins.repository.query.expression.Expression.Operator; 099import org.ametys.plugins.repository.query.expression.StringExpression; 100import org.ametys.plugins.workspaces.ObservationConstants; 101import org.ametys.plugins.workspaces.catalog.CatalogSiteType; 102import org.ametys.plugins.workspaces.categories.Category; 103import org.ametys.plugins.workspaces.categories.CategoryProviderExtensionPoint; 104import org.ametys.plugins.workspaces.members.JCRProjectMember; 105import org.ametys.plugins.workspaces.members.JCRProjectMember.MemberType; 106import org.ametys.plugins.workspaces.members.ProjectMemberManager; 107import org.ametys.plugins.workspaces.members.ProjectMemberManager.ProjectMember; 108import org.ametys.plugins.workspaces.project.modules.WorkspaceModule; 109import org.ametys.plugins.workspaces.project.modules.WorkspaceModuleExtensionPoint; 110import org.ametys.plugins.workspaces.project.objects.Project; 111import org.ametys.plugins.workspaces.project.objects.Project.InscriptionStatus; 112import org.ametys.plugins.workspaces.project.rights.ProjectRightHelper; 113import org.ametys.plugins.workspaces.tags.ProjectTagProviderExtensionPoint; 114import org.ametys.plugins.workspaces.util.StatisticColumn; 115import org.ametys.plugins.workspaces.util.StatisticsColumnType; 116import org.ametys.runtime.authentication.AccessDeniedException; 117import org.ametys.runtime.config.Config; 118import org.ametys.runtime.i18n.I18nizableText; 119import org.ametys.runtime.plugin.component.PluginAware; 120import org.ametys.web.repository.SiteAwareAmetysObject; 121import org.ametys.web.repository.page.ModifiablePage; 122import org.ametys.web.repository.page.Page; 123import org.ametys.web.repository.page.PageQueryHelper; 124import org.ametys.web.repository.page.SitemapElement; 125import org.ametys.web.repository.page.ZoneItem; 126import org.ametys.web.repository.site.Site; 127import org.ametys.web.repository.site.SiteDAO; 128import org.ametys.web.repository.site.SiteManager; 129import org.ametys.web.repository.sitemap.Sitemap; 130import org.ametys.web.site.SiteConfigurationManager; 131 132/** 133 * Helper component for managing project workspaces 134 */ 135public class ProjectManager extends AbstractLogEnabled implements Serviceable, Component, Contextualizable, PluginAware, Initializable, Observer 136{ 137 /** Avalon Role */ 138 public static final String ROLE = ProjectManager.class.getName(); 139 140 /** Constant for the {@link Cache} id (the {@link Cache} is in {@link CacheType#REQUEST REQUEST} attribute) for the {@link Project}s objects 141 * in cache by {@link RequestProjectCacheKey} (composition of project name and workspace name). */ 142 public static final String REQUEST_PROJECTBYID_CACHE = ProjectManager.class.getName() + "$ProjectById"; 143 144 /** Constant for the {@link Cache} id for the {@link Project} ids (as {@link String}s) in cache by project name (for whole application). */ 145 public static final String MEMORY_PROJECTIDBYNAMECACHE = ProjectManager.class.getName() + "$UUID"; 146 147 /** Constant for the {@link Cache} id (the {@link Cache} is in {@link CacheType#REQUEST REQUEST} attribute) for the {@link Page}s objects 148 * in cache by {@link RequestModuleCacheKey} (composition of project name and module name). */ 149 public static final String REQUEST_PAGESBYPROJECTANDMODULE_CACHE = ProjectManager.class.getName() + "$PagesByModule"; 150 151 /** Constant for the {@link Cache} id for the {@link Project} ids (as {@link String}s) in cache by project name (for whole application). */ 152 public static final String MEMORY_PAGESBYIDCACHE = ProjectManager.class.getName() + "$PageUUID"; 153 154 /** Constant for the {@link Cache} id for the {@link Project} ids (as {@link String}s) in cache by site name (for whole application). */ 155 public static final String MEMORY_SITEASSOCIATION_CACHE = ProjectManager.class.getName() + "$SiteAssociation"; 156 157 /** Workspaces plugin node name */ 158 private static final String __WORKSPACES_PLUGIN_NODE_NAME = "workspaces"; 159 160 /** Workspaces plugin node name */ 161 private static final String __WORKSPACES_PLUGIN_NODE_TYPE = RepositoryConstants.NAMESPACE_PREFIX + ":unstructured"; 162 163 /** The name of the projects root node */ 164 private static final String __PROJECTS_ROOT_NODE_NAME = "projects"; 165 166 /** The type of the projects root node */ 167 private static final String __PROJECTS_ROOT_NODE_TYPE = RepositoryConstants.NAMESPACE_PREFIX + ":unstructured"; 168 169 /** Constants for tags metadata */ 170 private static final String __PROJECTS_TAGS_PROPERTY = RepositoryConstants.NAMESPACE_PREFIX_INTERNAL + ":tags"; 171 172 private static final String __PAGE_MODULES_VALUE = "workspaces-modules"; 173 174 private static final String __IS_CACHE_FILLED = "###iscachefilled###"; 175 176 /** Ametys object resolver */ 177 protected AmetysObjectResolver _resolver; 178 179 /** The i18n utils. */ 180 protected I18nUtils _i18nUtils; 181 182 /** Site manager */ 183 protected SiteManager _siteManager; 184 185 /** Site DAO */ 186 protected SiteDAO _siteDao; 187 188 /** Site configuration manager */ 189 protected SiteConfigurationManager _siteConfigurationManager; 190 191 /** Module Managers EP */ 192 protected WorkspaceModuleExtensionPoint _moduleManagerEP; 193 194 /** Helper for user population */ 195 protected PopulationContextHelper _populationContextHelper; 196 197 /** Helper for group directory's context */ 198 protected GroupDirectoryContextHelper _groupDirectoryContextHelper; 199 200 /** The project members' manager */ 201 protected ProjectMemberManager _projectMemberManager; 202 203 /** Avalon context */ 204 protected Context _context; 205 206 private ObservationManager _observationManager; 207 208 private CurrentUserProvider _currentUserProvider; 209 210 private ProjectMemberManager _projectMembers; 211 212 private String _pluginName; 213 214 private ProjectRightHelper _projectRightHelper; 215 216 private ProjectTagProviderExtensionPoint _projectTagProviderEP; 217 218 private CategoryProviderExtensionPoint _categoryProviderEP; 219 220 private UserHelper _userHelper; 221 222 private AbstractCacheManager _cacheManager; 223 224 private UserAndGroupSearchManager _userAndGroupSearchManager; 225 226 private JackrabbitRepository _repository; 227 228 private WorkspaceSelector _workspaceSelector; 229 230 private RightManager _rightManager; 231 232 private GroupDirectoryContextHelper _directoryContextHelper; 233 234 @Override 235 public void contextualize(Context context) throws ContextException 236 { 237 _context = context; 238 } 239 240 @Override 241 public void service(ServiceManager manager) throws ServiceException 242 { 243 _resolver = (AmetysObjectResolver) manager.lookup(AmetysObjectResolver.ROLE); 244 _repository = (JackrabbitRepository) manager.lookup(AbstractRepository.ROLE); 245 _workspaceSelector = (WorkspaceSelector) manager.lookup(WorkspaceSelector.ROLE); 246 _i18nUtils = (I18nUtils) manager.lookup(I18nUtils.ROLE); 247 _siteManager = (SiteManager) manager.lookup(SiteManager.ROLE); 248 _siteDao = (SiteDAO) manager.lookup(SiteDAO.ROLE); 249 _siteConfigurationManager = (SiteConfigurationManager) manager.lookup(SiteConfigurationManager.ROLE); 250 _projectMembers = (ProjectMemberManager) manager.lookup(ProjectMemberManager.ROLE); 251 _observationManager = (ObservationManager) manager.lookup(ObservationManager.ROLE); 252 _currentUserProvider = (CurrentUserProvider) manager.lookup(CurrentUserProvider.ROLE); 253 _moduleManagerEP = (WorkspaceModuleExtensionPoint) manager.lookup(WorkspaceModuleExtensionPoint.ROLE); 254 _projectRightHelper = (ProjectRightHelper) manager.lookup(ProjectRightHelper.ROLE); 255 _projectTagProviderEP = (ProjectTagProviderExtensionPoint) manager.lookup(ProjectTagProviderExtensionPoint.ROLE); 256 _userHelper = (UserHelper) manager.lookup(UserHelper.ROLE); 257 _categoryProviderEP = (CategoryProviderExtensionPoint) manager.lookup(CategoryProviderExtensionPoint.ROLE); 258 _cacheManager = (AbstractCacheManager) manager.lookup(AbstractCacheManager.ROLE); 259 _populationContextHelper = (PopulationContextHelper) manager.lookup(PopulationContextHelper.ROLE); 260 _groupDirectoryContextHelper = (GroupDirectoryContextHelper) manager.lookup(GroupDirectoryContextHelper.ROLE); 261 _projectMemberManager = (ProjectMemberManager) manager.lookup(ProjectMemberManager.ROLE); 262 _userAndGroupSearchManager = (UserAndGroupSearchManager) manager.lookup(UserAndGroupSearchManager.ROLE); 263 _rightManager = (RightManager) manager.lookup(RightManager.ROLE); 264 _directoryContextHelper = (GroupDirectoryContextHelper) manager.lookup(GroupDirectoryContextHelper.ROLE); 265 } 266 267 public void initialize() throws Exception 268 { 269 _createCaches(); 270 _observationManager.registerObserver(this); 271 } 272 273 @Override 274 public void setPluginInfo(String pluginName, String featureName, String id) 275 { 276 _pluginName = pluginName; 277 } 278 279 /** 280 * Enumeration for the profile to assign for new module 281 */ 282 public enum ProfileForNewModule 283 { 284 /** No profile assigned for new modules */ 285 NONE, 286 287 /** Default profile assigned for new modules */ 288 DEFAULT_MEMBER_PROFILE 289 290 } 291 292 /** 293 * Retrieves all projects 294 * @return the projects 295 */ 296 public AmetysObjectIterable<Project> getProjects() 297 { 298 return getProjects(true); 299 } 300 301 /** 302 * Retrieves all projects 303 * @param onlyWorking true to retrieve only working projects with non null sites 304 * @return the projects 305 */ 306 public AmetysObjectIterable<Project> getProjects(boolean onlyWorking) 307 { 308 // As cache is computed from default JCR workspace, we need to filter on sites that exist into the current JCR workspace 309 Set<Project> projects = _getUUIDCache().values().stream() 310 .filter(_resolver::hasAmetysObjectForId) 311 .map(_resolver::<Project>resolveById) 312 // If needed, check if the site is not null, as it can happen if site was deleted from admin side 313 .filter(project -> !onlyWorking || Objects.nonNull(project.getSite())) 314 .collect(Collectors.toSet()); 315 316 return new CollectionIterable<>(projects); 317 } 318 319 /** 320 * Retrieves projects filtered by categories 321 * @param filteredCategories the filtered categories. Can be empty to no filter by categories. 322 * @return the projects 323 */ 324 public List<Project> getProjects(Set<String> filteredCategories) 325 { 326 return getProjects(filteredCategories, null, null, true); 327 } 328 329 /** 330 * Retrieves projects filtered by categories and/or keywords 331 * @param filteredCategories the filtered categories. Can be empty to no filter by categories. 332 * @param filteredKeywords the filtered keywords. Can be empty to no filter by keywords. 333 * @param anyMatch true to get projects matching categories OR keywords OR pattern 334 * @return the projects 335 */ 336 public List<Project> getProjects(Set<String> filteredCategories, Set<String> filteredKeywords, boolean anyMatch) 337 { 338 return getProjects(filteredCategories, filteredKeywords, null, anyMatch); 339 } 340 341 /** 342 * Retrieves projects filtered by categories and/or keywords and/or pattern 343 * @param filteredCategories the filtered categories. Can be empty to no filter by categories. 344 * @param filteredKeywords the filtered keywords. Can be empty to no filter by keywords. 345 * @param pattern to filter on pattern. Can be null or empty to no filter on pattern 346 * @param anyMatch true to get projects matching categories OR keywords OR pattern 347 * @return the projects 348 */ 349 public List<Project> getProjects(Set<String> filteredCategories, Set<String> filteredKeywords, String pattern, boolean anyMatch) 350 { 351 return getProjects(filteredCategories, filteredKeywords, null, anyMatch, false); 352 } 353 354 /** 355 * Retrieves projects filtered by categories and/or keywords and/or pattern 356 * @param filteredCategories the filtered categories. Can be null or empty to no filter by categories. 357 * @param filteredKeywords the filtered keywords. Can be empty to no filter by keywords. 358 * @param pattern to filter on pattern. Can be null or empty to no filter on pattern 359 * @param anyMatch true to get projects matching categories OR keywords OR pattern 360 * @param excludePrivate true to exclude private projects 361 * @return the projects 362 */ 363 public List<Project> getProjects(Set<String> filteredCategories, Set<String> filteredKeywords, String pattern, boolean anyMatch, boolean excludePrivate) 364 { 365 List<Predicate<Project>> filters = new ArrayList<>(); 366 if (filteredCategories != null && !filteredCategories.isEmpty()) 367 { 368 filters.add(p -> !Collections.disjoint(p.getCategories(), filteredCategories)); 369 } 370 371 if (filteredKeywords != null && !filteredKeywords.isEmpty()) 372 { 373 filters.add(p -> !Collections.disjoint(Arrays.asList(p.getKeywords()), filteredKeywords)); 374 } 375 376 Pattern patternFilter = StringUtils.isNotEmpty(pattern) ? Pattern.compile(pattern, Pattern.CASE_INSENSITIVE) : null; 377 if (patternFilter != null) 378 { 379 filters.add(p -> p.getTitle() != null && patternFilter.matcher(p.getTitle()).find() || p.getDescription() != null && patternFilter.matcher(p.getDescription()).find()); 380 } 381 382 Predicate<Project> fullMatch = filters.stream().reduce(anyMatch ? Predicate::or : Predicate::and).orElse(p -> Boolean.TRUE); 383 Predicate<Project> matchStatus = p -> !excludePrivate || p.getInscriptionStatus() != InscriptionStatus.PRIVATE; 384 385 return getProjects() 386 .stream() 387 .filter(matchStatus) 388 .filter(fullMatch) 389 .collect(Collectors.toList()); 390 } 391 392 /** 393 * Get the projects categories 394 * @return the projects categories 395 */ 396 public Set<Category> getProjectsCategories() 397 { 398 return getProjects().stream() 399 .map(Project::getCategories) 400 .flatMap(Collection::stream) 401 .map(id -> _categoryProviderEP.getTag(id, null)) 402 .filter(Objects::nonNull) 403 .collect(Collectors.toSet()); 404 } 405 406 /** 407 * Get the user's projects categories 408 * @param user the user 409 * @return the user's projects categories 410 */ 411 public Set<Category> getUserProjectsCategories(UserIdentity user) 412 { 413 return getUserProjects(user).keySet() 414 .stream() 415 .map(Project::getCategories) 416 .flatMap(Collection::stream) 417 .map(id -> _categoryProviderEP.getTag(id, null)) 418 .filter(Objects::nonNull) 419 .collect(Collectors.toSet()); 420 } 421 422 /** 423 * Get the projects modules 424 * @return the projects modules 425 */ 426 public Set<WorkspaceModule> getProjectsModules() 427 { 428 return getProjects().stream() 429 .map(Project::getModules) 430 .flatMap(Arrays::stream) 431 .map(id -> _moduleManagerEP.<WorkspaceModule>getModule(id)) 432 .filter(Objects::nonNull) 433 .collect(Collectors.toSet()); 434 } 435 436 /** 437 * Get the projects modules for new members (depending on the project configuration) 438 * @param project the project 439 * @return the project modules 440 */ 441 public Set<WorkspaceModule> getProjectModulesForNewMembers(Project project) 442 { 443 Site projectSite = project.getSite(); 444 445 // Check if project site overrides catalog configuration 446 String membersModulesPolicy = projectSite.getValueOrDefault(ProjectWorkspaceSiteType.PROJECT_OVERRIDE_MEMBERS_MODULES_POLICY_SITE_PARAM, ProjectWorkspaceSiteType.MembersModulesPolicy.GLOBAL.name()); 447 448 String membersModulesAsString = null; 449 if (membersModulesPolicy.equals(ProjectWorkspaceSiteType.MembersModulesPolicy.MEMBERS_MODULES_BY_PROJECT.name())) 450 { 451 membersModulesAsString = projectSite.getValue(ProjectWorkspaceSiteType.PROJECT_MEMBERS_MODULES_PROJECT_SITE_PARAM); 452 } 453 else 454 { 455 Site catalogSite = _siteManager.getSite(getCatalogSiteName()); 456 // Use #hasValueOrEmpty because we can't use #getValue with a default value. Indeed, the #getValue use the default value for null value or empty value. 457 membersModulesAsString = catalogSite.hasValueOrEmpty(CatalogSiteType.PROJECT_MEMBERS_MODULES_SITE_PARAM) 458 ? catalogSite.getValue(CatalogSiteType.PROJECT_MEMBERS_MODULES_SITE_PARAM) 459 : String.join(",", _moduleManagerEP.getExtensionsIds()); 460 } 461 462 String[] membersModuleIds = StringUtils.split(StringUtils.defaultString(membersModulesAsString), ","); 463 464 Set<WorkspaceModule> modules = new HashSet<>(); 465 for (String moduleId : membersModuleIds) 466 { 467 if (StringUtils.isNotBlank(moduleId)) 468 { 469 WorkspaceModule module = _moduleManagerEP.getModule(moduleId.trim()); 470 modules.add(module); 471 } 472 } 473 return modules; 474 } 475 476 /** 477 * Get the projects modules 478 * @param user the user 479 * @return the projects modules 480 */ 481 public Set<WorkspaceModule> getUserProjectsModules(UserIdentity user) 482 { 483 return getUserProjects(user).keySet() 484 .stream() 485 .map(Project::getModules) 486 .flatMap(Arrays::stream) 487 .map(id -> _moduleManagerEP.<WorkspaceModule>getModule(id)) 488 .filter(Objects::nonNull) 489 .collect(Collectors.toSet()); 490 } 491 492 /** 493 * Retrieves all projects for client side 494 * @return the projects 495 */ 496 @Callable(rights = "Runtime_Rights_Admin_Access", context = "/admin") 497 public List<Map<String, Object>> getProjectsForClientSide() 498 { 499 return getProjects(false) 500 .stream() 501 .map(p -> getProjectProperties(p)) 502 .collect(Collectors.toList()); 503 } 504 505 506 /** 507 * Retrieves a project by its name 508 * @param projectName The project name 509 * @return the project or <code>null</code> if not found 510 */ 511 public Project getProject(String projectName) 512 { 513 if (StringUtils.isBlank(projectName)) 514 { 515 return null; 516 } 517 518 Request request = _getRequest(); 519 if (request == null) 520 { 521 // There is no request to store cache 522 return _computeProject(projectName); 523 } 524 525 Cache<RequestProjectCacheKey, Project> projectsCache = _getRequestProjectCache(); 526 527 // The site key in the cache is of the form {site + workspace}. 528 String currentWorkspace = _workspaceSelector.getWorkspace(); 529 RequestProjectCacheKey projectKey = RequestProjectCacheKey.of(projectName, currentWorkspace); 530 531 try 532 { 533 Project project = projectsCache.get(projectKey, __ -> _computeProject(projectName)); 534 return project; 535 } 536 catch (CacheException e) 537 { 538 if (e.getCause() instanceof UnknownAmetysObjectException) 539 { 540 throw new UnknownAmetysObjectException(e.getMessage()); 541 } 542 else 543 { 544 throw e; 545 } 546 } 547 } 548 549 /** 550 * Get the user's projects 551 * @param user the user 552 * @return the user's projects 553 */ 554 public Map<Project, MemberType> getUserProjects(UserIdentity user) 555 { 556 return getUserProjects(user, Set.of()); 557 } 558 559 /** 560 * Get the user's projects filtered by categories 561 * @param user the user 562 * @param filteredCategories the filtered categories. Can be empty to no filter by categories 563 * @return the user's projects 564 */ 565 public Map<Project, MemberType> getUserProjects(UserIdentity user, Set<String> filteredCategories) 566 { 567 return getUserProjects(user, filteredCategories, null, null, true); 568 } 569 570 /** 571 * Get the user's projects filtered by categories OR keywords 572 * @param user the user 573 * @param filteredCategories the filtered categories. Can be empty to no filter by categories 574 * @param filteredKeywords the filtered keywords. Can be empty to no filter by keywords 575 * @return the user's projects 576 */ 577 public Map<Project, MemberType> getUserProjects(UserIdentity user, Set<String> filteredCategories, Set<String> filteredKeywords) 578 { 579 return getUserProjects(user, filteredCategories, filteredKeywords, null, true); 580 } 581 582 /** 583 * Get the user's projects filtered by categories, keywords and/or pattern 584 * @param user the user 585 * @param filteredCategories the filtered categories. Can be empty to no filter by categories. 586 * @param filteredKeywords the filtered keywords. Can be empty to no filter by keywords. 587 * @param pattern to filter on pattern. Can be null or empty to no filter on pattern 588 * @param anyMatch true to get projects matching categories OR keywords OR pattern 589 * @return the user's projects 590 */ 591 public Map<Project, MemberType> getUserProjects(UserIdentity user, Set<String> filteredCategories, Set<String> filteredKeywords, String pattern, boolean anyMatch) 592 { 593 return getUserProjects(user, filteredCategories, filteredKeywords, pattern, true, false); 594 } 595 596 /** 597 * Get the user's projects filtered by categories, keywords and/or pattern 598 * @param user the user 599 * @param filteredCategories the filtered categories. Can be empty to no filter by categories. 600 * @param filteredKeywords the filtered keywords. Can be empty to no filter by keywords. 601 * @param pattern to filter on pattern. Can be null or empty to no filter on pattern 602 * @param anyMatch true to get projects matching categories OR keywords OR pattern 603 * @param excludePrivate true to exclude private projects 604 * @return the user's projects 605 */ 606 public Map<Project, MemberType> getUserProjects(UserIdentity user, Set<String> filteredCategories, Set<String> filteredKeywords, String pattern, boolean anyMatch, boolean excludePrivate) 607 { 608 Map<Project, MemberType> userProjects = new HashMap<>(); 609 610 List<Project> projects = getProjects(filteredCategories, filteredKeywords, pattern, anyMatch, excludePrivate); 611 for (Project project : projects) 612 { 613 ProjectMember member = _projectMembers.getProjectMember(project, user); 614 if (member != null) 615 { 616 userProjects.put(project, member.getType()); 617 } 618 } 619 620 return userProjects; 621 } 622 623 /** 624 * Get the projects managed by the user 625 * @param user the user 626 * @return the projects for which the user is a manager 627 */ 628 public List<Project> getManagedProjects(UserIdentity user) 629 { 630 return getManagedProjects(user, Set.of()); 631 } 632 633 /** 634 * Get the projects managed by the user 635 * @param user the user 636 * @param filteredCategories the filtered categories. Can be empty to no filter by categories. 637 * @return the projects for which the user is a manager 638 */ 639 public List<Project> getManagedProjects(UserIdentity user, Set<String> filteredCategories) 640 { 641 return getProjects(filteredCategories) 642 .stream() 643 .filter(p -> ArrayUtils.contains(p.getManagers(), user)) 644 .collect(Collectors.toList()); 645 } 646 647 /** 648 * Returns true if the given project exists. 649 * @param projectName the project name. 650 * @return true if the given project exists. 651 */ 652 public boolean hasProject(String projectName) 653 { 654 Map<String, String> uuidCache = _getUUIDCache(); 655 if (uuidCache.containsKey(projectName)) 656 { 657 // As cache is computed from default JCR workspace, we need to check if the project exists into the current JCR workspace 658 return _resolver.hasAmetysObjectForId(uuidCache.get(projectName)); 659 } 660 return false; 661 } 662 663 /** 664 * Get all managers 665 * @return the managers 666 */ 667 public Set<UserIdentity> getManagers() 668 { 669 return getProjects() 670 .stream() 671 .map(Project::getManagers) 672 .flatMap(Arrays::stream) 673 .collect(Collectors.toSet()); 674 } 675 676 /** 677 * Determines if the current user is a manager of at least one project 678 * @return true if the user is a manager 679 */ 680 public boolean isManager() 681 { 682 return isManager(_currentUserProvider.getUser()); 683 } 684 685 /** 686 * Determines if the user is a manager of at least one project 687 * @param user the user 688 * @return true if the user is a manager 689 */ 690 public boolean isManager(UserIdentity user) 691 { 692 AmetysObjectIterable<Project> projects = getProjects(); 693 for (Project project : projects) 694 { 695 if (isManager(project, user)) 696 { 697 return true; 698 } 699 } 700 return false; 701 } 702 703 /** 704 * Determines if the user is a manager of the project 705 * @param projectName the project name 706 * @param user the user 707 * @return true if the user is a manager 708 */ 709 public boolean isManager(String projectName, UserIdentity user) 710 { 711 Project project = getProject(projectName); 712 if (project != null) 713 { 714 return isManager(project, user); 715 } 716 return false; 717 } 718 719 /** 720 * Determines if the user is a manager of the project 721 * @param project the project 722 * @param user the user 723 * @return true if the user is a manager 724 */ 725 public boolean isManager(Project project, UserIdentity user) 726 { 727 return ArrayUtils.contains(project.getManagers(), user); 728 } 729 730 /** 731 * Can the current user access backoffice on the site of the current project 732 * @param project The non null project to analyse 733 * @return true if the user can access to the backoffice 734 */ 735 public boolean canAccessBO(Project project) 736 { 737 Site site = project.getSite(); 738 if (site == null) 739 { 740 return false; 741 } 742 743 Request request = ContextHelper.getRequest(_context); 744 String currentSiteName = (String) request.getAttribute("siteName"); 745 try 746 { 747 request.setAttribute("siteName", site.getName()); // Setting temporarily this attribute to check user rights on any object on this site 748 return !_rightManager.getUserRights(_currentUserProvider.getUser(), "/cms").isEmpty(); 749 } 750 finally 751 { 752 request.setAttribute("siteName", currentSiteName); 753 } 754 } 755 756 /** 757 * Can the current user leave the project 758 * @param project The non null project to analyse 759 * @return true if the user can leave the project 760 */ 761 public boolean canLeaveProject(Project project) 762 { 763 if (project == null) 764 { 765 return false; 766 } 767 768 Site site = project.getSite(); 769 if (site == null) 770 { 771 return false; 772 } 773 774 UserIdentity userIdentity = _currentUserProvider.getUser(); 775 776 // As a user in a group can't leave the project, check if he is registered as User member 777 Set<ProjectMember> members = _projectMemberManager.getProjectMembers(project, false); 778 ProjectMember projectMember = members.stream() 779 .filter(member -> MemberType.USER == member.getType()) 780 .filter(member -> userIdentity.equals(member.getUser().getIdentity())) 781 .findFirst() 782 .orElse(null); 783 784 // The user is either on a group, or has not been found 785 if (projectMember == null) 786 { 787 return false; 788 } 789 790 // The user is the only remaining manager, and therefore can not leave the project 791 if (_projectMemberManager.isOnlyManager(project, userIdentity)) 792 { 793 return false; 794 } 795 796 return true; 797 } 798 799 /** 800 * Retrieves the mapping of all the projects name with their title on which the current user has access 801 * @return the map (projectName, projectTitle) for all projects 802 */ 803 @Callable (rights = Callable.CHECKED_BY_IMPLEMENTATION, decorators = ForceDefaultRepositoryWorkspaceCallableDecorator.DECORATOR_ID) 804 public List<Map<String, Object>> getUserProjectsData() 805 { 806 return getUserProjects(_currentUserProvider.getUser()) 807 .keySet() 808 .stream() 809 .map(p -> _project2json(p)) 810 .collect(Collectors.toList()); 811 } 812 813 /** 814 * Get the user modules on the given project. 815 * @param projectName the project name 816 * @return The maps of modules with the read access information 817 */ 818 @Callable (rights = Callable.CHECKED_BY_IMPLEMENTATION, decorators = ForceDefaultRepositoryWorkspaceCallableDecorator.DECORATOR_ID) 819 public Map<String, Object> getUserModules(String projectName) 820 { 821 Project project = this.getProject(projectName); 822 UserIdentity currentUser = _currentUserProvider.getUser(); 823 824 return Arrays.stream(project.getModules()) 825 .collect(Collectors.toMap( 826 mId -> mId, 827 mId -> _projectRightHelper.hasReadAccessOnModule(project, mId, currentUser))); 828 } 829 830 /** 831 * Retrieves the users that have not been yet added to a project with a given criteria 832 * @param projectName the project name 833 * @param limit limit of request 834 * @param criteria the criteria of the search 835 * @param previousSearchData the previous search data to compute offset. Null if first search 836 * @return list of users 837 */ 838 @SuppressWarnings("unchecked") 839 @Callable (rights = Callable.CHECKED_BY_IMPLEMENTATION, decorators = ForceDefaultRepositoryWorkspaceCallableDecorator.DECORATOR_ID) 840 public Map<String, Object> searchUserByProject(String projectName, int limit, String criteria, Map<String, Object> previousSearchData) 841 { 842 843 Project project = this.getProject(projectName); 844 845 if (!_projectRightHelper.canAddMember(project)) 846 { 847 throw new AccessDeniedException("User '" + _currentUserProvider.getUser() + "' tried to do read operation without convenient right"); 848 } 849 850 Map<String, Object> results = new HashMap<>(); 851 Site site = project.getSite(); 852 853 Set<String> projectMemberList = _projectMemberManager.getProjectMembers(project, false) 854 .stream() 855 .map(member -> 856 { 857 if (member.getType() == MemberType.USER) 858 { 859 return UserIdentity.userIdentityToString(member.getUser().getIdentity()); 860 } 861 else 862 { 863 GroupIdentity groupIdentityAsString = member.getGroup().getIdentity(); 864 return GroupIdentity.groupIdentityToString(groupIdentityAsString); 865 } 866 }) 867 .collect(Collectors.toSet()); 868 869 Set<String> contexts = new HashSet<>(Arrays.asList("/sites/" + site.getName(), "/sites-fo/" + site.getName())); 870 871 Map<String, Object> params = new HashMap<>(); 872 params.put("pattern", criteria); 873 874 Map<String, Object> result = new HashMap<>(); 875 Map<String, Object> searchData = previousSearchData; 876 List<Map<String, Object>> memberList = new ArrayList<>(); 877 878 Set<String> groupDirectories = _directoryContextHelper.getGroupDirectoriesOnContexts(contexts); 879 Set<String> userPopulations = getPopulation(site, true); 880 881 do 882 { 883 result = _userAndGroupSearchManager.searchUsersAndGroup(userPopulations, groupDirectories, limit - memberList.size(), searchData, params, true); 884 List<Map<String, Object>> filteredMembers = ((List<Map<String, Object>>) result.get("results")) 885 .stream() 886 .filter(member -> 887 { 888 return !projectMemberList.contains(member.get("login") + "#" + member.get("populationId")) && !projectMemberList.contains(member.get("id") + "#" + member.get("groupDirectory")); 889 }).collect(Collectors.toList()); 890 searchData = (Map<String, Object>) result.get("searchData"); 891 memberList.addAll(filteredMembers); 892 } 893 while (!result.containsKey("finished") && memberList.size() < limit); 894 895 results.put("searchData", searchData); 896 results.put("memberList", memberList); 897 return results; 898 } 899 900 /** 901 * Get the populations of the project 902 * @param site the project site 903 * @param excludeConfigurationPopulations true to exclude populations configured in the catalog site or in the project site 904 * @return the populations of the project 905 */ 906 public Set<String> getPopulation(Site site, boolean excludeConfigurationPopulations) 907 { 908 Set<String> contexts = new HashSet<>(Arrays.asList("/sites/" + site.getName(), "/sites-fo/" + site.getName())); 909 910 Set<String> userPopulations = _populationContextHelper.getUserPopulationsOnContexts(contexts, false, true); 911 912 if (excludeConfigurationPopulations) 913 { 914 Site catalogSite = _siteManager.getSite(getCatalogSiteName()); 915 916 // Get the excluded population configuration 917 String excludedPopulationsString = catalogSite.getValue(CatalogSiteType.PROJECT_EXTERNAL_POPULATIONS_SITE_PARAM); 918 919 // Check if project site overrides catalog configuration 920 String externalPopulationPolicy = site.getValueOrDefault(ProjectWorkspaceSiteType.PROJECT_OVERRIDE_EXTERNAL_POPULATION_POLICY_SITE_PARAM, ProjectWorkspaceSiteType.ExternalPopulationPolicy.GLOBAL.name()); 921 if (externalPopulationPolicy.equals(ProjectWorkspaceSiteType.ExternalPopulationPolicy.EXTERNAL_POPULATION_BY_PROJECT.name())) 922 { 923 excludedPopulationsString = site.getValue(ProjectWorkspaceSiteType.PROJECT_EXTERNAL_POPULATIONS_PROJECT_SITE_PARAM); 924 } 925 926 List<String> excludedPopulationsList = Arrays.asList(StringUtils.split(StringUtils.defaultString(excludedPopulationsString), ",")); 927 928 if (!excludedPopulationsList.isEmpty()) 929 { 930 userPopulations.removeAll(excludedPopulationsList); 931 } 932 } 933 934 return userPopulations; 935 } 936 937 /** 938 * Retrieves the mapping of all the projects name with their title (regarless user rights) 939 * @return the map (projectName, projectTitle) for all projects 940 */ 941 @Callable(rights = "Runtime_Rights_Admin_Access", context = "/admin") 942 public List<Map<String, Object>> getProjectsData() 943 { 944 return getProjects() 945 .stream() 946 .map(p -> _project2json(p)) 947 .collect(Collectors.toList()); 948 } 949 950 /** 951 * Get the project's main properties as json object 952 * @param project the project 953 * @return the json representation of project 954 */ 955 protected Map<String, Object> _project2json(Project project) 956 { 957 Map<String, Object> json = new HashMap<>(); 958 959 json.put("id", project.getId()); 960 json.put("name", project.getName()); 961 json.put("title", project.getTitle()); 962 json.put("url", getProjectUrl(project, StringUtils.EMPTY)); 963 964 return json; 965 } 966 /** 967 * Retrieves the project names 968 * @return the project names 969 */ 970 @Callable(rights = "Runtime_Rights_Admin_Access", context = "/admin") 971 public Collection<String> getProjectNames() 972 { 973 // As cache is computed from default JCR workspace, we need to filter on sites that exist into the current JCR workspace 974 return _getUUIDCache().entrySet().stream() 975 .filter(e -> _resolver.hasAmetysObjectForId(e.getValue())) 976 .map(Map.Entry::getKey) 977 .collect(Collectors.toList()); 978 } 979 980 /** 981 * Return the root for projects 982 * The root node will be created if necessary 983 * @return The root for projects 984 */ 985 public ModifiableTraversableAmetysObject getProjectsRoot() 986 { 987 try 988 { 989 ModifiableTraversableAmetysObject pluginsNode = _resolver.resolveByPath("/ametys:plugins"); 990 ModifiableTraversableAmetysObject workspacesPluginNode = _getOrCreateObject(pluginsNode, __WORKSPACES_PLUGIN_NODE_NAME, __WORKSPACES_PLUGIN_NODE_TYPE); 991 return _getOrCreateObject(workspacesPluginNode, __PROJECTS_ROOT_NODE_NAME, __PROJECTS_ROOT_NODE_TYPE); 992 } 993 catch (AmetysRepositoryException e) 994 { 995 throw new AmetysRepositoryException("Error getting the projects root node.", e); 996 } 997 } 998 999 /** 1000 * Retrieves the standard information of a project 1001 * @param projectId Identifier of the project 1002 * @return The map of information 1003 */ 1004 @Callable(rights = "Runtime_Rights_Admin_Access", context = "/admin") 1005 public Map<String, Object> getProjectProperties(String projectId) 1006 { 1007 return getProjectProperties((Project) _resolver.resolveById(projectId)); 1008 } 1009 1010 /** 1011 * Retrieves the standard information of a project 1012 * @param project The project 1013 * @return The map of information 1014 */ 1015 public Map<String, Object> getProjectProperties(Project project) 1016 { 1017 Map<String, Object> info = new HashMap<>(); 1018 1019 info.put("id", project.getId()); 1020 info.put("name", project.getName()); 1021 info.put("type", "project"); 1022 1023 info.put("title", project.getTitle()); 1024 info.put("description", project.getDescription()); 1025 info.put("inscriptionStatus", project.getInscriptionStatus().toString()); 1026 info.put("defaultProfile", project.getDefaultProfile()); 1027 1028 info.put("creationDate", project.getCreationDate()); 1029 1030 // check if the project workspace configuration is valid 1031 Site site = project.getSite(); 1032 boolean valid = site != null && _siteConfigurationManager.isSiteConfigurationValid(site); 1033 1034 Set<String> categories = project.getCategories(); 1035 info.put("categories", categories.stream() 1036 .map(c -> _categoryProviderEP.getTag(c, new HashMap<>())) 1037 .filter(Objects::nonNull) 1038 .map(t -> _tag2json(t)) 1039 .collect(Collectors.toList())); 1040 1041 Set<String> tags = project.getTags(); 1042 info.put("tags", tags.stream() 1043 .map(c -> _projectTagProviderEP.getTag(c, new HashMap<>())) 1044 .filter(Objects::nonNull) 1045 .map(t -> _tag2json(t)) 1046 .collect(Collectors.toList())); 1047 1048 info.put("valid", valid); 1049 1050 UserIdentity[] managers = project.getManagers(); 1051 info.put("managers", Arrays.stream(managers) 1052 .map(u -> _userHelper.user2json(u)) 1053 .collect(Collectors.toList())); 1054 1055 Map<String, String> siteProps = new HashMap<>(); 1056 // site map with id ,name, title and url property 1057 // { id: site id, name: site name, title: site title, url: site url } 1058 if (site != null) 1059 { 1060 siteProps.put("id", site.getId()); 1061 siteProps.put("name", site.getName()); 1062 siteProps.put("title", site.getTitle()); 1063 siteProps.put("url", site.getUrl()); 1064 } 1065 info.put("site", siteProps); 1066 1067 return info; 1068 } 1069 1070 private Map<String, Object> _tag2json(Tag tag) 1071 { 1072 Map<String, Object> json = new HashMap<>(); 1073 json.put("id", tag.getId()); 1074 json.put("name", tag.getName()); 1075 json.put("title", tag.getTitle()); 1076 return json; 1077 } 1078 1079 /** 1080 * Get the project URL. 1081 * @param project The project 1082 * @param defaultValue The default value to use if there is no site 1083 * @return The project URL if a site is configured, otherwise return the default value. 1084 */ 1085 public String getProjectUrl(Project project, String defaultValue) 1086 { 1087 Site site = project.getSite(); 1088 if (site == null) 1089 { 1090 return defaultValue; 1091 } 1092 else 1093 { 1094 return site.getUrl(); 1095 } 1096 } 1097 1098 /** 1099 * Create a project 1100 * @param name The project name 1101 * @param title The project title 1102 * @param description The project description 1103 * @param emailList Project mailing list 1104 * @param inscriptionStatus The inscription status of the project 1105 * @param defaultProfile The default profile for new members 1106 * @return A map containing the id of the new project or an error key. 1107 */ 1108 @Callable (rights = Callable.CHECKED_BY_IMPLEMENTATION, decorators = ForceDefaultRepositoryWorkspaceCallableDecorator.DECORATOR_ID) 1109 public Map<String, Object> createProject(String name, String title, String description, String emailList, String inscriptionStatus, String defaultProfile) 1110 { 1111 checkRightsForProjectCreation(InscriptionStatus.valueOf(inscriptionStatus.toUpperCase()), null); 1112 1113 Map<String, Object> result = new HashMap<>(); 1114 List<String> errors = new ArrayList<>(); 1115 1116 Map<String, Object> additionalValues = new HashMap<>(); 1117 additionalValues.put("description", description); 1118 additionalValues.put("emailList", emailList); 1119 additionalValues.put("inscriptionStatus", inscriptionStatus); 1120 additionalValues.put("defaultProfile", defaultProfile); 1121 1122 Project project = createProject(name, title, additionalValues, null, errors); 1123 1124 if (CollectionUtils.isEmpty(errors)) 1125 { 1126 result.put("id", project.getId()); 1127 } 1128 else 1129 { 1130 result.put("error", errors.get(0)); 1131 } 1132 1133 return result; 1134 } 1135 1136 /** 1137 * Create a project 1138 * @param name The project name 1139 * @param title The project title 1140 * @param additionalValues A list of optional additional values. Accepted values are : description, mailingList, inscriptionStatus, defaultProfile, tags, categoryTags, keywords and language 1141 * @param modulesIds The list of modules to activate. Can be null to activate all modules 1142 * @param errors A list that will be populated with the encountered errors. If null, errors will not be tracked. 1143 * @return The id of the new project 1144 */ 1145 public Project createProject(String name, String title, Map<String, Object> additionalValues, Set<String> modulesIds, List<String> errors) 1146 { 1147 if (StringUtils.isEmpty(title)) 1148 { 1149 throw new IllegalArgumentException(String.format("Cannot create project. Title is mandatory")); 1150 } 1151 1152 ModifiableTraversableAmetysObject projectsRoot = getProjectsRoot(); 1153 1154 // Project name should be unique 1155 if (hasProject(name)) 1156 { 1157 if (getLogger().isWarnEnabled()) 1158 { 1159 getLogger().warn(String.format("A project with the name '%s' already exists", name)); 1160 } 1161 1162 if (errors != null) 1163 { 1164 errors.add("project-exists"); 1165 } 1166 1167 return null; 1168 } 1169 1170 Project project = projectsRoot.createChild(name, Project.NODE_TYPE); 1171 project.setTitle(title); 1172 String description = (String) additionalValues.getOrDefault("description", null); 1173 if (StringUtils.isNotEmpty(description)) 1174 { 1175 project.setDescription(description); 1176 } 1177 String mailingList = (String) additionalValues.getOrDefault("emailList", null); 1178 if (StringUtils.isNotEmpty(mailingList)) 1179 { 1180 project.setMailingList(mailingList); 1181 } 1182 1183 String inscriptionStatus = (String) additionalValues.getOrDefault("inscriptionStatus", null); 1184 if (StringUtils.isNotEmpty(inscriptionStatus)) 1185 { 1186 project.setInscriptionStatus(inscriptionStatus); 1187 } 1188 1189 String defaultProfile = (String) additionalValues.getOrDefault("defaultProfile", null); 1190 if (StringUtils.isNotEmpty(defaultProfile)) 1191 { 1192 project.setDefaultProfile(defaultProfile); 1193 } 1194 1195 @SuppressWarnings("unchecked") 1196 List<String> tags = (List<String>) additionalValues.getOrDefault("tags", null); 1197 if (tags != null) 1198 { 1199 project.setTags(tags); 1200 } 1201 @SuppressWarnings("unchecked") 1202 List<String> categoryTags = (List<String>) additionalValues.getOrDefault("categoryTags", null); 1203 if (categoryTags != null) 1204 { 1205 project.setCategoryTags(categoryTags); 1206 } 1207 1208 @SuppressWarnings("unchecked") 1209 List<String> keywords = (List<String>) additionalValues.getOrDefault("keywords", null); 1210 if (keywords != null) 1211 { 1212 project.setKeywords(keywords.toArray(new String[keywords.size()])); 1213 } 1214 1215 project.setCreationDate(ZonedDateTime.now()); 1216 1217 // Create the project workspace = a site + a set of pages 1218 _createProjectWorkspace(project, errors); 1219 1220 activateModules(project, modulesIds, additionalValues); 1221 1222 if (CollectionUtils.isEmpty(errors)) 1223 { 1224 project.saveChanges(); 1225 1226 // Notify observers 1227 Map<String, Object> eventParams = new HashMap<>(); 1228 eventParams.put(ObservationConstants.ARGS_PROJECT, project); 1229 _observationManager.notify(new Event(ObservationConstants.EVENT_PROJECT_ADDED, _currentUserProvider.getUser(), eventParams)); 1230 1231 } 1232 else 1233 { 1234 deleteProject(project); 1235 } 1236 1237 clearCaches(); 1238 1239 return project; 1240 } 1241 1242 /** 1243 * Edit a project 1244 * @param id The project identifier 1245 * @param title The title to set 1246 * @param description The description to set 1247 * @param mailingList Project mailing list 1248 * @param inscriptionStatus The inscription status of the project 1249 * @param defaultProfile The default profile for new members 1250 */ 1251 @Callable(rights = ProjectConstants.RIGHT_PROJECT_EDIT, context = "/admin") 1252 public void editProject(String id, String title, String description, String mailingList, String inscriptionStatus, String defaultProfile) 1253 { 1254 Project project = _resolver.resolveById(id); 1255 editProject(project, title, description, mailingList, inscriptionStatus, defaultProfile); 1256 } 1257 1258 /** 1259 * Edit a project 1260 * @param project The project 1261 * @param title The title to set 1262 * @param description The description to set 1263 * @param mailingList Project mailing list 1264 * @param inscriptionStatus The inscription status of the project 1265 * @param defaultProfile The default profile for new members 1266 */ 1267 public void editProject(Project project, String title, String description, String mailingList, String inscriptionStatus, String defaultProfile) 1268 { 1269 checkRightsForProjectEdition(project, InscriptionStatus.valueOf(inscriptionStatus.toUpperCase()), null); 1270 1271 project.setTitle(title); 1272 1273 if (StringUtils.isNotEmpty(description)) 1274 { 1275 project.setDescription(description); 1276 } 1277 else 1278 { 1279 project.removeDescription(); 1280 } 1281 1282 if (StringUtils.isNotEmpty(mailingList)) 1283 { 1284 project.setMailingList(mailingList); 1285 } 1286 else 1287 { 1288 project.removeMailingList(); 1289 } 1290 1291 project.setInscriptionStatus(inscriptionStatus); 1292 project.setDefaultProfile(defaultProfile); 1293 1294 project.saveChanges(); 1295 1296 // Notify observers 1297 Map<String, Object> eventParams = new HashMap<>(); 1298 eventParams.put(ObservationConstants.ARGS_PROJECT, project); 1299 eventParams.put(org.ametys.plugins.workspaces.ObservationConstants.ARGS_PROJECT_ID, project.getId()); 1300 _observationManager.notify(new Event(ObservationConstants.EVENT_PROJECT_UPDATED, _currentUserProvider.getUser(), eventParams)); 1301 } 1302 1303 /** 1304 * Delete a list of project. 1305 * @param ids The ids of projects to delete 1306 * @return The ids of the deleted projects, unknowns projects and the deleted sites 1307 */ 1308 @Callable(rights = ProjectConstants.RIGHT_PROJECT_DELETE, context = "/admin") 1309 public Map<String, Object> deleteProjectsByIds(List<String> ids) 1310 { 1311 Map<String, Object> result = new HashMap<>(); 1312 List<Map<String, Object>> deleted = new ArrayList<>(); 1313 List<String> unknowns = new ArrayList<>(); 1314 1315 for (String id : ids) 1316 { 1317 try 1318 { 1319 Project project = _resolver.resolveById(id); 1320 1321 Map<String, Object> projectInfo = new HashMap<>(); 1322 projectInfo.put("id", id); 1323 projectInfo.put("title", project.getTitle()); 1324 projectInfo.put("sites", deleteProject(project)); 1325 1326 deleted.add(projectInfo); 1327 } 1328 catch (UnknownAmetysObjectException e) 1329 { 1330 getLogger().warn(String.format("Unable to delete the definition of id '%s', because it does not exist.", id), e); 1331 unknowns.add(id); 1332 } 1333 } 1334 1335 result.put("deleted", deleted); 1336 result.put("unknowns", unknowns); 1337 1338 return result; 1339 } 1340 1341 /** 1342 * Delete a project. 1343 * @param projects The list of projects to delete 1344 * @return list of deleted sites (each list entry contains a data map with 1345 * the id and the name of the delete site). 1346 */ 1347 public List<Map<String, String>> deleteProject(List<Project> projects) 1348 { 1349 List<Map<String, String>> deletedSitesInfo = new ArrayList<>(); 1350 1351 for (Project project : projects) 1352 { 1353 deletedSitesInfo.addAll(deleteProject(project)); 1354 } 1355 1356 return deletedSitesInfo; 1357 } 1358 1359 /** 1360 * Delete a project and its sites 1361 * @param project The project to delete 1362 * @return list of deleted sites (each list entry contains a data map with 1363 * the id and the name of the delete site). 1364 */ 1365 public List<Map<String, String>> deleteProject(Project project) 1366 { 1367 ModifiableAmetysObject parent = project.getParent(); 1368 1369 1370 // list of map entry with id, name and title property 1371 // { id: site id, name: site name } 1372 List<Map<String, String>> deletedSitesInfo = new ArrayList<>(); 1373 1374 Site site = project.getSite(); 1375 if (site != null) 1376 { 1377 try 1378 { 1379 Map<String, String> siteProps = new HashMap<>(); 1380 siteProps.put("id", site.getId()); 1381 siteProps.put("name", site.getName()); 1382 1383 _siteDao.deleteSite(site.getId()); 1384 deletedSitesInfo.add(siteProps); 1385 } 1386 catch (RepositoryException e) 1387 { 1388 String errorMsg = String.format("Error while trying to delete the site '%s' for the project '%s'.", site.getName(), project.getName()); 1389 getLogger().error(errorMsg, e); 1390 } 1391 } 1392 1393 String projectId = project.getId(); 1394 Collection<ProjectMember> projectMembers = _projectMembers.getProjectMembers(project, true); 1395 project.remove(); 1396 parent.saveChanges(); 1397 1398 // Notify observers 1399 Map<String, Object> eventParams = new HashMap<>(); 1400 eventParams.put(ObservationConstants.ARGS_PROJECT_ID, projectId); 1401 eventParams.put(ObservationConstants.ARGS_PROJECT_NAME, project.getName()); 1402 eventParams.put(ObservationConstants.ARGS_PROJECT_MEMBERS, projectMembers); 1403 _observationManager.notify(new Event(ObservationConstants.EVENT_PROJECT_DELETED, _currentUserProvider.getUser(), eventParams)); 1404 1405 clearCaches(); 1406 1407 return deletedSitesInfo; 1408 } 1409 1410 /** 1411 * Utility method to get or create an ametys object 1412 * @param <A> A sub class of AmetysObject 1413 * @param parent The parent object 1414 * @param name The ametys object name 1415 * @param type The ametys object type 1416 * @return ametys object 1417 * @throws AmetysRepositoryException if an repository error occurs 1418 */ 1419 private <A extends AmetysObject> A _getOrCreateObject(ModifiableTraversableAmetysObject parent, String name, String type) throws AmetysRepositoryException 1420 { 1421 A object; 1422 1423 if (parent.hasChild(name)) 1424 { 1425 object = parent.getChild(name); 1426 } 1427 else 1428 { 1429 object = parent.createChild(name, type); 1430 parent.saveChanges(); 1431 } 1432 1433 return object; 1434 } 1435 1436 /** 1437 * Get the project of an ametys object inside a project. 1438 * It can be an explorer node, or any type of resource in a module. 1439 * @param id The identifier of the ametys object 1440 * @return the project or null if not found 1441 */ 1442 public Project getParentProject(String id) 1443 { 1444 return getParentProject(_resolver.<AmetysObject>resolveById(id)); 1445 } 1446 1447 /** 1448 * Get the project of an ametys object inside a project. 1449 * It can be an explorer node, or any type of resource in a module. 1450 * @param object The ametys object 1451 * @return the project or null if not found 1452 */ 1453 public Project getParentProject(AmetysObject object) 1454 { 1455 AmetysObject ametysObject = object; 1456 // Go back to the local explorer root. 1457 do 1458 { 1459 ametysObject = ametysObject.getParent(); 1460 } 1461 while (ametysObject instanceof ExplorerNode); 1462 1463 if (!(ametysObject instanceof Project)) 1464 { 1465 getLogger().warn(String.format("No project found for ametys object with id '%s'", ametysObject.getId())); 1466 return null; 1467 } 1468 1469 return (Project) ametysObject; 1470 } 1471 1472 /** 1473 * Get the list of project names for a given site 1474 * @param siteName The site name 1475 * @return the list of project names 1476 */ 1477 @Callable(rights = "Runtime_Rights_Admin_Access", context = "/admin") 1478 public List<String> getProjectsForSite(String siteName) 1479 { 1480 Cache<String, List<Pair<String, String>>> cache = _getMemorySiteAssociationCache(); 1481 if (cache.hasKey(siteName)) 1482 { 1483 return cache.get(siteName).stream() 1484 .map(p -> p.getRight()) 1485 .collect(Collectors.toList()); 1486 } 1487 else 1488 { 1489 List<String> projectNames = new ArrayList<>(); 1490 1491 if (_siteManager.hasSite(siteName)) 1492 { 1493 Site site = _siteManager.getSite(siteName); 1494 getProjectsForSite(site) 1495 .stream() 1496 .map(Project::getName) 1497 .forEach(projectNames::add); 1498 } 1499 1500 return projectNames; 1501 } 1502 } 1503 1504 /** 1505 * Get the list of project for a given site 1506 * @param site The site 1507 * @return the list of project 1508 */ 1509 public List<Project> getProjectsForSite(Site site) 1510 { 1511 Cache<String, List<Pair<String, String>>> cache = _getMemorySiteAssociationCache(); 1512 if (cache.hasKey(site.getName())) 1513 { 1514 return cache.get(site.getName()).stream() 1515 .map(p -> _resolver.<Project>resolveById(p.getLeft())) 1516 .collect(Collectors.toList()); 1517 } 1518 1519 StringExpression siteExpression = new StringExpression(SiteAwareAmetysObject.METADATA_SITE, Operator.EQ, site.getName()); 1520 String query = QueryHelper.getXPathQuery(null, Project.NODE_TYPE, siteExpression); 1521 try (AmetysObjectIterable<Project> projects = _resolver.query(query)) 1522 { 1523 List<Pair<String, String>> projectsPairs = new ArrayList<>(); 1524 List<Project> result = new ArrayList<>(); 1525 for (Project project : projects) 1526 { 1527 projectsPairs.add(Pair.of(project.getId(), project.getName())); 1528 result.add(project); 1529 } 1530 1531 cache.put(site.getName(), projectsPairs); 1532 return result; 1533 } 1534 catch (AmetysRepositoryException e) 1535 { 1536 getLogger().error(String.format("Unable to find projects for site '%s'", site.getName()), e); 1537 } 1538 1539 return new ArrayList<>(); 1540 } 1541 1542 /** 1543 * Create the project workspace for a given project. 1544 * @param project The project for which the workspace must be created 1545 * @param errors A list of possible errors to populate. Can be null if the caller is not interested in error tracking. 1546 * @return The site created for this workspace 1547 */ 1548 protected Site _createProjectWorkspace(Project project, List<String> errors) 1549 { 1550 String initialSiteName = project.getName(); 1551 Site site = null; 1552 1553 Site catalogSite = _siteManager.getSite(getCatalogSiteName()); 1554 String rootId = catalogSite != null ? catalogSite.getId() : null; 1555 1556 Map<String, Object> result = _siteDao.createSite(rootId, initialSiteName, ProjectWorkspaceSiteType.TYPE_ID, true); 1557 1558 String siteId = (String) result.get("id"); 1559 String siteName = (String) result.get("name"); 1560 if (StringUtils.isNotEmpty(siteId)) 1561 { 1562 // Creation success 1563 site = _siteManager.getSite(siteName); 1564 1565 setProjectSiteTitle(site, project.getTitle()); 1566 1567 // Add site to project 1568 project.setSite(site); 1569 1570 site.saveChanges(); 1571 } 1572 1573 return site; 1574 } 1575 1576 /** 1577 * Get the project's tags 1578 * @return The project's tags 1579 */ 1580 public List<String> getTags() 1581 { 1582 AmetysObject projectsRootNode = getProjectsRoot(); 1583 if (projectsRootNode instanceof JCRAmetysObject) 1584 { 1585 Node node = ((JCRAmetysObject) projectsRootNode).getNode(); 1586 1587 try 1588 { 1589 return Arrays.stream(node.getProperty(__PROJECTS_TAGS_PROPERTY).getValues()) 1590 .map(LambdaUtils.wrap(Value::getString)) 1591 .collect(Collectors.toList()); 1592 } 1593 catch (PathNotFoundException e) 1594 { 1595 // property is not set, empty list will be returned. 1596 } 1597 catch (RepositoryException e) 1598 { 1599 throw new AmetysRepositoryException(e); 1600 } 1601 } 1602 1603 return new ArrayList<>(); 1604 } 1605 1606 /** 1607 * Add project's tags 1608 * @param newTags The new tags to add 1609 */ 1610 public synchronized void addTags(Collection<String> newTags) 1611 { 1612 if (CollectionUtils.isNotEmpty(newTags)) 1613 { 1614 AmetysObject projectsRootNode = getProjectsRoot(); 1615 if (projectsRootNode instanceof JCRAmetysObject) 1616 { 1617 // Concat existing tags with new lowercased tags 1618 String[] tags = Stream.concat(getTags().stream(), newTags.stream().map(String::trim).map(String::toLowerCase).filter(StringUtils::isNotEmpty)) 1619 .distinct() 1620 .toArray(String[]::new); 1621 1622 try 1623 { 1624 ((JCRAmetysObject) projectsRootNode).getNode().setProperty(__PROJECTS_TAGS_PROPERTY, tags); 1625 } 1626 catch (RepositoryException e) 1627 { 1628 throw new AmetysRepositoryException(e); 1629 } 1630 } 1631 } 1632 } 1633 1634 /** 1635 * Get the list of activated modules for a project 1636 * @param project The project 1637 * @return The list of activated modules 1638 */ 1639 public List<WorkspaceModule> getModules(Project project) 1640 { 1641 return _moduleManagerEP.getModules().stream() 1642 .filter(module -> isModuleActivated(project, module.getId())) 1643 .collect(Collectors.toList()); 1644 } 1645 1646 /** 1647 * Retrieves the page of the module for all available languages 1648 * @param project The project 1649 * @param moduleId The project module id 1650 * @return the page or null if not found 1651 */ 1652 public Set<Page> getModulePages(Project project, String moduleId) 1653 { 1654 if (_moduleManagerEP.hasExtension(moduleId)) 1655 { 1656 WorkspaceModule module = _moduleManagerEP.getExtension(moduleId); 1657 return getModulePages(project, module); 1658 } 1659 return null; 1660 } 1661 1662 /** 1663 * Return the possible module roots associated to a page 1664 * @param page The given page 1665 * @return A non null set of the data of the linked modules 1666 */ 1667 public Set<ModifiableResourceCollection> pageToModuleRoot(Page page) 1668 { 1669 Set<ModifiableResourceCollection> data = new LinkedHashSet<>(); 1670 1671 Page rootPage = page; 1672 SitemapElement parent = page.getParent(); 1673 while (!(parent instanceof Sitemap) && !page.hasValue(__PAGE_MODULES_VALUE)) 1674 { 1675 rootPage = (Page) parent; 1676 parent = parent.getParent(); 1677 } 1678 1679 String[] modulesRootsIds = rootPage.getValueOrDefault(__PAGE_MODULES_VALUE, new String[0]); 1680 if (modulesRootsIds.length > 0) 1681 { 1682 for (String moduleRootId : modulesRootsIds) 1683 { 1684 try 1685 { 1686 ModifiableResourceCollection moduleRoot = _resolver.resolveById(moduleRootId); 1687 data.add(moduleRoot); 1688 } 1689 catch (UnknownAmetysObjectException e) 1690 { 1691 // Ignore obsolete data 1692 } 1693 } 1694 } 1695 1696 return data; 1697 } 1698 1699 /** 1700 * Mark the given page as this module page. The modified page will not be saved. 1701 * @param page The page to change 1702 * @param moduleRoot The workspace module that use this page 1703 */ 1704 public void tagProjectPage(ModifiablePage page, ModifiableResourceCollection moduleRoot) 1705 { 1706 String[] currentModules = page.getValueOrDefault(__PAGE_MODULES_VALUE, new String[0]); 1707 1708 Set<String> modules = new LinkedHashSet<>(Arrays.asList(currentModules)); 1709 modules.add(moduleRoot.getId()); 1710 1711 String[] newModules = new String[modules.size()]; 1712 modules.toArray(newModules); 1713 1714 page.setValue(__PAGE_MODULES_VALUE, newModules); 1715 } 1716 1717 /** 1718 * Remove the mark on the given page of this module. The modified page will not be saved. 1719 * @param page The page to change 1720 * @param moduleRoot The workspace module that use this page 1721 */ 1722 public void untagProjectPage(ModifiablePage page, ModifiableResourceCollection moduleRoot) 1723 { 1724 if (moduleRoot != null) 1725 { 1726 String[] currentModules = page.getValueOrDefault(__PAGE_MODULES_VALUE, new String[0]); 1727 1728 Set<String> modules = new LinkedHashSet<>(Arrays.asList(currentModules)); 1729 modules.remove(moduleRoot.getId()); 1730 1731 String[] newModules = new String[modules.size()]; 1732 modules.toArray(newModules); 1733 1734 page.setValue(__PAGE_MODULES_VALUE, newModules); 1735 } 1736 } 1737 1738 /** 1739 * Get a page in the site of a given project with a specific tag 1740 * @param project The project 1741 * @param workspaceModule the module 1742 * @return The module's pages 1743 */ 1744 public Set<Page> getModulePages(Project project, WorkspaceModule workspaceModule) 1745 { 1746 Request request = _getRequest(); 1747 if (request == null) 1748 { 1749 // There is no request to store cache 1750 return _computePages(project, workspaceModule); 1751 } 1752 1753 Cache<RequestModuleCacheKey, Set<Page>> pagesCache = _getRequestPageCache(); 1754 1755 // The site key in the cache is of the form {site + workspace}. 1756 String currentWorkspace = _workspaceSelector.getWorkspace(); 1757 RequestModuleCacheKey pagesKey = RequestModuleCacheKey.of(project.getName(), workspaceModule.getId(), currentWorkspace); 1758 1759 try 1760 { 1761 return pagesCache.get(pagesKey, __ -> _computePages(project, workspaceModule)); 1762 } 1763 catch (CacheException e) 1764 { 1765 if (e.getCause() instanceof UnknownAmetysObjectException) 1766 { 1767 throw (UnknownAmetysObjectException) e.getCause(); 1768 } 1769 else 1770 { 1771 throw new RuntimeException("An error occurred while computing page of module " + workspaceModule.getModuleName() + " in project " + project.getName(), e); 1772 } 1773 } 1774 } 1775 1776 private Set<Page> _computePages(Project project, WorkspaceModule workspaceModule) 1777 { 1778 Set<String> pagesUUids = _getMemoryPageCache().get(ModuleCacheKey.of(project.getName(), workspaceModule.getId()), __ -> _computePagesIds(project, workspaceModule)); 1779 if (pagesUUids != null) 1780 { 1781 return pagesUUids.stream().map(uuid -> _resolver.<Page>resolveById(uuid)).collect(Collectors.toSet()); 1782 } 1783 else 1784 { 1785 // Project may be present in cache for 'default' workspace but does not exist in current JCR workspace 1786 throw new UnknownAmetysObjectException("There is no pages for '" + project.getName() + "', module '" + workspaceModule.getModuleName() + "'"); 1787 } 1788 } 1789 1790 private Set<String> _computePagesIds(Project project, WorkspaceModule workspaceModule) 1791 { 1792 Site site = project.getSite(); 1793 String siteName = site != null ? site.getName() : null; 1794 if (StringUtils.isEmpty(siteName)) 1795 { 1796 return null; 1797 } 1798 1799 ModifiableResourceCollection moduleRoot = workspaceModule.getModuleRoot(project, false); 1800 if (moduleRoot != null) 1801 { 1802 Expression expression = new StringExpression(__PAGE_MODULES_VALUE, Operator.EQ, moduleRoot.getId()); 1803 String query = PageQueryHelper.getPageXPathQuery(siteName, null, null, expression, null); 1804 1805 return StreamSupport.stream(_resolver.query(query).spliterator(), false) 1806 .map(page -> page.getId()) 1807 .collect(Collectors.toSet()); 1808 } 1809 else 1810 { 1811 return Set.of(); 1812 } 1813 } 1814 1815 /** 1816 * Activate the list of module of the project 1817 * @param project The project 1818 * @param moduleIds The list of modules. Can be null to activate all modules 1819 * @param additionalValues A list of optional additional values. Accepted values are : description, mailingList, inscriptionStatus, defaultProfile, tags, categoryTags, keywords and language 1820 */ 1821 public void activateModules(Project project, Set<String> moduleIds, Map<String, Object> additionalValues) 1822 { 1823 Set<String> modules = moduleIds == null ? _moduleManagerEP.getExtensionsIds() : moduleIds; 1824 1825 for (String moduleId : modules) 1826 { 1827 WorkspaceModule module = _moduleManagerEP.getModule(moduleId); 1828 if (module != null && !isModuleActivated(project, moduleId)) 1829 { 1830 module.activateModule(project, additionalValues); 1831 project.addModule(moduleId); 1832 } 1833 } 1834 1835 _setDefaultProfileForMembers(project, modules); 1836 1837 project.saveChanges(); 1838 } 1839 1840 private void _setDefaultProfileForMembers(Project project, Set<String> modules) 1841 { 1842 String profileForNewModule = StringUtils.defaultString(Config.getInstance().getValue("workspaces.profile.new.module")); 1843 1844 if (profileForNewModule.equals(ProfileForNewModule.DEFAULT_MEMBER_PROFILE.name())) 1845 { 1846 Set<String> defaultProfiles = Set.of(StringUtils.defaultString(Config.getInstance().getValue("workspaces.profile.default"))); 1847 Map<JCRProjectMember, Object> projectMembers = _projectMembers.getJCRProjectMembers(project); 1848 1849 Set<WorkspaceModule> modulesForMembers = getProjectModulesForNewMembers(project); 1850 for (String moduleId : modules) 1851 { 1852 WorkspaceModule module = _moduleManagerEP.getModule(moduleId); 1853 Set<String> profiles = modulesForMembers.contains(module) ? defaultProfiles : Set.of(); 1854 for (JCRProjectMember member : projectMembers.keySet()) 1855 { 1856 _projectMembers.setProfileOnModule(member, project, module, profiles); 1857 } 1858 } 1859 } 1860 } 1861 1862 /** 1863 * Initialize the sitemap with the active module of the project 1864 * @param project The project 1865 * @param sitemap The sitemap 1866 */ 1867 public void initializeModulesSitemap(Project project, Sitemap sitemap) 1868 { 1869 Set<String> modules = _moduleManagerEP.getExtensionsIds(); 1870 1871 for (String moduleId : modules) 1872 { 1873 if (_moduleManagerEP.hasExtension(moduleId)) 1874 { 1875 WorkspaceModule module = _moduleManagerEP.getExtension(moduleId); 1876 1877 if (isModuleActivated(project, moduleId)) 1878 { 1879 module.initializeSitemap(project, sitemap); 1880 } 1881 } 1882 } 1883 } 1884 1885 /** 1886 * Determines if a module is activated 1887 * @param project The project 1888 * @param moduleId The id of module 1889 * @return true if the module the currently activated 1890 */ 1891 public boolean isModuleActivated(Project project, String moduleId) 1892 { 1893 return ArrayUtils.contains(project.getModules(), moduleId); 1894 } 1895 1896 /** 1897 * Remove the explorer root node of the project module, remove all events 1898 * related to that module and set it to deactivated 1899 * @param project The project 1900 * @param moduleIds The id of module to activate 1901 */ 1902 public void deactivateModules(Project project, Set<String> moduleIds) 1903 { 1904 for (String moduleId : moduleIds) 1905 { 1906 WorkspaceModule module = _moduleManagerEP.getModule(moduleId); 1907 if (module != null && isModuleActivated(project, moduleId)) 1908 { 1909 module.deactivateModule(project); 1910 project.removeModule(moduleId); 1911 } 1912 } 1913 1914 project.saveChanges(); 1915 } 1916 1917 1918 /** 1919 * Get the list of profiles configured for the workspaces' projects 1920 * @return The list of profiles as JSON 1921 */ 1922 @Callable(rights = {ProjectConstants.RIGHT_PROJECT_CREATE_PRIVATE, ProjectConstants.RIGHT_PROJECT_CREATE_PUBLIC_MODERATED, ProjectConstants.RIGHT_PROJECT_CREATE_PUBLIC_OPENED, ProjectConstants.RIGHT_PROJECT_EDIT}, context = "/admin") 1923 public Map<String, Object> getProjectProfiles() 1924 { 1925 Map<String, Object> result = new HashMap<>(); 1926 List<Map<String, Object>> profiles = _projectRightHelper.getProfiles().stream().map(p -> p.toJSON()).collect(Collectors.toList()); 1927 result.put("profiles", profiles); 1928 return result; 1929 } 1930 1931 /** 1932 * Get the site name holding the catalog of projects 1933 * @return the catalog's site name 1934 * @throws UnknownCatalogSiteException when the config is invalid 1935 */ 1936 public String getCatalogSiteName() throws UnknownCatalogSiteException 1937 { 1938 String catalogSiteName = Config.getInstance().getValue("workspaces.catalog.site.name"); 1939 if (!_siteManager.hasSite(catalogSiteName)) 1940 { 1941 throw new UnknownCatalogSiteException("Unknown site '" + catalogSiteName + "'. The global Ametys configuration is invalid for the parameter 'workspaces.catalog.site.name'"); 1942 } 1943 return catalogSiteName; 1944 } 1945 1946 /** 1947 * Get the site name holding the users directory 1948 * @return the users directory's site name 1949 * @throws UnknownUserDirectorySiteException when the config is invalid 1950 */ 1951 public String getUsersDirectorySiteName() throws UnknownUserDirectorySiteException 1952 { 1953 String udSiteName = Config.getInstance().getValue("workspaces.member.userdirectory.site.name"); 1954 if (!_siteManager.hasSite(udSiteName)) 1955 { 1956 throw new UnknownUserDirectorySiteException("Unknown site '" + udSiteName + "'. The global Ametys configuration is invalid for the parameter 'workspaces.member.userdirectory.site.name'"); 1957 } 1958 return udSiteName; 1959 } 1960 1961 @Override 1962 public boolean supports(Event event) 1963 { 1964 return event.getId().equals(ObservationConstants.EVENT_PROJECT_DELETED) 1965 || event.getId().equals(ObservationConstants.EVENT_PROJECT_UPDATED) 1966 || event.getId().equals(ObservationConstants.EVENT_PROJECT_ADDED) 1967 || event.getId().equals(org.ametys.web.ObservationConstants.EVENT_PAGE_ADDED) 1968 || event.getId().equals(org.ametys.web.ObservationConstants.EVENT_PAGE_DELETED); 1969 } 1970 1971 public int getPriority() 1972 { 1973 return 0; 1974 } 1975 1976 public void observe(Event event, Map<String, Object> transientVars) throws Exception 1977 { 1978 clearCaches(); 1979 } 1980 1981 /** 1982 * Prefix project title 1983 * @param site the site 1984 * @param title the title 1985 */ 1986 public void setProjectSiteTitle(Site site, String title) 1987 { 1988 I18nizableText i18nSiteTitle = new I18nizableText("plugin." + _pluginName, "PLUGINS_WORKSPACES_PROJECT_DEFAULT_PROJECT_WORKSPACE_TITLE", Arrays.asList(title)); 1989 site.setTitle(_i18nUtils.translate(i18nSiteTitle)); 1990 } 1991 1992 private Project _computeProject(String projectName) 1993 { 1994 if (hasProject(projectName)) 1995 { 1996 String uuid = _getUUIDCache().get(projectName); 1997 return _resolver.<Project>resolveById(uuid); 1998 } 1999 else 2000 { 2001 // Project may be present in cache for 'default' workspace but does not exist in current JCR workspace 2002 throw new UnknownAmetysObjectException("There is no site named '" + projectName + "'"); 2003 } 2004 } 2005 2006 /** 2007 * Check rights to create project 2008 * @param inscriptionStatus the inscription status 2009 * @param zoneItem the zoneItem containing catalog service. Must be a catalog service if not null 2010 */ 2011 public void checkRightsForProjectCreation(InscriptionStatus inscriptionStatus, ZoneItem zoneItem) 2012 { 2013 SitemapElement catalogPage = zoneItem != null ? zoneItem.getZone().getSitemapElement() : null; 2014 2015 if (catalogPage != null && !_projectRightHelper.hasCatalogReadAccess(zoneItem)) 2016 { 2017 throw new AccessDeniedException("User " + _currentUserProvider.getUser() + " tried to create project from page '" + catalogPage.getId() + "' without sufficient rights"); 2018 } 2019 2020 switch (inscriptionStatus) 2021 { 2022 case PRIVATE: 2023 boolean hasRightToCreatePrivateProjetOnPages = catalogPage != null ? _rightManager.currentUserHasRight(ProjectConstants.RIGHT_PROJECT_CREATE_PRIVATE, catalogPage) == RightResult.RIGHT_ALLOW : false; 2024 if (!hasRightToCreatePrivateProjetOnPages && _rightManager.currentUserHasRight(ProjectConstants.RIGHT_PROJECT_CREATE_PRIVATE, "/${WorkspaceName}") != RightResult.RIGHT_ALLOW) 2025 { 2026 throw new AccessDeniedException("User " + _currentUserProvider.getUser() + " tried to create private project without sufficient rights"); 2027 } 2028 break; 2029 case MODERATED: 2030 boolean hasRightToCreateModeratedProjetOnPages = catalogPage != null ? _rightManager.currentUserHasRight(ProjectConstants.RIGHT_PROJECT_CREATE_PUBLIC_MODERATED, catalogPage) == RightResult.RIGHT_ALLOW : false; 2031 if (!hasRightToCreateModeratedProjetOnPages && _rightManager.currentUserHasRight(ProjectConstants.RIGHT_PROJECT_CREATE_PUBLIC_MODERATED, "/${WorkspaceName}") != RightResult.RIGHT_ALLOW) 2032 { 2033 throw new AccessDeniedException("User " + _currentUserProvider.getUser() + " tried to create public project with moderation without sufficient rights"); 2034 } 2035 break; 2036 case OPEN: 2037 boolean hasRightToCreateOpenProjetOnPages = catalogPage != null ? _rightManager.currentUserHasRight(ProjectConstants.RIGHT_PROJECT_CREATE_PUBLIC_OPENED, catalogPage) == RightResult.RIGHT_ALLOW : false; 2038 if (!hasRightToCreateOpenProjetOnPages && _rightManager.currentUserHasRight(ProjectConstants.RIGHT_PROJECT_CREATE_PUBLIC_OPENED, "/${WorkspaceName}") != RightResult.RIGHT_ALLOW) 2039 { 2040 throw new AccessDeniedException("User " + _currentUserProvider.getUser() + " tried to create public project without sufficient rights"); 2041 } 2042 break; 2043 default: 2044 throw new IllegalArgumentException("Inscription status '" + inscriptionStatus.toString() + "' is unknown"); 2045 } 2046 } 2047 2048 /** 2049 * Check rights to edit project 2050 * @param project the project 2051 * @param inscriptionStatus the inscription status 2052 * @param zoneItem the zoneItem containing catalog service. Must be a catalog service if not null 2053 */ 2054 public void checkRightsForProjectEdition(Project project, InscriptionStatus inscriptionStatus, ZoneItem zoneItem) 2055 { 2056 InscriptionStatus oldInscriptionStatus = project.getInscriptionStatus(); 2057 SitemapElement catalogPage = zoneItem != null ? zoneItem.getZone().getSitemapElement() : null; 2058 2059 if (catalogPage != null && !_projectRightHelper.hasCatalogReadAccess(zoneItem)) 2060 { 2061 throw new AccessDeniedException("User " + _currentUserProvider.getUser() + " tried to edit project from page '" + catalogPage.getId() + "' without sufficient rights"); 2062 } 2063 2064 if (oldInscriptionStatus != inscriptionStatus) 2065 { 2066 boolean canCreatePrivateProjet = _rightManager.currentUserHasRight(ProjectConstants.RIGHT_PROJECT_CREATE_PRIVATE, "/${WorkspaceName}") == RightResult.RIGHT_ALLOW 2067 || (catalogPage != null ? _rightManager.currentUserHasRight(ProjectConstants.RIGHT_PROJECT_CREATE_PRIVATE, catalogPage) == RightResult.RIGHT_ALLOW : false); 2068 boolean canCreatePublicProjetWithModeration = _rightManager.currentUserHasRight(ProjectConstants.RIGHT_PROJECT_CREATE_PUBLIC_MODERATED, "/${WorkspaceName}") == RightResult.RIGHT_ALLOW 2069 || (catalogPage != null ? _rightManager.currentUserHasRight(ProjectConstants.RIGHT_PROJECT_CREATE_PUBLIC_MODERATED, catalogPage) == RightResult.RIGHT_ALLOW : false); 2070 boolean canCreatePublicProjet = _rightManager.currentUserHasRight(ProjectConstants.RIGHT_PROJECT_CREATE_PUBLIC_OPENED, "/${WorkspaceName}") == RightResult.RIGHT_ALLOW 2071 || (catalogPage != null ? _rightManager.currentUserHasRight(ProjectConstants.RIGHT_PROJECT_CREATE_PUBLIC_OPENED, catalogPage) == RightResult.RIGHT_ALLOW : false); 2072 2073 switch (oldInscriptionStatus) 2074 { 2075 case PRIVATE: 2076 if (!canCreatePrivateProjet) 2077 { 2078 throw new AccessDeniedException("User " + _currentUserProvider.getUser() + " tried to edit private project without sufficient rights"); 2079 } 2080 break; 2081 case MODERATED: 2082 if (!canCreatePublicProjetWithModeration) 2083 { 2084 throw new AccessDeniedException("User " + _currentUserProvider.getUser() + " tried to edit public project with moderation without sufficient rights"); 2085 } 2086 break; 2087 case OPEN: 2088 if (!canCreatePublicProjet) 2089 { 2090 throw new AccessDeniedException("User " + _currentUserProvider.getUser() + " tried to edit public project without sufficient rights"); 2091 } 2092 break; 2093 default: 2094 throw new IllegalArgumentException("Inscription status '" + oldInscriptionStatus.toString() + "' is unknown"); 2095 } 2096 2097 switch (inscriptionStatus) 2098 { 2099 case PRIVATE: 2100 if (!canCreatePrivateProjet) 2101 { 2102 throw new AccessDeniedException("User " + _currentUserProvider.getUser() + " tried to edit project to private project without sufficient rights"); 2103 } 2104 break; 2105 case MODERATED: 2106 if (!canCreatePublicProjetWithModeration) 2107 { 2108 throw new AccessDeniedException("User " + _currentUserProvider.getUser() + " tried to edit project to public project with moderation without sufficient rights"); 2109 } 2110 break; 2111 case OPEN: 2112 if (!canCreatePublicProjet) 2113 { 2114 throw new AccessDeniedException("User " + _currentUserProvider.getUser() + " tried to edit project to public project without sufficient rights"); 2115 } 2116 break; 2117 default: 2118 throw new IllegalArgumentException("Inscription status '" + inscriptionStatus.toString() + "' is unknown"); 2119 } 2120 } 2121 } 2122 2123 /** 2124 * Clear the site cache 2125 */ 2126 public void clearCaches () 2127 { 2128 _getMemorySiteAssociationCache().invalidateAll(); 2129 _getMemoryProjectCache().invalidateAll(); 2130 _getMemoryPageCache().invalidateAll(); 2131 _getRequestProjectCache().invalidateAll(); 2132 _getRequestPageCache().invalidateAll(); 2133 } 2134 2135 private Cache<String, List<Pair<String, String>>> _getMemorySiteAssociationCache() 2136 { 2137 return _cacheManager.get(MEMORY_SITEASSOCIATION_CACHE); 2138 } 2139 2140 private Cache<String, String> _getMemoryProjectCache() 2141 { 2142 return _cacheManager.get(MEMORY_PROJECTIDBYNAMECACHE); 2143 } 2144 2145 private Cache<ModuleCacheKey, Set<String>> _getMemoryPageCache() 2146 { 2147 return _cacheManager.get(MEMORY_PAGESBYIDCACHE); 2148 } 2149 2150 private Cache<RequestProjectCacheKey, Project> _getRequestProjectCache() 2151 { 2152 return _cacheManager.get(REQUEST_PROJECTBYID_CACHE); 2153 } 2154 2155 private Cache<RequestModuleCacheKey, Set<Page>> _getRequestPageCache() 2156 { 2157 return _cacheManager.get(REQUEST_PAGESBYPROJECTANDMODULE_CACHE); 2158 } 2159 2160 2161 /** 2162 * Creates the caches 2163 */ 2164 protected void _createCaches() 2165 { 2166 _cacheManager.createMemoryCache(MEMORY_SITEASSOCIATION_CACHE, 2167 new I18nizableText("plugin.workspaces", "PLUGINS_WORKSPACES_CACHE_PROJECT_MANAGER_LABEL"), 2168 new I18nizableText("plugin.workspaces", "PLUGINS_WORKSPACES_CACHE_PROJECT_MANAGER_DESCRIPTION"), 2169 true, 2170 null); 2171 _cacheManager.createMemoryCache(MEMORY_PROJECTIDBYNAMECACHE, 2172 new I18nizableText("plugin.workspaces", "PLUGINS_WORKSPACES_PROJECT_MANAGER_UUID_CACHE_LABEL"), 2173 new I18nizableText("plugin.workspaces", "PLUGINS_WORKSPACES_PROJECT_MANAGER_UUID_CACHE_DESCRIPTION"), 2174 true, 2175 null); 2176 _cacheManager.createMemoryCache(MEMORY_PAGESBYIDCACHE, 2177 new I18nizableText("plugin.workspaces", "PLUGINS_WORKSPACES_PROJECT_MANAGER_PAGEUUID_CACHE_LABEL"), 2178 new I18nizableText("plugin.workspaces", "PLUGINS_WORKSPACES_PROJECT_MANAGER_PAGEUUID_CACHE_DESCRIPTION"), 2179 true, 2180 null); 2181 _cacheManager.createRequestCache(REQUEST_PROJECTBYID_CACHE, 2182 new I18nizableText("plugin.workspaces", "PLUGINS_WORKSPACES_PROJECT_MANAGER_REQUEST_CACHE_LABEL"), 2183 new I18nizableText("plugin.workspaces", "PLUGINS_WORKSPACES_PROJECT_MANAGER_REQUEST_CACHE_DESCRIPTION"), 2184 false); 2185 _cacheManager.createRequestCache(REQUEST_PAGESBYPROJECTANDMODULE_CACHE, 2186 new I18nizableText("plugin.workspaces", "PLUGINS_WORKSPACES_PROJECT_MANAGER_PAGEREQUEST_CACHE_LABEL"), 2187 new I18nizableText("plugin.workspaces", "PLUGINS_WORKSPACES_PROJECT_MANAGER_PAGEREQUEST_CACHE_DESCRIPTION"), 2188 false); 2189 } 2190 2191 private synchronized Map<String, String> _getUUIDCache() 2192 { 2193 if (!_getMemoryProjectCache().hasKey(__IS_CACHE_FILLED)) 2194 { 2195 Session defaultSession = null; 2196 try 2197 { 2198 // Force default workspace to execute query 2199 defaultSession = _repository.login(RepositoryConstants.DEFAULT_WORKSPACE); 2200 2201 String jcrQuery = "//element(*, ametys:project)"; 2202 2203 AmetysObjectIterable<Project> projects = _resolver.query(jcrQuery, defaultSession); 2204 2205 for (Project project : projects) 2206 { 2207 _getMemoryProjectCache().put(project.getName(), project.getId()); 2208 } 2209 2210 _getMemoryProjectCache().put(__IS_CACHE_FILLED, null); 2211 } 2212 catch (RepositoryException e) 2213 { 2214 throw new AmetysRepositoryException(e); 2215 } 2216 finally 2217 { 2218 if (defaultSession != null) 2219 { 2220 defaultSession.logout(); 2221 } 2222 } 2223 } 2224 2225 Map<String, String> cacheAsMap = _getMemoryProjectCache().asMap(); 2226 cacheAsMap.remove(__IS_CACHE_FILLED); 2227 return cacheAsMap; 2228 } 2229 2230 private static final class RequestProjectCacheKey extends AbstractCacheKey 2231 { 2232 private RequestProjectCacheKey(String projectName, String workspaceName) 2233 { 2234 super(projectName, workspaceName); 2235 } 2236 2237 static RequestProjectCacheKey of(String projectName, String workspaceName) 2238 { 2239 return new RequestProjectCacheKey(projectName, workspaceName); 2240 } 2241 } 2242 2243 private static final class ModuleCacheKey extends AbstractCacheKey 2244 { 2245 private ModuleCacheKey(String projectName, String moduleId) 2246 { 2247 super(projectName, moduleId); 2248 } 2249 2250 static ModuleCacheKey of(String projectName, String moduleId) 2251 { 2252 return new ModuleCacheKey(projectName, moduleId); 2253 } 2254 } 2255 2256 private static final class RequestModuleCacheKey extends AbstractCacheKey 2257 { 2258 private RequestModuleCacheKey(String projectName, String moduleId, String workspaceName) 2259 { 2260 super(projectName, moduleId, workspaceName); 2261 } 2262 2263 static RequestModuleCacheKey of(String projectName, String moduleId, String workspaceName) 2264 { 2265 return new RequestModuleCacheKey(projectName, moduleId, workspaceName); 2266 } 2267 } 2268 2269 private Request _getRequest () 2270 { 2271 try 2272 { 2273 return (Request) _context.get(ContextHelper.CONTEXT_REQUEST_OBJECT); 2274 } 2275 catch (ContextException ce) 2276 { 2277 getLogger().info("Unable to get the request", ce); 2278 return null; 2279 } 2280 } 2281 2282 /** 2283 * Retrieves all projects for client side 2284 * @return the projects 2285 */ 2286 @Callable(rights = "Runtime_Rights_Admin_Access", context = "/admin") 2287 public List<Map<String, Object>> getProjectsStatisticsForClientSide() 2288 { 2289 return getProjects() 2290 .stream() 2291 .map(p -> getProjectStatistics(p)) 2292 .collect(Collectors.toList()); 2293 } 2294 2295 /** 2296 * Retrieves the standard information of a project 2297 * @param project The project 2298 * @return The map of information 2299 */ 2300 public Map<String, Object> getProjectStatistics(Project project) 2301 { 2302 Map<String, Object> statistics = new HashMap<>(); 2303 2304 statistics.put("title", project.getTitle()); 2305 2306 long totalSize = 0; 2307 for (WorkspaceModule moduleManager : _moduleManagerEP.getModules()) 2308 { 2309 Map<String, Object> moduleStatistics = moduleManager.getStatistics(project); 2310 statistics.putAll(moduleStatistics); 2311 Long size = (Long) moduleStatistics.get(moduleManager.getModuleSizeKey()); 2312 totalSize += (size != null && size >= 0) ? (Long) moduleStatistics.get(moduleManager.getModuleSizeKey()) : 0; 2313 } 2314 2315 statistics.put("totalSize", totalSize); 2316 2317 ZonedDateTime creationDate = project.getCreationDate(); 2318 2319 statistics.put("creationDate", creationDate); 2320 statistics.put("managers", Arrays.stream(project.getManagers()) 2321 .map(u -> _userHelper.user2json(u)) 2322 .collect(Collectors.toList())); 2323 2324 return statistics; 2325 } 2326 2327 /** 2328 * Retrieves all projects for client side 2329 * @return the projects 2330 */ 2331 @Callable(rights = "Runtime_Rights_Admin_Access", context = "/admin") 2332 public List<Map<String, Object>> getProjectsStatisticsColumnsModel() 2333 { 2334 return getStatisticHeaders() 2335 .stream() 2336 .map(p -> p.convertToJSON()) 2337 .collect(Collectors.toList()); 2338 } 2339 2340 private List<StatisticColumn> getStatisticHeaders() 2341 { 2342 2343 List<StatisticColumn> flatStatisticHeaders = getFlatStatisticHeaders(); 2344 List<StatisticColumn> headers = new ArrayList<>(); 2345 for (StatisticColumn statisticColumn : flatStatisticHeaders) 2346 { 2347 // this column have a parent, we have to find it and attach it 2348 if (statisticColumn.getGroup() != null) 2349 { 2350 Optional<StatisticColumn> parent = flatStatisticHeaders.stream() 2351 .filter(column -> column.getId().equals(statisticColumn.getGroup())) 2352 .findAny(); 2353 if (parent.isPresent()) 2354 { 2355 parent.get().addSubColumn(statisticColumn); 2356 } 2357 } 2358 else 2359 { 2360 headers.add(statisticColumn); 2361 } 2362 } 2363 2364 return headers; 2365 } 2366 2367 private List<StatisticColumn> getFlatStatisticHeaders() 2368 { 2369 List<StatisticColumn> headers = new ArrayList<>(); 2370 headers.add(new StatisticColumn("title", new I18nizableText("plugin.workspaces", "PLUGINS_WORKSPACES_PROJECT_STATISTICS_TOOL_COLUMN_TITLE")) 2371 .withType(StatisticsColumnType.STRING) 2372 .withWidth(200) 2373 .withRenderer("Ametys.plugins.workspaces.project.tool.ProjectsGridHelper.renderTitle")); 2374 headers.add(new StatisticColumn("creationDate", new I18nizableText("plugin.workspaces", "PLUGINS_WORKSPACES_PROJECT_STATISTICS_TOOL_COLUMN_CREATION")) 2375 .withType(StatisticsColumnType.DATE) 2376 .withWidth(150)); 2377 headers.add(new StatisticColumn("managers", new I18nizableText("plugin.workspaces", "PLUGINS_WORKSPACES_PROJECT_STATISTICS_TOOL_COLUMN_MANAGERS")) 2378 .withRenderer("Ametys.grid.GridColumnHelper.renderUser") 2379 .withFilter(false)); 2380 for (WorkspaceModule moduleManager : _moduleManagerEP.getModules()) 2381 { 2382 headers.addAll(moduleManager.getStatisticModel()); 2383 } 2384 2385 StatisticColumn elements = new StatisticColumn(WorkspaceModule.GROUP_HEADER_ELEMENTS_ID, new I18nizableText("plugin.workspaces", "PLUGINS_WORKSPACES_PROJECT_STATISTICS_TOOL_COLUMN_ELEMENTS")) 2386 .withFilter(false); 2387 headers.add(elements); 2388 2389 StatisticColumn activatedModules = new StatisticColumn(WorkspaceModule.GROUP_HEADER_ACTIVATED_ID, new I18nizableText("plugin.workspaces", "PLUGINS_WORKSPACES_PROJECT_STATISTICS_TOOL_COLUMN_ACTIVE_MODULES")) 2390 .isHidden(true) 2391 .withFilter(false); 2392 headers.add(activatedModules); 2393 2394 StatisticColumn lastActivity = new StatisticColumn(WorkspaceModule.GROUP_HEADER_LAST_ACTIVITY_ID, new I18nizableText("plugin.workspaces", "PLUGINS_WORKSPACES_PROJECT_STATISTICS_TOOL_COLUMN_LAST_ACTIVITY")).isHidden(true); 2395 headers.add(lastActivity); 2396 2397 StatisticColumn modulesSize = new StatisticColumn(WorkspaceModule.GROUP_HEADER_SIZE_ID, new I18nizableText("plugin.workspaces", "PLUGINS_WORKSPACES_PROJECT_STATISTICS_TOOL_COLUMN_MODULES_SIZE")) 2398 .withFilter(false); 2399 modulesSize.addSubColumn(new StatisticColumn("totalSize", new I18nizableText("plugin.workspaces", "PLUGINS_WORKSPACES_PROJECT_STATISTICS_TOOL_COLUMN_MODULES_SIZE_TOTAL")) 2400 .withRenderer("Ametys.plugins.workspaces.project.tool.ProjectsGridHelper.renderSize") 2401 .withType(StatisticsColumnType.LONG)); 2402 2403 headers.add(modulesSize); 2404 2405 return headers; 2406 } 2407 2408 /** 2409 * Check if the user is in one of the populations of project 2410 * @param project the project 2411 * @param user the user 2412 * @return true if the user is in one of the populations of project 2413 */ 2414 public boolean isUserInProjectPopulations(Project project, UserIdentity user) 2415 { 2416 Site site = project.getSite(); 2417 2418 if (site == null) 2419 { 2420 throw new IllegalArgumentException("Cannot determine if user " + UserIdentity.userIdentityToString(user) + " can connect to the project " + project.getName() + " since the project has no associated site to determine the populations"); 2421 } 2422 String siteName = site.getName(); 2423 2424 Set<String> populations = _populationContextHelper.getUserPopulationsOnContext("/sites/" + siteName, false); 2425 Set<String> frontPopulations = _populationContextHelper.getUserPopulationsOnContext("/sites-fo/" + siteName, false); 2426 2427 return populations.contains(user.getPopulationId()) || frontPopulations.contains(user.getPopulationId()); 2428 } 2429 2430 /** 2431 * Thrown to indicate that the catalog site is unknown 2432 */ 2433 public class UnknownCatalogSiteException extends IllegalArgumentException 2434 { 2435 /** 2436 * Construct a {@code UnknownCatalogSiteException} with the specified message 2437 * @param message the message 2438 */ 2439 public UnknownCatalogSiteException(String message) 2440 { 2441 super(message); 2442 } 2443 } 2444 2445 /** 2446 * Thrown to indicate that the user directory site is unknown 2447 */ 2448 public class UnknownUserDirectorySiteException extends IllegalArgumentException 2449 { 2450 /** 2451 * Construct a {@code UnknownUserDirectorySiteException} with the specified message 2452 * @param message the message 2453 */ 2454 public UnknownUserDirectorySiteException(String message) 2455 { 2456 super(message); 2457 } 2458 } 2459}