/*
ESUP-portail is a french academic project developed under the GPL (General Public License) augmented according to the following :
A binary or source file developped by ESUP-portail can be used or compiled with products under Apache license.
The official english text of the GPL can be found here : http://www.gnu.org/licenses/gpl.html .
A non official french translation can be found here : http://www.linux-France.org/article/these/gpl.html .
The different kinds of licenses governing the products developed by the Apache foundation can be found here : http://www.apache.org/licenses .
It follows that you can as well as use download contents as well modify and redistribute them provided you respect the GPL terms.
Downloading and using such contents do not provide any guaranty.
Be sure that you have well understood the terms of the license before using the contents it covers.
The ESUP-portail distribution includes the following distributions :
    * UPortal :
      software developed by JA-SIG (Java Architecture - Special Interest Group)
      You can find the license page here : http://mis105.udel.edu/ja-sig/uportal/license.html
    * CAS :
      SSO solution developed by Yale University
      You can find the project page here : http://www.yale.edu/tp/auth
    * Cocoon :
      XML framework distributed by the Apache foundation under Apache license;
      Please find the full text here : http://cocoon.apache.org/2.1/license.html
    * Mod_dav:
      A DAV module for Apache web server
      You can find the project page here : http://www.webdav.org/mod_dav
    * IMP :
      webmail from Horde application framework
      You can find the project page here : http://www.horde.org
    * …. To be completed
*/
package org.esupportail.portal.channels.CStockage.channelAction.classic.sharing;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.StringTokenizer;
import java.util.Vector;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ojb.broker.util.GUID;
import org.esupportail.portal.channels.CStockage.config.Server;
import org.esupportail.portal.channels.CStockage.config.Space;
import org.esupportail.portal.channels.CStockage.exception.AclAccessException;
import org.esupportail.portal.channels.CStockage.exception.AclReadException;
import org.esupportail.portal.channels.CStockage.exception.AclWriteException;
import org.esupportail.portal.channels.CStockage.exception.DataBaseException;
import org.esupportail.portal.channels.CStockage.exception.NotSupportedAclException;
import org.esupportail.portal.channels.CStockage.exception.PropertiesException;
import org.esupportail.portal.channels.CStockage.exception.ServerException;
import org.esupportail.portal.channels.CStockage.provider.access.ServerAccess;
import org.esupportail.portal.channels.CStockage.spacesPersonalization.DataBaseAccess;
import org.esupportail.portal.channels.CStockage.spacesPersonalization.ServerTool;
import org.esupportail.portal.channels.CStockage.spacesPersonalization.target.GroupForPersonalization;
import org.esupportail.portal.channels.CStockage.spacesPersonalization.target.OtherPrincipalForPersonalization;
import org.esupportail.portal.channels.CStockage.spacesPersonalization.target.UserForPersonalization;
import org.esupportail.portal.utils.webdav.acl.EsupPermission;
import org.esupportail.portal.utils.webdav.acl.EsupPermissions;

/**
 * Id: SharingTool.java,v 1.0 13 janv. 2005
 * Copyright (c) 2005 Esup Portail (www.esup-portail.org)
 * Classes: SharingTool
 * Original Author: Yohan Colmant
 * This class is a tool used to manage the sharing actions
 */
public class SharingTool {

	/**
	 * Logger object
	 */
	protected static final Log log = LogFactory.getLog(SharingTool.class);
	
	
	/**
	 * The object used to access the database
	 */
	private DataBaseAccess dbAccess;
	
	
	/**
	 * If the server into the database is administrated
	 */
	public static final String ADMINISTRATED_SERVER = "administrated_server";

	
	/**
	 * Constructor
	 * @throws PropertiesException
	 */
	public SharingTool() throws PropertiesException {
		dbAccess = new DataBaseAccess();		
	}
	

	

	
	
	
	
	/******************
	 *    SHARING 
	 *****************/
	
	
	

	/**
	 * Return the server name with the url of the server and the path
	 * @param serverUrl the url of the server
	 * @param path the path on the server
	 * @return the server name with the url of the server and the path
	 */
	private static String getServerName(String serverUrl, String path) {
		return serverUrl+path;
	}
	
	


	/**
	 * Get the users for whose the resource is shared from the acl
	 * @param serverUrl the url of the server
	 * @return an object array composed by one Space and 2 hashtables. The first hashtable contains users, the second contains groups
	 * @throws DataBaseException
	 * @throws PropertiesException
	 * @throws ServerException
	 * @throws AclReadException
	 * @throws AclAccessException
	 * @throws AclWriteException
	 * @throws NotSupportedAclException
	 */
	public Object[] getTargetsOfAvailableSpaceFromAcl(Space currentSpace, String serverUrl) throws DataBaseException, PropertiesException, ServerException, AclReadException, AclAccessException, AclWriteException, NotSupportedAclException {

		String path = currentSpace.getCurrentPath();
		
		Space sharedSpace = null;
		Vector users = new Vector();
		Vector groups = new Vector();
		Vector others = new Vector();
		Vector inherited = new Vector();
		boolean denyAllAll = false;
		boolean publicDirectory = false;
		
		String nearestDenyAllAll = null;
		
		// do the request to know the ids in the database
		Vector result = dbAccess.getAvailableSpace(getServerName(serverUrl, path));
		
		// get the server object
		if (result!=null && result.size()!=0) {
			String[] line = (String[])result.elementAt(0);
			String serverId = line[0];
			String serverXml = line[1];
			
			ServerTool spaceTool = new ServerTool(serverXml);
			ArrayList spaces = spaceTool.getSpaces();
			
			sharedSpace = (Space)spaces.get(0);
			sharedSpace.getServer().setId(serverId);
			
			// get the space owner
			String ownerKey = line[2];
			
			UserForPersonalization owner = new UserForPersonalization(ownerKey);
			owner.getPersonalization().setReading(1);
			owner.getPersonalization().setWriting(1);
			owner.getPersonalization().setSharing(1);
			owner.getPersonalization().setSecurityRight(true);
			owner.getPersonalization().setModifiable(false);
			sharedSpace.setOwner(owner);
			// log
			if (log.isDebugEnabled()){
				log.debug("getTargetsOfAvailableSpaceFromAcl"+" :: Owner found in database for the current space: "+owner);
			}
		}
		else {
			Server ser = (Server)currentSpace.getServer().clone();
			Space spa = (Space)currentSpace.cloneWithoutServer();
			
			ArrayList list = new ArrayList(1);
			list.add(spa);
			ser.setSpaces(list);
			ser.setId(null);
			
			spa.setServer(ser);
			
			sharedSpace = spa;
			sharedSpace.setLabel(null);
			sharedSpace.setKey(null);

			// if the current space is personal
			if (currentSpace.isPersonnalSpace()) {
				UserForPersonalization owner = currentSpace.getOwner();
				if (owner != null) {
					owner = (UserForPersonalization)owner.clone();
					sharedSpace.setOwner(owner);
				}
				else {
					owner = getSpaceOwnerInMetadata(currentSpace);
					sharedSpace.setOwner(owner);
				}
				
				// log
				if (log.isDebugEnabled()){
					log.debug("getTargetsOfAvailableSpaceFromAcl"+" :: Owner found in database for the personal space: "+owner);
				}
			}
			else {

				// get the space owner
				UserForPersonalization owner = getSpaceOwnerInMetadata(currentSpace);
				sharedSpace.setOwner(owner);
				// log
				if (log.isDebugEnabled()){
					log.debug("getTargetsOfAvailableSpaceFromAcl"+" :: Owner found in metadata: "+owner);
				}
			}
			
		}
		
		// the acl attributes
		String aclUserPrefix = currentSpace.getAclUserPrefix();
		String aclGroupPrefix = currentSpace.getAclGroupPrefix();
		String aclUportalGroup = currentSpace.getAclUportalGroup();
		String aclSecurity = currentSpace.getAclSecurity();
		
		// get the acl
		EsupPermissions permissions = currentSpace.getServerAccessObject().getPermissions(path);
		
		// get the permissions not inherited and on users and groups
		Iterator iter = permissions.iterator();
		
		while (iter.hasNext()) {
			EsupPermission perm = (EsupPermission)iter.next();
			//System.out.println(perm);
			/*if (!perm.isInherited()) {
				System.out.print(perm+" ");
				System.out.print(perm.isPrincipalUser()+" ");
				System.out.println(perm.isPrincipalGroup());
			}*/
			
			String principal = perm.getPrincipal();
			
			// check if the permission is not herited, or if it is herited from the parent collection
			/*String parentPath = currentSpace.getParentPath();
			if (parentPath!=null && parentPath.startsWith("/")) {
				parentPath = parentPath.substring(1);
			}
			if (parentPath!=null &&  parentPath.endsWith("/")) {
				parentPath = parentPath.substring(0, parentPath.length()-1);
			}
			String inheritedFrom = perm.getInheritedFrom();
			if (inheritedFrom!=null) {
				if (inheritedFrom.startsWith("/")) {
					inheritedFrom = inheritedFrom.substring(1);
				}
				if (inheritedFrom.endsWith("/")) {
					inheritedFrom = inheritedFrom.substring(0, inheritedFrom.length()-1);
				}
			}*/
			//if (!perm.isInherited()) || (perm.isInherited() && inheritedFrom.equals(parentPath))) {
	
			// if grant
			boolean permIsGrant = perm.isGrantPermission();
			
			// if user
			if (perm.isPrincipalUser()) {
				
				String key = principal.substring(aclUserPrefix.length());
				//System.out.println("user: "+key+" "+perm.getPermissionType());
				
				// get the good permission
				UserForPersonalization user = null;

				// if not inherited
				if (!perm.isInherited()) {
					for (int i=0; i<users.size() && user==null; i++) {
						UserForPersonalization u = (UserForPersonalization)users.elementAt(i);
						
						// if the key is the same
						if (key.equals(u.getKey())) {
						
							// if the both are not inherited
							if (!u.getPersonalization().isInheritedAcl()) {
								user = u;
							}
						}
					}
				}
				
				// if inherited
				else {
					for (int i=0; i<inherited.size() && user==null; i++) {
						Object obj = inherited.elementAt(i);
						if (obj instanceof UserForPersonalization) {
							UserForPersonalization u = (UserForPersonalization)obj;
							
							// if the key is the same
							if (key.equals(u.getKey())) {
							
								// if the both are inherited from the same path
								if (u.getPersonalization().isInheritedAcl() && perm.getInheritedFrom().equals(u.getPersonalization().getInheritedFrom())) {
									user = u;
								}
							}
						}
					}
				}
				
				// if user not found, we set it
				if (user == null) {
					user = new UserForPersonalization(key);
					
					if (!perm.isInherited())
						users.addElement(user);
					else inherited.addElement(user);
				}
				

				// id of the space from the database
				String spaceId = getIdOfAvailableSpaceFromDatabase(currentSpace, serverUrl, path, key, DataBaseAccess.TARGET_IS_USER);
				user.getPersonalization().setIdOfSharing(spaceId);
				
				if (perm.getPermissionType().equals(EsupPermission.READ)) {
					if (permIsGrant)
						user.getPersonalization().setReading(1);
					else user.getPersonalization().setReading(-1);
				}
				else {
					if (perm.getPermissionType().equals(EsupPermission.WRITE)) {
						if (permIsGrant) {
							user.getPersonalization().setWriting(1);
							if (user.getPersonalization().getSharing()==-1) {
								user.getPersonalization().setSharing(0);
							}
						}
						else user.getPersonalization().setWriting(-1);
					}
					else {
						if (perm.getPermissionType().equals(EsupPermission.WRITE_ACL)) {
							if (permIsGrant)
								user.getPersonalization().setSharing(1);
							else {
								user.getPersonalization().setSharing(-1);
							}
						}
						else {
							if (perm.getPermissionType().equals(EsupPermission.ALL)) {
								if (permIsGrant) {
									user.getPersonalization().setReading(1);
									user.getPersonalization().setWriting(1);
									user.getPersonalization().setSharing(1);
								}
								else {
									user.getPersonalization().setReading(-1);
									user.getPersonalization().setWriting(-1);
									user.getPersonalization().setSharing(-1);
								}
								//user.getPersonalization().setModifiable(false);
							}
						}
					}
				}
				
				//user.setInheritableAcl(perm.isInheritable());
				user.getPersonalization().setInheritedAcl(perm.isInherited());
				user.getPersonalization().setInheritedFrom(perm.getInheritedFrom());
			}
			
			// if group
			else if (perm.isPrincipalGroup() && principal.startsWith(aclGroupPrefix+aclUportalGroup)) {
				
				String hierarchy = principal.substring((aclGroupPrefix+aclUportalGroup).length());
				
				StringTokenizer strToken = new StringTokenizer(hierarchy, "/");
				String key = "";
				while (strToken.hasMoreTokens()) {
					key = strToken.nextToken();
				}
				//System.out.println("group: "+key+" "+perm.getPermissionType());
				
				// get the good permission
				GroupForPersonalization group = null;

				// if not inherited
				if (!perm.isInherited()) {
					for (int i=0; i<groups.size() && group==null; i++) {
						GroupForPersonalization g = (GroupForPersonalization)groups.elementAt(i);
						
						// if the key is the same
						if (key.equals(g.getKey())) {
						
							// if the both are not inherited
							if (!g.getPersonalization().isInheritedAcl()) {
								group = g;
							}
						}
					}
				}
				
				// if inherited
				else {
					for (int i=0; i<inherited.size() && group==null; i++) {
						Object obj = inherited.elementAt(i);
						if (obj instanceof GroupForPersonalization) {
							GroupForPersonalization g = (GroupForPersonalization)obj;
							
							// if the key is the same
							if (key.equals(g.getKey())) {
							
								// if the both are inherited from the same path
								if (g.getPersonalization().isInheritedAcl() && perm.getInheritedFrom().equals(g.getPersonalization().getInheritedFrom())) {
									group = g;
								}
							}
						}
					}
				}
		
				
				// if group not found, we set it
				if (group == null) {
					group = new GroupForPersonalization(hierarchy);
					
					if (!perm.isInherited())
						groups.addElement(group);
					else inherited.addElement(group);
				}

				// id of the space from the database
				String spaceId = getIdOfAvailableSpaceFromDatabase(currentSpace, serverUrl, path, key, DataBaseAccess.TARGET_IS_GROUP);
				group.getPersonalization().setIdOfSharing(spaceId);
				
				if (perm.getPermissionType().equals(EsupPermission.READ)) {
					if (permIsGrant)
						group.getPersonalization().setReading(1);
					else group.getPersonalization().setReading(-1);
				}
				else {
					if (perm.getPermissionType().equals(EsupPermission.WRITE)) {
						if (permIsGrant) {
							group.getPersonalization().setWriting(1);
							if (group.getPersonalization().getSharing()==-1) {
								group.getPersonalization().setSharing(0);
							}
						}
						else group.getPersonalization().setWriting(-1);
					}
					else {
						if (perm.getPermissionType().equals(EsupPermission.WRITE_ACL)) {
							if (permIsGrant)
								group.getPersonalization().setSharing(1);
							else {
								group.getPersonalization().setSharing(-1);
							}
						}
						else {
							if (perm.getPermissionType().equals(EsupPermission.ALL)) {
								if (permIsGrant) {
									group.getPersonalization().setReading(1);
									group.getPersonalization().setWriting(1);
									group.getPersonalization().setSharing(1);
								}
								else {
									group.getPersonalization().setReading(-1);
									group.getPersonalization().setWriting(-1);
									group.getPersonalization().setSharing(-1);
								}
								//group.getPersonalization().setModifiable(false);
							}
						}
					}
				}
					
				//group.setInheritableAcl(perm.isInheritable());
				group.getPersonalization().setInheritedAcl(perm.isInherited());
				group.getPersonalization().setInheritedFrom(perm.getInheritedFrom());
			}
			
			// the principal is not a user or a group from the portal
			else {
				
				String key = principal;
				
				// if grant read all
				if (perm.isGrantPermission() && perm.isPrincipalAll() && perm.getPermissionType().equals(EsupPermission.READ) && !perm.isInherited()) {
					publicDirectory = true;
				}
				
				// if deny all all
				else if (perm.isDenyPermission() && perm.isPrincipalAll()&& perm.getPermissionType().equals(EsupPermission.ALL) && !perm.isInherited()) {
					denyAllAll = true;
				}
				
				// not public
				else {
					
					// get the good permission
					OtherPrincipalForPersonalization other = null;
					
					// if not inherited
					if (!perm.isInherited()) {
						for (int i=0; i<others.size() && other==null; i++) {
							OtherPrincipalForPersonalization o = (OtherPrincipalForPersonalization)others.elementAt(i);
							
							// if the key is the same
							if (key.equals(o.getKey())) {
							
								// if the both are not inherited
								if (!o.getPersonalization().isInheritedAcl()) {
									other = o;
								}
							}
						}
					}
					
					// if inherited
					else {
						for (int i=0; i<inherited.size() && other==null; i++) {
							Object obj = inherited.elementAt(i);
							if (obj instanceof OtherPrincipalForPersonalization) {
								OtherPrincipalForPersonalization o = (OtherPrincipalForPersonalization)obj;
								
								// if the key is the same
								if (key.equals(o.getKey())) {
								
									// if the both are inherited from the same path
									if (o.getPersonalization().isInheritedAcl() && perm.getInheritedFrom().equals(o.getPersonalization().getInheritedFrom())) {
										other = o;
									}
								}
							}
						}
					}
					
					// if other not found, we set it
					if (other == null) {
						other = new OtherPrincipalForPersonalization(key);
						
						if (!perm.isInherited()) {
							others.addElement(other);
						}
						else {
							// if this is a deny all all
							if (perm.isPrincipalAll() && perm.isDenyPermission() && perm.getPermissionType().equals(EsupPermission.ALL)) {
								
								String inheritedFrom = perm.getInheritedFrom();
								
								// check if it is nearest than the other one
								if (nearestDenyAllAll==null) {
									nearestDenyAllAll = inheritedFrom;
								}
								else {
									if (inheritedFrom.compareTo(nearestDenyAllAll)>0) {
										nearestDenyAllAll = inheritedFrom;
									}
								}
							}
							
							inherited.addElement(other);
						}
					}
					

					if (perm.getPermissionType().equals(EsupPermission.READ)) {
						if (permIsGrant)
							other.getPersonalization().setReading(1);
						else other.getPersonalization().setReading(-1);
					}
					else {
						if (perm.getPermissionType().equals(EsupPermission.WRITE)) {
							if (permIsGrant)
								other.getPersonalization().setWriting(1);
							else other.getPersonalization().setWriting(-1);
						}
						else {
							if (perm.getPermissionType().equals(EsupPermission.WRITE_ACL)) {
								if (permIsGrant)
									other.getPersonalization().setSharing(1);
								else other.getPersonalization().setSharing(-1);
							}
							else {
								if (perm.getPermissionType().equals(EsupPermission.ALL)) {
									if (permIsGrant) {
										other.getPersonalization().setReading(1);
										other.getPersonalization().setWriting(1);
										other.getPersonalization().setSharing(1);
									}
									else {
										other.getPersonalization().setReading(-1);
										other.getPersonalization().setWriting(-1);
										other.getPersonalization().setSharing(-1);
									}
								}
							}
						}
					}
					other.getPersonalization().setInheritedAcl(perm.isInherited());
					other.getPersonalization().setInheritedFrom(perm.getInheritedFrom());
					other.getPersonalization().setModifiable(false);
				}
			}
		//}
			
			
		}
		
		// delete each inherited permission after the nearest deny all all
		if (nearestDenyAllAll!=null) {
			for (int i=0; i<inherited.size(); i++) {
				Object o = inherited.elementAt(i);
				if (o instanceof UserForPersonalization) {
					UserForPersonalization user = (UserForPersonalization)o;
					if (user.getPersonalization().getInheritedFrom().compareTo(nearestDenyAllAll)<0) {
						inherited.remove(i);
						i--;
					}
				}
				else if (o instanceof GroupForPersonalization) {
					GroupForPersonalization group = (GroupForPersonalization)o;
					if (group.getPersonalization().getInheritedFrom().compareTo(nearestDenyAllAll)<0) {
						inherited.remove(i);
						i--;
					}
				}
				else {
					OtherPrincipalForPersonalization other = (OtherPrincipalForPersonalization)o;
					if (other.getPersonalization().getInheritedFrom().compareTo(nearestDenyAllAll)<0) {
						inherited.remove(i);
						i--;
					}
				}
			}
		}
		
		// if we don't have any deny all all on the resource, but we have one on the parent
		if (!denyAllAll) {
			
			// if this space is still not in the database
			if (sharedSpace.getKey() == null) {
				
				// if there is a deny all all on the parent resource
				if (nearestDenyAllAll!=null) {
					String nearestDenyAllAllLight = Space.getPathWithoutFirstAndLastSlash(nearestDenyAllAll);
					String parentPathLight = Space.getPathWithoutFirstAndLastSlash(currentSpace.getParentPath());
					if (nearestDenyAllAllLight!=null && nearestDenyAllAllLight.equals(parentPathLight)) {
						//System.out.println("ON PREND PAS L'HERITAGE PAR DEFAUT");
						denyAllAll = true;
					}
				}
			}
			
		}
		
		// if the security acl is set
		for (int i=0; i<others.size(); i++) {
			OtherPrincipalForPersonalization other = (OtherPrincipalForPersonalization)others.elementAt(i);
			if (other.getKey().equals(aclSecurity)) {
				if (other.getPersonalization().getReading()==1 && other.getPersonalization().getWriting()==1 && other.getPersonalization().getSharing()==1) {
					//System.out.println("acl de securite trouve !!!");
					other.getPersonalization().setSecurityRight(true);
					other.getPersonalization().setModifiable(false);
				}
			}
		}
		
		// return the result
		Object[] res = new Object[7];
		res[0] = sharedSpace;
		res[1] = users;
		res[2] = groups;
		res[3] = others;
		res[4] = inherited;
		res[5] = new Boolean(!denyAllAll);
		res[6] = new Boolean(publicDirectory);
		return res;
	}
	
	
	
	
	
	
	public UserForPersonalization getSpaceOwnerInMetadata(Space space) throws PropertiesException, ServerException {
		
		// if we are not in a personal space, we get it in the metadata
		String ownerKey = space.getServerAccessObject().getProperty(space.getAclNamespace(), space.getSpaceRootPath(), "owner");
		int lastIndexOfPrefix = ownerKey.lastIndexOf(space.getAclUserPrefix());
		ownerKey = ownerKey.substring(lastIndexOfPrefix+space.getAclUserPrefix().length());
		UserForPersonalization owner = new UserForPersonalization(ownerKey);
		owner.getPersonalization().setReading(1);
		owner.getPersonalization().setWriting(1);
		owner.getPersonalization().setSharing(1);
		owner.getPersonalization().setSecurityRight(true);
		owner.getPersonalization().setModifiable(false);
		return owner;

	}
	
	
	
	/**
	 * Get the users for whose the resource is shared from the database
	 * @param serverUrl the url of the server
	 * @param path the path of the resource
	 * @return an object array composed by one Space and 2 hashtables. The first hashtable contains users, the second contains groups
	 * @throws DataBaseException
	 * @throws PropertiesException
	 * @throws ServerException
	 */
	/*private Object[] getTargetsOfAvailableSpaceFromDatabase(Space currentSpace, String serverUrl, String path) throws DataBaseException, PropertiesException, ServerException {

		Space sharedSpace = null;
		Hashtable users = new Hashtable();
		Hashtable groups = new Hashtable();
		
		// do the request
		Vector result = dbAccess.getTargetsOfAvailableSpace(getServerName(serverUrl, path));
		
		// get the server object
		if (result!=null && result.size()!=0) {
			
			String[] line = (String[])result.elementAt(0);
			String serverId = line[0];
			String serverXml = line[1];
			
			ServerTool spaceTool = new ServerTool(serverXml);
			ArrayList spaces = spaceTool.getSpaces();
			
			sharedSpace = (Space)spaces.get(0);
			sharedSpace.getServer().setId(serverId);
		
		
			// for each user and group
			for (int i=0; result!=null && i<result.size(); i++) {
				line = (String[])result.elementAt(i);
				
				String availableSpaceTargetId = line[2];
				String targetKey = line[3];
				String targetIsUser = line[4];
				String read = line[5];
				String write = line[6];
				String share = line[7];
				
				// if the target is a user
				if (targetIsUser.equals("T")) {
					UserForPersonalization user = new UserForPersonalization(targetKey);
					user.getPersonalization().setIdOfSharing(availableSpaceTargetId);
					user.getPersonalization().setReading(read);
					user.getPersonalization().setWriting(write);
					user.getPersonalization().setSharing(share);
					users.put(user.getKey(), user);
				}
				
				// the target is a group
				else {
					GroupForPersonalization group = new GroupForPersonalization(targetKey, null);
					group.getPersonalization().setIdOfSharing(availableSpaceTargetId);
					group.getPersonalization().setReading(read);
					group.getPersonalization().setWriting(write);
					group.getPersonalization().setSharing(share);
					groups.put(group.getKey(), group);
				}
			}
		}
		else {
			Server ser = (Server)currentSpace.getServer().clone();
			Space spa = (Space)currentSpace.cloneWithoutServer();
			
			ArrayList list = new ArrayList(1);
			list.add(spa);
			ser.setSpaces(list);
			ser.setId(null);
			
			spa.setServer(ser);
			
			sharedSpace = spa;
			sharedSpace.setLabel(null);
			sharedSpace.setKey(null);
		}
		
		// return the result
		Object[] res = new Object[4];
		res[0] = sharedSpace;
		res[1] = users;
		res[2] = groups;
		res[3] = new Hashtable();
		return res;
	}*/
	
	
	
	
	/**
	 * Get the users for whose the resource is shared from the database
	 * @param serverUrl the url of the server
	 * @param path the path of the resource
	 * @return the id of the available space target id
	 * @throws DataBaseException
	 * @throws PropertiesException
	 * @throws ServerException
	 */
	private String getIdOfAvailableSpaceFromDatabase(Space currentSpace, String serverUrl, String path, String targetKey, String targetType) throws DataBaseException, PropertiesException, ServerException {

		Space sharedSpace = null;
		
		// do the request
		Vector result = dbAccess.getTargetsOfAvailableSpace(getServerName(serverUrl, path));
		
		// get the id
		if (result!=null && result.size()!=0) {
			
			String[] line = (String[])result.elementAt(0);
			String serverId = line[0];
			String serverXml = line[1];
			
			ServerTool spaceTool = new ServerTool(serverXml);
			ArrayList spaces = spaceTool.getSpaces();
			
			sharedSpace = (Space)spaces.get(0);
			sharedSpace.getServer().setId(serverId);
		
		
			// for each user and group
			for (int i=0; result!=null && i<result.size(); i++) {
				line = (String[])result.elementAt(i);
				
				String availableSpaceTargetId = line[2];
				String targetKeyDB = line[3];
				String targetTypeFromDB = line[4];
				
				// if we have the good target
				if ((targetType.equals(targetTypeFromDB)) && (targetKey.equals(targetKeyDB))) {
					return availableSpaceTargetId;
				}
			}
		}
		
			
		return null;
	}
	
	
	
	
	
	
	
	
	
	/**
	 * Add sharing properties for the users and groups into the database
	 * @param currentSpace the current space we are using
	 * @param sharedSpace the space we are sharing
	 * @param serverUrl the url of the server
	 * @param fromKey the key of the people who shares
	 * @param path the resource path
	 * @param users the target users
	 * @param groups the target groups
	 * @throws DataBaseException
	 * @throws AclAccessException
	 * @throws AclWriteException
	 * @throws AclReadException
	 * @throws NotSupportedAclException
	 * @throws PropertiesException
	 */
	public void addStorageAvailableSpace(Space currentSpace, Space sharedSpace, String serverUrl, String fromKey, String path, Vector users, Vector groups, Vector others, Boolean inheritance, Boolean isPublic, Space spaceSharing) throws DataBaseException, AclAccessException, AclWriteException, AclReadException, NotSupportedAclException, PropertiesException {
	
		////////////////////////
		// add into the database
		
		// the server id
		String serverId = sharedSpace.getServer().getId();
		
		// if serverId == null, we generate a new id
		if (serverId == null) {
			serverId = new GUID().toString();
			sharedSpace.getServer().setId(serverId);
		}
		
		// for each space, we generate a key
		ArrayList spaces = sharedSpace.getServer().getSpaces();
		for (int i=0; i<spaces.size(); i++) {
			Space s = (Space)spaces.get(i);
			if (s.getKey() == null)
				s.setKey(new GUID().toString());
		}

		// the xml server
		String xmlServer = sharedSpace.getXml();

		// we add the server sharing to the database
		String ownerKey = null;
		if (sharedSpace.getOwner()!=null) {
			ownerKey = sharedSpace.getOwner().getKey();
		}
		dbAccess.addStorageAvailableSpace(serverId, getServerName(serverUrl, path), xmlServer, fromKey, ownerKey, sharedSpace.getCurrentViewer().getSpaceRootPath());
		
		ServerAccess access = currentSpace.getServerAccessObject();
		
		// the users
		for (int i=0; i<users.size(); i++) {
			
			UserForPersonalization user = (UserForPersonalization)users.elementAt(i);
			
			
			// if we don't have this, we add into database
			if (!user.getPersonalization().isSecurityRight()) {
				dbAccess.addStorageAvailableSpaceTarget(user.getKey(), DataBaseAccess.TARGET_IS_USER, serverId, sharedSpace.getKey(), false);			
			}
		
			/////////////////////
			// set the ACL rights
			if (currentSpace.allowsSharing()) {
				String principal = currentSpace.getAclUserPrefix()+user.getKey();
				if (user.getPersonalization().getSharing()==1 && user.getPersonalization().getReading()==1 && user.getPersonalization().getWriting()==1) {
					access.grant(path, principal, EsupPermission.ALL);
				}
				else {
					if (user.getPersonalization().getSharing()==1) {
						access.grant(path, principal, EsupPermission.WRITE_ACL);
					}
					if (user.getPersonalization().getReading()==1) {
						access.grant(path, principal, EsupPermission.READ);
					}
					if (user.getPersonalization().getWriting()==1) {
						access.grant(path, principal, EsupPermission.WRITE);
						access.deny(path, principal, EsupPermission.WRITE_ACL);
					}
				}
			}
		}
		

		// the groups
		for (int i=0; i<groups.size(); i++) {
			
			GroupForPersonalization group = (GroupForPersonalization)groups.elementAt(i);
			
			// if we don't have this, we add into database
			//if (group.getPersonalization().isAddInDatabase()) {
				dbAccess.addStorageAvailableSpaceTarget(group.getKey(), DataBaseAccess.TARGET_IS_GROUP, serverId, sharedSpace.getKey(), false);
			//}
		
			/////////////////////
			// set the ACL rights
			if (currentSpace.allowsSharing()) {
				Vector groupHierarchyKey = group.getGroupHierarchy();
				if (groupHierarchyKey!=null) {
					String principal = currentSpace.getAclGroupPrefix();
					if (currentSpace.getAclUportalGroup()!=null && !currentSpace.getAclUportalGroup().trim().equals("")) {
						principal = principal+currentSpace.getAclUportalGroup()+"/";
					}
					for (int j=0; j<groupHierarchyKey.size(); j++) {
						principal = principal + groupHierarchyKey.elementAt(j);
						if (j!=groupHierarchyKey.size()-1)
							principal = principal + "/";
					}
					if (group.getPersonalization().getSharing()==1 && group.getPersonalization().getReading()==1 && group.getPersonalization().getWriting()==1) {
						access.grant(path, principal, EsupPermission.ALL);
					}
					else {
						if (group.getPersonalization().getSharing()==1) {
							access.grant(path, principal, EsupPermission.WRITE_ACL);
						}
						if (group.getPersonalization().getReading()==1) {
							access.grant(path, principal, EsupPermission.READ);
						}
						if (group.getPersonalization().getWriting()==1) {
							access.grant(path, principal, EsupPermission.WRITE);
							access.deny(path, principal, EsupPermission.WRITE_ACL);
						}
					}
				}
			}
		}
		
		

		// the others
		for (int i=0; i<others.size(); i++) {
			
			OtherPrincipalForPersonalization other = (OtherPrincipalForPersonalization)others.elementAt(i);
			
			// if we don't have this, we add into database
			//if (group.getPersonalization().isAddInDatabase()) {
				//dbAccess.addStorageAvailableSpaceTarget(group.getKey(), DataBaseAccess.TARGET_IS_GROUP, serverId, sharedSpace.getKey(), false);
			//}
		
			/////////////////////
			// set the ACL rights
			if (currentSpace.allowsSharing()) {
				String principal = other.getKey();
				if (other.getPersonalization().getSharing()==1 && other.getPersonalization().getReading()==1 && other.getPersonalization().getWriting()==1) {
					access.grant(path, principal, EsupPermission.ALL);
				}
				else {
					if (other.getPersonalization().getSharing()==1) {
						access.grant(path, principal, EsupPermission.WRITE_ACL);
					}
					if (other.getPersonalization().getReading()==1) {
						access.grant(path, principal, EsupPermission.READ);
					}
					if (other.getPersonalization().getWriting()==1) {
						access.grant(path, principal, EsupPermission.WRITE);
						access.deny(path, principal, EsupPermission.WRITE_ACL);
					}
				}
				
			}
		}
		
		// add or remove the inheritance
		if (inheritance!=null)
			setInheritance(currentSpace, inheritance.booleanValue());
		
		// add or remove the inheritance
		if (isPublic!=null)
			setPublic(currentSpace, isPublic.booleanValue(), spaceSharing);
		
		
	}
	


	
	/**
	 * When the database attribute of a user change, we update the database
	 * @param serverId the id of the server
	 * @param spaceKey the key of the shared space
	 * @param usersToUpdateForDatabase the users to update
	 */
	/*public void updateDatabaseUsers(String serverId, String spaceKey, Vector usersToUpdateForDatabase) throws DataBaseException {
		
		for (int i=0; i<usersToUpdateForDatabase.size(); i++) {
			UserForPersonalization user = (UserForPersonalization)usersToUpdateForDatabase.elementAt(i);
			if (user.getPersonalization().isAddInDatabase()) {
				dbAccess.addStorageAvailableSpaceTarget(user.getKey(), true, serverId, spaceKey, false);
			}
			else {
				dbAccess.delStorageUsersPreferences(user.getPersonalization().getIdOfSharing());
				dbAccess.delStorageAvailableSpaceTarget(user.getPersonalization().getIdOfSharing());
			}
		}
	}*/
	
	
	
	/**
	 * When the database attribute of a user change, we update the database
	 * @param serverId the id of the server
	 * @param spaceKey the key of the shared space
	 * @param groupsToUpdateForDatabase the groups to update
	 */
	/*public void updateDatabaseGroups(String serverId, String spaceKey, Vector groupsToUpdateForDatabase) throws DataBaseException {
		
		for (int i=0; i<groupsToUpdateForDatabase.size(); i++) {
			GroupForPersonalization group = (GroupForPersonalization)groupsToUpdateForDatabase.elementAt(i);
			if (group.getPersonalization().isAddInDatabase()) {
				dbAccess.addStorageAvailableSpaceTarget(group.getKey(), false, serverId, spaceKey, false);
			}
			else {
				dbAccess.delStorageUsersPreferences(group.getPersonalization().getIdOfSharing());
				dbAccess.delStorageAvailableSpaceTarget(group.getPersonalization().getIdOfSharing());
			}
		}
	}*/
	
	
	
	
	

	/**
	 * Delete sharing properties for users into the database
	 * @param currentSpace the current space
	 * @param users we want to delete preferences
	 * @param serverId the id of the server
	 * @throws DataBaseException
	 * @throws AclAccessException
	 * @throws AclWriteException
	 * @throws AclReadException
	 * @throws NotSupportedAclException
	 * @throws PropertiesException
	 */
	public void delStorageAvailableSpaceForUsers(Space currentSpace, Vector users, String serverId) throws DataBaseException, AclAccessException, AclWriteException, AclReadException, NotSupportedAclException, PropertiesException {
		
		// for each user
		for(int i=0; i<users.size(); i++) {
		
			UserForPersonalization user = (UserForPersonalization)users.elementAt(i);
			
			// delete from the database
			if (!user.getPersonalization().isSecurityRight()) {
				String id = user.getPersonalization().getIdOfSharing();
				dbAccess.delStorageUsersPreferences(id);
				dbAccess.delStorageAvailableSpaceTarget(id);
			}
		
			// remove the ACL
			if (currentSpace.allowsSharing()) {
				String principal = currentSpace.getAclUserPrefix()+user.getKey();
				currentSpace.getServerAccessObject().revoke(currentSpace.getCurrentPath(), principal, EsupPermission.READ);
				currentSpace.getServerAccessObject().revoke(currentSpace.getCurrentPath(), principal, EsupPermission.WRITE);
				currentSpace.getServerAccessObject().revoke(currentSpace.getCurrentPath(), principal, EsupPermission.WRITE_ACL);
				currentSpace.getServerAccessObject().revoke(currentSpace.getCurrentPath(), principal, EsupPermission.ALL);
			}
		}
		
		// check if we have to delete from the available spaces table
		Vector v = dbAccess.getTargetsOfAvailableSpace(getServerName(currentSpace.getUrl(), currentSpace.getCurrentPath()));
		if (v==null || v.size() == 0) {
			dbAccess.delStorageAvailableSpace(serverId);
		}
		
		
	}
	
	
	
	


	/**
	 * Delete sharing properties for groups into the database
	 * @param currentSpace the current space
	 * @param groups the groups we want to delete sharing
	 * @param serverId the id of the server
	 * @throws DataBaseException
	 * @throws AclAccessException
	 * @throws AclWriteException
	 * @throws AclReadException
	 * @throws NotSupportedAclException
	 * @throws PropertiesException
	 */
	public void delStorageAvailableSpaceForGroups(Space currentSpace, Vector groups, String serverId) throws DataBaseException, AclAccessException, AclWriteException, AclReadException, NotSupportedAclException, PropertiesException {

		// for each group
		for(int i=0; i<groups.size(); i++) {
		
			GroupForPersonalization group = (GroupForPersonalization)groups.elementAt(i);
			
			// delete from the database
			String id = group.getPersonalization().getIdOfSharing();		
			dbAccess.delStorageUsersPreferences(id);
			dbAccess.delStorageAvailableSpaceTarget(id);
		
			// remove the ACL
			if (currentSpace.allowsSharing()) {
				Vector groupHierarchyKey = group.getGroupHierarchy();
				if (groupHierarchyKey!=null) {
					String principal = currentSpace.getAclGroupPrefix();
					if (currentSpace.getAclUportalGroup()!=null && !currentSpace.getAclUportalGroup().trim().equals("")) {
						principal = principal+currentSpace.getAclUportalGroup()+"/";
					}
					for (int j=0; j<groupHierarchyKey.size(); j++) {
						principal = principal + groupHierarchyKey.elementAt(j);
						if (j!=groupHierarchyKey.size()-1)
							principal = principal + "/";
					}
					
					currentSpace.getServerAccessObject().revoke(currentSpace.getCurrentPath(), principal, EsupPermission.READ);
					currentSpace.getServerAccessObject().revoke(currentSpace.getCurrentPath(), principal, EsupPermission.WRITE);
					currentSpace.getServerAccessObject().revoke(currentSpace.getCurrentPath(), principal, EsupPermission.WRITE_ACL);
					currentSpace.getServerAccessObject().revoke(currentSpace.getCurrentPath(), principal, EsupPermission.ALL);
				}
			}
		}

		// check if we have to delete from the available spaces table
		Vector v = dbAccess.getTargetsOfAvailableSpace(getServerName(currentSpace.getUrl(), currentSpace.getCurrentPath()));
		if (v==null || v.size() == 0) {
			dbAccess.delStorageAvailableSpace(serverId);
		}
		
		
	}
	
	
	
	/**
	 * Delete sharing properties for others into the acl
	 * @param currentSpace the current space
	 * @param others the others we want to delete sharing
	 * @param serverId the id of the server
	 * @throws DataBaseException
	 * @throws AclAccessException
	 * @throws AclWriteException
	 * @throws AclReadException
	 * @throws NotSupportedAclException
	 * @throws PropertiesException
	 */
	public void delStorageAvailableSpaceForOthers(Space currentSpace, Vector others, String serverId) throws DataBaseException, AclAccessException, AclWriteException, AclReadException, NotSupportedAclException, PropertiesException {

		// for each other
		for(int i=0; i<others.size(); i++) {
		
			OtherPrincipalForPersonalization other = (OtherPrincipalForPersonalization)others.elementAt(i);
			
			// remove the ACL
			if (currentSpace.allowsSharing()) {
				String principal = other.getKey();
				currentSpace.getServerAccessObject().revoke(currentSpace.getCurrentPath(), principal, EsupPermission.READ);
				currentSpace.getServerAccessObject().revoke(currentSpace.getCurrentPath(), principal, EsupPermission.WRITE);
				currentSpace.getServerAccessObject().revoke(currentSpace.getCurrentPath(), principal, EsupPermission.WRITE_ACL);
				currentSpace.getServerAccessObject().revoke(currentSpace.getCurrentPath(), principal, EsupPermission.ALL);
			}
		}

		
	}
	
	
	
	/**
	 * Update the "reading" and "writing" attributes for a specifical sharing for a user
	 * @param currentSpace the current space
	 * @param users the target users
	 * @throws DataBaseException
	 * @throws AclAccessException
	 * @throws AclWriteException
	 * @throws AclReadException
	 * @throws NotSupportedAclException
	 * @throws PropertiesException
	 */
	public void updateReadAndWriteAndShareSpaceUsers(Space currentSpace, Vector users)throws DataBaseException, AclAccessException, AclWriteException, AclReadException, NotSupportedAclException, PropertiesException {

		// for each group
		for (int i=0; i<users.size(); i++) {
		
			UserForPersonalization user = (UserForPersonalization)users.elementAt(i);			
			
			// update the database		
			//dbAccess.updateReadAndWriteAndShareSpace(user.getPersonalization().isReading(), user.getPersonalization().isWriting(), user.getPersonalization().isSharing(), user.getPersonalization().isObliged(), user.getPersonalization().getIdOfSharing());
			
			// update the ACL
			if (currentSpace.allowsSharing()) {
				String path = currentSpace.getCurrentPath();
				
				String principal = currentSpace.getAclUserPrefix()+user.getKey();
				ServerAccess access = currentSpace.getServerAccessObject();
				access.revoke(currentSpace.getCurrentPath(), principal, EsupPermission.READ);
				access.revoke(currentSpace.getCurrentPath(), principal, EsupPermission.WRITE);
				access.revoke(currentSpace.getCurrentPath(), principal, EsupPermission.WRITE_ACL);
				access.revoke(currentSpace.getCurrentPath(), principal, EsupPermission.ALL);
				if (user.getPersonalization().getReading()==1 && user.getPersonalization().getWriting()==1 && user.getPersonalization().getSharing()==1) {
					access.grant(path, principal, EsupPermission.ALL);
				}
				else {
					if (user.getPersonalization().getReading()==1) {
						access.grant(path, principal, EsupPermission.READ);
					}
					if (user.getPersonalization().getWriting()==1) {
						access.grant(path, principal, EsupPermission.WRITE);
						if (user.getPersonalization().getSharing()!=1) {
							access.deny(path, principal, EsupPermission.WRITE_ACL);
						}
					}
					if (user.getPersonalization().getSharing()==1) {
						access.grant(path, principal, EsupPermission.WRITE_ACL);
					}
				}
			}
		}
	}

	
	/**
	 * Update the "reading" and "writing" attributes for a specifical sharing for a group
	 * @param currentSpace the current space
	 * @param groups the target groups
	 * @throws DataBaseException
	 * @throws AclAccessException
	 * @throws AclWriteException
	 * @throws AclReadException
	 * @throws NotSupportedAclException
	 * @throws PropertiesException
	 */
	public void updateReadAndWriteAndShareSpaceGroups(Space currentSpace, Vector groups)throws DataBaseException, AclAccessException, AclWriteException, AclReadException, NotSupportedAclException, PropertiesException {

		// for each group
		for (int i=0; i<groups.size(); i++) {
		
			GroupForPersonalization group = (GroupForPersonalization)groups.elementAt(i);
			
			// update the database
			//dbAccess.updateReadAndWriteAndShareSpace(group.getPersonalization().isReading(), group.getPersonalization().isWriting(), group.getPersonalization().isSharing(), group.getPersonalization().isObliged(), group.getPersonalization().getIdOfSharing());

			// update the ACL
			if (currentSpace.allowsSharing()) {
				String path = currentSpace.getCurrentPath();
				
				Vector groupHierarchyKey = group.getGroupHierarchy();				
				if (groupHierarchyKey!=null) {
					String principal = currentSpace.getAclGroupPrefix();
					if (currentSpace.getAclUportalGroup()!=null && !currentSpace.getAclUportalGroup().trim().equals("")) {
						principal = principal+currentSpace.getAclUportalGroup()+"/";
					}
					for (int j=0; j<groupHierarchyKey.size(); j++) {
						principal = principal + groupHierarchyKey.elementAt(j);
						if (j!=groupHierarchyKey.size()-1)
							principal = principal + "/";
					}
					
					ServerAccess access = currentSpace.getServerAccessObject();
					access.revoke(currentSpace.getCurrentPath(), principal, EsupPermission.READ);
					access.revoke(currentSpace.getCurrentPath(), principal, EsupPermission.WRITE);
					access.revoke(currentSpace.getCurrentPath(), principal, EsupPermission.WRITE_ACL);
					access.revoke(currentSpace.getCurrentPath(), principal, EsupPermission.ALL);
					if (group.getPersonalization().getReading()==1 && group.getPersonalization().getWriting()==1 && group.getPersonalization().getSharing()==1) {
						access.grant(path, principal, EsupPermission.ALL);
					}
					else {
						if (group.getPersonalization().getReading()==1) {
							access.grant(path, principal, EsupPermission.READ);
						}
						if (group.getPersonalization().getWriting()==1) {
							access.grant(path, principal, EsupPermission.WRITE);
							if (group.getPersonalization().getSharing()!=1) {
								access.deny(path, principal, EsupPermission.WRITE_ACL);
							}
						}
						if (group.getPersonalization().getSharing()==1) {
							access.grant(path, principal, EsupPermission.WRITE_ACL);
						}
					}
				}
			}
		}
		
	}
	
	
	
	

	/**
	 * Update the "reading" and "writing" attributes for a specifical sharing for an other principal
	 * @param currentSpace the current space
	 * @param others the target others
	 * @throws DataBaseException
	 * @throws AclAccessException
	 * @throws AclWriteException
	 * @throws AclReadException
	 * @throws NotSupportedAclException
	 * @throws PropertiesException
	 */
	public void updateReadAndWriteAndShareSpaceOthers(Space currentSpace, Vector others)throws DataBaseException, AclAccessException, AclWriteException, AclReadException, NotSupportedAclException, PropertiesException {

		// for each other
		for (int i=0; i<others.size(); i++) {
		
			OtherPrincipalForPersonalization other = (OtherPrincipalForPersonalization)others.elementAt(i);
			
			// update the ACL
			if (currentSpace.allowsSharing()) {
				String path = currentSpace.getCurrentPath();			
				String principal = other.getKey();
				
				ServerAccess access = currentSpace.getServerAccessObject();
				access.revoke(currentSpace.getCurrentPath(), principal, EsupPermission.READ);
				access.revoke(currentSpace.getCurrentPath(), principal, EsupPermission.WRITE);
				access.revoke(currentSpace.getCurrentPath(), principal, EsupPermission.WRITE_ACL);
				access.revoke(currentSpace.getCurrentPath(), principal, EsupPermission.ALL);
				if (other.getPersonalization().getReading()==1 && other.getPersonalization().getWriting()==1 && other.getPersonalization().getSharing()==1) {
					access.grant(path, principal, EsupPermission.ALL);
				}
				else {
					if (other.getPersonalization().getReading()==1) {
						access.grant(path, principal, EsupPermission.READ);
					}
					if (other.getPersonalization().getWriting()==1) {
						access.grant(path, principal, EsupPermission.WRITE);
						if (other.getPersonalization().getSharing()!=1) {
							access.deny(path, principal, EsupPermission.WRITE_ACL);
						}
					}
					if (other.getPersonalization().getSharing()==1) {
						access.grant(path, principal, EsupPermission.WRITE_ACL);
					}
				}
			}
		}
		
	}
	
	
	

	/**
	 * Update the label of the sharing properties into the database for users
	 * @param sharedSpace the space we are sharing
	 * @throws DataBaseException
	 */
	public void updateXmlServerAvailableSpace(Space sharedSpace) throws DataBaseException {

		// update the database
		dbAccess.updateXmlServerAvailableSpace(sharedSpace.getXml(), sharedSpace.getServer().getId());

	}
	
	


	/**
	 * Delete sharing properties for url and path into the database
	 * @param url the url of the space
	 * @param path the path of the space
	 * @throws DataBaseException
	 */
	public void delStorageAvailableSpaceForSpecifiedPath(String url, String path) throws DataBaseException {
 
		// get ids of spaces with the specified url and path
		Vector[] ids = dbAccess.getIdOfSpacesWithServerName(getServerName(url, path));
		Vector id_storage_available_spaces = ids[0];
		Vector id_storage_available_spaces_targets = ids[1];
		
		// for each we delete from preferences database
		for (int i=0; i<id_storage_available_spaces_targets.size(); i++) {
			String id = (String)id_storage_available_spaces_targets.elementAt(i);
			
			// delete from the database			
			dbAccess.delStorageUsersPreferences(id);
			dbAccess.delStorageAvailableSpaceTarget(id);
		}
		
		// for each id, we delete from the 2 tables in database
		for (int i=0; i<id_storage_available_spaces.size(); i++) {
			String id = (String)id_storage_available_spaces.elementAt(i);
			
			// delete from the database			
			dbAccess.delStorageAvailableSpace(id);
		}
			
	}
	
	
	
	
	/**
	 * Delete all privileges in ACL and Database
	 * @param currentSpace the current space
	 * @param serverId the id of the server
	 * @param spaceId the id of the space used here
	 * @throws DataBaseException
	 */
	public void deleteAllPrivileges(Space currentSpace, String serverId, String spaceId) throws DataBaseException, NotSupportedAclException, PropertiesException, AclAccessException, AclWriteException, AclReadException {

		// update the ACL
		if (currentSpace.allowsSharing()) {
			
			// revoke the ACL
			ServerAccess access = currentSpace.getServerAccessObject();
			access.revokeAllPermissons(currentSpace.getCurrentPath());
			
			// get the ids of targets in database
			Vector ids = dbAccess.getTargetsOfSpace(serverId, spaceId);
			
			// delete in database
			for (int i=0; i<ids.size(); i++) {
				String id = (String)ids.elementAt(i);
				//System.out.println(id);
				dbAccess.delStorageUsersPreferences(id);
				dbAccess.delStorageAvailableSpaceTarget(id);
				dbAccess.delStorageAvailableSpace(serverId);
			}
			
		}
			
	}

	

	/**
	 * Update the path of shared spaces
	 * @param url the url of the space
	 * @param oldPath the old path of the space
	 * @param newPath the new path of the space
	 * @return the result of the query
	 * @throws DataBaseException
	 */
	public void updatePathOfSharing(String url, String oldPath, String newPath) throws DataBaseException {

		// get ids and xml with specified url and path
		Vector[] res = dbAccess.getIdAndXmlOfSharing(getServerName(url, oldPath));
		
		// replace into xml the path
		Vector xmls = res[1];
		Vector xmlsReplace = new Vector();
		for (int i=0; i<xmls.size(); i++) {
			String xml = (String)xmls.elementAt(i);
			String xmlReplace = xml.replaceAll("path=\""+oldPath+"\"", "path=\""+newPath+"\"");
			xmlsReplace.add(xmlReplace);
		}
		
		// set new path and xml
		Vector ids = res[0];
		for (int i=0; i<ids.size(); i++) {
			String id = (String)ids.elementAt(i);
			String xml = (String)xmlsReplace.elementAt(i);
			dbAccess.updatePathOfSharing(getServerName(url, newPath), xml, id);
		}
			
	}
	
	
	
	
	
	/**
	 * Update the inheritance
	 * @param currentSpace the current space
	 * @param inheritance the inheritance in this directory
	 * @throws AclAccessException
	 * @throws AclWriteException
	 * @throws AclReadException
	 * @throws NotSupportedAclException
	 * @throws PropertiesException
	 */
	public void setInheritance(Space currentSpace, boolean inheritance)throws AclAccessException, AclWriteException, AclReadException, NotSupportedAclException, PropertiesException {

		ServerAccess access = currentSpace.getServerAccessObject();
		
		access.revoke(currentSpace.getCurrentPath(), EsupPermission.PRINCIPAL_ALL, EsupPermission.ALL);
		
		if (!inheritance)
			access.deny(currentSpace.getCurrentPath(), EsupPermission.PRINCIPAL_ALL, EsupPermission.ALL);
	}
	
	
	/**
	 * Update the inheritance
	 * @param currentSpace the current space
	 * @param publicDirectory if this directory is public or not
	 * @throws AclAccessException
	 * @throws AclWriteException
	 * @throws AclReadException
	 * @throws NotSupportedAclException
	 * @throws PropertiesException
	 */
	public void setPublic(Space currentSpace, boolean publicDirectory, Space sharedSpace)throws DataBaseException, AclAccessException, AclWriteException, AclReadException, NotSupportedAclException, PropertiesException {
		
		if (publicDirectory)
			dbAccess.addStorageAvailableSpaceTarget(DataBaseAccess.TARGET_ALL, DataBaseAccess.TARGET_IS_ALL, sharedSpace.getServer().getId(), sharedSpace.getKey(), false);
		else dbAccess.delStorageAvailableSpaceTargetAll(sharedSpace.getServer().getId(), sharedSpace.getKey());
		
		ServerAccess access = currentSpace.getServerAccessObject();
		
		access.revoke(currentSpace.getCurrentPath(), EsupPermission.PRINCIPAL_ALL, EsupPermission.READ);
		
		if (publicDirectory)
			access.grant(currentSpace.getCurrentPath(), EsupPermission.PRINCIPAL_ALL, EsupPermission.READ);
	}
	
}
