<%
/**
 *	$RCSfile: forumPerms.jsp,v $
 *	$Revision: 1.1.1.1 $
 *	$Date: 2002/09/09 13:50:28 $
 */
%>

<%@ page import="java.util.*,
                 java.net.URLEncoder,
                 com.jivesoftware.forum.*,
                 com.jivesoftware.forum.util.*"
    errorPage="error.jsp"
%>
 
<%!	// Global variables, methods, etc
	
    // Global permission definitions
    static final int READ = ForumPermissions.READ;
    static final int CREATE_THREAD = ForumPermissions.CREATE_THREAD;
    static final int CREATE_MESSAGE = ForumPermissions.CREATE_MESSAGE;
    static final int MODERATE_THREADS = ForumPermissions.MODERATE_THREADS;
    static final int MODERATE_MESSAGES = ForumPermissions.MODERATE_MESSAGES;
    
    // types of users/groups to give permissions to
    static final int ANYBODY = 1;
    static final int REGISTERED = 2;
    static final int USER = 3;
    static final int GROUP = 4;
    
    // anonymous user & special user constants
    static final long GUEST_ID = -1L;
    static final long REGISTERED_ID = 0L;
	
    // Returns the total number of users (registered users plus the "anonymous
    // user" and the "all registered users" user) with permission to a given
    // permission type.
	private int getUserPermCount(PermissionsManager permManager, int type) {
        // All registered users...
		int count = permManager.usersWithPermissionCount(type);
        // ... plus the "anonymous" user
		if (permManager.anonymousUserHasPermission(type)) {
			count++;
		}
        // ... plus the "registered users" user
		if (permManager.registeredUserHasPermission(type)) {
			count++;
		}
		return count;
	}
    
    // Returns an iterator of users with permission types of both 
    // MODERATE_THREADS and MODERATE_MESSAGES
    private Iterator getUserModerators(PermissionsManager permManager) {
        // Temporarily hold all moderators in a hashmap so when we combine the
        // thread & message moderators, duplicates will be ignored.
        Map moderators = new HashMap();
        
        // add thread moderators (user)
        for (Iterator iter=permManager.usersWithPermission(MODERATE_THREADS);iter.hasNext();) {
            User user = (User)iter.next();
            moderators.put(user.getUsername(),user);
        }
        // add message moderators (user)
        for (Iterator iter=permManager.usersWithPermission(MODERATE_MESSAGES);iter.hasNext();) {
            User user = (User)iter.next();
            moderators.put(user.getUsername(),user);
        }
        
        // Sort the user moderators list
        List moderatorList = new ArrayList(moderators.values());
        Object[] moderatorArray = moderatorList.toArray();
        Arrays.sort(moderatorArray, new Comparator() {
            public int compare(Object o1, Object o2) {
                User u1 = (User)o1;
                User u2 = (User)o2;
                return (u1.getUsername().compareTo(u2.getUsername()));
            }
        });
        
        return (Arrays.asList(moderatorArray)).iterator();
    }
    
    // Returns an iterator of users with permission types of both 
    // MODERATE_THREADS and MODERATE_MESSAGES
    private Iterator getGroupModerators(PermissionsManager permManager) {
        // Temporarily hold all moderators in a hashmap so when we combine the
        // thread & message moderators, duplicates will be ignored.
        Map moderators = new HashMap();
        
        // add thread moderators (groups)
        for (Iterator iter=permManager.groupsWithPermission(MODERATE_THREADS);iter.hasNext();) {
            Group group = (Group)iter.next();
            moderators.put(group.getName(),group);
        }
        // add message moderators (groups)
        for (Iterator iter=permManager.groupsWithPermission(MODERATE_MESSAGES);iter.hasNext();) {
            Group group = (Group)iter.next();
            moderators.put(group.getName(),group);
        }
        
        // Sort the user moderators list
        List moderatorList = new ArrayList(moderators.values());
        Object[] moderatorArray = moderatorList.toArray();
        Arrays.sort(moderatorArray, new Comparator() {
            public int compare(Object o1, Object o2) {
                Group g1 = (Group)o1;
                Group g2 = (Group)o2;
                return (g1.getName().compareTo(g2.getName()));
            }
        });
        
        return (Arrays.asList(moderatorArray)).iterator();
    }
    
    // Returns an iterator of users sorted by username
    private Iterator getSortedUserIterator(Iterator users) {
        // Add elements to a list
        List list = new LinkedList();
        while (users.hasNext()) {
            list.add(users.next());
        }
        // if the list size is <= 1, just return the orig iterator -- no sorting
        // necessary
        if (list.size() <= 1) {
            return users;
        }
        else {
            Object[] sortedUsers = list.toArray();
            Arrays.sort(sortedUsers, new Comparator() {
                public int compare(Object o1, Object o2) {
                    User u1 = (User)o1;
                    User u2 = (User)o2;
                    return (u1.getUsername().compareTo(u2.getUsername()));
                }
            });
            List sortedList = new ArrayList();
            for (int i=0; i<sortedUsers.length; i++) {
                sortedList.add(sortedUsers[i]);
            }
            return sortedList.iterator();
        }
    }
    
    // Returns an iterator of groups sorted by group name
    private Iterator getSortedGroupIterator(Iterator groups) {
        // Add elements to a list
        List list = new LinkedList();
        while (groups.hasNext()) {
            list.add(groups.next());
        }
        // if the list size is <= 1, just return the orig iterator -- no sorting
        // necessary
        if (list.size() <= 1) {
            return groups;
        }
        else {
            Object[] sortedGroups = list.toArray();
            Arrays.sort(sortedGroups, new Comparator() {
                public int compare(Object o1, Object o2) {
                    Group g1 = (Group)o1;
                    Group g2 = (Group)o2;
                    return (g1.getName().compareTo(g2.getName()));
                }
            });
            List sortedList = new ArrayList();
            for (int i=0; i<sortedGroups.length; i++) {
                sortedList.add(sortedGroups[i]);
            }
            return sortedList.iterator();
        }
    }
    
    // 
    private long[] getUserIDs(String[] items) {
        return getIDs(items, "u");
    }
    
    // 
    private long[] getGroupIDs(String[] items) {
        return getIDs(items, "g");
    }
    
    // 
    private long[] getIDs(String[] items, String prefix) {
        if (items == null) {
            return new long[0];
        }
        long[] IDs = new long[items.length];
        int size = 0;
        for (int i=0; i<items.length; i++) {
            String item = items[i];
            if (item != null && item.startsWith(prefix)) {
                try {
                    IDs[size] = Long.parseLong(item.substring(1,item.length()));
                    size++;
                }
                catch (Exception e) {}
            }
        }
        if (size == IDs.length) {
            return IDs;
        }
        else {
            long[] temp = new long[size];
            for (int i=0; i<temp.length; i++) {
                temp[i] = IDs[i];
            }
            return temp;
        }
    }
%>

<%@ include file="include/global.jsp" %>

<%	// get parameters
	
	int forumID = ParamUtils.getIntParameter(request,"forum",-1);
	int[] permissions = ParamUtils.getIntParameters(request,"permission",-1);
    int givePermTo = ParamUtils.getIntParameter(request,"givePermTo",-1);
    boolean add = ParamUtils.getBooleanParameter(request,"add");
    boolean remove = ParamUtils.getBooleanParameter(request,"remove");
    String username = ParamUtils.getParameter(request,"username");
    String groupname = ParamUtils.getParameter(request,"groupname");
    String[] items = request.getParameterValues("items");
    int itemType = ParamUtils.getIntParameter(request,"itemType",-1);
    
    // UserManager for getting and setting users or lists of users
	UserManager userManager = forumFactory.getUserManager();
    
    // GroupManager for getting and setting groups or list of groups
	GroupManager groupManager = forumFactory.getGroupManager();
	
    // Load the forum
	Forum forum = null;
    if (forumID != -1L) {
        forum = forumFactory.getForum(forumID);
    }
	
	// This forum's permission manager
	PermissionsManager permManager = null;
    if (forum != null) {
        permManager = forum.getPermissionsManager();
    }
    else {
        permManager = forumFactory.getPermissionsManager();
    }
    
    // add a new permission if requested
    if (add) {
        // Check to see that the user clicked a permission radio button and
        // selected at least one permission
        if (givePermTo > 0 && (permissions!=null && permissions.length>0)) {
            switch (givePermTo) {
                case ANYBODY:
                    // Add anonymous user permissions
                    for (int i=0; i<permissions.length; i++) {
                        permManager.addAnonymousUserPermission(permissions[i]);
                    }
                    break;
                case REGISTERED:
                    // Add registered user permissions
                    for (int i=0; i<permissions.length; i++) {
                        permManager.addRegisteredUserPermission(permissions[i]);
                    }
                    break;
                case USER:
                    try {
                        // get the user:
                        User user = userManager.getUser(username);
                        // Add the user permission
                        for (int i=0; i<permissions.length; i++) {
                            permManager.addUserPermission(user, permissions[i]);
                        }
                    } catch (Exception ignored) {}
                    break;
                case GROUP:
                    try {
                        // get the user:
                        Group group = groupManager.getGroup(groupname);
                        // Add the user permission
                        for (int i=0; i<permissions.length; i++) {
                            permManager.addGroupPermission(group, permissions[i]);
                        }
                    } catch (Exception ignored) {}
                    break;
                default:
            }
        }
        
        // done adding, so redirect back to this page
        response.sendRedirect("forumPerms.jsp?forum="+forumID);
        return;
    }
    
    // remove a permission if requested
    if (remove) {
        // Get the lists of user IDs and group IDs.
        long[] userIDs = getUserIDs(items);
        long[] groupIDs = getGroupIDs(items);
        
        // if there are user perms or group perms to remove:
        if (userIDs.length > 0 || groupIDs.length > 0) {
            // users first,
            for (int i=0; i<userIDs.length; i++) {
                if (userIDs[i] == GUEST_ID) {
                    permManager.removeAnonymousUserPermission(itemType);
                }
                else if (userIDs[i] == REGISTERED_ID) {
                    permManager.removeRegisteredUserPermission(itemType);
                }
                else {
                    try {
                        User user = userManager.getUser(userIDs[i]);
                        permManager.removeUserPermission(user,itemType);
                    }
                    catch (Exception ignored) {}
                }
            }
            // groups next
            for (int i=0; i<groupIDs.length; i++) {
                try {
                    Group group = groupManager.getGroup(groupIDs[i]);
                    permManager.removeGroupPermission(group,itemType);
                }
                catch (Exception ignored) {}
            }
        }
        
        // done removing, so redirect back to this page
        response.sendRedirect("forumPerms.jsp?forum="+forumID);
        return;
    }
    
    // Iterators of forum types
	Iterator usersWithReadPerm = permManager.usersWithPermission(READ);
	Iterator usersWithThreadPerm = permManager.usersWithPermission(CREATE_THREAD);
	Iterator usersWithMessagePerm = permManager.usersWithPermission(CREATE_MESSAGE);
    Iterator userModerators = getUserModerators(permManager);
    Iterator groupModerators = getGroupModerators(permManager);
	Iterator groupsWithReadPerm = permManager.groupsWithPermission(READ);
	Iterator groupsWithThreadPerm = permManager.groupsWithPermission(CREATE_THREAD);
	Iterator groupsWithMessagePerm = permManager.groupsWithPermission(CREATE_MESSAGE);
%>

<%  // special onload command to load the sidebar
    if (forum != null) {
        onload = " onload=\"parent.frames['sidebar'].location.href='sidebar.jsp?sidebar=forum';\"";
    }
%>
<%@ include file="include/header.jsp" %>

<p>

<%  // Title of this page and breadcrumbs
    String title = null;
    String[][] breadcrumbs = null;
    if (forum != null) {
        title = "Forum Permissions";
        breadcrumbs = new String[][] {
            {"Main", "main.jsp"},
            {"Forums", "forums.jsp"},
            {"Edit Forum", "editForum.jsp?forum="+forumID},
            {"Forum Permissions", "forumPerms.jsp?forum="+forumID}
        };
    }
    else {
        title = "Global Permissions";
        breadcrumbs = new String[][] {
            {"Main", "main.jsp"},
            {"Global Permissions", "forumPerms.jsp"}
        };
    }
%>
<%@ include file="include/title.jsp" %>

<font size="-1">
<%  if (forum != null) { %>
Set the specific permissions for this forum.
<%  } else { // global %>
Edit global permissions to set the permissions policies that all of your 
forums will use.
<%  } %>
Permissions are always additive, such that the final permissions for a forum
will be global permissions, plus forum specific permissions.
</font>

<p>

<font size="-1"><b>Permission Summary</b></font>
<ul>
    <font size="-1">
    Below is a summary of permissions associated with various users. To remove
    a permission for a user, select the user and click "Remove".
    <p>
    </font>
    <table bgcolor="<%= tableBorderColor %>" cellpadding="0" cellspacing="0" border="0" width="90%">
    <tr><td>
    <table bgcolor="<%= tableBorderColor %>" cellpadding="0" cellspacing="1" border="0" width="100%">
    <tr bgcolor="#eeeeee">
        <td align="center"><table cellpadding="3" cellspacing="0" border="0"><tr><td><font size="-2" face="verdana"><b>READ</b></font></td></tr></table></td>
        <td align="center"><table cellpadding="3" cellspacing="0" border="0"><tr><td><font size="-2" face="verdana"><b>CREATE THREAD</b></font></td></tr></table></td>
        <td align="center"><table cellpadding="3" cellspacing="0" border="0"><tr><td><font size="-2" face="verdana"><b>CREATE MESSAGE</b></font></td></tr></table></td>
        <td align="center"><table cellpadding="3" cellspacing="0" border="0"><tr><td><font size="-2" face="verdana"><b>MODERATOR</b></font></td></tr></table></td>
    </tr>
    <tr bgcolor="#ffffff">
        <form action="forumPerms.jsp">
        <input type="hidden" name="forum" value="<%= forumID %>">
        <input type="hidden" name="remove" value="true">
        <input type="hidden" name="itemType" value="<%= READ %>">
        <td align="center">
            <table cellpadding="3" cellspacing="0" border="0"><tr><td>
            <select size="5" name="items" multiple
             onchange="">
        <%	if (permManager.anonymousUserHasPermission(READ)) { %>
		    <option value="u-1">* Anybody
        <%  } %>
        <%	if (permManager.registeredUserHasPermission(READ)) { %>
		    <option value="u0">* Registered Users
        <%  } %>
        <%  while (usersWithReadPerm.hasNext()) {
                User user = (User)usersWithReadPerm.next();
        %>
            <option value="u<%= user.getID() %>"><%= user.getUsername() %>
        <%  } %>
        <%  while (groupsWithReadPerm.hasNext()) {
                Group group = (Group)groupsWithReadPerm.next();
        %>
            <option value="g<%= group.getID() %>"><%= group.getName() %>
        <%  } %>
            </select>
            </td></tr></table><img src="images/line_gray.gif" width="100%" height="5" border="0"
            ><table cellpadding="3" cellspacing="0" border="0"><tr><td
            ><input type="submit" value="Remove"></td></tr></table>
        </td>
        </form>
        <form action="forumPerms.jsp">
        <input type="hidden" name="forum" value="<%= forumID %>">
        <input type="hidden" name="remove" value="true">
        <input type="hidden" name="itemType" value="<%= CREATE_THREAD %>">
        <td align="center">
            <table cellpadding="3" cellspacing="0" border="0"><tr><td>
            <select size="5" name="items" multiple>
        <%	if (permManager.anonymousUserHasPermission(CREATE_THREAD)) { %>
		    <option value="u-1">* Anybody
        <%  } %>
        <%	if (permManager.registeredUserHasPermission(CREATE_THREAD)) { %>
		    <option value="u0">* Registered Users
        <%  } %>
        <%  while (usersWithThreadPerm.hasNext()) {
                User user = (User)usersWithThreadPerm.next();
        %>
            <option value="u<%= user.getID() %>"><%= user.getUsername() %>
        <%  } %>
        <%  while (groupsWithThreadPerm.hasNext()) {
                Group group = (Group)groupsWithThreadPerm.next();
        %>
            <option value="g<%= group.getID() %>"><%= group.getName() %>
        <%  } %>
            </select>
            </td></tr></table><img src="images/line_gray.gif" width="100%" height="5" border="0"
            ><table cellpadding="3" cellspacing="0" border="0"><tr><td
            ><input type="submit" value="Remove"></td></tr></table>
        </td>
        </form>
        <form action="forumPerms.jsp">
        <input type="hidden" name="forum" value="<%= forumID %>">
        <input type="hidden" name="remove" value="true">
        <input type="hidden" name="itemType" value="<%= CREATE_MESSAGE %>">
        <td align="center">
            <table cellpadding="3" cellspacing="0" border="0"><tr><td>
            <select size="5" name="items" multiple>
        <%	if (permManager.anonymousUserHasPermission(CREATE_MESSAGE)) { %>
		    <option value="u-1">* Anybody
        <%  } %>
        <%	if (permManager.registeredUserHasPermission(CREATE_MESSAGE)) { %>
		    <option value="u0">* Registered Users
        <%  } %>
        <%  while (usersWithMessagePerm.hasNext()) {
                User user = (User)usersWithMessagePerm.next();
        %>
            <option value="u<%= user.getID() %>"><%= user.getUsername() %>
        <%  } %>
        <%  while (groupsWithMessagePerm.hasNext()) {
                Group group = (Group)groupsWithMessagePerm.next();
        %>
            <option value="g<%= group.getID() %>"><%= group.getName() %>
        <%  } %>
            </select>
            </td></tr></table><img src="images/line_gray.gif" width="100%" height="5" border="0"
            ><table cellpadding="3" cellspacing="0" border="0"><tr><td
            ><input type="submit" value="Remove"></td></tr></table>
        </td>
        </form>
        <form action="forumPerms.jsp">
        <input type="hidden" name="forum" value="<%= forumID %>">
        <input type="hidden" name="remove" value="true">
        <input type="hidden" name="itemType" value="<%= MODERATE_THREADS %>">
        <td align="center">
            <table cellpadding="3" cellspacing="0" border="0"><tr><td>
            <select size="5" name="items" multiple>
        <%	if (permManager.anonymousUserHasPermission(MODERATE_THREADS)
                || permManager.anonymousUserHasPermission(MODERATE_MESSAGES)) { %>
		    <option value="u-1">* Anybody
        <%  } %>
        <%	if (permManager.registeredUserHasPermission(MODERATE_THREADS)
                || permManager.registeredUserHasPermission(MODERATE_MESSAGES)) { %>
		    <option value="u0">* Registered Users
        <%  } %>
        <%  while (userModerators.hasNext()) {
                User user = (User)userModerators.next();
        %>
            <option value="u<%= user.getID() %>"><%= user.getUsername() %>
        <%  } %>
        <%  while (groupModerators.hasNext()) {
                Group group = (Group)groupModerators.next();
        %>
            <option value="g<%= group.getID() %>"><%= group.getName() %>
        <%  } %>
            </select>
            </td></tr></table><img src="images/line_gray.gif" width="100%" height="5" border="0"
            ><table cellpadding="3" cellspacing="0" border="0"><tr><td
            ><input type="submit" value="Remove"></td></tr></table>
        </td>
        </form>
    </tr>
    </table>
    </td></tr>
    </table>
</ul>

<form method="post" action="forumPerms.jsp" name="addForm">
<input type="hidden" name="add" value="true">
<input type="hidden" name="forum" value="<%= forumID %>">

<font size="-1"><b>Add Permission</b></font>
<ul>
    <table bgcolor="<%= tableBorderColor %>" cellpadding="0" cellspacing="0" border="0" width="">
    <tr><td>
    <table bgcolor="<%= tableBorderColor %>" cellpadding="0" cellspacing="1" border="0" width="100%">
    <tr bgcolor="#ffffff">
        <td>
        
        <table cellpadding="2" cellspacing="0" border="0" width="100%">
        <tr bgcolor="#eeeeee">
        	<td><font size="-1"><b>Give:</b></font></td>
            <td colspan="3">&nbsp;</td>
        	<td><font size="-1"><b>the permissions:</b></font></td>
            <td colspan="2">&nbsp;</td>
        </tr>
        <tr>
            <td colspan="7"><img src="images/blank.gif" width="1" height="5" border="0"></td>
        </tr>
        <tr>
            <td rowspan="4">&nbsp;</td>
        	<td><input type="radio" name="givePermTo" value="<%= ANYBODY %>" id="el01"></td>
            <td colspan="2"><font size="-1"><label for="el01">Anybody (including guests)</label></font></td>
            <td rowspan="4">&nbsp;</td>
        	<td><input type="checkbox" name="permission" value="<%= READ %>" id="el02"></td>
            <td><font size="-1"><label for="el02">Read</label></font></td>
        </tr>
        <tr>
            <td><input type="radio" name="givePermTo" value="<%= REGISTERED %>" id="el03"></td>
            <td colspan="2"><font size="-1"><label for="el03">Registered Users</label></font></td>
        	<td><input type="checkbox" name="permission" value="<%= CREATE_THREAD %>" id="el04"></td>
            <td><font size="-1"><label for="el04">Create Thread</label></font></td>
        </tr>
        <tr>
            <td><input type="radio" name="givePermTo" value="<%= USER %>" id="el05"></td>
            <td><font size="-1"><label for="el05">User:</label></font></td>
            <td><input type="text" name="username" value="(enter username)" size="20" onclick="this.select();document.addForm.givePermTo[2].checked=true;"></td>
        	<td><input type="checkbox" name="permission" value="<%= CREATE_MESSAGE %>" id="el06"></td>
            <td><font size="-1"><label for="el06">Create Message</label></font></td>
        </tr>
        <tr>
            <td><input type="radio" name="givePermTo" value="<%= GROUP %>" id="el07"></td>
            <td><font size="-1"><label for="el07">Group:</label></font></td>
            <td><input type="text" name="groupname" value="(enter group name)" size="20" onclick="this.select();document.addForm.givePermTo[3].checked=true;"></td>
        	<td><input type="checkbox" name="permission" value="<%= MODERATE_THREADS %>" id="el08"></td>
            <td><font size="-1"><label for="el08">Moderator</label></font></td>
        </tr>
        <tr>
            <td colspan="7"><img src="images/blank.gif" width="1" height="5" border="0"></td>
        </tr>
        </table>
        
        </td>
    </tr>
    <tr bgcolor="#ffffff">
        <td align="center">
        
        <table>
            <tr><td>
            <input type="submit" value="Add Permission">
            </td>
        </tr>
        </table>
        
        </td>
    </tr>
    </table>
    </td></tr>
    </table>
</ul>
</form>

<p>

<%@ include file="include/footer.jsp" %>