/*
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.injac;
 
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Vector;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.esupportail.portal.channels.CAnnuaire.CAnnuaireServantFactory;
import org.esupportail.portal.channels.CStockage.channelAction.AbstractChannelAction;
import org.esupportail.portal.channels.CStockage.channelAction.BufferAction;
import org.esupportail.portal.channels.CStockage.channelAction.Constants;
import org.esupportail.portal.channels.CStockage.channelAction.injac.acl.InjacAclManager;
import org.esupportail.portal.channels.CStockage.channelAction.injac.actions.DocumentEditionAction;
import org.esupportail.portal.channels.CStockage.channelAction.injac.actions.DocumentPublicationAction;
import org.esupportail.portal.channels.CStockage.channelAction.injac.actions.DocumentRejectAction;
import org.esupportail.portal.channels.CStockage.channelAction.injac.actions.DocumentUnpublicationAction;
import org.esupportail.portal.channels.CStockage.channelAction.injac.actions.MetadataManagerAction;
import org.esupportail.portal.channels.CStockage.channelAction.injac.config.MetadataFileProfile;
import org.esupportail.portal.channels.CStockage.channelAction.injac.config.RenderingType;
import org.esupportail.portal.channels.CStockage.channelAction.injac.metadata.InjacSpaceManagementProperties;
import org.esupportail.portal.channels.CStockage.channelAction.injac.metadata.MetaDataConstants;
import org.esupportail.portal.channels.CStockage.channelAction.injac.metadata.MetaDataManager;
import org.esupportail.portal.channels.CStockage.config.Space;
import org.esupportail.portal.channels.CStockage.exception.ApplicationException;
import org.esupportail.portal.channels.CStockage.exception.BadFormatException;
import org.esupportail.portal.channels.CStockage.exception.CancelException;
import org.esupportail.portal.channels.CStockage.exception.CopyException;
import org.esupportail.portal.channels.CStockage.exception.CreateDirectoryException;
import org.esupportail.portal.channels.CStockage.exception.DeleteException;
import org.esupportail.portal.channels.CStockage.exception.InjacDocumentException;
import org.esupportail.portal.channels.CStockage.exception.NoneSelectedResourceException;
import org.esupportail.portal.channels.CStockage.exception.NotAuthorizedAccessPublishedDocumentException;
import org.esupportail.portal.channels.CStockage.exception.NotAuthorizedDeleteException;
import org.esupportail.portal.channels.CStockage.exception.NotAuthorizedException;
import org.esupportail.portal.channels.CStockage.exception.NotAuthorizedNewDirException;
import org.esupportail.portal.channels.CStockage.exception.NotAuthorizedRenameException;
import org.esupportail.portal.channels.CStockage.exception.NotExistsResourceException;
import org.esupportail.portal.channels.CStockage.exception.NotManagerInSpaceException;
import org.esupportail.portal.channels.CStockage.exception.NotSupportedAclException;
import org.esupportail.portal.channels.CStockage.exception.NotWriterInSpaceException;
import org.esupportail.portal.channels.CStockage.exception.PasteDeletedResourceException;
import org.esupportail.portal.channels.CStockage.exception.PropertiesException;
import org.esupportail.portal.channels.CStockage.exception.ServerException;
import org.esupportail.portal.channels.CStockage.exception.StillExistsException;
import org.esupportail.portal.channels.CStockage.exception.TooMuchSelectedException;
import org.esupportail.portal.channels.CStockage.exception.ChannelException;
import org.esupportail.portal.channels.CStockage.exception.UploadException;
import org.esupportail.portal.channels.CStockage.provider.ResourceControl;
import org.esupportail.portal.channels.CStockage.provider.access.ServerAccess;
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.channels.CStockage.userManagement.Group;
import org.esupportail.portal.channels.CStockage.userManagement.User;
import org.jasig.portal.ChannelRuntimeData;
import org.jasig.portal.ChannelStaticData;
import org.jasig.portal.MultipartDataSource;
import org.jasig.portal.PortalException;
import org.jasig.portal.channels.groupsmanager.CGroupsManagerServantFactory;
import org.jasig.portal.groups.EntityGroupImpl;
import org.jasig.portal.security.IPerson;
import org.jasig.portal.services.GroupService;
import org.jasig.portal.utils.XSLT;
import org.xml.sax.ContentHandler;

/**
 * Id: ChannelAction.java,v 1.0 27 sept. 2004
 * Copyright (c) 2004 Esup Portail (www.esup-portail.org)
 * Classes: ChannelAction
 * Original Author: Yohan Colmant
 * Class used to manage the actions when we are in an injac space context
 */
public class ChannelAction extends AbstractChannelAction {

	

	/**
	 * Logger object
	 */
	protected static final Log log = LogFactory.getLog(ChannelAction.class);
	
	
	
	/**
	 * Object use to manage an injac space properties
	 */
	private InjacSpaceManagementProperties smp;
	 

	/**
	 * Object used to know the properties of the current directory
	 */
	private DirectoryProperties directoryProperties;
	
	

	/**
	 * The metadata we have to set
	 */
	private Vector metadatasToSet = new Vector();
	
	
	
	
	
	/**
	 * Default constructor
	 * 
	 */
	public ChannelAction() {		
	
	}
	
	/**
	 * Init the object used to manage the actions of the channel
	 * @param person the uportal person object
	 * @param currentSpace the current space used
	 * @param spaces all the spaces used
	 * @param buffer the buffer used to get for example the clipboard
	 * @param userPortalLogin The user login in the portal
	 * @param userGroups The groups of the user in the portal
	 * @throws ChannelException
	 */
	public void init(IPerson person, Space currentSpace, ArrayList spaces, BufferAction buffer, String userPortalLogin, Vector userGroups) {
		super.init(person, currentSpace, spaces, buffer, userPortalLogin, userGroups);
		//setCurrentDirectoryProperties();		
	}
	
	
	/**
	 * Init the current viewer of the space
	 * @throws ChannelException
	 */
	//protected void initPrivilegesOfTheCurrentViewer() throws ChannelException {}
	
	/**
	 * Set the properties of the currentDirectory
	 * @throws ServerException
	 */
	private void setCurrentDirectoryProperties() throws ServerException {
		setCurrentDirectoryProperties(null);
	}
	
	
	
	/**
	 * Set the properties of the currentDirectory
	 * @param injacType the type of the directory
	 * @throws ServerException
	 */
	private void setCurrentDirectoryProperties(String injacType) throws ServerException {
		String currentDirPath = this.currentSpace.getCurrentPath();
		
		String localInjacType = injacType;
		if (localInjacType==null)
			localInjacType = MetaDataManager.getDirectoryType(currentSpace, currentDirPath);
		
		if (localInjacType!=null && localInjacType.equals(MetaDataConstants.INJAC_TYPE_SPACE)) {
			boolean userIsWriter = isUserWriterInSpace(currentDirPath, currentSpace, this.userPortalLogin, this.userGroups);
			boolean userIsEditor = isUserEditorInSpace(currentDirPath, currentSpace, this.userPortalLogin, this.userGroups);
			boolean userIsManager = isUserManagerInSpace(currentDirPath, currentSpace, this.userPortalLogin, this.userGroups);
			String rootDocumentName = MetaDataManager.getSpaceRootDocumentName(currentSpace, currentDirPath);
			
			if (this.directoryProperties == null) {
				this.directoryProperties = new DirectoryProperties(localInjacType, userIsWriter, userIsEditor, userIsManager, rootDocumentName);
			}
			else {
				this.directoryProperties.setType(localInjacType);
				this.directoryProperties.setUserIsWriter(userIsWriter);
				this.directoryProperties.setUserIsEditor(userIsEditor);
				this.directoryProperties.setUserIsManager(userIsManager);
				this.directoryProperties.setRootDocumentName(rootDocumentName);
				this.directoryProperties.setMetadataList(null);
			}
		}
		
		else {
			
			if (this.directoryProperties == null) {
				this.directoryProperties = new DirectoryProperties(injacType, false, false, false, null);
			}
			else {
				this.directoryProperties.setType(injacType);
				this.directoryProperties.setUserIsWriter(false);
				this.directoryProperties.setUserIsEditor(false);
				this.directoryProperties.setUserIsManager(false);
				this.directoryProperties.setRootDocumentName(null);
				this.directoryProperties.setMetadataList(null);
			}
		}
	}
	
	
	

	/**
	 * Check if the current user is manager in the specified space
	 * @param spacePath the space access path
	 * @param currentSpace the current space used
	 * @param userPortalLogin the uportal access login
	 * @param userGroups the groups of the user
	 * @return true if manager, false else
	 * @throws ServerException
	 */
	public static boolean isUserManagerInSpace(String spacePath, Space currentSpace, String userPortalLogin, Vector userGroups) throws ServerException {		
		String injacType = MetaDataManager.getDirectoryType(currentSpace, spacePath);
		if (injacType!=null && injacType.equals(MetaDataConstants.INJAC_TYPE_SPACE)) {
			boolean isManager = InjacSpaceManagementProperties.isUserManager(userPortalLogin, userGroups, currentSpace, spacePath);
			//System.out.println("Manager sur "+spacePath+": "+isManager);
			return isManager;
		}
		else return false;		
	}
	
	
	/**
	 * Check if the current user is writer in the specified space
	 * @param spacePath the space access path
	 * @param currentSpace the current space used
	 * @param userPortalLogin the uportal access login
	 * @param userGroups the groups of the user
	 * @return true if writer, false else
	 * @throws ServerException
	 */
	public static boolean isUserWriterInSpace(String spacePath, Space currentSpace, String userPortalLogin, Vector userGroups) throws ServerException {		
		String injacType = MetaDataManager.getDirectoryType(currentSpace, spacePath);
		if (injacType!=null && injacType.equals(MetaDataConstants.INJAC_TYPE_SPACE)) {
			boolean isWriter = InjacSpaceManagementProperties.isUserWriter(userPortalLogin, userGroups, currentSpace, spacePath);
			//System.out.println("Writer sur espace "+spacePath+": "+isWriter);
			return isWriter;
		}
		else return false;		
	}
	
	

	
	/**
	 * Check if the current user is editor in the specified space
	 * @param spacePath the space access path
	 * @param currentSpace the current space used
	 * @param userPortalLogin the uportal access login
	 * @param userGroups the groups of the user
	 * @return true if editor, false else
	 * @throws ServerException
	 */
	public static boolean isUserEditorInSpace(String spacePath, Space currentSpace, String userPortalLogin, Vector userGroups) throws ServerException {		
		String injacType = MetaDataManager.getDirectoryType(currentSpace, spacePath);
		if (injacType!=null && injacType.equals(MetaDataConstants.INJAC_TYPE_SPACE)) {
			boolean isEditor = InjacSpaceManagementProperties.isUserEditor(userPortalLogin, userGroups, currentSpace, spacePath);
			//System.out.println("Editor sur "+spacePath+": "+isEditor);
			return isEditor;
		}
		else return false;		
	}
	
	
	/**
	 * Check if the current user is the owner of the specified document
	 * @param documentPath the document access path
	 * @param currentSpace the current space used
	 * @param userPortalLogin the uportal access login
	 * @return true if author, false else
	 * @throws ServerException
	 */
	public static boolean isUserDocumentOwner(String documentPath, Space currentSpace, String userPortalLogin) throws ServerException {		
		
		String owner = MetaDataManager.getDocumentOwner(currentSpace, documentPath);
		
		boolean isOwner = owner.equals(userPortalLogin);			
		if (isOwner)
			return true;
		else return false;		
		
	}
	
	
	
	
	
	
	
	
	/**
	 * Manage the specific actions when refreshing the channel for the specific channel mode
	 * @param currentMode the current channel mode
	 * @param staticData the static data channel object
	 * @param runtimeData the runtime data channel object
	 * @param out the contentHandler used in the renderXml
	 * @param xslt the xslt motor object
	 * @param setStaticDataException the excpetion throwed in the setStaticData method
	 * @throws PortalException
	 */
	public StringBuffer specificCheckCalledAction(String currentMode, ChannelStaticData staticData, ChannelRuntimeData runtimeData, ContentHandler out, XSLT xslt, ChannelException setStaticDataException) throws ChannelException, PortalException {		


		//////////////////////////////////////////////////////
		// D I R E C T O R Y		
		//prepare create
		if (currentMode.equals(Constants.SET_NAME_FOR_CREATE_DIR_MODE)) {		
			stylesheet = new StringBuffer("setNewDirectory");
			return new StringBuffer();
		}
		//Real create
		else if (currentMode.equals(Constants.CREATE_DIR_MODE)) {					
			createDir(runtimeData);		
			return renderXmlWithInformation("2004");
		}
		
		//////////////////////////////////////////////////////
		// U P L O A D
		//prepare
		else if (currentMode.equals(Constants.SET_FILE_TO_UPLOAD_MODE)) {										
			stylesheet = new StringBuffer("setUpload");
			return new StringBuffer();
		} 
		//Real upload
		else if (currentMode.equals(Constants.UPLOAD_MODE)) {
			upload(runtimeData);			
			return renderXmlWithInformation("2001");
		} 

		//////////////////////////////////////////////////////
		//D E L E T E
		//confirm
		else if (currentMode.equals(Constants.CONFIRM_DELETE_MODE)) {									
			stylesheet = new StringBuffer("confirmDelete");
			return renderXmlConfirmDelete(runtimeData);
		}
		
		//Real delete
		else if (currentMode.equals(Constants.DELETE_MODE)) {										
			delete(runtimeData);			
			return renderXmlWithInformation("2002");
		}
		
		//////////////////////////////////////////////////////  
		//C O P Y
		//set clipboard
		else if (currentMode.equals(Constants.SET_CLIPBOARD_FOR_COPY_MODE)) {								
			setClipboard(Constants.COPY_MODE, runtimeData);
			return renderXmlWithInformation("2007");
		}
		
		// ask if we paste really
		else if (currentMode.equals(Constants.CONFIRM_PASTE_MODE)) {			
			stylesheet = new StringBuffer("confirmPaste");								
			return renderXmlConfirmPaste();
		}
		
		//Real paste
		else if (currentMode.equals(Constants.PASTE_MODE)) {
			stylesheet = new StringBuffer("CStockage");
			return paste(runtimeData);						
		}
		
		//////////////////////////////////////////////////////
		//M O V E
		//set clipboard
		else if (currentMode.equals(Constants.SET_CLIPBOARD_FOR_MOVE_MODE)) {			
			setClipboard(Constants.MOVE_MODE, runtimeData);
			return renderXmlWithInformation("2007");
		}			
		
		//////////////////////////////////////////////////////
		//R E N A M E
		//prepare
		else if (currentMode.equals(Constants.SET_NAME_FOR_RENAME_MODE)) {
			stylesheet = new StringBuffer("setRename");
			return renderXmlSetNameForRename(runtimeData);		
		}
		//Real rename
		else if (currentMode.equals(Constants.RENAME_MODE)) {				
			rename(runtimeData);			
			return renderXmlWithInformation("2003");
		} 
		
		//////////////////////////////////////////////////////
		// S P A C E
		//prepare create
		else if (currentMode.equals(InjacConstants.SET_NAME_FOR_CREATE_SPACE_MODE)) {		
			stylesheet = new StringBuffer("setNewSpace");	
			return new StringBuffer();
		}
		//Real create
		else if (currentMode.equals(InjacConstants.CREATE_SPACE_MODE)) {		
			stylesheet = new StringBuffer("CStockage");	
			return createSpace(runtimeData, staticData, out);
		}
		//admin
		else if (currentMode.equals(InjacConstants.ADMIN_SPACE_MODE)) {		
			stylesheet = new StringBuffer("adminSpace");
			return renderXmlAdminSpace(runtimeData, staticData, out);				
		}
		
		// valid the servant results
		else if (currentMode.equals(Constants.VALID_SERVANT_RESULTS)) {		
			stylesheet = new StringBuffer("adminSpace");
			return renderXmlAdminSpaceValidServantResults(staticData);				
		}
		
		//////////////////////////////////////////////////////
		// D O C U M E N T   M E T A D A T A
		// metadata
		else if (currentMode.equals(InjacConstants.SET_METADATA_ON_DOCUMENT_MODE)) {		
			stylesheet = new StringBuffer("documentMetaData");
			return MetadataManagerAction.renderXmlMetadataManager(runtimeData, stylesheet, spaces, metadatasToSet, userPortalLogin, userGroups, currentSpace, directoryProperties, buffer, this.buffer.getCurrentSortType());
		}
		
		//////////////////////////////////////////////////////  
		//S U B M I T   D O C U M E N T

		// ask the mode to submit
		else if (currentMode.equals(InjacConstants.CHOOSE_SUBMIT_MODE)) {
			
			// if we checked files
			if (runtimeData.getParameterValues("listeFic")!=null) {
				stylesheet = new StringBuffer("confirmSubmit");												
				return DocumentEditionAction.renderXmlConfirmSubmit(runtimeData, buffer, stylesheet, spaces, metadatasToSet, userPortalLogin, userGroups, currentSpace, directoryProperties);
			}
			
			else {
				
				// if buffer is empty, we upload
				if (buffer.getClipboard()==null || buffer.getClipboard().size()==0) {
					stylesheet = new StringBuffer("setFileToUploadForSubmit");
					return new StringBuffer();
				}
				
				// if the buffer is not empty
				else {
					stylesheet = new StringBuffer("chooseSubmitMode");
					return new StringBuffer();
				}
			}
		}
		
		// we verify the choice of the user
		else if (currentMode.equals(InjacConstants.VERIFY_CHOICE_FOR_SUBMIT_MODE)) {			
			return verifyChoiceForSubmitMode(runtimeData);
		}
		
		// if we upload a document
		else if (currentMode.equals(InjacConstants.SET_FILE_TO_UPLOAD_FOR_SUBMIT_MODE)) {			
			stylesheet = new StringBuffer("setFileToUploadForSubmit");
			return new StringBuffer();
		}
		
		//Real submit
		else if (currentMode.equals(InjacConstants.SUBMIT_MODE)) {
			stylesheet = new StringBuffer("CStockage");				
			StringBuffer temp = DocumentEditionAction.submit(runtimeData, stylesheet, spaces, metadatasToSet, userPortalLogin, userGroups, currentSpace, directoryProperties, buffer, this.buffer.getCurrentSortType());
			return temp;
		}
		
		//////////////////////////////////////////////////////  
		//P U B L I S H   D O C U M E N T

		// ask the mode to publish
		else if (currentMode.equals(InjacConstants.CHOOSE_PUBLISH_MODE)) {
			
			// if not writer and editor
			//if (!isUserWriterInSpace(currentSpace.getPath(), currentSpace, userPortalLogin, userGroups) && isUserEditorInSpace(currentSpace.getPath(), currentSpace, userPortalLogin, userGroups)) {
			if (!directoryProperties.isUserWriter() && directoryProperties.isUserEditor()) {

				// if we checked files
				stylesheet = new StringBuffer("confirmPublish");												
				return DocumentPublicationAction.renderXmlConfirmPublish(runtimeData, buffer, stylesheet, spaces, metadatasToSet, userPortalLogin, userGroups, currentSpace, directoryProperties);
				
			}
			
			// if writer and editor
			else {

				// if we checked files
				if (runtimeData.getParameterValues("listeFic")!=null) {
					stylesheet = new StringBuffer("confirmPublish");												
					return DocumentPublicationAction.renderXmlConfirmPublish(runtimeData, buffer, stylesheet, spaces, metadatasToSet, userPortalLogin, userGroups, currentSpace, directoryProperties);
				}
				
				else {
					
					// if buffer is empty, we upload
					if (buffer.getClipboard()==null || buffer.getClipboard().size()==0) {
						stylesheet = new StringBuffer("setFileToUploadForPublish");
						return new StringBuffer();
					}
					
					// if the buffer is not empty
					else {
						stylesheet = new StringBuffer("choosePublishMode");
						return new StringBuffer();
					}
				}
			}
			
		}
		
		// we verify the choice of the user
		else if (currentMode.equals(InjacConstants.VERIFY_CHOICE_FOR_PUBLISH_MODE)) {			
			return verifyChoiceForPublishMode(runtimeData);
		}
		
		// if we upload a document
		else if (currentMode.equals(InjacConstants.SET_FILE_TO_UPLOAD_FOR_PUBLISH_MODE)) {			
			stylesheet = new StringBuffer("setFileToUploadForPublish");
			return new StringBuffer();
		}
		
		//Real publish
		else if (currentMode.equals(InjacConstants.PUBLISH_MODE)) {
			stylesheet = new StringBuffer("CStockage");				
			return DocumentPublicationAction.publish(runtimeData, stylesheet, spaces, metadatasToSet, userPortalLogin, userGroups, currentSpace, directoryProperties, buffer, this.buffer.getCurrentSortType());
		}
		
		//////////////////////////////////////////////////////  
		//U N P U B L I S H   D O C U M E N T
		
		// ask if we want to unpublish
		else if (currentMode.equals(InjacConstants.CONFIRM_UNPUBLISH_MODE)) {			
			stylesheet = new StringBuffer("confirmUnpublish");												
			return DocumentUnpublicationAction.renderXmlConfirmUnpublish(runtimeData, buffer, stylesheet, metadatasToSet, userPortalLogin, userGroups, currentSpace, directoryProperties);
		}
		
		//Real unpublish
		else if (currentMode.equals(InjacConstants.UNPUBLISH_MODE)) {
			stylesheet = new StringBuffer("CStockage");				
			return DocumentUnpublicationAction.unpublish(runtimeData, stylesheet, spaces, metadatasToSet, userPortalLogin, userGroups, currentSpace, directoryProperties, this.buffer.getCurrentSortType());
		}
		
		//////////////////////////////////////////////////////  
		//R E J E C T   D O C U M E N T
		
		// ask if we want to reject
		else if (currentMode.equals(InjacConstants.CONFIRM_REJECT_MODE)) {			
			stylesheet = new StringBuffer("confirmReject");												
			return DocumentRejectAction.renderXmlConfirmReject(runtimeData, buffer, stylesheet, metadatasToSet, userPortalLogin, userGroups, currentSpace, directoryProperties);
		}
		
		//Real reject
		else if (currentMode.equals(InjacConstants.REJECT_MODE)) {
			stylesheet = new StringBuffer("CStockage");				
			return DocumentRejectAction.reject(runtimeData, stylesheet, spaces, metadatasToSet, userPortalLogin, userGroups, currentSpace, directoryProperties, buffer, this.buffer.getCurrentSortType());
		}
		

		//////////////////////////////////////////////////////  
		//P R I N C I P A L   D O C U M E N T
		
		// ask if we want to set as principal
		else if (currentMode.equals(InjacConstants.CONFIRM_ROOT_DOCUMENT_MODE)) {			
			stylesheet = new StringBuffer("confirmSetRootDocument");												
			return renderXmlConfirmRootDocumentSetting(runtimeData);
		}
		
		//set as principal
		else if (currentMode.equals(InjacConstants.ROOT_DOCUMENT_MODE)) {
			rootDocumentSetting(runtimeData);			
			return renderXmlWithInformation("2016");
		}
		
		else return new StringBuffer();
	}


	

	
	/**
	 * Return the xml when we have to show a information message
	 * @return the xml when we have to show a information message
	 */
	public StringBuffer renderXmlWithInformation(String informationCode) {
		stylesheet = new StringBuffer("CStockage");
		return DefaultRenderXml.getXml(spaces, currentSpace, null, informationCode, userPortalLogin, userGroups, directoryProperties, this.buffer.getCurrentSortType());
	}
	
	
	
	
	

	/**
	 * For the selected mode, we check the properties of the current directory
	 * @throws Exception
	 */
	/*protected void checkCurrentDirectoryProperties() throws Exception {
		// if the current directory properties has not been still initialized
		if (this.directoryProperties == null) {
			setCurrentDirectoryProperties();
		}
	}*/
	
	

	
	/**
	 * Return the xml when we have a BadConnexionParameters exception
	 * @param e the throwed exception
	 * @return the xml when we have a BadConnexionParameters exception
	 */
	public StringBuffer renderXmlBadConnexionParametersException(ChannelException e) throws PropertiesException {
		return DefaultRenderXml.getXmlForPasswordSetting(spaces, currentSpace, e);
	}
	
	
	/**
	 * Return the xml when we have a ChannelException exception
	 * @param e the throwed exception
	 * @return the xml when we have a ChannelException exception
	 */
	public StringBuffer renderXmlChannelException(ChannelException e) {
		return DefaultRenderXml.getXml(spaces, currentSpace, e, null, userPortalLogin, userGroups, directoryProperties, this.buffer.getCurrentSortType());
	}
	
	
	
	
	
	
	
	

	
	/**
	 * Generate the XML String for this mod
	 * @param runtimeData the runtime data channel object
	 * @return le XML pour ce mode
	 * @throws ChannelException
	 */
	protected StringBuffer renderXmlShowCurrentDir(ChannelRuntimeData runtimeData) throws ChannelException {
		
		//When we enter in a sub directory ...
		String targetDirectory = runtimeData.getParameter("targetDirectory");
		if (targetDirectory != null) {

			// log
			if (log.isDebugEnabled()){
				log.debug("renderXmlShowCurrentDir"+" :: targetDirectory = "+targetDirectory);
			}
			
			String currentPath = this.currentSpace.getCurrentPath();
			ServerAccess access = this.currentSpace.getServerAccessObject();
			
			if (!access.exists(targetDirectory, currentPath)) {
				NotExistsResourceException e = new NotExistsResourceException();
				// log
				if (log.isDebugEnabled()){
					log.debug("renderXmlShowCurrentDir"+" ::  "+e);
				}
				throw e;
			}
			
			// check if the target is a published document
			String fullPath = currentPath+targetDirectory;
			String directoryType = MetaDataManager.getDirectoryType(currentSpace, fullPath);
			if (directoryType!=null && directoryType.equals(MetaDataConstants.INJAC_TYPE_DOCUMENT)) {
				
				// if we are the document owner
				boolean owner = isUserDocumentOwner(fullPath, currentSpace, userPortalLogin);				
				if (owner) {
					String documentState = MetaDataManager.getDocumentState(currentSpace, fullPath);					
					// the document if published
					if (documentState.equals(MetaDataConstants.DOCUMENT_PUBLISHED_STATE)) {
						NotAuthorizedAccessPublishedDocumentException e = new NotAuthorizedAccessPublishedDocumentException();
						// log
						if (log.isDebugEnabled()){
							log.debug("renderXmlShowCurrentDir"+" ::  "+e);
						}
						throw e;					
					}					
				}
				
				// we are not the document owner
				else {
					
					// we are editor in the space
					boolean editor = directoryProperties.isUserEditor();					
					if (editor) {						
						String documentState = MetaDataManager.getDocumentState(currentSpace, fullPath);						
						// the document if published
						if (documentState.equals(MetaDataConstants.DOCUMENT_PUBLISHED_STATE)) {
							NotAuthorizedAccessPublishedDocumentException e = new NotAuthorizedAccessPublishedDocumentException();
							// log
							if (log.isDebugEnabled()){
								log.debug("renderXmlShowCurrentDir"+" ::  "+e);
							}
							throw e;					
						}						
					}
					
					// we are not editor, not owner
					else {
						NotAuthorizedException e = new NotAuthorizedException();
						// log
						if (log.isDebugEnabled()){
							log.debug("renderXmlShowCurrentDir"+" ::  "+e);
						}
						throw e;
					}
					
					
				}
				
			}			

			// we add it to path
			currentSpace.addPathElement(targetDirectory);
			
			// init the properties of this directory
			setCurrentDirectoryProperties(directoryType);
			
			
			return DefaultRenderXml.getXml(spaces, currentSpace, null , null, userPortalLogin, userGroups, directoryProperties, this.buffer.getCurrentSortType());
		}
		else {
			//... by naviguation tool
			String dir = runtimeData.getParameter("link");
			if (dir != null) {
				int index = Integer.parseInt(dir);
				int curentDirLength = currentSpace.getPathSize();
				if (index < curentDirLength) {					
					for (int i=0; i< (curentDirLength-(index+1)); i++) {						
						currentSpace.removePathElement(currentSpace.getPathSize()-1);
					}			
				}				

				// init the properties of this directory
				setCurrentDirectoryProperties();
				
				return DefaultRenderXml.getXml(spaces, currentSpace, null , null, userPortalLogin, userGroups, directoryProperties, this.buffer.getCurrentSortType());
			}
		}
		
		// init the properties of this directory
		if (this.directoryProperties ==null)
			setCurrentDirectoryProperties();		
		
		// all others cases
		return DefaultRenderXml.getXml(spaces, currentSpace, null , null, userPortalLogin, userGroups, directoryProperties, this.buffer.getCurrentSortType());
	}
	
	
	/**
	 * Go to the parent directory
	 * @throws ChannelException
	 */
	protected void directoryBack() throws ChannelException {
		// log
		if (log.isDebugEnabled()){
			log.debug("directoryBack");
		}
		
		if (currentSpace.getPathSize()>1) {			
			currentSpace.removePathElement(currentSpace.getPathSize()-1);			

			// init the properties of this directory
			setCurrentDirectoryProperties();
		}
	}
	
	
	
	

	
	/**
	 * Start the upload
	 * @param runtimeData the runtime data channel object
	 * @throws ChannelException
	 */
	private void upload(ChannelRuntimeData runtimeData) throws ChannelException {
	       
		String submit = runtimeData.getParameter("Submit");
		Object inputFile = runtimeData.getObjectParameter("input_file");        
	
		if (submit == null) {		
			throw new CancelException();		       		       	
		}
		else {			
			// if file is null
			if (inputFile == null) {	
				// log
				if (log.isDebugEnabled()){
					log.debug("upload"+" :: NotExistsResourceException");
				}
				
				throw new NotExistsResourceException();
			}			
			
			// get a reference to the file
			MultipartDataSource mps = (MultipartDataSource)inputFile;   	        	
			
			try {
				// check the file size				
				InputStream stream = mps.getInputStream();
				String fileName = mps.getName();
				
				// check if it still exist

				// the file to upload to the webdav			           					
	            String cible = currentSpace.getCurrentPath()+fileName;                                            
	            
	            // check if the file still exists 
	            boolean exist = false;                       
	            exist = currentSpace.getServerAccessObject().exists(cible);
	            
	            // we check if a directory has this name
	            /*if(!cible.endsWith(("/"))){
	            	exist = exist || currentSpace.getServerAccessObject().exists(cible+"/");
	            }*/
	            
	            if ( exist ) {            	

	        		// log
	        		if (log.isDebugEnabled()){
	        			log.debug("upload"+" :: "+fileName+" already exist");
	        		}
	        		
	            	throw new StillExistsException();
	            } 
				
				/*
				int fileSize = stream.available();
				if (fileSize > 29999) {
					stream.close();
					
					if (log.isDebugEnabled()){
						log.debug("upload"+" :: inputFile = "+fileName+" size too important:"+fileSize);
					}
					throw new SizeLimitUploadException();
				}																	
				*/
				// log
				if (log.isDebugEnabled()){
					log.debug("upload"+" :: inputFile = "+fileName);
				}
				
				String path = currentSpace.getCurrentPath();
		        this.currentSpace.getServerAccessObject().upload(fileName, stream, path);
			}
			catch(IOException e) {
				log.error("upload"+" :: inputFile = "+mps.getName()+" "+e);
				throw new UploadException();		
			}			
	        
		}
	}

	
	
	
	

	/**
	 * Generate the XML String for this mod
	 * @param runtimeData the runtime data channel object
	 * @throws CancelException
	 * @throws ApplicationException
	 * @throws CreateDirectoryException
	 * @throws StillExistsException
	 * @throws BadFormatException
	 * @throws NotAuthorizedException
	 * @throws NotAuthorizedNewDirException
	 * @throws NotExistsResourceException
	 */
	private void createDir(ChannelRuntimeData runtimeData) throws CancelException, ApplicationException, CreateDirectoryException, StillExistsException, BadFormatException, NotAuthorizedException, NotAuthorizedNewDirException, NotExistsResourceException, PropertiesException{
		String submit = runtimeData.getParameter("Submit");
		
		if (submit == null) {
			throw new CancelException();
		} else {
				
			String path = currentSpace.getCurrentPath();
			
			String newDirName = runtimeData.getParameter("new_dir");
			this.currentSpace.getServerAccessObject().createDir(newDirName, path);
        	

			// log
			if (log.isDebugEnabled()){
				log.debug("createDir"+" :: newDirName = "+newDirName);
			}
			
		}
	}

	
	
	
	


	/**************************
	 *   Rename/Delete methods
	 **************************/
		
	
	
	
	/**
	 * Generate the XML String for this mod
	 * @param runtimeData the runtime data channel object
	 * @return the XML String for this mod
	 * @throws ChannelException
	 */
	private StringBuffer renderXmlSetNameForRename(ChannelRuntimeData runtimeData) throws ChannelException {
		// we get the files we want to rename
		String[] files = runtimeData.getParameterValues("listeFic");
		
		if (files == null) {

			// log
			if (log.isDebugEnabled()){
				log.debug("renderXmlSetNameForRename"+" :: NoneSelectedResourceException");
			}

			stylesheet = new StringBuffer("CStockage");
			throw new NoneSelectedResourceException();
			//return WebdavRenderXml.getXml(spaces, currentSpace, new NoneSelectedResourceException(), null, config);
		}		
		else {
			// if there is more than one file
			if (files.length > 1) {

				// log
				if (log.isDebugEnabled()){
					log.debug("renderXmlSetNameForRename"+" :: TooMuchSelectedException");
				}
				
				stylesheet = new StringBuffer("CStockage");
				throw new TooMuchSelectedException();
				//return WebdavRenderXml.getXml(spaces, currentSpace, new TooMuchSelectedException(), null, config);
			}
			else {
				String fileToRename = files[0];

				// log
				if (log.isDebugEnabled()){
					log.debug("renderXmlSetNameForRename"+" :: fileToRename = "+fileToRename);
				}
				
				// check if we are able to rename this resource
				String currentPath = this.currentSpace.getCurrentPath();
				String fullPath = currentPath+fileToRename;
				String directoryType = MetaDataManager.getDirectoryType(currentSpace, fullPath);

				// if injac document
				if (directoryType!=null && directoryType.equals(MetaDataConstants.INJAC_TYPE_DOCUMENT)) {
					
					// if we are not the document owner
					if (!(isUserDocumentOwner(fullPath, currentSpace, userPortalLogin) || directoryProperties.isUserEditor()) ) {			
						NotAuthorizedDeleteException e = new NotAuthorizedDeleteException();

						// log
						if (log.isDebugEnabled()){
							log.debug("renderXmlSetNameForRename"+" :: "+e);
						}
						
						throw e;
					}
					
					else {
						String documentState = MetaDataManager.getDocumentState(currentSpace, fullPath);											
						
						// the document if published
						if (documentState!=null && documentState.equals(MetaDataConstants.DOCUMENT_PUBLISHED_STATE)) {
							NotAuthorizedAccessPublishedDocumentException e = new NotAuthorizedAccessPublishedDocumentException();

							// log
							if (log.isDebugEnabled()){
								log.debug("renderXmlSetNameForRename"+" :: "+e);
							}
							
							throw e;					
						}
					}
					
					
				}
				
				// if injac space
				else if (directoryType!=null && directoryType.equals(MetaDataConstants.INJAC_TYPE_SPACE)) {
					
					// if we are not the space manager
					if (!directoryProperties.isUserManager()) {									
						NotAuthorizedRenameException e = new NotAuthorizedRenameException();

						// log
						if (log.isDebugEnabled()){
							log.debug("renderXmlSetNameForRename"+" :: "+e);
						}
						
						throw e;
					}					
					
				}
				
				
				
				buffer.setFileToRename(fileToRename);
				StringBuffer sb = new StringBuffer();
				sb.append("<OLD>");
				fileToRename = fileToRename.replaceAll("&","&amp;");
				fileToRename = fileToRename.replaceAll("\"","&#148;");
				sb.append(fileToRename);
				sb.append("</OLD>");
				return sb;
			}					
		}
	}
	
	
	/**
	 * Generate the XML String for this mod
	 * @param runtimeData the runtime data channel object
	 * @throws ChannelException
	 */
	private void rename(ChannelRuntimeData runtimeData) throws ChannelException{
		String submit = runtimeData.getParameter("Submit");
		
		if (submit == null) {
			buffer.setFileToRename(null);
			throw new CancelException();
		}
		else {
			// we clicked on the validate button: we rename 
			String path = currentSpace.getCurrentPath();		
						
			String newName = runtimeData.getParameter("new_name");

			// log
			if (log.isDebugEnabled()){
				log.debug("rename"+" :: newName = "+newName);
			}
			
			this.currentSpace.getServerAccessObject().rename(buffer.getFileToRename(), newName, path);
			
			// if the file we are renaming is the default document of a space
			if (this.directoryProperties.getType().equals(MetaDataConstants.INJAC_TYPE_SPACE)) {
				if (this.directoryProperties.getRootDocumentName().equals(buffer.getFileToRename())) {
					MetaDataManager.setSpaceRootDocumentName(currentSpace, currentSpace.getCurrentPath(), newName);
					this.directoryProperties.setRootDocumentName(newName);
				}			
			}
			
			
			
			buffer.setFileToRename(null);						
		}
	}
		
	
	
	
	
	
	/**
	 * Generate the XML String for this mod
	 * @param runtimeData the runtime data channel object
	 * @return le XML pour ce mode
	 * @throws ChannelException
	 */
	private StringBuffer renderXmlConfirmDelete(ChannelRuntimeData runtimeData) throws ChannelException {
		// Xml generated
		StringBuffer xml = new StringBuffer();
		
		String[] filesToDelete = runtimeData.getParameterValues("listeFic");
		buffer.setFilesToDelete(filesToDelete);	
		if (filesToDelete == null) {
			// log
			if (log.isDebugEnabled()){
				log.debug("renderXmlConfirmDelete"+" :: NoneSelectedResourceException");
			}
			
			throw new NoneSelectedResourceException();			
		}
		
		else {
			
			//For each piece of the selection
			for (int j=0;j<filesToDelete.length;j++) {
				String fileName = filesToDelete[j];								
				
				// check if we are able to rename this resource
				String currentPath = this.currentSpace.getCurrentPath();
				String fullPath = currentPath+fileName;
				String directoryType = MetaDataManager.getDirectoryType(currentSpace, fullPath);
				
				// if injac document
				if (directoryType!=null && directoryType.equals(MetaDataConstants.INJAC_TYPE_DOCUMENT)) {
					
					// if we are not the document owner
					if (!(isUserDocumentOwner(fullPath, currentSpace, userPortalLogin) || directoryProperties.isUserEditor()) ) {					
						NotAuthorizedDeleteException e = new NotAuthorizedDeleteException();

						// log
						if (log.isDebugEnabled()){
							log.debug("renderXmlConfirmDelete"+" :: "+e);
						}
						
						throw e;
					}
					
				}
				
				// if injac space
				else if (directoryType!=null && directoryType.equals(MetaDataConstants.INJAC_TYPE_SPACE)) {
					
					// if we are not the space manager
					if (!directoryProperties.isUserManager()) {									
						NotAuthorizedDeleteException e = new NotAuthorizedDeleteException();

						// log
						if (log.isDebugEnabled()){
							log.debug("renderXmlConfirmDelete"+" :: "+e);
						}
						
						throw e;
					}					
					
				}
				
				
				//String path = currentSpace.getPath();			
				
				//check if it is a directory or a file
				boolean isDirectory = false;	
				if (directoryType==null) {
					isDirectory = this.currentSpace.getServerAccessObject().isDirectory(fileName, currentPath);
				}
				else {
					isDirectory = true;
				}
				if (isDirectory) {	
					
					//check if non empty
					boolean empty = this.currentSpace.getServerAccessObject().isEmpty(fileName, currentPath);														
					
					fileName = fileName.replaceAll("&","&amp;");
					fileName = fileName.replaceAll("\"","&#148;");
					xml.append("<DIR name=\""+fileName+"\" empty=\""+empty+"\"/>");									
				}
				
				else if (!isDirectory) {					
					fileName = fileName.replaceAll("&","&amp;");
					fileName = fileName.replaceAll("\"","&#148;");
					xml.append("<FILE name=\""+fileName+"\"/>");
				}		
			}
			return xml;					
		}
	}
	
		
	
	
	
	/**
	 * Generate the XML String for this mod
	 * @param runtimeData the runtime data channel object
	 * @throws ChannelException
	 */
	private void delete(ChannelRuntimeData runtimeData) throws ChannelException  {
		String submit = runtimeData.getParameter("Submit");
		
		if (submit == null) {
			throw new CancelException();
		}
			
		String path = currentSpace.getCurrentPath();	
		
		String[] filesToDelete = buffer.getFilesToDelete();
		
		for (int i=0; i<filesToDelete.length; i++) {
			String file = (String)filesToDelete[i];

			// log
			if (log.isDebugEnabled()){
				log.debug("delete"+" :: file = "+file);
			}
			
			this.currentSpace.getServerAccessObject().delete(file, path);				
		}
			
		buffer.setFilesToDelete(null);								
	} 
	
	
	
	
	

	/************************
	 *   Copy/Move methods
	 ************************/
		
	
	
	/**
	 * Generate the XML String for this mod
	 * @param mode used: copy or move
	 * @param runtimeData the runtime data channel object
	 * @throws NoneSelectedResourceException
	 * @throws ApplicationException
	 * @throws NotAuthorizedException
	 */
	private void setClipboard(String mode, ChannelRuntimeData runtimeData) throws NoneSelectedResourceException, ApplicationException, NotAuthorizedException, ServerException {			
		
		
		//check the files/directories from parameters
		String[] files = runtimeData.getParameterValues("listeFic");
		if (files == null) {
			NoneSelectedResourceException e = new NoneSelectedResourceException();

			// log
			if (log.isDebugEnabled()){
				log.debug("setClipboard"+" NoneSelectedResourceException");
			}

			throw e;			
		}		
		else {
			
			// we check if we are authorized to copy all selected resources			
			String tempPath = currentSpace.getCurrentPath();
			Vector types = new Vector(files.length);
			for (int j=0;j<files.length;j++) {
				String fileName = files[j];
				if (!this.currentSpace.getServerAccessObject().canRead(fileName, tempPath)) {
					
					// we erase the clipboard					
					buffer.setClipboard(null);
					buffer.setClipboardParameter(null);
					buffer.setClipboardPath(null);
					buffer.setClipboardSpace(null);
					buffer.setTypes(null);
					
					// we throw an exception
					NotAuthorizedException e = new NotAuthorizedException();

					// log
					if (log.isDebugEnabled()){
						log.debug("setClipboard"+" NotAuthorizedException");
					}

					throw e;					
				}
				
				else {	
					
					// check the role on each selected resource
					String type = MetaDataManager.getDirectoryType(this.currentSpace, tempPath+fileName);
					types.addElement(type);
					
					// if we are in a space
					if (directoryProperties.getType().equals(MetaDataConstants.INJAC_TYPE_SPACE)) {
						
						// if document
						if (type.equals(MetaDataConstants.INJAC_TYPE_DOCUMENT)) {
							
							// if not editor
							if (!this.directoryProperties.isUserEditor()) {
								
								// if not writer
								if (!this.directoryProperties.isUserWriter()) {
	
									// we throw an exception
									NotAuthorizedException e = new NotAuthorizedException();
	
									// log
									if (log.isDebugEnabled()){
										log.debug("setClipboard"+" not writer in space NotAuthorizedException");
									}
									throw e;
								}
								
								// if writer
								else {
									
									// if not owner
									if (!userPortalLogin.equals(MetaDataManager.getDocumentOwner(this.currentSpace, tempPath+fileName))) {
	
										// we throw an exception
										NotAuthorizedException e = new NotAuthorizedException();
	
										// log
										if (log.isDebugEnabled()){
											log.debug("setClipboard"+" not owner of the document in space NotAuthorizedException");
										}
										throw e;
									}
									
								}
								
							}
							
						}
						
						// if space
						else if (type.equals(MetaDataConstants.INJAC_TYPE_SPACE)){
							// the user is not manager
							if (!this.directoryProperties.isUserManager()) {
	
								// we throw an exception
								NotAuthorizedException e = new NotAuthorizedException();
	
								// log
								if (log.isDebugEnabled()){
									log.debug("setClipboard"+" not manager in space NotAuthorizedException");
								}
								throw e;
							}
						}
					}
				}
			}
			
			// if none NotAuthorizedException throwed
			
			// files/directories to copy			
			buffer.setClipboard(new Vector());
			buffer.setClipboardPath(currentSpace.getCurrentPath());
			buffer.setClipboardSpace(this.currentSpace);
			buffer.setTypes(types);
			
			for (int j=0;j<files.length;j++) {
				String fileName = files[j];

				// log
				if (log.isDebugEnabled()){
					log.debug("setClipboard"+" :: add "+fileName+" into the clipboard");
				}
				
				buffer.getClipboard().addElement(fileName);				
			}			
		}

		// log
		if (log.isDebugEnabled()){
			log.debug("setClipboard"+" :: setClipboardParameter("+mode+")");
		}
		
		buffer.setClipboardParameter(mode);
	}
	
	
	
	
	/**
	 * Generate the XML String for this mod
	 * @return the XML String for this mod
	 * @throws ChannelException
	 */
	private StringBuffer renderXmlConfirmPaste() throws ChannelException {
		
		// we check if we can paste here
		try {

			// log
			if (log.isDebugEnabled()){
				log.debug("renderXmlConfirmPaste"+" :: canPaste "+buffer.getClipboard()+" ?");
			}
				
			this.currentSpace.getServerAccessObject().canPaste(buffer.getClipboardSpace(), this.currentSpace.getKey(), buffer.getClipboardPath(), buffer.getClipboard(), buffer.getClipboard(), currentSpace.getCurrentPath());
		}
		catch (PasteDeletedResourceException e) {
			buffer.setClipboard(null);
			buffer.setClipboardParameter(null);
			buffer.setClipboardPath(null);
			buffer.setClipboardSpace(null);
			buffer.setTypes(null);
			
			// log
			if (log.isDebugEnabled()){
				log.debug("renderXmlConfirmPaste"+" :: "+e);
			}			
			
			throw e;
		}
		
		// Xml generated
		StringBuffer xml = new StringBuffer();
		
		//For each piece of the selection
		Vector clipboard = buffer.getClipboard();

		for (int j=0;j<clipboard.size();j++){
			String fileName = (String)clipboard.elementAt(j);				
			
			//check if it is a directory or a file
			boolean isDirectory = buffer.getClipboardSpace().getServerAccessObject().isDirectory(fileName, buffer.getClipboardPath());								
	
			if (isDirectory) {	
				
				//check if non empty
				boolean empty = buffer.getClipboardSpace().getServerAccessObject().isEmpty(fileName, buffer.getClipboardPath());														
				
				if (!empty) {
					fileName = fileName.replaceAll("&","&amp;");
					fileName = fileName.replaceAll("\"","&#148;");
					xml.append("<DIR name=\""+fileName+"\" empty=\""+false+"\"/>");
				}
				else if (empty) {											
					fileName = fileName.replaceAll("&","&amp;");
					fileName = fileName.replaceAll("\"","&#148;");
					xml.append("<DIR name=\""+fileName+"\" empty=\""+true+"\"/>");
				}
			}				
			else if (!isDirectory) {				
				fileName = fileName.replaceAll("&","&amp;");
				fileName = fileName.replaceAll("\"","&#148;");
				xml.append("<FILE name=\""+fileName+"\"/>");
			}
		}
			
		return xml;							
	}
	
	
	/**
	 * Generate the XML String for this mod
	 * @param runtimeData the runtime data channel object
	 * @return the XML String for this mod
	 * @throws ChannelException
	 */
	private StringBuffer paste(ChannelRuntimeData runtimeData) throws ChannelException {
		String submit = runtimeData.getParameter("Submit");
		
		Vector clipboard = buffer.getClipboard();
		Vector types = buffer.getTypes();
		String clipboardPath = buffer.getClipboardPath();
		String clipboardParameter = buffer.getClipboardParameter();
		Space clipboardSpace = buffer.getClipboardSpace();
		
		// if submit
		if (submit != null) {
			
			// if we are in a space
			if (this.directoryProperties.getType().equals(MetaDataConstants.INJAC_TYPE_SPACE)) {
				
				if (types==null || types.size()==0) {
					CopyException ex = new CopyException();
					log.error("paste"+" :: types of resources is empty "+ex);
					throw ex;
				}
				
				// for each element
				else {
					for (int i=0; i<clipboard.size(); i++) {
						String clipboardElement = ((String)clipboard.elementAt(i));
						String type = (String)types.elementAt(i);
						
						boolean unpublish = false;
						
						// check if we can paste here
						if (type.equals(MetaDataConstants.INJAC_TYPE_SPACE)) {
							
							// if user is manager
							if (directoryProperties.isUserManager()) {
								
							}
							
							// if user is not manager
							else {
								NotManagerInSpaceException ex = new NotManagerInSpaceException();
								log.error("paste"+" :: the user is not manager on space "+ex);
								throw ex;
							}
							
						}
						
						// if the directory is a document
						else if (type.equals(MetaDataConstants.INJAC_TYPE_DOCUMENT)) {
							
							// if user is manager
							if (directoryProperties.isUserWriter()) {
								
								// check the status of the document
								String status = MetaDataManager.getDocumentState(buffer.getClipboardSpace(), buffer.getClipboardPath()+clipboardElement);
								if (status.equals(MetaDataConstants.DOCUMENT_PUBLISHED_STATE)) {

									// if we are not editor in the space
									if (!this.directoryProperties.isUserEditor()) {
										unpublish = true;
									}
									
									// if the metadata profile is different here than the original space
									else {
										
										String metadataProfileTo = null;
										if (directoryProperties.getMetadataList()!=null) {
											metadataProfileTo = directoryProperties.getMetadataList().getStringToParse();
										}
										else {
											metadataProfileTo = MetaDataManager.getMetadataSpaceProfile(currentSpace, currentSpace.getCurrentPath());
										}
										String metadataProfileFrom = MetaDataManager.getMetadataSpaceProfile(buffer.getClipboardSpace(), buffer.getClipboardPath());
										
										if (!metadataProfileFrom.equals(metadataProfileTo)) {
											unpublish = true;
										}
									}
									

								}
								
							}
							
							// if user is not manager
							else {
								NotWriterInSpaceException ex = new NotWriterInSpaceException();
								log.error("paste"+" :: the user is not writer on space "+ex);
								throw ex;
							}
						}
						
						// neither space or document
						else {
							InjacDocumentException ex = new InjacDocumentException();
							log.error("paste"+" :: the resource is neither a space or a document "+ex);
							throw ex;
						}
						
						
						// do the copy
						if (clipboardParameter.equals(Constants.COPY_MODE)) {
		
							// log
							if (log.isDebugEnabled()){
								log.debug("paste"+" :: copy clipboardElement = "+clipboardElement);
							}
		
							this.currentSpace.getServerAccessObject().copy(clipboardElement, clipboardElement, clipboardSpace, clipboardPath, currentSpace.getKey(), currentSpace.getCurrentPath());
						}
						
						// do the move
						else {
		
							// log
							if (log.isDebugEnabled()){
								log.debug("paste"+" :: move clipboardElement = "+clipboardElement);
							}
		
							this.currentSpace.getServerAccessObject().move(clipboardElement, clipboardElement, clipboardSpace, clipboardPath, currentSpace.getKey(), currentSpace.getCurrentPath());
						}
						
						// unpublish
						if (unpublish) {
							MetaDataManager.setDirectoryAsWaitingDocument(this.currentSpace, currentSpace.getCurrentPath()+clipboardElement);
						}
					}
				}
				
			}
			
			// if we are not in a space
			else {
				
				for (int i=0; i<clipboard.size(); i++) {
					String clipboardElement = ((String)clipboard.elementAt(i));
					
					if (clipboardParameter.equals(Constants.COPY_MODE)) {
	
						// log
						if (log.isDebugEnabled()){
							log.debug("paste"+" :: copy clipboardElement = "+clipboardElement);
						}
	
						this.currentSpace.getServerAccessObject().copy(clipboardElement, clipboardElement, clipboardSpace, clipboardPath, currentSpace.getKey(), currentSpace.getCurrentPath());
					}
					else {
	
						// log
						if (log.isDebugEnabled()){
							log.debug("paste"+" :: move clipboardElement = "+clipboardElement);
						}
	
						this.currentSpace.getServerAccessObject().move(clipboardElement, clipboardElement, clipboardSpace, clipboardPath, currentSpace.getKey(), currentSpace.getCurrentPath());
					}						
				}	
			}
		}
		
		// if cancel
		else {
			CancelException e = new CancelException();

			// log
			if (log.isDebugEnabled()){
				log.debug("paste"+" :: CancelException");
			}
			
			throw e;			
		}				
		
		
		
		// if well done
		if (clipboardParameter.equals(Constants.COPY_MODE)) {			
			/*
			// if we want to set empty the clipboard
			clipboard = null;
			clipboardParameter = null;
			clipboardPath = null;
			*/
			return DefaultRenderXml.getXml(spaces, currentSpace, null, "2005", userPortalLogin, userGroups, directoryProperties, this.buffer.getCurrentSortType());	
		}
		else {
			buffer.setClipboard(null);
			buffer.setClipboardParameter(null);
			buffer.setClipboardPath(null);
			buffer.setClipboardSpace(null);
			buffer.setTypes(null);
			return DefaultRenderXml.getXml(spaces, currentSpace, null, "2006", userPortalLogin, userGroups, directoryProperties, this.buffer.getCurrentSortType());	
		}
	}
	
	
	

	
	/************************
	 *    Submit methods
	 ************************/
	
	/**
	 * When we choose the mode for the submit, we verify the choice
	 * @param runtimeData the ChannelRuntimeData object
	 * @throws CancelException
	 * @throws ChannelException
	 */
	private StringBuffer verifyChoiceForSubmitMode(ChannelRuntimeData runtimeData) throws CancelException, ChannelException {
		
		// if we choose the clipboard
		if (runtimeData.getParameter("clipboard")!=null) {
			stylesheet = new StringBuffer("confirmSubmit");												
			return DocumentEditionAction.renderXmlConfirmSubmit(runtimeData, buffer, stylesheet, spaces, metadatasToSet, userPortalLogin, userGroups, currentSpace, directoryProperties);
		}

		
		else {
			// if we choose the upload
			if (runtimeData.getParameter("upload")!=null) {
				stylesheet = new StringBuffer("setFileToUploadForSubmit");
				return new StringBuffer();
			}
			
			// cancel
			else {
				CancelException e = new CancelException();

				// log
				if (log.isDebugEnabled()){
					log.debug("verifyChoiceForSubmitMode"+" :: "+e);
				}
				throw e;
			}
		}
		
		
		
	}
	
	
	
	

	
	/************************
	 *    Publish methods
	 ************************/
	
	/**
	 * When we choose the mode for the publication, we verify the choice
	 * @param runtimeData the ChannelRuntimeData object
	 * @throws CancelException
	 * @throws ChannelException
	 */
	private StringBuffer verifyChoiceForPublishMode(ChannelRuntimeData runtimeData) throws CancelException, ChannelException {
		
		// if we choose the clipboard
		if (runtimeData.getParameter("clipboard")!=null) {
			stylesheet = new StringBuffer("confirmPublish");												
			return DocumentPublicationAction.renderXmlConfirmPublish(runtimeData, buffer, stylesheet, spaces, metadatasToSet, userPortalLogin, userGroups, currentSpace, directoryProperties);
		}

		
		else {
			// if we choose the upload
			if (runtimeData.getParameter("upload")!=null) {
				stylesheet = new StringBuffer("setFileToUploadForPublish");
				return new StringBuffer();
			}
			
			// cancel
			else {
				CancelException e = new CancelException();

				// log
				if (log.isDebugEnabled()){
					log.debug("verifyChoiceForPublishMode"+" :: "+e);
				}
				throw e;
			}
		}
		
		
		
	}
	
	
	

	
	/************************
	 * Space admin methods
	 ************************/
	
	
	
	/**
	 * If we are creating a new Space
	 */
	private boolean creatingNewSpace = false;
	
	/**
	 * The name of the new space while creating
	 */
	private String creatingNewSpaceName = null;
	

	/**
	 * The vector used to add people when we use a servant channel
	 */
	private Vector userTypeForAdd;

	/**
	 * The name of user type for add: reader_group, ... ?
	 */
	private String userTypeForAddName;
	
	
	/**
	 * Return XML for the space administration mode 
	 * @param runtimeData
	 * @param staticData
	 * @param out
	 * @return XML for the space administration mode 
	 * @throws PortalException
	 * @throws ChannelException
	 */
	private StringBuffer renderXmlAdminSpace(ChannelRuntimeData runtimeData, ChannelStaticData staticData, ContentHandler out) throws PortalException, ChannelException {				

		if (!currentSpace.managesAcl()) {
			log.error("renderXmlAdminSpace"+" :: the acl are not supported");
			throw new NotSupportedAclException();
		}
		
		try {
		
			// the SpaceManagementProperties object used here		
			if (smp == null) {
				
				if (creatingNewSpace==true) {
					if (this.currentSpace.getServerAccessObject().exists(creatingNewSpaceName, this.currentSpace.getCurrentPath())) {
						
						creatingNewSpaceName = null;
						smp = null;
						
						StillExistsException e = new StillExistsException();

						// log
						if (log.isDebugEnabled()){
							log.debug("renderXmlAdminSpace"+" :: "+e);
						}
						throw e;						
					}
					else {
						smp = InjacSpaceManagementProperties.getProperties(currentSpace, directoryProperties, true);
					}
					smp.setTitle(creatingNewSpaceName);
					smp.setDescription("");
				}
				
				else {
					smp = InjacSpaceManagementProperties.getProperties(currentSpace, directoryProperties, false);
					if (smp.getTitle()==null || smp.getTitle().trim().equals("")) {
						smp.setTitle(currentSpace.getPathElementAt(currentSpace.getPathSize()-1));
					}
				}
				
			}
					
			// if we change the metadata file
			String metadataFile = runtimeData.getParameter("metadataFile");
			if (metadataFile!=null)
				adminSpaceChangeMetadataFile(metadataFile);			
			
			// if we change the metadata file
			String renderingType = runtimeData.getParameter("renderingType");
			if (renderingType!=null)
				adminSpaceChangeRenderType(renderingType);	
			
			// if change "public" or "not public"
			String pub = runtimeData.getParameter("change_public");
			if (pub!=null && pub.equals("true")) {
				if (smp.isPublicReading())
					smp.setPublicReading(false);
				else {
					smp.setPublicReading(true);
				}
			}
			

			// if change the title
			String title = runtimeData.getParameter("title");
			if (title!=null) {
				smp.setTitle(title);
			}
			
			// if change the description
			String description = runtimeData.getParameter("description");
			if (description!=null) {
				smp.setDescription(description);
			}
			
			
			// if we click on "valid" or "cancel"
			String action = runtimeData.getParameter("adminAction");
			if (action!=null && !action.equals("")) {
				if (action.equals("cancel"))
					return renderXmlAdminSpaceCancel();
				else if (action.equals("valid"))
					return renderXmlAdminSpaceValid(runtimeData);
				else return renderXmlAdminSpaceGenerateXml();
			}
		
			else {
				
				// if click on delete
				adminSpaceDelete(runtimeData);
				
				// if click on add
				boolean add = adminSpaceAdd(runtimeData, staticData, out);
		
				if (add)
					return null;
				else return renderXmlAdminSpaceGenerateXml();
			}
		}
		catch(ChannelException e) {			
			creatingNewSpaceName = null;
			smp = null;
			
			// log
			if (log.isDebugEnabled()){
				log.debug("renderXmlAdminSpace"+" :: "+e);
			}
			throw e;
		}
		catch(PortalException e) {			
			creatingNewSpaceName = null;
			smp = null;

			// log
			if (log.isDebugEnabled()){
				log.debug("renderXmlAdminSpace"+" :: "+e);
			}	
			throw e;
		}
	}
	
	
	
	
	/**
	 * When click on cancel
	 * @return the xml when we click on cancel
	 * @throws CancelException
	 */
	private StringBuffer renderXmlAdminSpaceCancel() throws CancelException {
		this.smp = null;
		this.creatingNewSpace = false;
		
		CancelException e = new CancelException();

		// log
		if (log.isDebugEnabled()){
			log.debug("renderXmlAdminSpaceCancel"+" :: "+e);
		}
		throw e;
	}
	
	
	
	/**
	 * When valid the properties
	 * @param runtimeData
	 * @return xml when we set the properties
	 * @throws ChannelException
	 */
	private StringBuffer renderXmlAdminSpaceValid(ChannelRuntimeData runtimeData) throws ChannelException {
		
		// to access the server
		ServerAccess access = this.currentSpace.getServerAccessObject();				
		
		// the resource path
		String path = this.currentSpace.getCurrentPath();
		
		// if we are creating a new Space
		if (creatingNewSpace) {
			
			// we create a directory and fix the metadata to it to know that it is a space			
			try {
				access.createDir(this.creatingNewSpaceName, path);				
				boolean wellDone = MetaDataManager.setDirectoryAsSpace(currentSpace, path+this.creatingNewSpaceName);				
				if (!wellDone) {
					access.delete(this.creatingNewSpaceName, path);
				}
			}
			catch(ServerException e) {
				this.smp = null;
				this.creatingNewSpace = false;

				// log
				if (log.isDebugEnabled()){
					log.debug("renderXmlAdminSpaceValid"+" :: "+e);
				}				
				throw new CreateDirectoryException();
			}
			catch(DeleteException e) {
				this.smp = null;
				this.creatingNewSpace = false;

				// log
				if (log.isDebugEnabled()){
					log.debug("renderXmlAdminSpaceValid"+" :: "+e);
				}
				throw new CreateDirectoryException();
			}
			catch(NotAuthorizedDeleteException e) {
				this.smp = null;
				this.creatingNewSpace = false;

				// log
				if (log.isDebugEnabled()){
					log.debug("renderXmlAdminSpaceValid"+" :: "+e);
				}
				throw new CreateDirectoryException();
			}
			
			path = this.currentSpace.getCurrentPath()+this.creatingNewSpaceName;			
		}			
		
		try {
			// set the metadata
			boolean wellDone = MetaDataManager.setMetadataOnSpace(currentSpace, path, smp);
		
			if (!wellDone) {
				this.smp = null;
				this.creatingNewSpace = false;
			
				ApplicationException e = new ApplicationException();

				// log
				if (log.isDebugEnabled()){
					log.debug("renderXmlAdminSpaceValid"+" :: "+e);
				}
				throw e;
			}
		
			// set the ACL
			InjacAclManager.setReadersAclOnSpace(this.currentSpace, path, smp);
							
			this.setCurrentDirectoryProperties();
			this.smp = null;
		
			// if space creation
			if (creatingNewSpace) {
				creatingNewSpace = false;
				stylesheet = new StringBuffer("CStockage");
				return DefaultRenderXml.getXml(spaces, currentSpace, null, "2009", userPortalLogin, userGroups, directoryProperties, this.buffer.getCurrentSortType());
			}
		
			// if metadata modification
			else {
				this.creatingNewSpace = false;
				stylesheet = new StringBuffer("CStockage");
				return DefaultRenderXml.getXml(spaces, currentSpace, null, "2008", userPortalLogin, userGroups, directoryProperties, this.buffer.getCurrentSortType());
			}
			
			
		}
		catch(ChannelException e) {
			this.smp = null;
			this.creatingNewSpace = false;

			// log
			if (log.isDebugEnabled()){
				log.debug("renderXmlAdminSpaceValid"+" :: "+e);
			}
			throw e;
		}
	}
	
	
	
	
	/**
	 * When we change the metadata file
	 * @param choice the metadata file choice
	 * @throws PropertiesException
	 */
	private void adminSpaceChangeMetadataFile(String choice) throws PropertiesException {
		this.smp.setSelectedMetadataProfile(choice);
	}
	
	

	/**
	 * When we change the rendering type
	 * @param choice the rendering type choice
	 * @throws PropertiesException
	 */
	private void adminSpaceChangeRenderType(String choice) throws PropertiesException {
		this.smp.setSelectedRenderingType(choice);
	}
	
	
	
	/**
	 * When we want to add a user or a group
	 * @param runtimeData the runtime data object used in this channel
	 * @param staticData the static data object used in this channel
	 * @param out the output object used for the rendering
	 * @return true is we clicked on add, else false
	 * @throws PropertiesException
	 * @throws PortalException
	 */
	private boolean adminSpaceAdd(ChannelRuntimeData runtimeData, ChannelStaticData staticData, ContentHandler out) throws PropertiesException, PortalException {		

		userTypeForAddName= null;
		
		// check wich vector we have to use		
		if (runtimeData.getParameter("add_reader_group") != null) {
			userTypeForAdd = smp.getModifiedReaderGroups();
			userTypeForAddName= "reader_group";
		}
		else {
			if (runtimeData.getParameter("add_reader_user") != null) {
				userTypeForAdd = smp.getModifiedReaderUsers();
				userTypeForAddName= "reader_user";
			}
			else {
				if (runtimeData.getParameter("add_writer_group") != null) {
					userTypeForAdd = smp.getWriterGroups();
					userTypeForAddName= "writer_group";
				}
				else {
					if (runtimeData.getParameter("add_writer_user") != null) {
						userTypeForAdd = smp.getWriterUsers();
						userTypeForAddName= "writer_user";
					}
					else {
						if (runtimeData.getParameter("add_editor_group") != null) {
							userTypeForAdd = smp.getEditorGroups();
							userTypeForAddName= "editor_group";
						}
						else {
							if (runtimeData.getParameter("add_editor_user") != null) {
								userTypeForAdd = smp.getEditorUsers();
								userTypeForAddName= "editor_user";
							}
							else {
								if (runtimeData.getParameter("add_manager_group") != null) {
									userTypeForAdd = smp.getManagerGroups();
									userTypeForAddName= "manager_group";
								}
								else {
									if (runtimeData.getParameter("add_manager_user") != null) {
										userTypeForAdd = smp.getManagerUsers();	
										userTypeForAddName= "manager_user";
									}
								}
							}
						}
					}
				}
			}
		}
		
		// if we didn't click on "add"
		if (userTypeForAddName==null) {
			return false;
		}
		
		// check if we want to choice a group or a user
		if (userTypeForAddName.endsWith("group")) {		
			slave = CGroupsManagerServantFactory.getGroupsServantforSelection(staticData, null, GroupService.EVERYONE, true, true);
		}
		else {
			staticData.setParameter("returnServant", "multiple");
			slave = CAnnuaireServantFactory.getAnnuaireServant(staticData);
		}
		slave.setRuntimeData(runtimeData);		
		slave.renderXML(out);
		
		return true;
	}
	
	
	
	/**
	 * When we check the servant results
	 * @param staticData the static data object used in this channel
	 * @return the xml after getting the servant results
	 * @throws PropertiesException
	 */
	private StringBuffer renderXmlAdminSpaceValidServantResults(ChannelStaticData staticData) throws PropertiesException {
		
		// get the results
		Object[] objs = slave.getResults();
		if (objs!=null) {
			for (int i=0; i<objs.length; i++) {
				Object obj = objs[i];
			
				// if we have a people from the CAnnuaire servant
				if (obj instanceof org.esupportail.portal.channels.CAnnuaire.Personne) {
					org.esupportail.portal.channels.CAnnuaire.Personne pers = (org.esupportail.portal.channels.CAnnuaire.Personne)obj;
					
					UserForPersonalization user = new UserForPersonalization(pers);
					user.getPersonalization().setInheritedAcl(false);
					user.getPersonalization().setReading(1);
				
					// if there still this user in the list
					if (!userTypeForAdd.contains(user)){
						userTypeForAdd.add(user);
					}
					
					// if user reader
					/*if (userTypeForAddName.equals("reader_user")) {
						
						if (!smp.getModifiedReaderUsers().contains(user)) {
							smp.getModifiedReaderUsers().add(user);
						}						
					}*/

				}
			
				// if we have a group from the CGroupManager servant
				else if (obj instanceof org.jasig.portal.groups.EntityGroupImpl) {
					EntityGroupImpl egi = (EntityGroupImpl)obj;
					String leafType = egi.getLeafType().getName();
				
					// if the selection is really a group of persons
					if (leafType.equals("org.jasig.portal.security.IPerson")) {					
					
						try {
							GroupForPersonalization group = new GroupForPersonalization(egi);
							group.getPersonalization().setInheritedAcl(false);
							group.getPersonalization().setReading(1);
							
							// if there still this group in the list
							if (!userTypeForAdd.contains(group)){
								userTypeForAdd.add(group);
							}	

							// if group reader
							/*if (userTypeForAddName.equals("reader_group")) {
								
								if (!smp.getModifiedReaderGroups().contains(group)) {
									smp.getModifiedReaderGroups().add(group);
								}
								
							}*/
						}
						catch(ServerException e) {							
							log.error("renderXmlAdminSpaceValidServantResults"+" :: "+e);							
						}
					}
				}									
			}
		}
		
		slave = null;		
		staticData.setParameter("groupManagerFinished", "false");	
		return renderXmlAdminSpaceGenerateXml();
	}
	
	
	
	/**
	 * When we delete a user or a group
	 * @param runtimeData the runtime data object used in the channel
	 * @throws PropertiesException
	 */
	private void adminSpaceDelete(ChannelRuntimeData runtimeData) throws PropertiesException {
		
		// the vector we have to use
		Vector vector = null;
		String[] selection = null;	
		
		boolean isGroup = false;
		
		// check wich vector we have to use
		if (runtimeData.getParameter("delete_reader_group") != null) {
			vector = smp.getModifiedReaderGroups();
			selection = runtimeData.getParameterValues("reader_group_list");
			isGroup = true;
		}
		else {
			if (runtimeData.getParameter("delete_reader_user") != null) {
				vector = smp.getModifiedReaderUsers();
				selection = runtimeData.getParameterValues("reader_user_list");
			}
			else {
				if (runtimeData.getParameter("delete_writer_group") != null) {
					vector = smp.getWriterGroups();
					selection = runtimeData.getParameterValues("writer_group_list");
					isGroup = true;
				}
				else {
					if (runtimeData.getParameter("delete_writer_user") != null) {
						vector = smp.getWriterUsers();
						selection = runtimeData.getParameterValues("writer_user_list");
					}
					else {
						if (runtimeData.getParameter("delete_editor_group") != null) {
							vector = smp.getEditorGroups();
							selection = runtimeData.getParameterValues("editor_group_list");
							isGroup = true;
						}
						else {
							if (runtimeData.getParameter("delete_editor_user") != null) {
								vector = smp.getEditorUsers();
								selection = runtimeData.getParameterValues("editor_user_list");
							}
							else {
								if (runtimeData.getParameter("delete_manager_group") != null) {
									vector = smp.getManagerGroups();
									selection = runtimeData.getParameterValues("manager_group_list");
									isGroup = true;
								}
								else {
									if (runtimeData.getParameter("delete_manager_user") != null) {
										vector = smp.getManagerUsers();
										selection = runtimeData.getParameterValues("manager_user_list");
									}
								}
							}
						}
					}
				}
			}
		}
		

		// if none selected
		if (selection==null || selection.length==0)
			return;
		
		
		
		
		
		
		boolean canDelete = true;
		
		// can not delete all managers
		String deleteManagerGroup = runtimeData.getParameter("delete_manager_group");
		String deleteManagerUser = runtimeData.getParameter("delete_manager_user");
		if (deleteManagerGroup!=null || deleteManagerUser!=null) {
			Vector managerUsers = smp.getManagerUsers();
			Vector managerGroups = smp.getManagerGroups();
			int total = managerGroups.size()+managerUsers.size();
			
			if (total-selection.length <= 0)
				canDelete = false;
		}
		
		// delete
		if (canDelete) {
			for (int i=selection.length-1; i>=0; i--) {
				
				// the key
				String key = selection[i];
				
				// delete
				if (isGroup) {
					try {
						vector.remove(new Group(key, key));
					}
					catch(ServerException e) {
						log.error("renderXmlAdminSpaceDelete"+" :: "+e);
					}
				}
				else {
					vector.remove(new User(key, key));
				}
				
				// if user reader
				/*if (isReaderUser) {
					UserForPersonalization u = new UserForPersonalization(key, key);
					
					if (smp.getModifiedReaderUsers().contains(u)) {
						smp.getModifiedReaderUsers().remove(u);
					}
					//else smp.getDeletedReaderUsers().add(u);
					
				}*/

				// if group reader
				/*if (isReaderGroup) {
					try {
						GroupForPersonalization g = new GroupForPersonalization(key, key);
						
						if (smp.getModifiedReaderGroups().contains(g)) {
							smp.getModifiedReaderGroups().remove(g);
						}
						//else smp.getDeletedReaderGroups().add(g);
					}
					catch(ServerException e) {
						log.error("renderXmlAdminSpaceDelete"+" :: "+e);
					}
				}*/
				
			}
		}
	}
	
	
	
	
	
	
	/**
	 * Generate xml for the administration rendering
	 * @return the xml for the administration rendering
	 * @throws PropertiesException
	 */
	private StringBuffer renderXmlAdminSpaceGenerateXml() throws PropertiesException {

		// the xml generated
		String xml = "";		
		
		// the space name
		xml += "<space name=\"";
		for (int i=0; i<currentSpace.getPathSize(); i++) {			
			if (i!=0)
				xml += " > ";
			String n = currentSpace.getPathElementAt(i);			
			n = n.replaceAll("&","&amp;");
			n = n.replaceAll("\"","&#148;");			
			xml += (n);
		}
		
		if (this.creatingNewSpace) {
			xml += (" > ");
			String n = this.creatingNewSpaceName;
			n = n.replaceAll("&","&amp;");
			n = n.replaceAll("\"","&#148;");			
			xml += (n);
		}
		
		xml += ("\"/>");
		
		
		// generate the XML

		// title
		String title = smp.getTitle();
		xml += ("\n<title>");
		title = title.replaceAll("&","&amp;");
		title = title.replaceAll("\"","&#148;");
		xml += (title);
		xml += ("</title>\n");
		
		// description
		String description = smp.getDescription();
		xml += ("\n<description>");
		description = description.replaceAll("&","&amp;");
		description = description.replaceAll("\"","&#148;");
		xml += (description);
		xml += ("</description>\n");
		
		// metadata list
		ArrayList metadataProfiles = smp.getAvailableMetadataProfiles();
		String selectedProfile = smp.getSelectedMetadataProfile();
		xml += ("<metadata>\n");
		for (int i=0; i<metadataProfiles.size(); i++) {
			MetadataFileProfile mdp = (MetadataFileProfile)metadataProfiles.get(i);
			String label = mdp.getLabel();			
			if (selectedProfile.equals(mdp.getFileName()))
				xml += ("<md name=\""+mdp.getFileName()+"\" label=\""+label+"\" default=\"true\"   />\n");
			else xml += ("<md name=\""+mdp.getFileName()+"\" label=\""+label+"\" />\n");
		}		
		xml += ("</metadata>\n");
		
		// rendering type
		ArrayList renderingTypes = smp.getAvailableRenderingTypes();
		String selectedRenteringType = smp.getSelectedRenderingType();
		xml += ("<renderingType>\n");
		for (int i=0; i<renderingTypes.size(); i++) {
			RenderingType rt = (RenderingType)renderingTypes.get(i);
			if (selectedRenteringType.equals(rt.getSkinFile()))
				xml += ("<render name=\""+rt.getSkinFile()+"\" label=\""+rt.getLabel()+"\" default=\"true\"   />\n");
			else xml += ("<render name=\""+rt.getSkinFile()+"\" label=\""+rt.getLabel()+"\" />\n");
		}		
		xml += ("</renderingType>\n");
		
		// writers
		xml += ("<writer>\n");
		xml += ("<groups>\n");
		Vector writersGrp = smp.getWriterGroups();
		for (int i=0; i<writersGrp.size(); i++) {
			Group g = (Group)writersGrp.elementAt(i);
			xml += ("<group key=\""+g.getKey()+"\" name=\""+g.getDisplayName()+"\"/>\n");
		}
		xml += ("</groups>\n");
		xml += ("<users>\n");
		Vector writersUsr = smp.getWriterUsers();
		for (int i=0; i<writersUsr.size(); i++) {
			User u = (User)writersUsr.elementAt(i);
			xml += ("<user key=\""+u.getKey()+"\" name=\""+u.getDisplayName()+"\"/>\n");
		}
		xml += ("</users>\n");
		xml += ("</writer>\n");
		
		//editors
		xml += ("<editor>\n");
		xml += ("<groups>\n");
		Vector editorsGrp = smp.getEditorGroups();
		for (int i=0; i<editorsGrp.size(); i++) {
			Group g = (Group)editorsGrp.elementAt(i);
			xml += ("<group key=\""+g.getKey()+"\" name=\""+g.getDisplayName()+"\"/>\n");
		}
		xml += ("</groups>\n");
		xml += ("<users>\n");
		Vector editorsUsr = smp.getEditorUsers();
		for (int i=0; i<editorsUsr.size(); i++) {
			User u = (User)editorsUsr.elementAt(i);
			xml += ("<user key=\""+u.getKey()+"\" name=\""+u.getDisplayName()+"\"/>\n");
		}
		xml += ("</users>\n");
		xml += ("</editor>\n");
		
		//managers
		xml += ("<manager>\n");
		xml += ("<groups>\n");
		Vector managersGrp = smp.getManagerGroups();
		for (int i=0; i<managersGrp.size(); i++) {
			Group g = (Group)managersGrp.elementAt(i);
			xml += ("<group key=\""+g.getKey()+"\" name=\""+g.getDisplayName()+"\"/>\n");
		}
		xml += ("</groups>\n");
		xml += ("<users>\n");
		Vector managersUsr = smp.getManagerUsers();
		for (int i=0; i<managersUsr.size(); i++) {
			User u = (User)managersUsr.elementAt(i);
			xml += ("<user key=\""+u.getKey()+"\" name=\""+u.getDisplayName()+"\"/>\n");
		}		
		xml += ("</users>\n");
		xml += ("</manager>\n");
		
		
		// readers
		boolean pub = smp.isPublicReading();
		xml += ("<reader public=\""+pub+"\">\n");
		//if (!pub) {
		
		xml += ("<users>\n");
		Vector readersUsr = smp.getModifiedReaderUsers();
		for (int i=0; i<readersUsr.size(); i++) {
			UserForPersonalization user = (UserForPersonalization)readersUsr.elementAt(i);
			//xml += ("<user key=\""+u.getKey()+"\" name=\""+u.getDisplayName()+"\"/>\n");
			xml += "<user key=\""+user.getKey()+"\" name=\""+user.getDisplayName()+"\" modifiable=\""+user.getPersonalization().isModifiable()+"\" inherited=\""+user.getPersonalization().isInheritedAcl()+"\"/>\n";
		}			
		xml += "</users>\n";	
		
		xml += ("<groups>\n");
			Vector readersGrp = smp.getModifiedReaderGroups();
			for (int i=0; i<readersGrp.size(); i++) {
				GroupForPersonalization group = (GroupForPersonalization)readersGrp.elementAt(i);
				//xml += ("<group key=\""+g.getKey()+"\" name=\""+g.getDisplayName()+"\"/>\n");
				xml += "<group key=\""+group.getKey()+"\" name=\""+group.getDisplayName()+"\" modifiable=\""+group.getPersonalization().isModifiable()+"\" inherited=\""+group.getPersonalization().isInheritedAcl()+"\"/>\n";
			}
		xml += ("</groups>\n");
		
		xml += ("<others>\n");
		Vector readersOth = smp.getModifiedReaderOthers();
		for (int i=0; i<readersOth.size(); i++) {
			OtherPrincipalForPersonalization group = (OtherPrincipalForPersonalization)readersOth.elementAt(i);
			xml += "<other key=\""+group.getKey()+"\" name=\""+group.getDisplayName()+"\" modifiable=\""+group.getPersonalization().isModifiable()+"\" inherited=\""+group.getPersonalization().isInheritedAcl()+"\"/>\n";
		}
		xml += ("</others>\n");
		
		
		//}
		xml += ("</reader>\n");
		
		
		//System.out.println(xml+"\n");
		
		StringBuffer sb = new StringBuffer(xml);
		
		return sb;
	}
	
	
	
	/**
	 * Generate the xml for the creating space mod
	 * @param runtimeData the runtime data channel object
	 * @param staticData the static data channel object
	 * @param out the object used for the rendering
	 * @return the xml for the creating space mod
	 * @throws ChannelException
	 * @throws PortalException
	 */	
	private StringBuffer createSpace(ChannelRuntimeData runtimeData, ChannelStaticData staticData, ContentHandler out) throws ChannelException, PortalException {
		String submit = runtimeData.getParameter("Submit_create");
		
		if (submit == null) {
			CancelException e = new CancelException();

			// log
			if (log.isDebugEnabled()){
				log.debug("createSpace"+" :: "+e);
			}
			throw e;
		} 
		
		else {
			
			// we are creating a new space
			this.creatingNewSpace = true;
			
			// the new space name
			this.creatingNewSpaceName = runtimeData.getParameter("spaceName");
			
			// if name is well formed
			boolean wellFormed = ResourceControl.isWellFormed(creatingNewSpaceName);
        	if ( !wellFormed ) {
        		this.creatingNewSpace = false;

    			// log
    			if (log.isDebugEnabled()){
    				log.debug("createSpace"+" :: "+creatingNewSpaceName+" not well formed");
    			}
            	throw new BadFormatException();
        	}
			
        	stylesheet = new StringBuffer("adminSpace");
        	return renderXmlAdminSpace(runtimeData, staticData, out);
        	        	
		}
	}


	
	
	
	
	

	/**
	 * Generate the XML when we ask a root document setting confirmation
	 * @param runtimeData the channel runtimedata object
	 * @return the XML String for this mod
	 * @throws ChannelException
	 */
	private StringBuffer renderXmlConfirmRootDocumentSetting(ChannelRuntimeData runtimeData) throws ChannelException {
		
		String[] files = runtimeData.getParameterValues("listeFic");

		// Xml generated
		StringBuffer xml = new StringBuffer();
		
		// if not selected
		if (files == null || files.length==0) {						
			NoneSelectedResourceException e = new NoneSelectedResourceException();

			// log
			if (log.isDebugEnabled()){
				log.debug("renderXmlConfirmRootDocumentSetting"+" :: NoneSelectedResourceException");
			}
			
			throw e;			
		}
		
		// if too much selected
		if (files.length>1) {			
			TooMuchSelectedException e = new TooMuchSelectedException();

			// log
			if (log.isDebugEnabled()){
				log.debug("renderXmlConfirmRootDocumentSetting"+" :: TooMuchSelectedException");
			}
			
			throw e;			
		}
		
		// if one resource selected
		String selectionName = files[0];
		String selectionPath = currentSpace.getCurrentPath();
		String selectionFullPath = selectionPath+selectionName;
		
		// check if the resource is an injac document
		String documentType = MetaDataManager.getDirectoryType(currentSpace, selectionFullPath);
		if (documentType.equals(MetaDataConstants.INJAC_TYPE_DOCUMENT)) {
					
			
			// check if the resource state is "published"
			String documentState = MetaDataManager.getDocumentState(currentSpace, selectionFullPath);
			if (documentState.equals(MetaDataConstants.DOCUMENT_PUBLISHED_STATE)) {
				selectionName = selectionName.replaceAll("&","&amp;");
				selectionName = selectionName.replaceAll("\"","&#148;");
				selectionPath = selectionPath.replaceAll("&","&amp;");
				selectionPath = selectionPath.replaceAll("\"","&#148;");
				
				xml.append("<DOCUMENT name=\""+selectionName+"\" path=\""+selectionPath+"\" />");
			}
			
			else {			
				InjacDocumentException e = new InjacDocumentException();

				// log
				if (log.isDebugEnabled()){
					log.debug("renderXmlConfirmRootDocumentSetting"+" :: InjacDocumentException");
				}
				
				throw e;				
			}						
			
		}
		
		else {
			InjacDocumentException e = new InjacDocumentException();

			// log
			if (log.isDebugEnabled()){
				log.debug("renderXmlConfirmRootDocumentSetting"+" :: InjacDocumentException");
			}
			
			throw e;			
		}		
			
		return xml;		
	
	}
	
	
	
	
	/**
	 * Generate the XML String and set the document as root
	 * @param runtimeData the runtime data channel object
	 * @return the XML String for this mod
	 * @throws ChannelException
	 */
	private void rootDocumentSetting(ChannelRuntimeData runtimeData) throws ChannelException {
		String submit = runtimeData.getParameter("Submit_root");
		
		String documentName = runtimeData.getParameter("documentName");
		String documentPath = runtimeData.getParameter("documentPath");
		
		// if submit
		if (submit != null) {			
			MetaDataManager.setSpaceRootDocumentName(currentSpace, documentPath, documentName);
			//this.setCurrentDirectoryProperties();
			//String rootDocumentName = MetaDataManager.getSpaceRootDocumentName(currentSpace, currentSpace.getPath());
			this.directoryProperties.setRootDocumentName(documentName);
		}
		
		// if cancel
		else {			
			CancelException e = new CancelException();

			// log
			if (log.isDebugEnabled()){
				log.debug("rootDocumentSetting"+" :: CancelException");
			}
			
			throw e;
		}				
				
	}
	
	
	
	
	
}







