--- /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
+ *
+ * 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.directory.impl;
+
+import javax.naming.Binding;
+import javax.naming.NamingEnumeration;
+import javax.naming.directory.Attributes;
+import javax.naming.directory.SearchControls;
+import javax.naming.directory.SearchResult;
+
+import com.liferay.portal.kernel.exception.PortalException;
+import com.liferay.portal.kernel.exception.SystemException;
+import com.liferay.portal.kernel.log.Log;
+import com.liferay.portal.kernel.log.LogFactoryUtil;
+import com.liferay.portal.kernel.util.PrefsPropsUtil;
+import com.liferay.portal.kernel.util.PropsKeys;
+import com.liferay.portal.kernel.util.StringPool;
+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.security.ldap.PortalLDAPUtil;
+import com.liferay.portal.service.OrganizationLocalServiceUtil;
+import com.liferay.portal.service.RoleLocalServiceUtil;
+import com.pentila.entSavoie.ENTRoleUtilFactory;
+import com.pentila.entSavoie.ENTRolesConstants;
+import com.pentila.entSavoie.directory.OrganizationFinderService;
+import com.pentila.entSavoie.userProperties.model.UserProperties;
+import com.pentila.entSavoie.userProperties.service.UserPropertiesLocalServiceUtil;
+import com.pentila.entSavoie.utils.ENTCacheUtils;
+import com.pentila.entSavoie.utils.ENTMainUtilsLocalServiceUtil;
+import com.pentila.entSavoie.utils.ENTOrganizationsUtil;
+
+
+/**
+ * Class used to fetch organizations
+ * @author Cedric Lecarpentier
+ */
+public class OrganizationFinderServiceImpl implements OrganizationFinderService{
+
+ /**
+ * Returns true if the user is a student or a parent
+ * @param user
+ * @return
+ */
+ public boolean hasRestriction(User user) throws PortalException, SystemException {
+ boolean restriction = false;
+
+ for (Role r : ENTRoleUtilFactory.getInstance(user.getCompanyId()).getENTRoles(user)) {
+ if (r.getName().equals(ENTRolesConstants.NATIONAL_1)
+ || r.getName().equals(ENTRolesConstants.NATIONAL_2) ) {
+ restriction = true;
+ }
+ }
+ // Except administrators
+ if (RoleLocalServiceUtil.hasUserRole(user.getUserId(), user.getCompanyId(), RoleConstants.ADMINISTRATOR, false)) {
+ restriction = false;
+ }
+ return restriction;
+ }
+
+
+ /**
+ * Returns the user's rattach school
+ */
+ public Organization getEtabRatachement(User user) {
+
+ String cacheKey = "etabRatachementCache_" + user.getUserId();
+
+ // Get Organization from cache instance
+ Organization cacheOrg = (Organization) ENTCacheUtils.getObjectFromCache(cacheKey);
+ if(cacheOrg == null){
+ // if misscache, process
+ try {
+ cacheOrg = fetchRattachSchool(user);
+ } catch (Exception e) {
+ _log.error("Error when processing rattach school for user "+user.getFullName(), e);
+ }
+ ENTCacheUtils.storeObjectIntoCache(cacheKey,cacheOrg,-1);
+ }
+ return cacheOrg;
+ }
+
+
+ /**
+ * Fetch user's rattach school
+ */
+ private Organization fetchRattachSchool(User user) throws Exception{
+
+ // First try : if supann schema, return principal organization
+ if (ENTMainUtilsLocalServiceUtil.isSchemaSupann(user.getCompanyId())){
+ return ENTOrganizationsUtil.getOrCreateRootOrg(user.getCompanyId());
+ }
+
+ // Second try : use the UserProperties etabId, which is updated during synchronization
+ UserProperties userProperties = UserPropertiesLocalServiceUtil.getUserPropertiesByUserId(user.getUserId());
+ if (userProperties != null && userProperties.getEtabId() != 0) {
+ Organization org = OrganizationLocalServiceUtil.getOrganization(userProperties.getEtabId());
+ return org;
+ }
+
+ // Third try : use LDAP (case of manually created users)
+ String orgName = null;
+ Binding b = PortalLDAPUtil.getUser(user.getCompanyId(),user.getScreenName());
+ if(b == null){
+ return null;
+ }
+ String[] attrs2fetch = {"ENTPersonStructRattach"};
+ Attributes attrs = PortalLDAPUtil.doContextAttributes(user.getCompanyId(), PortalLDAPUtil.getNameInNamespace(user.getCompanyId(),b),attrs2fetch);
+ String[] attrs2fetchForOrg = {"ENTStructureNomCourant", "l", "ENTStructureUAI"};
+ Attributes orgNameAttrs = PortalLDAPUtil.doContextAttributes(user.getCompanyId(), attrs.get("ENTPersonStructRattach").get().toString(),attrs2fetchForOrg);
+ orgName = orgNameAttrs.get("ENTStructureNomCourant").get().toString();
+
+ String etabNameType = ENTMainUtilsLocalServiceUtil.getENTSynchroEtabName(user.getCompanyId());
+ if (etabNameType.equals("full")) {
+ if (orgNameAttrs.get("l") != null) {
+ orgName += " - " + orgNameAttrs.get("l").get().toString();
+ }
+ if (orgNameAttrs.get("ENTStructureUAI") != null) {
+ orgName += " - " + orgNameAttrs.get("ENTStructureUAI").get().toString();
+ }
+ }
+ return OrganizationLocalServiceUtil.getOrganization(user.getCompanyId(), orgName);
+ }
+
+
+ /**
+ * Get school's attribute from LDAP
+ */
+ public String getEtabLDAPAttribute(Organization org, String attribute) {
+ String initName = org.getName();
+ String cacheName = null;
+
+ try {
+
+ // Clé du cache
+ //key for user group etab name
+ String cacheKey="UG_EtabCache_"+attribute + org.getOrganizationId();
+
+ // Get value from cache instance
+ cacheName = (String) ENTCacheUtils.getObjectFromCache(cacheKey);
+ // On regarde si le cache est null ou non
+ if(cacheName==null){
+
+ //if misscache, set new value to variable
+ try {
+
+ Binding binding = null;
+
+ String baseDN = PrefsPropsUtil.getString(org.getCompanyId(),
+ PropsKeys.LDAP_BASE_DN);
+
+ NamingEnumeration<SearchResult> enu = null;
+
+ // si classic --> ENTStructureNomCourant
+ // si full --> ENTStructureNomCourant + l + RNE
+ String etabNameType = ENTMainUtilsLocalServiceUtil.getENTSynchroEtabName(org.getCompanyId());
+ if (etabNameType.equals("full")) {
+ // on se base sur le RNE pour realiser la recherche
+ int lindex = initName.lastIndexOf(" - ");
+ initName = initName.substring(lindex+3, initName.length());
+
+ try {
+
+ StringBuilder filter = new StringBuilder();
+
+ filter.append(StringPool.OPEN_PARENTHESIS);
+ filter.append("ENTStructureUAI");
+ filter.append(StringPool.EQUAL);
+ filter.append(initName);
+ filter.append(StringPool.CLOSE_PARENTHESIS);
+
+ SearchControls cons = new SearchControls(
+ SearchControls.SUBTREE_SCOPE, 1, 0, null, false, false);
+
+ enu = PortalLDAPUtil.doContextSearch(org.getCompanyId(), "ou=etablissements,"+PrefsPropsUtil.getString(org.getCompanyId(),"ldap.base.dn"), filter.toString(), cons);
+ } catch (Exception e) {
+ throw e;
+ }
+ }
+ else {
+ try {
+
+ StringBuilder filter = new StringBuilder();
+
+ filter.append(StringPool.OPEN_PARENTHESIS);
+ filter.append("ENTStructureNomCourant");
+ filter.append(StringPool.EQUAL);
+ filter.append(initName);
+ filter.append(StringPool.CLOSE_PARENTHESIS);
+
+ SearchControls cons = new SearchControls(
+ SearchControls.SUBTREE_SCOPE, 1, 0, null, false, false);
+
+ enu = PortalLDAPUtil.doContextSearch(org.getCompanyId(), "ou=etablissements,"+PrefsPropsUtil.getString(org.getCompanyId(),"ldap.base.dn"), filter.toString(), cons);
+ } catch (Exception e) {
+ throw e;
+ }
+ }
+
+ if (enu.hasMoreElements()) {
+ binding = enu.nextElement();
+
+ enu.close();
+
+ } else {
+ return null;
+ }
+
+ String[] attrs2fetch = {attribute};
+ Attributes attrs = PortalLDAPUtil.doContextAttributes(org.getCompanyId(), binding.getName() + ",ou=etablissements,"+PrefsPropsUtil.getString(org.getCompanyId(),"ldap.base.dn"),attrs2fetch);
+
+ cacheName = attrs.get(attribute).get().toString();
+
+ } catch (Exception e) {
+ //e.printStackTrace();
+ }
+ ENTCacheUtils.storeObjectIntoCache(cacheKey,cacheName,-1);
+ }
+ else{
+ //could find and get value from cache instance
+ }
+ } catch (Exception e) {
+ //if (_log.isErrorEnabled()) {
+ // _log.error(e);
+ //}
+ }
+
+ return cacheName;
+ }
+
+
+ /**
+ * Stocke un objet dans le cache s'il n'est pas présent et retourne le rne de rattachement du user
+ */
+ public String getUserLDAPAttribute(User user, String attribute) {
+
+ String cacheKey="userLDAPAttribute"+ attribute +user.getUserId();
+ String cacheValue = (String) ENTCacheUtils.getObjectFromCache(cacheKey);
+ if (cacheValue == null) {
+ //if misscache, fetch value
+ try {
+ cacheValue = getUserLDAPAttributeAction(user, attribute);
+ } catch (Exception e) {
+ _log.error("Error when fetching user's attribute "+attribute+" in LDAP", e);
+ }
+ ENTCacheUtils.storeObjectIntoCache(cacheKey,cacheValue,-1);
+ }
+ return cacheValue;
+ }
+
+ /**
+ * Get user's attribute from LDAP
+ * @param user
+ * @param attribute
+ * @return
+ */
+ private String getUserLDAPAttributeAction(User user, String attribute) throws Exception{
+
+ String value = "";
+ try {
+ Binding b = PortalLDAPUtil.getUser(user.getCompanyId(), user.getScreenName());
+ if (b == null){
+ return null;
+ }
+ String[] attrs2fetch = {attribute};
+ Attributes attrs = PortalLDAPUtil.doContextAttributes(user.getCompanyId(), PortalLDAPUtil.getNameInNamespace(user.getCompanyId(),b), attrs2fetch);
+
+ value = attrs.get(attribute).get().toString();
+ } catch(Exception e){
+ _log.error("Error when fetching user's attribute "+attribute+" in LDAP", e);
+ }
+ return value;
+ }
+
+
+ private static Log _log = LogFactoryUtil.getLog(OrganizationFinderServiceImpl.class);
+}