/*
 * eXist Open Source Native XML Database
 * Copyright (C) 2001-2010 The eXist Project
 * http://exist-db.org
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *  
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *  
 *  $Id$
 */
package org.exist.xquery.functions.xmldb;

import org.apache.log4j.Logger;
import org.exist.EXistException;
import org.exist.dom.QName;
import org.exist.security.Account;
import org.exist.security.Group;
import org.exist.security.PermissionDeniedException;
import org.exist.security.SecurityManager;
import org.exist.security.Subject;
import org.exist.security.internal.aider.GroupAider;
import org.exist.storage.DBBroker;
import org.exist.xquery.BasicFunction;
import org.exist.xquery.Cardinality;
import org.exist.xquery.FunctionSignature;
import org.exist.xquery.XPathException;
import org.exist.xquery.XQueryContext;
import org.exist.xquery.value.BooleanValue;
import org.exist.xquery.value.FunctionParameterSequenceType;
import org.exist.xquery.value.FunctionReturnSequenceType;
import org.exist.xquery.value.Sequence;
import org.exist.xquery.value.SequenceIterator;
import org.exist.xquery.value.SequenceType;
import org.exist.xquery.value.Type;

/**
 * @author Adam Retter <adam@existsolutions.com>
 * @author <a href="mailto:shabanovd@gmail.com">Dmitriy Shabanov</a>
 */
public class XMLDBCreateGroup extends BasicFunction {

	protected static final Logger logger = Logger.getLogger(XMLDBCreateUser.class);

	public final static FunctionSignature signatures[] = {
			new FunctionSignature(new QName("create-group", XMLDBModule.NAMESPACE_URI, XMLDBModule.PREFIX),
					"Create a new user group. $group is the group name. The current user will be the groups manager.",
					new SequenceType[] { new FunctionParameterSequenceType("group", Type.STRING, Cardinality.EXACTLY_ONE, "The group name") },
					new FunctionReturnSequenceType(Type.BOOLEAN, Cardinality.EXACTLY_ONE, "true() or false() indicating the outcome of the operation"),
					"Use xmldb:create-group($group, $group-manager-username) instead."),

			new FunctionSignature(
					new QName("create-group", XMLDBModule.NAMESPACE_URI, XMLDBModule.PREFIX),
					"Create a new user group, with an initial member. $group is the group name, $group-manager-username are the groups managers in addition to the current user.",
					new SequenceType[] {
							new FunctionParameterSequenceType("group", Type.STRING, Cardinality.EXACTLY_ONE, "The group name"),
							new FunctionParameterSequenceType("group-manager-username", Type.STRING, Cardinality.ONE_OR_MORE,
									"The name of the user(s) who will be the groups manager") }, new FunctionReturnSequenceType(Type.BOOLEAN,
							Cardinality.EXACTLY_ONE, "true() or false() indicating the outcome of the operation")), };

	/**
	 * @param context
	 */
	public XMLDBCreateGroup(XQueryContext context, FunctionSignature signature) {
		super(context, signature);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.exist.xquery.Expression#eval(org.exist.dom.DocumentSet,
	 * org.exist.xquery.value.Sequence, org.exist.xquery.value.Item)
	 */
	@Override
	public Sequence eval(Sequence args[], Sequence contextSequence) throws XPathException {

		String groupName = args[0].getStringValue();

		if (context.getSubject().getName().equals("guest") || groupName.equals("dba")) {
			XPathException xPathException = 
				new XPathException(this, "Permission denied, calling account '" + context.getSubject().getName()
					+ "' must be an authenticated account to call this function.");
			logger.error("Invalid user", xPathException);
			throw xPathException;
		}

		logger.info("Attempting to create group " + groupName);

		Group group = new GroupAider(groupName);

		DBBroker broker = context.getBroker();
		Subject currentUser = broker.getSubject();

		try {

			SecurityManager sm = broker.getBrokerPool().getSecurityManager();

			// add the current user as a group manager
			group.addManager(currentUser);

			if (args.length == 2) {
				// add the additional group managers, this also makes sure they
				// all exist first!
				for (SequenceIterator i = args[1].iterate(); i.hasNext();) {
					String groupManager = i.nextItem().getStringValue();

					Account groupManagerAccount = sm.getAccount(null, groupManager);
					if (groupManagerAccount == null) {
						logger.error("Could not find the user: " + groupManager);
						// throw exception is better -shabanovd
						return BooleanValue.FALSE;
					}
					group.addManager(groupManagerAccount);
				}
			}

			// create the group
			group = sm.addGroup(group);

			return BooleanValue.TRUE;

		} catch (PermissionDeniedException pde) {
			throw new XPathException(this, 
					"Permission denied, calling account '" + context.getSubject().getName()
					+ "' do not authorize to call this function.");
		} catch (EXistException exe) {
			logger.error("Failed to create group: " + group, exe);
		}

		return BooleanValue.FALSE;
	}
}
@@ -5192,16 +5192,1149 @@
 roup);%0A%0A
+                        //TEMP - ESCALATE TO DBA :-(%0A                        //START TEMP - we also need to make every manager a member of the group otherwise%0A                        //they do not show up as group memebers automatically - this is a design problem because group%0A                        //membership is managed on the user and not the group, this needs to be fixed!%0A                        //see XMLDBAddUserToGroup also%0A                        Subject currentSubject = context.getBroker().getSubject();%0A                        try %7B%0A                            //escalate%0A                            context.getBroker().setSubject(sm.getSystemSubject());%0A%0A                            //perform action%0A                            for(Account manager : group.getManagers()) %7B%0A                                manager.addGroup(group);%0A                                sm.updateAccount(sm.getSystemSubject(), manager);%0A                            %7D%0A                        %7D finally %7B%0A                            context.getBroker().setSubject(currentSubject);%0A                        %7D%0A                        //END TEMP%0A%0A
 %09%09%09retur

Fix for working around the issue that managers are not automatically considered as members of a group