--- /dev/null
+package com.pentila.entSavoie.utils;
+
+import java.text.Normalizer;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.portlet.PortletPreferences;
+
+import com.liferay.contacts.util.InstitutionalListsFactory;
+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.language.LanguageUtil;
+import com.liferay.portal.kernel.log.Log;
+import com.liferay.portal.kernel.log.LogFactoryUtil;
+import com.liferay.portal.kernel.util.OrderByComparator;
+import com.liferay.portal.model.Group;
+import com.liferay.portal.model.Organization;
+import com.liferay.portal.model.Role;
+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.UserLocalServiceUtil;
+import com.liferay.portal.util.comparator.GroupNameComparator;
+import com.pentila.entSavoie.ENTDisplayUtil;
+import com.pentila.entSavoie.ENTRolesConstants;
+import com.pentila.entSavoie.administrationTools.model.CommunicationPrefs;
+import com.pentila.entSavoie.administrationTools.service.CommunicationPrefsLocalServiceUtil;
+import com.pentila.entSavoie.amis.model.FriendFolder;
+import com.pentila.entSavoie.amis.service.FriendFolderLocalServiceUtil;
+import com.pentila.entSavoie.carnetDAdresses.model.ListProperty;
+import com.pentila.entSavoie.carnetDAdresses.model.Liste;
+import com.pentila.entSavoie.carnetDAdresses.service.ListeLocalServiceUtil;
+import com.pentila.entSavoie.communityInfos.model.CommunityInfos;
+import com.pentila.entSavoie.communityInfos.service.CommunityInfosLocalServiceUtil;
+import com.pentila.entSavoie.directory.OrganizationFinderServiceUtil;
+import com.pentila.entSavoie.institutionalList.model.ListeInstDetails;
+import com.pentila.entSavoie.userProperties.model.UserRelationship;
+import com.pentila.entSavoie.userProperties.service.UserPropertiesLocalServiceUtil;
+import com.pentila.entSavoie.userProperties.service.UserRelationshipLocalServiceUtil;
+import com.pentila.entSavoie.userRelationship.UserRelationshipConstants;
+
+import edu.emory.mathcs.backport.java.util.Collections;
+
+public class ENTAddressBookListsManager {
+
+ public static final String USER_MIGRATE_LISTS = "migrate";
+ public static final String USER_CURRENT_LISTS = "current";
+
+ private static Log logger = LogFactoryUtil.getLog(ENTAddressBookListsManager.class);
+
+
+
+ public static JSONArray getUserAdressBookLists(User user) {
+
+ JSONArray userLists = JSONFactoryUtil.createJSONArray();
+
+ // Get user's roleType
+ int roleType = getUsersRoleType(user);
+
+ boolean isAdmin = false;
+ Organization rattachSchool = null;
+ try {
+ isAdmin = RoleLocalServiceUtil.hasUserRole(user.getUserId(), user.getCompanyId(), ENTRolesConstants.GROUP_ADMIN, false);
+ rattachSchool = OrganizationFinderServiceUtil.getEtabRatachement(user);
+ } catch (Exception e) {}
+
+ // Loop over user's schools
+ List<Organization> userSchools = OrganizationFilter.getUserSchools(user);
+ for (Organization school : userSchools) {
+
+ JSONObject orgJson = JSONFactoryUtil.createJSONObject();
+ orgJson.put("categoryName", ENTDisplayUtil.formatSCONETName(school.getName(), true));
+ orgJson.put("schoolId", school.getOrganizationId());
+ orgJson.put("isInstitutionalCategory", true);
+
+ JSONArray orgListsJson = getSchoolListsForRoleType(user, school, roleType, isAdmin);
+
+ orgJson.put("categoryList", orgListsJson);
+ if (rattachSchool != null && rattachSchool.getOrganizationId() == school.getOrganizationId()) {
+ orgJson.put("isSelected", true);
+ } else {
+ orgJson.put("isSelected", false);
+ }
+ userLists.put(orgJson);
+
+ }
+ return userLists;
+ }
+
+ public static JSONObject getSchoolContactsForRoleType(String search, User user, Organization school, int roleType, int start, int limit, OrderByComparator comparator) {
+
+ JSONObject result = JSONFactoryUtil.createJSONObject();
+ JSONArray schoolContacts = JSONFactoryUtil.createJSONArray();
+ logger.info("Searching contacts in school "+school.getName()+" for user "+user.getFullName()+" with search '"+search+"' and limited between "+start+" and "+limit);
+
+ long _start = System.currentTimeMillis();
+ CommunicationPrefs communicationPrefs = CommunicationPrefsLocalServiceUtil.getCommunicationPrefs(school.getOrganizationId(), roleType);
+ try {
+ Role studentRole = RoleLocalServiceUtil.getRole(school.getCompanyId(), ENTRolesConstants.NATIONAL_1);
+ Role parentRole = RoleLocalServiceUtil.getRole(school.getCompanyId(), ENTRolesConstants.NATIONAL_2);
+ Role teacherRole = RoleLocalServiceUtil.getRole(school.getCompanyId(), ENTRolesConstants.NATIONAL_3);
+ Role otherRole = RoleLocalServiceUtil.getRole(school.getCompanyId(), ENTRolesConstants.NATIONAL_7);
+ Role adminRole = RoleLocalServiceUtil.getRole(school.getCompanyId(), ENTRolesConstants.GROUP_ADMIN);
+ boolean isAdmin = RoleLocalServiceUtil.hasUserRole(user.getUserId(), adminRole.getRoleId());
+ long nbResults = 0;
+ List<User> resultUsers = new ArrayList<User>();
+
+ // 1. Fetch users at school-level if needed, from start to limit, ordered by given comparator, with given search keyword
+ // 2. Fetch users at class-level if needed, from start to limit, ordered by given comparator, with given search keyword
+ // 3. Fetch myChildren or myParents if needed
+ // 4. Aggregate, sort and limit from start to limit
+ // 5. Convert to JSON
+
+ List<Organization> userClasses = new ArrayList<Organization>();
+ if (isAdmin || communicationPrefs.getAllStudents() || communicationPrefs.getAllParents() || communicationPrefs.getAllTeachers() || communicationPrefs.getAllPersonals() || communicationPrefs.getAllOthers()) {
+
+ logger.info("Searching at school-level scope");
+ // Scope is the whole school
+ List<Long> orgIds = new ArrayList<Long>();
+ orgIds.add(school.getOrganizationId());
+
+ long time0 = System.currentTimeMillis();
+ List<Long> roleIds = new ArrayList<Long>();
+ if (!isAdmin && communicationPrefs.getAllStudents()) {
+ roleIds.add(studentRole.getRoleId());
+ }
+ if (!isAdmin && communicationPrefs.getAllParents()) {
+ roleIds.add(parentRole.getRoleId());
+ }
+ if (!isAdmin && communicationPrefs.getAllTeachers()) {
+ roleIds.add(teacherRole.getRoleId());
+ }
+ if (!isAdmin && communicationPrefs.getAllPersonals()) {
+ for (String personalRoleNat : CommunicationPrefsConstants.PERSONAL_ROLES.keySet()) {
+ try {
+ Role role = RoleLocalServiceUtil.getRole(school.getCompanyId(), personalRoleNat);
+ roleIds.add(role.getRoleId());
+ } catch (Exception e) {
+ }
+ }
+ }
+ if (!isAdmin && communicationPrefs.getAllOthers()) {
+ roleIds.add(otherRole.getRoleId());
+ }
+ List<User> schoolUsers = UserPropertiesLocalServiceUtil.getUserFromContactSearch(search, orgIds, roleIds, new ArrayList<String>(), -1, -1, start, limit, comparator);
+
+ if (start == 0) {
+ nbResults += UserPropertiesLocalServiceUtil.getUserCountFromContactSearch(search, orgIds, roleIds, new ArrayList<String>(), -1, -1);
+ logger.info("First call : got a total of "+nbResults+" users");
+ }
+
+ long time1 = System.currentTimeMillis();
+ logger.info(" >> School-level search on "+roleIds.size()+" roles fetched "+schoolUsers.size()+" results in "+(time1 - time0)+" ms");
+ resultUsers.addAll(schoolUsers);
+ }
+
+ if (communicationPrefs.getClassStudents() || communicationPrefs.getClassParents() || communicationPrefs.getClassTeachers()) {
+ long time0 = System.currentTimeMillis();
+ // Scope is the user's classes only
+ userClasses = OrganizationFilter.getUserClassesAndGroups(user);
+ logger.info("Fetched "+userClasses.size()+" classes for standard user and school "+school.getName());
+
+ List<Long> roleIds = new ArrayList<Long>();
+ if (communicationPrefs.getClassStudents() && !communicationPrefs.getAllStudents()) {
+ roleIds.add(studentRole.getRoleId());
+ }
+ if (communicationPrefs.getClassParents() && !communicationPrefs.getAllParents()) {
+ roleIds.add(parentRole.getRoleId());
+ }
+ if (communicationPrefs.getClassTeachers() && !communicationPrefs.getAllTeachers()) {
+ roleIds.add(teacherRole.getRoleId());
+ }
+ List<Long> orgIds = new ArrayList<Long>();
+ for (Organization userClass : userClasses) {
+ orgIds.add(userClass.getOrganizationId());
+ }
+ List<User> classUsers = UserPropertiesLocalServiceUtil.getUserFromContactSearch(search, orgIds, roleIds, new ArrayList<String>(), -1, -1, start, limit, comparator);
+ long time1 = System.currentTimeMillis();
+ if (start == 0) {
+ nbResults += UserPropertiesLocalServiceUtil.getUserCountFromContactSearch(search, orgIds, roleIds, new ArrayList<String>(), -1, -1);
+ logger.info("First call : got a total of "+nbResults+" users");
+ }
+ logger.info(" >> Class-level search on "+roleIds.size()+" roles and "+orgIds.size()+" classes fetched "+classUsers.size()+" results in "+(time1 - time0)+" ms");
+ resultUsers.addAll(classUsers);
+
+ }
+
+ // Add myChildren if needed
+ if (communicationPrefs.getMyChildren()) {
+ List<UserRelationship> parentRelationships = UserRelationshipLocalServiceUtil.getUserRelationshipByToUserIdRelationType(user.getUserId(), UserRelationshipConstants.PARENT_RELATION);
+ for (UserRelationship parentRelationship : parentRelationships) {
+ resultUsers.add(UserLocalServiceUtil.getUser(parentRelationship.getFromUserId()));
+ nbResults++;
+ }
+ }
+
+ // Add myParents if needed
+ if (communicationPrefs.getMyParents()) {
+ List<UserRelationship> parentRelationships = UserRelationshipLocalServiceUtil.getUserRelationshipByFromUserIdRelationType(user.getUserId(), UserRelationshipConstants.PARENT_RELATION);
+ for (UserRelationship parentRelationship : parentRelationships) {
+ resultUsers.add(UserLocalServiceUtil.getUser(parentRelationship.getToUserId()));
+ nbResults++;
+ }
+ }
+
+ logger.info("Found a total of "+resultUsers.size()+" users");
+ result.put("nbResults", nbResults);
+
+ // Unify the list
+ List<User> uniqueList = new ArrayList<User>();
+ List<Long> uniqueIdsList = new ArrayList<Long>();
+ for (User _user : resultUsers) {
+ if (!uniqueIdsList.contains(_user.getUserId())) {
+ uniqueList.add(_user);
+ uniqueIdsList.add(_user.getUserId());
+ }
+ }
+ logger.info("After unification: "+uniqueList.size()+" users");
+
+
+ // Now loop over aggregated list resultUsers and sort it with given comparator
+ Collections.sort(uniqueList, comparator);
+
+ // TODO : better manage start and limit
+ List<User> sortedUserList = uniqueList.subList(start, ((uniqueList.size() < limit) ? uniqueList.size() : limit));
+
+ // Convert to JSON
+ for (User sortedUser : sortedUserList) {
+ JSONObject jsonUser = JsonUserFactory.convertUserToJson(sortedUser);
+ schoolContacts.put(jsonUser);
+ }
+
+ } catch (Exception e) {
+ logger.error("Error when fetching all school's classes for "+school.getName(), e);
+ }
+
+ long end = System.currentTimeMillis();
+ logger.info("Full getSchool contacts for user "+user.getFullName()+" and school "+school.getName()+" took "+(end - _start)+" ms");
+ result.put("contacts", schoolContacts);
+ return result;
+ }
+
+
+ private static JSONArray getSchoolListsForRoleType(User user, Organization school, int roleType, boolean isAdmin) {
+
+ JSONArray orgLists = JSONFactoryUtil.createJSONArray();
+
+ long start = System.currentTimeMillis();
+ CommunicationPrefs communicationPrefs = CommunicationPrefsLocalServiceUtil.getCommunicationPrefs(school.getOrganizationId(), roleType);
+ try {
+
+ // The list of all school classes and groups
+ List<Organization> userClasses = new ArrayList<Organization>();
+ if (isAdmin) {
+ userClasses = OrganizationFilter.filterNotArchivedOrganizations(OrganizationFilter.filterNotSuffixedOrganizations(OrganizationLocalServiceUtil.getOrganizations(school.getCompanyId(), school.getOrganizationId())));
+ logger.info("Fetched "+userClasses.size()+" classes for admin user and school "+school.getName());
+ } else {
+ userClasses = OrganizationFilter.getUserClassesAndGroups(user);
+ logger.info("Fetched "+userClasses.size()+" classes for standard user and school "+school.getName());
+ }
+
+ Role studentRole = RoleLocalServiceUtil.getRole(school.getCompanyId(), ENTRolesConstants.NATIONAL_1);
+ Role parentRole = RoleLocalServiceUtil.getRole(school.getCompanyId(), ENTRolesConstants.NATIONAL_2);
+ Role teacherRole = RoleLocalServiceUtil.getRole(school.getCompanyId(), ENTRolesConstants.NATIONAL_3);
+ Role otherRole = RoleLocalServiceUtil.getRole(school.getCompanyId(), ENTRolesConstants.NATIONAL_7);
+
+ if (communicationPrefs.getAllStudents()) {
+ JSONObject classJson = buildJson("Eleves de l'etablissement", studentRole.getRoleId(), 0, school.getOrganizationId(), false, false);
+ orgLists.put(classJson);
+ }
+
+ if (communicationPrefs.getClassStudents()) {
+ for (Organization userClass : userClasses) {
+ JSONObject classJson = buildJson("Eleves de "+ ENTDisplayUtil.formatSCONETName(userClass.getName(), false), studentRole.getRoleId(), userClass.getOrganizationId(), school.getOrganizationId(), false, false);
+ orgLists.put(classJson);
+ }
+ }
+
+ if (communicationPrefs.getAllParents()) {
+ JSONObject classJson = buildJson("Parents de l'etablissement", parentRole.getRoleId(), 0, school.getOrganizationId(), false, false);
+ orgLists.put(classJson);
+ }
+
+ if (communicationPrefs.getClassParents()) {
+ for (Organization userClass : userClasses) {
+ JSONObject classJson = buildJson("Parents de "+ ENTDisplayUtil.formatSCONETName(userClass.getName(), false), parentRole.getRoleId(), userClass.getOrganizationId(), school.getOrganizationId(), false, false);
+ orgLists.put(classJson);
+ }
+ }
+
+ if (communicationPrefs.getAllTeachers()) {
+ JSONObject classJson = buildJson("Enseignants de l'etablissement", teacherRole.getRoleId(), 0, school.getOrganizationId(), false, false);
+ orgLists.put(classJson);
+ }
+
+ if (communicationPrefs.getClassTeachers()) {
+ for (Organization userClass : userClasses) {
+ JSONObject classJson = buildJson("Enseignants de "+ ENTDisplayUtil.formatSCONETName(userClass.getName(), false), teacherRole.getRoleId(), userClass.getOrganizationId(), school.getOrganizationId(), false, false);
+ orgLists.put(classJson);
+ }
+ }
+
+ if (communicationPrefs.getAllPersonals()) {
+ // Build over all roles included in 'Personal'
+ for (String personalRoleNat : CommunicationPrefsConstants.PERSONAL_ROLES.keySet()) {
+ try {
+ Role role = RoleLocalServiceUtil.getRole(school.getCompanyId(), personalRoleNat);
+ JSONObject classJson = buildJson(CommunicationPrefsConstants.PERSONAL_ROLES.get(personalRoleNat), role.getRoleId(), 0, school.getOrganizationId(), false, false);
+ orgLists.put(classJson);
+ } catch (Exception e) {
+ }
+ }
+ }
+
+ if (communicationPrefs.getAllOthers()) {
+ JSONObject classJson = buildJson("Personnels de la collectivité", otherRole.getRoleId(), 0, school.getOrganizationId(), false, false);
+ orgLists.put(classJson);
+ }
+
+ if (communicationPrefs.getMyChildren()) {
+ JSONObject classJson = buildJson("Mes enfants", studentRole.getRoleId(), 0, school.getOrganizationId(), true, false);
+ orgLists.put(classJson);
+ }
+
+ if (communicationPrefs.getMyParents()) {
+ JSONObject classJson = buildJson("Mes parents", parentRole.getRoleId(), 0, school.getOrganizationId(), false, true);
+ orgLists.put(classJson);
+ }
+
+ } catch (Exception e) {
+ logger.error("Error when fetching all school's classes for "+school.getName(), e);
+ }
+
+ long end = System.currentTimeMillis();
+ logger.info("Full getSchoolList for user "+user.getFullName()+" and school "+school.getName()+" took "+(end - start)+" ms");
+ return orgLists;
+ }
+
+
+ private static JSONObject buildJson(String name, long roleId, long organizationId, long schoolId, boolean myChildren, boolean myParents) {
+
+ JSONObject classJson = JSONFactoryUtil.createJSONObject();
+ classJson.put("listName", name);
+ classJson.put("roleId", roleId);
+ classJson.put("orgId", organizationId);
+ classJson.put("schoolId", schoolId);
+ classJson.put("myChildren", myChildren);
+ classJson.put("myParents", myParents);
+ classJson.put("isDisplayed", true);
+ return classJson;
+ }
+
+
+ public static int getUsersRoleType(User user) {
+ int roleType = 0;
+ try {
+ if (ENTRolesConstants.isStudent(user)) {
+ roleType = 1;
+ } else if (ENTRolesConstants.isParent(user)) {
+ roleType = 2;
+ } else if (ENTRolesConstants.isTeacher(user)) {
+ roleType = 3;
+ } else if (ENTRolesConstants.isPersonal(user)) {
+ roleType = 4;
+ } else {
+ roleType = 5;
+ }
+ } catch (Exception e) {
+ logger.error("Error when determinig user's roleType for "+user.getFullName(), e);
+ }
+ return roleType;
+ }
+
+
+
+
+ /**
+ * Get the menu list name for institutional lists (usually the school name)
+ * @param user The user currently getting his lists
+ * @param lid The list we want the menu for
+ * @return the menu name for the list received
+ */
+ public static String getListMenuName(User user, ListeInstDetails lid) {
+ String listMenuName = "";
+
+ try {
+ Organization org = OrganizationLocalServiceUtil.getOrganization(lid.getOrgId());
+ listMenuName = org.getName();
+ } catch (Exception e) {
+ logger.error(e);
+ }
+
+ // If no grouping name is found use the default one
+ if(listMenuName.equals("")){
+ listMenuName = LanguageUtil.get(user.getLocale(), "institutionnelles");
+ }
+
+ return listMenuName;
+ }
+
+ /**
+ * NB: The archives are not displayed for the moment
+ * Get the user's institutional lists (Current lists and archives)
+ * @param user The user currently getting his institutional list
+ * @param search The searching term to match
+ * @return a HashMap which link a string with a ListInstDetails List. These lists contains the user's institutional lists to display.
+ */
+ public static HashMap<String, List<ListeInstDetails> > getUserInstitutionalLists(User user, String search) {
+ HashMap<String, List<ListeInstDetails> > userInstitutionalLists = new HashMap<String, List<ListeInstDetails>>();
+ List<ListeInstDetails> userCurrentInstistutionalLists = new ArrayList<ListeInstDetails>();
+ List<ListeInstDetails> userArchiveLists = new ArrayList<ListeInstDetails>();
+
+ InstitutionalListsFactory ilf = new InstitutionalListsFactory(user);
+ List<ListeInstDetails> lids = new ArrayList<ListeInstDetails>();
+ try {
+ lids = ilf.getInstitutionnalLists();
+ } catch (Exception e) {
+ logger.error(e);
+ }
+
+ String searchQuery = getStringReadyForSearch(search);
+ //We cut the list in two : archives and actual lists
+ for (ListeInstDetails lid : lids) {
+
+ //Apply search filter and check if search matches
+ String listName = getStringReadyForSearch(lid.getListeInstDetailsName());
+ boolean isPositiveToSearch = (listName.length() >= searchQuery.length() && listName.contains(searchQuery));
+
+ if (search.equals("") || isPositiveToSearch) {
+ try{
+ long subOrgId = Long.valueOf(lid.getSubOrgId());
+ Organization org = OrganizationLocalServiceUtil.getOrganization(subOrgId);
+ // Get preferences to recognize migrate organization. We do not display them anymore so just continue when finding one
+ PortletPreferences prefs = org.getPreferences();
+
+ if (prefs.getValue("migrate", "none").equals("done")) {
+ //userArchiveLists.add(lid);
+ continue;
+ }
+ else {
+ String instGroupName = lid.getListeInstDetailsName().trim();
+
+ String suffixToRemove = " - Parents";
+ if(instGroupName.endsWith(suffixToRemove)){
+ continue;
+ //instGroupName = instGroupName.substring(0 , (instGroupName.length()-suffixToRemove.length()));
+ }
+
+ userCurrentInstistutionalLists.add(lid);
+ }
+ } catch (Exception e) {
+ logger.error(e);
+ }
+ }
+ }
+
+ userInstitutionalLists.put(USER_CURRENT_LISTS, userCurrentInstistutionalLists);
+ userInstitutionalLists.put(USER_MIGRATE_LISTS, userArchiveLists);
+
+ return userInstitutionalLists;
+ }
+
+ /**
+ * Get the user's personal lists (The ones he has created)
+ * @param group The group of the user current
+ * @param search The searching term to match
+ * @return a Liste List which contains the user's personal lists
+ */
+ public static List<Liste> getUserPersonalLists(Group group, String search) {
+ List<Liste> listPersoResult = new ArrayList<Liste>();
+
+ //Get all users personnal list
+ try {
+ List<Liste> lesListes = ListeLocalServiceUtil.findByGroupId(group.getGroupId());
+
+ String searchQuery = getStringReadyForSearch(search);
+
+ for (Liste list : lesListes) {
+ String listName = "";
+ Map<String, List<ListProperty>> propsMap = ListeLocalServiceUtil.getPropertiesMap(list.getListeId());
+ if (propsMap.containsKey("name") && !propsMap.get("name").isEmpty()){
+ listName = propsMap.get("name").get(0).getValue_();
+ }
+
+ if (!listName.contains("LFR_ORGANIZATION"))
+ {
+ //Apply search filter
+ listName = getStringReadyForSearch(listName);
+ boolean isPositiveToSearch = (listName.length() >= searchQuery.length() && listName.contains(searchQuery));
+
+ if (search.equals("") || isPositiveToSearch) {
+ listPersoResult.add(list);
+ }
+ }
+ }
+ } catch (SystemException e) {
+ logger.error(e);
+ }
+
+ return listPersoResult;
+ }
+
+ /**
+ * Get the user's friends lists
+ * @param user The user currently getting his friends list
+ * @param search The searching term to match
+ * @return a FriendFolder List which contains the user's friends lists
+ */
+ public static List<FriendFolder> getUserFriendsLists(User user, String search) {
+ List<FriendFolder> listAmisResult = new ArrayList<FriendFolder>();
+ List<FriendFolder> listesAmis;
+
+ try {
+ listesAmis = FriendFolderLocalServiceUtil.getFriendFolderByUserIDParentFolderId(user.getUserId(), 0);
+
+ String searchQuery = getStringReadyForSearch(search);
+
+ for (FriendFolder ff : listesAmis) {
+ //Apply search filter
+ String friendsListNameNormalized = getStringReadyForSearch(ff.getName());
+ boolean isPositiveToSearch = (friendsListNameNormalized.length() >= searchQuery.length() && friendsListNameNormalized.contains(searchQuery));
+
+ if (search.equals("") || isPositiveToSearch) {
+ listAmisResult.add(ff);
+ }
+ }
+ } catch (SystemException e) {
+ logger.error(e);
+ }
+
+ return listAmisResult;
+ }
+
+ /**
+ * Get the user's groups lists (without institutional ones)
+ * @param user The user currently getting his groups list
+ * @param search The searching term to match
+ * @return a Group List which contains the user's groups
+ */
+ public static List<Group> getUserGroupsLists(User user, String search) {
+ List<Group> groupListResult = new ArrayList<Group>();
+
+ LinkedHashMap<String, Object> groupParams = new LinkedHashMap<String, Object>();
+ groupParams.put("usersGroups", new Long(user.getUserId()));
+ groupParams.put("active", Boolean.TRUE);
+ GroupNameComparator gnc = new GroupNameComparator();
+
+ try {
+ List<Group> userAllGroups = GroupLocalServiceUtil.search(user.getCompanyId(), null, null, groupParams, QueryUtil.ALL_POS, QueryUtil.ALL_POS, gnc);
+
+ String searchQuery = getStringReadyForSearch(search);
+
+ for (Group group: userAllGroups) {
+ if (group.getName().contains("LFR_ORGANIZATION")) {
+ continue;
+ }
+
+ //Apply search filter
+ String groupNameNormalized = getStringReadyForSearch(group.getName());
+ boolean isPositiveToSearch = (groupNameNormalized.length() >= searchQuery.length() && groupNameNormalized.contains(searchQuery));
+
+ if (search.equals("") || isPositiveToSearch) {
+ CommunityInfos ci = CommunityInfosLocalServiceUtil.getCommunityInfosByGroupId(group.getGroupId());
+ if (ci.getStatus() == 0 && ci.isGroupContactList()) {
+ groupListResult.add(group);
+ }
+ }
+ }
+ } catch (Exception e) {
+ logger.error(e);
+ }
+
+ return groupListResult;
+ }
+
+ /**
+ * Lower and normalize a search term (the goal is to ignore case and accented characters)
+ * @param term A word to translate into normalized form
+ * @return the term ready for search
+ */
+ private static String getStringReadyForSearch(String term) {
+ term = term.toLowerCase();
+ term = Normalizer.normalize(term, Normalizer.Form.NFD);
+ term = term.replaceAll("[^\\p{ASCII}]","");
+
+ return term;
+ }
+}