--- /dev/null
+/*******************************************************************************
+ * Copyright Igor Barma, Alexandre Desoubeaux, Christian Martel, Eric Brun, Mathieu Amblard, Gwenael Gevet, Pierre Guillot, 2012
+ * Copyright Alexandre Desoubeaux, Christian Martel, Cedric Lecarpentier, Alexandre Lefevre, Marc Salvat 2014-2016
+ * Copyright Alexandre Desoubeaux, Christian Martel, Cedric Lecarpentier, Marc Salvat, Marc Suarez, Harifetra Ramamonjy 2017
+ * Copyright Alexandre Desoubeaux, Christian Martel, Cedric Lecarpentier, Alexandre Lefevre, Marc Salvat 2014-2016
+ * Copyright Alexandre Desoubeaux, Christian Martel, Cedric Lecarpentier, Marc Salvat, Marc Suarez, Harifetra Ramamonjy 2017
+ *
+ * This file is part of the work and learning management system Pentila Nero.
+ *
+ * Pentila Nero is free software. You can redistribute it and/or modify since
+ * you respect the terms of either (at least one of the both license) :
+ * - under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ * - the CeCILL-C as published by CeCILL-C; either version 1 of the
+ * License, or any later version
+ * - the GNU Lesser General Public License as published by the
+ * Free Software Foundation, either version 3 of the license,
+ * or (at your option) any later version.
+ *
+ * There are special exceptions to the terms and conditions of the
+ * licenses as they are applied to this software. View the full text of
+ * the exception in file LICENSE-PROJECT.txt in the directory of this software
+ * distribution.
+ *
+ * Pentila Nero is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * Licenses for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * and the CeCILL-C and the GNU Lesser General Public License along with
+ * Pentila Nero. If not, see :
+ * <http://www.gnu.org/licenses/> and
+ * <http://www.cecill.info/licences.fr.html>.
+ ******************************************************************************/
+package com.pentila.entSavoie.utils;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import com.liferay.contacts.util.GroupFilter;
+import com.liferay.contacts.util.OrganizationConstants;
+import com.liferay.contacts.util.OrganizationFilter;
+import com.liferay.portal.kernel.dao.orm.QueryUtil;
+import com.liferay.portal.kernel.exception.SystemException;
+import com.liferay.portal.kernel.json.JSONArray;
+import com.liferay.portal.kernel.json.JSONFactoryUtil;
+import com.liferay.portal.kernel.json.JSONObject;
+import com.liferay.portal.kernel.log.Log;
+import com.liferay.portal.kernel.log.LogFactoryUtil;
+import com.liferay.portal.model.Group;
+import com.liferay.portal.model.Organization;
+import com.liferay.portal.model.Role;
+import com.liferay.portal.model.RoleConstants;
+import com.liferay.portal.model.User;
+import com.liferay.portal.service.GroupLocalServiceUtil;
+import com.liferay.portal.service.OrganizationLocalServiceUtil;
+import com.liferay.portal.service.RoleLocalServiceUtil;
+import com.liferay.portal.service.UserGroupRoleLocalServiceUtil;
+import com.liferay.portal.service.UserLocalServiceUtil;
+import com.liferay.portal.util.comparator.GroupNameComparator;
+import com.pentila.entSavoie.ENTRoleUtilFactory;
+import com.pentila.entSavoie.ENTRolesConstants;
+import com.pentila.entSavoie.communityInfos.model.CommunityInfos;
+import com.pentila.entSavoie.communityInfos.model.GroupInfos;
+import com.pentila.entSavoie.communityInfos.service.CommunityInfosLocalServiceUtil;
+import com.pentila.entSavoie.directory.OrganizationFinderServiceUtil;
+
+public class GroupCacheUtil {
+
+ private static Log logger = LogFactoryUtil.getLog(GroupCacheUtil.class);
+
+ public static final String SCHOOLS = "schools";
+ public static final String INSTITUTIONAL_GROUPS = "institutionalGroups";
+ public static final String PERSONAL_GROUPS = "personalGroups";
+ public static final String OPENED_GROUPS = "openedGroups";
+
+ public static final String GROUP_ORG_ID = "orgId";
+ public static final String GROUP_ORG_NAME = "orgName";
+ public static final String GROUP_GROUP_ID = "groupId";
+ public static final String GROUP_GROUP_NAME = "groupName";
+ public static final String GROUP_IS_MIGRATED = "isMigrated";
+ public static final String GROUP_IS_DOCUMENTS = "isDocuments";
+ public static final String GROUP_IS_NEWS = "isNews";
+ public static final String GROUP_IS_FORUM = "isForum";
+ public static final String GROUP_IS_CDT = "isCdt";
+ public static final String GROUP_DEFAULT_VIEW = "defaultView";
+ public static final String GROUP_IS_ADMINISTRATOR = "isAdministrator";
+
+ // 30 minutes cache
+ private static final long EXPIRATION_TIME_MILLIS = 1800000;
+
+ public static void removeGroupCache(User user) {
+ String cacheKey="userGroups_"+user.getUserId();
+ ENTCacheUtils.removeObjectFromCache(cacheKey);
+ }
+
+ public static void removeGroupCache(long userId) {
+ String cacheKey="userGroups_"+userId;
+ ENTCacheUtils.removeObjectFromCache(cacheKey);
+ }
+
+ public static JSONObject getUserGroups(User user) {
+
+ String cacheKey="userGroups_"+user.getUserId();
+
+ // Get value from cache instance
+ JSONObject cacheObject = (JSONObject) ENTCacheUtils.getObjectFromCache(cacheKey);
+ if (cacheObject == null) {
+ long time0 = System.currentTimeMillis();
+ logger.info("Group list is not cached for user "+user.getFullName()+" => building it");
+ try {
+ cacheObject = buildUserGroupsJson(user);
+ } catch (Exception e) {
+ logger.error("Error while building user's group list for user "+user.getFullName(), e);
+ }
+ long time1 = System.currentTimeMillis();
+ logger.info("Group list built for user "+user.getFullName()+" in "+(time1 - time0)+" ms");
+ ENTCacheUtils.storeObjectIntoCache(cacheKey, cacheObject, EXPIRATION_TIME_MILLIS);
+ } else {
+ //logger.info("User group list is cached for user "+user.getFullName()+" => using it");
+ }
+
+ return cacheObject;
+ }
+
+
+ public static List<Long> getUserGroupIdsWithNews(User user, String filter) {
+
+ List<Long> groupIdList = new ArrayList<Long>();
+
+ JSONObject userJson = getUserGroups(user);
+
+ // Get institutional groups
+ JSONArray institutionalGroups = getInstitutionalGroups(user, userJson, true);
+ for (int i = 0 ; i < institutionalGroups.length() ; i++) {
+ JSONObject institutionalGroup = institutionalGroups.getJSONObject(i);
+ if (institutionalGroup.getBoolean(GROUP_IS_NEWS) && !institutionalGroup.getBoolean(GROUP_IS_MIGRATED) && (filter.equals("") || institutionalGroup.getString(GROUP_GROUP_NAME).contains(filter))) {
+ groupIdList.add(institutionalGroup.getLong(GROUP_GROUP_ID));
+ }
+ }
+
+ // Get personal groups
+ JSONArray personalGroups = getPersonalGroups(user, userJson);
+ for (int i = 0 ; i < personalGroups.length() ; i++) {
+ JSONObject personalGroup = personalGroups.getJSONObject(i);
+ if (personalGroup.getBoolean(GROUP_IS_NEWS) && (filter.equals("") || personalGroup.getString(GROUP_GROUP_NAME).contains(filter))) {
+ groupIdList.add(personalGroup.getLong(GROUP_GROUP_ID));
+ }
+ }
+
+ // Get opened groups
+ JSONArray openedGroups = getOpenedGroups(user, userJson);
+ for (int i = 0 ; i < openedGroups.length() ; i++) {
+ JSONObject openedGroup = openedGroups.getJSONObject(i);
+ if (openedGroup.getBoolean(GROUP_IS_NEWS) && (filter.equals("") || openedGroup.getString(GROUP_GROUP_NAME).contains(filter))) {
+ groupIdList.add(openedGroup.getLong(GROUP_GROUP_ID));
+ }
+ }
+
+ userJson.put("hasArchivedOrgs", false);
+ return groupIdList;
+ }
+
+ public static List<Long> getUserPersonalAdminGroupIdsWithNews(User user, String filter) {
+
+ List<Long> groupIdList = new ArrayList<Long>();
+
+ JSONObject userJson = getUserGroups(user);
+
+ // Get personal groups
+ JSONArray personalGroups = getPersonalGroups(user, userJson);
+ for (int i = 0 ; i < personalGroups.length() ; i++) {
+ JSONObject personalGroup = personalGroups.getJSONObject(i);
+ if (personalGroup.getBoolean(GROUP_IS_NEWS) && (filter.equals("") || personalGroup.getString(GROUP_GROUP_NAME).contains(filter)) && personalGroup.getBoolean(GROUP_IS_ADMINISTRATOR)) {
+ groupIdList.add(personalGroup.getLong(GROUP_GROUP_ID));
+ }
+ }
+
+ return groupIdList;
+ }
+
+
+ public static JSONArray getUserGroupsWithDocuments(User user) {
+
+ JSONArray groupArray = JSONFactoryUtil.createJSONArray();
+ JSONObject userJson = getUserGroups(user);
+
+ // Get institutional groups
+ JSONArray institutionalGroups = getInstitutionalGroups(user, userJson);
+ for (int i = 0 ; i < institutionalGroups.length() ; i++) {
+ JSONObject institutionalGroup = institutionalGroups.getJSONObject(i);
+ if (institutionalGroup.getBoolean(GROUP_IS_DOCUMENTS) && !institutionalGroup.getBoolean(GROUP_IS_MIGRATED)) {
+ groupArray.put(institutionalGroup);
+ }
+ }
+
+ // Get personal groups
+ JSONArray personalGroups = getPersonalGroups(user, userJson);
+ for (int i = 0 ; i < personalGroups.length() ; i++) {
+ JSONObject personalGroup = personalGroups.getJSONObject(i);
+ if (personalGroup.getBoolean(GROUP_IS_DOCUMENTS)) {
+ groupArray.put(personalGroup);
+ }
+ }
+
+ // Get opened groups
+ JSONArray openedGroups = getOpenedGroups(user, userJson);
+ for (int i = 0 ; i < openedGroups.length() ; i++) {
+ JSONObject openedGroup = openedGroups.getJSONObject(i);
+ if (openedGroup.getBoolean(GROUP_IS_DOCUMENTS)) {
+ groupArray.put(openedGroup);
+ }
+ }
+
+ return groupArray;
+ }
+
+
+ public static JSONArray getUserGroupsWithForums(User user) {
+
+ JSONArray groupArray = JSONFactoryUtil.createJSONArray();
+ JSONObject userJson = getUserGroups(user);
+
+ // Get institutional groups
+ JSONArray institutionalGroups = getInstitutionalGroups(user, userJson);
+ for (int i = 0 ; i < institutionalGroups.length() ; i++) {
+ JSONObject institutionalGroup = institutionalGroups.getJSONObject(i);
+ if (institutionalGroup.getBoolean(GROUP_IS_FORUM) && !institutionalGroup.getBoolean(GROUP_IS_MIGRATED)) {
+ groupArray.put(institutionalGroup);
+ }
+ }
+
+ // Get personal groups
+ JSONArray personalGroups = getPersonalGroups(user, userJson);
+ for (int i = 0 ; i < personalGroups.length() ; i++) {
+ JSONObject personalGroup = personalGroups.getJSONObject(i);
+ if (personalGroup.getBoolean(GROUP_IS_FORUM)) {
+ groupArray.put(personalGroup);
+ }
+ }
+
+ // Get opened groups
+ JSONArray openedGroups = getOpenedGroups(user, userJson);
+ for (int i = 0 ; i < openedGroups.length() ; i++) {
+ JSONObject openedGroup = openedGroups.getJSONObject(i);
+ if (openedGroup.getBoolean(GROUP_IS_FORUM)) {
+ groupArray.put(openedGroup);
+ }
+ }
+ return groupArray;
+ }
+
+ public static JSONArray getInstitutionalGroups(User user) {
+ JSONObject json = getUserGroups(user);
+ return json.getJSONArray(INSTITUTIONAL_GROUPS);
+ }
+
+ public static JSONArray getInstitutionalGroups(User user, JSONObject json) {
+ return getInstitutionalGroups(user, json, false);
+ }
+
+ /**
+ * Returns all user's institutional groups
+ * - if teacher or local admin : remove parent groups (except school-level parents org)
+ * - if parent : let parent groups
+ */
+ public static JSONArray getInstitutionalGroups(User user, JSONObject json, boolean withParentGroups) {
+ if (withParentGroups) {
+ return json.getJSONArray(INSTITUTIONAL_GROUPS);
+ } else {
+ boolean isParent = false;
+ try {
+ isParent = RoleLocalServiceUtil.hasUserRole(user.getUserId(), user.getCompanyId(), ENTRolesConstants.NATIONAL_2, false);
+ } catch (Exception e) {
+ }
+ if (isParent) {
+ return json.getJSONArray(INSTITUTIONAL_GROUPS);
+ } else {
+ JSONArray institutionnalGroupsWithoutParents = JSONFactoryUtil.createJSONArray();
+ // Build the school-level group 'CLG - Parents' name
+ String schoolLevelParentsOrg = "";
+ JSONArray institutionnalGroups = json.getJSONArray(INSTITUTIONAL_GROUPS);
+ for (int i = 0 ; i < institutionnalGroups.length() ; i++) {
+ JSONObject group = institutionnalGroups.getJSONObject(i);
+ if (group.getString(GROUP_ORG_NAME).endsWith(OrganizationConstants.ORG_SUFFIX_PERSONNELS)) {
+ schoolLevelParentsOrg = group.getString(GROUP_ORG_NAME).substring(0, group.getString(GROUP_ORG_NAME).length() - OrganizationConstants.ORG_SUFFIX_PERSONNELS.length()) + OrganizationConstants.ORG_SUFFIX_PARENTS;
+ }
+ }
+ // Now filter all ' - Parents' suffixed groups, except for the school-level Parents group
+ for (int i = 0 ; i < institutionnalGroups.length() ; i++) {
+ JSONObject group = institutionnalGroups.getJSONObject(i);
+ if (!group.getString(GROUP_ORG_NAME).endsWith(OrganizationConstants.ORG_SUFFIX_PARENTS) || group.getString(GROUP_ORG_NAME).equals(schoolLevelParentsOrg)) {
+ institutionnalGroupsWithoutParents.put(group);
+ }
+ }
+ return institutionnalGroupsWithoutParents;
+ }
+ }
+
+ }
+
+ public static JSONArray getUserSchools(User user) {
+ JSONObject json = getUserGroups(user);
+ return json.getJSONArray(SCHOOLS);
+ }
+
+ public static JSONArray getPersonalGroups(User user) {
+ JSONObject json = getUserGroups(user);
+ return json.getJSONArray(PERSONAL_GROUPS);
+ }
+
+ public static JSONArray getPersonalGroups(User user, JSONObject json) {
+ return json.getJSONArray(PERSONAL_GROUPS);
+ }
+
+ public static JSONArray getOpenedGroups(User user) {
+ JSONObject json = getUserGroups(user);
+ return json.getJSONArray(OPENED_GROUPS);
+ }
+
+ public static JSONArray getOpenedGroups(User user, JSONObject json) {
+ return json.getJSONArray(OPENED_GROUPS);
+ }
+
+
+ /**
+ * Builds the user's group list stored in cache
+ */
+ private static JSONObject buildUserGroupsJson(User user) {
+
+ JSONObject userGroupsJson = JSONFactoryUtil.createJSONObject();
+
+ Organization masterSchool = null;
+ try {
+ masterSchool = OrganizationFinderServiceUtil.getEtabRatachement(user);
+ } catch (Exception e) {
+ logger.error("Error when fetching the master school for user "+user.getFullName(), e);
+ }
+ if (masterSchool != null) {
+ userGroupsJson.put("masterSchool", masterSchool.getOrganizationId());
+ }
+
+ // Classes
+ JSONObject institutionalGroupsAndSchools = fetchUserInstitutionalGroups(user, false);
+ JSONArray institutionalGroups = institutionalGroupsAndSchools.getJSONArray(INSTITUTIONAL_GROUPS);
+ JSONArray enrichedInstitutionalGroups = enrichJsonWithGroupInfos(user.getCompanyId(), institutionalGroups);
+ enrichJsonWithAdminInfo(user, enrichedInstitutionalGroups);
+ userGroupsJson.put(SCHOOLS, institutionalGroupsAndSchools.getJSONArray(SCHOOLS));
+ userGroupsJson.put(INSTITUTIONAL_GROUPS, enrichedInstitutionalGroups);
+
+ // Personal groups
+ JSONArray personalGroups = fetchUserPersonalGroups(user);
+ JSONArray enrichedPersonalGroups = enrichJsonWithGroupInfos(user.getCompanyId(), personalGroups);
+ userGroupsJson.put(PERSONAL_GROUPS, enrichedPersonalGroups);
+
+ // Opened groups
+ JSONArray openedGroups = fetchOpenedGroups();
+ enrichJsonWithGroupInfos(user.getCompanyId(), openedGroups);
+ userGroupsJson.put(OPENED_GROUPS, openedGroups);
+
+ return userGroupsJson;
+ }
+
+
+ /**
+ * Fetches the list of institutional organizations, archived or not
+ */
+ private static JSONObject fetchUserInstitutionalGroups(User user, boolean archive) {
+
+ JSONObject userInstitutionnalGroupsJson = JSONFactoryUtil.createJSONObject();
+
+ JSONArray jsonArray = JSONFactoryUtil.createJSONArray();
+ JSONArray jsonSchoolArray = JSONFactoryUtil.createJSONArray();
+
+ OrganizationFilter.buildSchoolYearRanges();
+
+ List<Organization> userOrgList = new ArrayList<Organization>();
+ try {
+ userOrgList = user.getOrganizations();
+ } catch (Exception e) {
+ logger.error("Error while retrieving user organizations for user "+user.getFullName());
+ }
+
+ boolean hasWholeSchoolVisibility = false;
+
+ try {
+ hasWholeSchoolVisibility = ENTRolesConstants.hasGlobalVisibilityOnGroupClassOnItsSchool(user);
+ } catch (Exception e) {
+ logger.error("Error when determining if user "+user.getFullName()+" has whole visibility on its school", e);
+ }
+
+ if (hasWholeSchoolVisibility) {
+ // Extract schools
+ List<Organization> userSchoolList = OrganizationFilter.filterSchools(userOrgList);
+
+ // For the schools, get all classes
+ for (Organization school : userSchoolList) {
+ List<Organization> schoolClasses = getSchoolClasses(school);
+ userOrgList.addAll(schoolClasses);
+ }
+ }
+
+ // Filter archived organizations or not
+ List<Organization> archivedUserOrgList = new ArrayList<Organization>();
+ for (Organization org : userOrgList) {
+ if (archive == OrganizationFilter.isArchived(org)) {
+ archivedUserOrgList.add(org);
+ }
+ }
+
+ // Remove duplicates and org root
+ List<Organization> uniqueUserOrgList = new ArrayList<Organization>();
+ for (Organization org : archivedUserOrgList) {
+ try {
+ if (org.isRoot() && !ENTRolesConstants.hasVisibilityOnOrgRoot(user)) {
+ continue;
+ }
+ if (!uniqueUserOrgList.contains(org)) {
+ uniqueUserOrgList.add(org);
+ }
+ } catch (Exception e) {
+ logger.error("Error when determining if user "+user.getFullName()+" has visibility on root organization", e);
+ }
+ }
+
+ // Get the associated group of these organizations
+ List<Group> groupList = new ArrayList<Group>();
+ try {
+ groupList = GroupFilter.getGroupsFromOrganizations(uniqueUserOrgList);
+ } catch (Exception e) {
+ logger.error("Error while fetching groups related to user's orgs", e);
+ }
+
+ // Convert organizations to Json object
+ for (Organization org : uniqueUserOrgList) {
+
+ Group orgGroup = null;
+ for (Group group : groupList) {
+ if (group.getClassPK() == org.getOrganizationId()) {
+ orgGroup = group;
+ break;
+ }
+ }
+
+ JSONObject orgJson = convertOrganizationToJson(org, orgGroup, archive);
+ jsonArray.put(orgJson);
+ if (OrganizationFilter.isOrgSchool(org)) {
+ jsonSchoolArray.put(orgJson);
+ }
+ }
+
+ userInstitutionnalGroupsJson.put(SCHOOLS, jsonSchoolArray);
+ userInstitutionnalGroupsJson.put(INSTITUTIONAL_GROUPS, jsonArray);
+
+ return userInstitutionnalGroupsJson;
+ }
+
+
+ private static JSONArray fetchUserPersonalGroups(User user) {
+
+ JSONArray jsonResult = JSONFactoryUtil.createJSONArray();
+
+ LinkedHashMap<String, Object> groupParams = new LinkedHashMap<String, Object>();
+ groupParams.put("usersGroups", new Long(user.getUserId()));
+ groupParams.put("active", Boolean.TRUE);
+ GroupNameComparator gnc = new GroupNameComparator();
+ List<Group> userPersonalGroups = new ArrayList<Group>();
+ try {
+ userPersonalGroups = GroupLocalServiceUtil.search(user.getCompanyId(), null, null, groupParams, QueryUtil.ALL_POS, QueryUtil.ALL_POS, gnc);
+ } catch (Exception e) {
+ logger.error("Error while retrieving the list of personal groups for user "+user.getFullName());
+ }
+
+ // Convert groups to Json
+ for (Group group : userPersonalGroups) {
+
+ if (group.getName().contains("LFR_ORGANIZATION")) {
+ continue;
+ }
+ CommunityInfos communityInfos = null;
+ try {
+ communityInfos = CommunityInfosLocalServiceUtil.getCommunityInfosByGroupId(group.getGroupId());
+ } catch (Exception e) {
+ logger.error("Error when getting community infos associated to group "+group.getName()+" (id "+group.getGroupId()+")");
+ }
+ if (communityInfos != null && communityInfos.getStatus() != 3) {
+
+ boolean isGroupAdministrator = false;
+
+ try {
+ Role administratorRole = RoleLocalServiceUtil.getRole(user.getCompanyId(), RoleConstants.SITE_ADMINISTRATOR);
+ boolean isSiteAdministrator = UserGroupRoleLocalServiceUtil.hasUserGroupRole(user.getUserId(), group.getGroupId(), administratorRole.getRoleId());
+ Role siteOwnerRole = RoleLocalServiceUtil.getRole(user.getCompanyId(), RoleConstants.SITE_OWNER);
+ boolean isSiteOwner = UserGroupRoleLocalServiceUtil.hasUserGroupRole(user.getUserId(), group.getGroupId(), siteOwnerRole.getRoleId());
+ isGroupAdministrator = isSiteAdministrator || isSiteOwner;
+ } catch (Exception e) {
+ logger.error("Error when determinig if user "+user.getUserId()+" is administrator of group "+group.getGroupId(), e);
+ }
+
+ JSONObject groupJson = convertGroupToJson(group, isGroupAdministrator);
+ jsonResult.put(groupJson);
+ }
+ }
+
+ return jsonResult;
+ }
+
+
+ private static JSONArray fetchOpenedGroups() {
+
+ JSONArray jsonResult = JSONFactoryUtil.createJSONArray();
+
+// List<Group> openedGroups = new ArrayList<Group>();
+// try {
+// List<CommunityInfos> openedGroupsInfos = CommunityInfosLocalServiceUtil.getCommunityInfosByStatusPolitic(0, 2);
+// for (CommunityInfos openedGroupInfos: openedGroupsInfos) {
+// Group openedGroup = GroupLocalServiceUtil.getGroup(openedGroupInfos.getGroupId());
+// openedGroups.add(openedGroup);
+// }
+// } catch (Exception e) {
+// logger.error("Error while fetching opened groups", e);
+// }
+//
+// // Convert groups to Json
+// for (Group openedGroup : openedGroups) {
+// JSONObject groupJson = convertGroupToJson(openedGroup);
+// jsonResult.put(groupJson);
+// }
+ return jsonResult;
+ }
+
+
+ private static List<Organization> getSchoolClasses(Organization school) {
+
+ List<Organization> classesList = new ArrayList<Organization>();
+
+ try {
+ classesList = OrganizationLocalServiceUtil.getOrganizations(school.getCompanyId(), school.getOrganizationId());
+ } catch (SystemException e) {
+ logger.info("Error when fetching the list of classes for school "+school.getName());
+ }
+ return classesList;
+ }
+
+
+ private static JSONObject convertOrganizationToJson(Organization org, Group orgGroup, boolean isMigrated) {
+
+ JSONObject orgJson = JSONFactoryUtil.createJSONObject();
+
+ orgJson.put(GROUP_ORG_ID, org.getOrganizationId());
+ orgJson.put(GROUP_ORG_NAME, org.getName());
+ orgJson.put(GROUP_GROUP_ID, orgGroup.getGroupId());
+ orgJson.put(GROUP_GROUP_NAME, orgGroup.getName());
+ orgJson.put(GROUP_IS_MIGRATED, isMigrated);
+
+ return orgJson;
+ }
+
+ private static JSONObject convertGroupToJson(Group group, boolean isAdministrator) {
+
+ JSONObject groupJson = JSONFactoryUtil.createJSONObject();
+
+ groupJson.put(GROUP_GROUP_ID, group.getGroupId());
+ groupJson.put(GROUP_GROUP_NAME, group.getName());
+ groupJson.put(GROUP_IS_ADMINISTRATOR, isAdministrator);
+
+ return groupJson;
+ }
+
+
+ private static void enrichJsonWithAdminInfo(User user, JSONArray jsonArray) {
+
+ try {
+ Role roleAdministrator = RoleLocalServiceUtil.getRole(user.getCompanyId(), RoleConstants.SITE_ADMINISTRATOR);
+ Role roleOwner = RoleLocalServiceUtil.getRole(user.getCompanyId(), RoleConstants.SITE_OWNER);
+ Role adminGrpRole = ENTRoleUtilFactory.getInstance(user.getCompanyId()).getRole(ENTRolesConstants.GROUP_ADMIN);
+ Role teacher = RoleLocalServiceUtil.getRole(user.getCompanyId(), ENTRolesConstants.NATIONAL_3);
+ Role persDirRole = RoleLocalServiceUtil.getRole(user.getCompanyId(), ENTRolesConstants.NATIONAL_4);
+
+ boolean isLocalAdmin = RoleLocalServiceUtil.hasUserRole(user.getUserId(), adminGrpRole.getRoleId());
+ boolean isTeacher = RoleLocalServiceUtil.hasUserRole(user.getUserId(), teacher.getRoleId());
+ boolean isPersDir = RoleLocalServiceUtil.hasUserRole(user.getUserId(), persDirRole.getRoleId());
+
+ for (int i = 0 ; i < jsonArray.length() ; i++) {
+ JSONObject jsonObj = jsonArray.getJSONObject(i);
+ if (isLocalAdmin || isPersDir) {
+ jsonObj.put(GROUP_IS_ADMINISTRATOR, true);
+ continue;
+ }
+ String groupIdStr = jsonObj.getString(GROUP_GROUP_ID);
+ Long groupId = Long.parseLong(groupIdStr);
+ Group orgGroup = GroupLocalServiceUtil.getGroup(groupId);
+
+ boolean isAdministrator = UserGroupRoleLocalServiceUtil.hasUserGroupRole(user.getUserId(), orgGroup.getGroupId(), roleAdministrator.getRoleId());
+ boolean isOwner = UserGroupRoleLocalServiceUtil.hasUserGroupRole(user.getUserId(), orgGroup.getGroupId(), roleOwner.getRoleId());
+ boolean hasAdminRight = isAdministrator || isOwner || isLocalAdmin;
+
+ // Teachers and persdir have admin rights on their institutional groups
+ if (!hasAdminRight && !orgGroup.isRegularSite()) {
+
+ if(isTeacher || isPersDir) {
+ hasAdminRight = true;
+ }
+ }
+
+ }
+ } catch (Exception e) {
+ logger.error("Error while enriching group cache structure with the administrator info", e);
+ }
+ }
+
+
+ private static JSONArray enrichJsonWithGroupInfos(long companyId, JSONArray jsonArray) {
+
+ JSONArray result = JSONFactoryUtil.createJSONArray();
+ String defaultView = ENTMainUtilsLocalServiceUtil.getEntGroupDefaultView(companyId);
+
+ // Build the list of groupIds
+ List<Long> groupIdList = new ArrayList<Long>();
+ for (int i = 0 ; i < jsonArray.length() ; i++) {
+ JSONObject jsonObj = jsonArray.getJSONObject(i);
+ String groupIdStr = jsonObj.getString(GROUP_GROUP_ID);
+ Long groupId = Long.parseLong(groupIdStr);
+ groupIdList.add(groupId);
+ }
+
+ // Return if no group
+ if (groupIdList.size() == 0) {
+ return result;
+ }
+
+ // Fetch community infos and group infos for all these groups
+ Map<Long, CommunityInfos> communityInfosMap = new HashMap<Long, CommunityInfos>();
+ try {
+ communityInfosMap = CommunityInfosLocalServiceUtil.getCommunityForGroups(groupIdList);
+ } catch (Exception e) {
+ logger.error("Error while getting community infos for all user's groups", e);
+ }
+
+ if (communityInfosMap == null || communityInfosMap.size() == 0) {
+ logger.error("Error : community infos map or group infos map is null or empty, no data enrichment performed");
+ return result;
+ }
+
+ Map<Long, GroupInfos> groupInfosMap = new HashMap<Long, GroupInfos>();
+ try {
+ groupInfosMap = CommunityInfosLocalServiceUtil.getGroupInfosForGroups(groupIdList);
+ } catch (Exception e) {
+ logger.error("Error while getting group infos for all user's groups", e);
+ }
+
+ // Enrich the JSON structure
+ for (int i = 0 ; i < jsonArray.length() ; i++) {
+ JSONObject jsonObj = jsonArray.getJSONObject(i);
+ String groupIdStr = jsonObj.getString("groupId");
+ Long groupId = Long.parseLong(groupIdStr);
+
+ if (groupInfosMap != null && groupInfosMap.containsKey(groupId)) {
+ jsonObj.put(GROUP_DEFAULT_VIEW, groupInfosMap.get(groupId).getDefaultGroupView());
+ } else {
+ jsonObj.put(GROUP_DEFAULT_VIEW, defaultView);
+ }
+
+ //System.out.println("enrichJsonWithGroupInfos for groupId "+groupId);
+ CommunityInfos ci = communityInfosMap.get(groupId);
+ if (ci != null) {
+ if (ci.getStatus() != 0) {
+ continue;
+ }
+ jsonObj.put(GROUP_IS_NEWS, ci.getIsNewsActive());
+ jsonObj.put(GROUP_IS_DOCUMENTS, ci.getIsDocumentsActive());
+ jsonObj.put(GROUP_IS_FORUM, ci.getIsForumActive());
+ jsonObj.put(GROUP_IS_CDT, ci.getViewInCDT());
+ }
+ result.put(jsonObj);
+ }
+ return result;
+ }
+
+ /**
+ * Add migrated organization to cache object if not already done
+ */
+ public static void addMigratedOrgs(User user) {
+
+ String cacheKey="userGroups_"+user.getUserId();
+
+ JSONObject userGroupsJson = getUserGroups(user);
+
+ // Fetch archived orgs if not already done
+ if (!userGroupsJson.getBoolean("hasArchivedOrgs")) {
+ JSONArray archivedOrgs = fetchUserInstitutionalGroups(user, true).getJSONArray(INSTITUTIONAL_GROUPS);
+ JSONArray enrichedArchivedOrgs = enrichJsonWithGroupInfos(user.getCompanyId(), archivedOrgs);
+
+ for (int i = 0 ; i < enrichedArchivedOrgs.length() ; i++) {
+ JSONObject archivedOrg = enrichedArchivedOrgs.getJSONObject(i);
+ userGroupsJson.getJSONArray(INSTITUTIONAL_GROUPS).put(archivedOrg);
+ }
+ userGroupsJson.put("hasArchivedOrgs", true);
+
+ // Expiration date in milliseconds
+ ENTCacheUtils.removeObjectFromCache(cacheKey);
+ ENTCacheUtils.storeObjectIntoCache(cacheKey, userGroupsJson, EXPIRATION_TIME_MILLIS);
+ }
+ }
+
+
+ public static void updateDefaultView (User user, long groupId, String defaultView) {
+
+ boolean found = false;
+ JSONObject userGroups = getUserGroups(user);
+ JSONArray institutionnalGroups = getInstitutionalGroups(user);
+ for (int i = 0 ; i < institutionnalGroups.length() ; i++) {
+ JSONObject institutionnalGroup = institutionnalGroups.getJSONObject(i);
+ String groupIdStr = institutionnalGroup.getString(GROUP_GROUP_ID);
+ Long jsonGroupId = Long.parseLong(groupIdStr);
+
+ if (jsonGroupId == groupId) {
+ institutionnalGroup.put(GROUP_DEFAULT_VIEW, defaultView);
+ found = true;
+ }
+ }
+ if (!found) {
+ JSONArray personalGroups = getPersonalGroups(user);
+ for (int i = 0 ; i < personalGroups.length() ; i++) {
+ JSONObject personalGroup = personalGroups.getJSONObject(i);
+ String groupIdStr = personalGroup.getString(GROUP_GROUP_ID);
+ Long jsonGroupId = Long.parseLong(groupIdStr);
+
+ if (jsonGroupId == groupId) {
+ personalGroup.put(GROUP_DEFAULT_VIEW, defaultView);
+ found = true;
+ }
+ }
+ }
+ if (!found) {
+ JSONArray openedGroups = getOpenedGroups(user);
+ for (int i = 0 ; i < openedGroups.length() ; i++) {
+ JSONObject openedGroup = openedGroups.getJSONObject(i);
+ String groupIdStr = openedGroup.getString(GROUP_GROUP_ID);
+ Long jsonGroupId = Long.parseLong(groupIdStr);
+
+ if (jsonGroupId == groupId) {
+ openedGroup.put(GROUP_DEFAULT_VIEW, defaultView);
+ found = true;
+ }
+ }
+ }
+
+ // Store updated json into cache
+ String cacheKey="userGroups_"+user.getUserId();
+ ENTCacheUtils.storeObjectIntoCache(cacheKey, userGroups, EXPIRATION_TIME_MILLIS);
+ }
+
+ /**
+ * Returns true if the given user is administrator of the personal group given
+ * @param user
+ * @param groupId
+ * @return
+ */
+ public static boolean isUserGroupAdmin(User user, long groupId) {
+
+ // Look into personal groups
+ JSONArray personalGroups = getPersonalGroups(user);
+ for (int i = 0 ; i < personalGroups.length() ; i++) {
+ JSONObject personalGroup = personalGroups.getJSONObject(i);
+ String groupIdStr = personalGroup.getString(GROUP_GROUP_ID);
+ Long jsonGroupId = Long.parseLong(groupIdStr);
+
+ if (jsonGroupId == groupId) {
+ return personalGroup.getBoolean(GROUP_IS_ADMINISTRATOR);
+ }
+ }
+
+ // Search into institutional groups
+ JSONArray institutionalGroups = getInstitutionalGroups(user);
+ for (int i = 0 ; i < institutionalGroups.length() ; i++) {
+ JSONObject institutionalGroup = institutionalGroups.getJSONObject(i);
+ String groupIdStr = institutionalGroup.getString(GROUP_GROUP_ID);
+ Long jsonGroupId = Long.parseLong(groupIdStr);
+
+ if (jsonGroupId == groupId) {
+ return institutionalGroup.getBoolean(GROUP_IS_ADMINISTRATOR);
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Returns true if the given user is administrator of the personal group given
+ * @param user
+ * @param groupId
+ * @return
+ */
+ public static void setAdmin(long userId, long groupId, boolean isAdmin) {
+
+ User user = null;
+ try {
+ user = UserLocalServiceUtil.getUser(userId);
+ } catch (Exception e) {
+ logger.error("Error when fetching user with id "+userId);
+ return;
+ }
+
+ // Look into personal groups
+ JSONObject userGroups = getUserGroups(user);
+ JSONArray personalGroups = getPersonalGroups(user, userGroups);
+ for (int i = 0 ; i < personalGroups.length() ; i++) {
+ JSONObject personalGroup = personalGroups.getJSONObject(i);
+ String groupIdStr = personalGroup.getString(GROUP_GROUP_ID);
+ Long jsonGroupId = Long.parseLong(groupIdStr);
+
+ if (jsonGroupId == groupId) {
+ personalGroup.put(GROUP_IS_ADMINISTRATOR, isAdmin);
+ }
+ }
+
+ // Search into institutional groups
+ JSONArray institutionalGroups = getInstitutionalGroups(user, userGroups);
+ for (int i = 0 ; i < institutionalGroups.length() ; i++) {
+ JSONObject institutionalGroup = institutionalGroups.getJSONObject(i);
+ String groupIdStr = institutionalGroup.getString(GROUP_GROUP_ID);
+ Long jsonGroupId = Long.parseLong(groupIdStr);
+
+ if (jsonGroupId == groupId) {
+ institutionalGroup.put(GROUP_IS_ADMINISTRATOR, isAdmin);
+ }
+ }
+
+ // Store updated json into cache
+ String cacheKey="userGroups_"+user.getUserId();
+ ENTCacheUtils.storeObjectIntoCache(cacheKey, userGroups, EXPIRATION_TIME_MILLIS);
+ }
+
+
+}