def siloview(self, silo):
     if not request.environ.get('repoze.who.identity'):
         abort(401, "Not Authorised")
     if not ag.granary.issilo(silo):
         abort(404)
     ident = request.environ.get('repoze.who.identity')
     c.ident = ident
     silos = ag.authz(ident, permission=['administrator', 'manager'])
     if not silo in silos:
         abort(403, "Do not have administrator or manager credentials for silo %s"%silo)
     user_groups = list_user_groups(ident['user'].user_name)
     if ('*', 'administrator') in user_groups:
         c.roles = ["admin", "manager", "user"]
     elif (silo, 'administrator') in user_groups:
         c.roles = ["admin", "manager", "user"]
     elif (silo, 'manager') in user_groups:
         c.roles = ["manager", "user"]
     else:
         abort(403, "Do not have administrator or manager credentials for silo %s"%silo)
     c.silo = silo
     
     http_method = request.environ['REQUEST_METHOD']
     
     if http_method == "GET":
         c.users = list_group_users(silo)
         accept_list = None
         if 'HTTP_ACCEPT' in request.environ:
             try:
                 accept_list = conneg_parse(request.environ['HTTP_ACCEPT'])
             except:
                 accept_list= [MT("text", "html")]
         if not accept_list:
             accept_list= [MT("text", "html")]
         mimetype = accept_list.pop(0)
         while(mimetype):
             if str(mimetype).lower() in ["text/html", "text/xhtml"]:
                 return render("/silo_users.html")
             elif str(mimetype).lower() in ["text/plain", "application/json"]:
                 response.content_type = 'application/json; charset="UTF-8"'
                 response.status_int = 200
                 response.status = "200 OK"
                 return simplejson.dumps(c.users)
             try:
                 mimetype = accept_list.pop(0)
             except IndexError:
                 mimetype = None
         #Whoops nothing satisfies - return text/plain
         response.content_type = 'application/json; charset="UTF-8"'
         response.status_int = 200
         response.status = "200 OK"
         return simplejson.dumps(c.users)
    def siloview(self, silo):
        if not request.environ.get('repoze.who.identity'):
            abort(401, "Not Authorised")
        if not ag.granary.issilo(silo):
            abort(404)
        ident = request.environ.get('repoze.who.identity')
        c.ident = ident
        c.silo = silo
        silos = ag.authz(ident, permission=['administrator', 'manager'])
        if not silo in silos:
            abort(403, "Do not have administrator or manager credentials for silo %s"%silo)
        user_groups = list_user_groups(ident['user'].user_name)
        if ('*', 'administrator') in user_groups:
            #User is super user
            c.roles = ["admin", "manager", "user"]
        elif (silo, 'administrator') in user_groups:
            c.roles = ["admin", "manager", "user"]
        elif (silo, 'manager') in user_groups:
            c.roles = ["manager", "user"]
        else:
            abort(403, "Do not have administrator or manager credentials for silo %s"%silo)
        http_method = request.environ['REQUEST_METHOD']

        c.kw = ag.granary.describe_silo(silo)
        if http_method == "GET":
            accept_list = None
            if 'HTTP_ACCEPT' in request.environ:
                try:
                    accept_list = conneg_parse(request.environ['HTTP_ACCEPT'])
                except:
                    accept_list= [MT("text", "html")]
            if not accept_list:
                accept_list= [MT("text", "html")]
            mimetype = accept_list.pop(0)
            while(mimetype):
                if str(mimetype).lower() in ["text/html", "text/xhtml"]:
                    return render("/admin_siloview.html")
                elif str(mimetype).lower() in ["text/plain", "application/json"]:
                    response.content_type = 'application/json; charset="UTF-8"'
                    response.status_int = 200
                    response.status = "200 OK"
                    return simplejson.dumps(dict(c.kw))
                try:
                    mimetype = accept_list.pop(0)
                except IndexError:
                    mimetype = None
            #Whoops nothing satisfies - return text/html            
            return render("/admin_siloview.html")
        elif http_method == "POST":
            params = request.POST
            #Get existing owners, admins, managers and submitters
            owners = []
            admins = []
            managers = []
            submitters = []
            if 'owners' in c.kw and c.kw['owners']:
                owners = [x.strip() for x in c.kw['owners'].split(",") if x]
            if 'administrators' in c.kw and c.kw['administrators']:
                admins = [x.strip() for x in c.kw['administrators'].split(",") if x]
            if 'managers' in c.kw and c.kw['managers']:
                managers = [x.strip() for x in c.kw['managers'].split(",") if x]
            if 'submitters' in c.kw and c.kw['submitters']:
                submitters = [x.strip() for x in c.kw['submitters'].split(",") if x]

            #Get new members
            new_owners = []
            #Get new admins
            new_admins = []
            if 'administrators' in params and params['administrators']:
                returned_admins = [x.strip() for x in params['administrators'].split(",") if x]
                new_admins = [x for x in returned_admins if not x in admins]
                new_owners.extend(new_admins)
            #Get new managers
            new_managers = []
            if 'managers' in params and params['managers']:
                returned_managers = [x.strip() for x in params['managers'].split(",") if x]
                new_managers = [x for x in returned_managers if not x in managers]
                new_owners.extend(new_managers)
            #Get new submitters
            new_submitters = []
            if 'submitters' in params and params['submitters']:
                returned_submitters = [x.strip() for x in params['submitters'].split(",") if x]
                new_submitters = [x for x in returned_submitters if not x in submitters]
                new_owners.extend(new_submitters)

            #Check if the new members exist. If not return 403
            existing_users = list_usernames()
            new_owners = list(set(new_owners))
            for o in new_owners:
                if not o in existing_users:
                    abort (403, "User %s does not exist"%o)

            if new_admins and not 'admin' in c.roles:
                abort (403, "Only administrators can assing users to role 'administrator'")

            owners.extend(new_owners)
            new_admins = list(set(new_admins))
            admins.extend(new_admins)
            new_managers = list(set(new_managers))
            managers.extend(new_managers)
            new_submitters = list(set(new_submitters))
            submitters.extend(new_submitters)

            # Update silo info
            updateMetadata = False
            for term in accepted_params:
                if term in params and not term in ['owners', 'administrators', 'managers', 'submitters'] and params[term]:
                    c.kw[term] = params[term]
                    updateMetadata = True 
            if new_owners or new_admins or new_managers or new_submitters or updateMetadata:
                new_silo_users = []
                if new_owners:
                    c.kw['owners'] = ','.join(owners)
                if new_admins:
                    c.kw['administrators'] = ','.join(admins)
                    for a in new_admins:
                        new_silo_users.append((a, 'administrator'))
                if new_managers:
                    c.kw['managers'] = ','.join(managers)
                    for a in new_managers:   
                        new_silo_users.append((a, 'manager'))
                if new_submitters:
                    c.kw['submitters'] = ','.join(submitters)
                    for a in new_submitters:
                        new_silo_users.append((a, 'submitter'))
                #Add metadat changes to the silo
                ag.granary.describe_silo(silo, **c.kw)
                ag.granary.sync()
                #Add new silo users into database
                if new_silo_users:
                    add_group_users(silo, new_silo_users)
            if updateMetadata:
                try:
                    ag.b.silo_change(silo, ident=ident['repoze.who.userid'])
                except:
                    pass
                       
            # conneg return
            accept_list = None
            if 'HTTP_ACCEPT' in request.environ:
                try:
                    accept_list = conneg_parse(request.environ['HTTP_ACCEPT'])
                except:
                    accept_list= [MT("text", "html")]
            if not accept_list:
                accept_list= [MT("text", "html")]
            mimetype = accept_list.pop(0)
            while(mimetype):
                if str(mimetype).lower() in ["text/html", "text/xhtml"]:
                    c.message = "Metadata updated"
                    c.kw = ag.granary.describe_silo(silo)
                    return render("/admin_siloview.html")
                elif str(mimetype).lower() in ["text/plain", "application/json"]:
                    response.content_type = "text/plain"
                    response.status_int = 204
                    response.status = "204 Updated"
                    #return "Updated Silo %s" % silo
                    return
                try:
                    mimetype = accept_list.pop(0)
                except IndexError:
                    mimetype = None
            # Whoops - nothing satisfies - return text/plain
            response.content_type = "text/plain"
            response.status_int = 204
            response.status = "204 Updated"
            return
        elif http_method == "DELETE":
            # Deletion of an entire Silo...
            # Serious consequences follow this action
            # Walk through all the items, emit a delete msg for each
            # and then remove the silo
            todelete_silo = ag.granary.get_rdf_silo(silo)
            #for item in todelete_silo.list_items():
            #    try:
            #        ag.b.deletion(silo, item, ident=ident['repoze.who.userid'])
            #    except:
            #        pass
            ag.granary.delete_silo(silo)
            try:
                ag.b.silo_deletion(silo, ident=ident['repoze.who.userid'])
            except:
                pass
            try:
                del ag.granary.state[silo]
            except:
                pass
            ag.granary.sync()
            ag.granary._register_silos()
            #Delete silo from database
            delete_silo(silo)
            # conneg return
            accept_list = None
            response.content_type = "text/plain"
            response.status_int = 200
            response.status = "200 OK"
            return "{'ok':'true'}"
    def userview(self, username):
        if not request.environ.get('repoze.who.identity'):
            abort(401, "Not Authorised")

        ident = request.environ.get('repoze.who.identity')

        http_method = request.environ['REQUEST_METHOD']

        if http_method == 'GET' or 'DELETE':
            #Admins, managers and user can see user data / delete the user
            if not ('administrator' in ident['permissions'] or \
                   'manager' in ident['permissions'] or ident['user'].user_name == username):
                abort(403, "Do not have administrator or manager credentials to view profiles of other users")
        elif http_method == 'POST':
            #Only user can updte their data
            if not ident['user'].user_name == username:
                abort(403, "Login as %s to edit profile"%username)

        existing_users = list_usernames()
        if not username in existing_users:
            abort(404, "User not found")

        c.ident = ident
        c.username = username

        if http_method == "GET":
            c.user = list_user(username)
            accept_list = None
            if 'HTTP_ACCEPT' in request.environ:
                try:
                    accept_list = conneg_parse(request.environ['HTTP_ACCEPT'])
                except:
                    accept_list= [MT("text", "html")]
            if not accept_list:
                accept_list= [MT("text", "html")]
            mimetype = accept_list.pop(0)
            while(mimetype):
                if str(mimetype).lower() in ["text/html", "text/xhtml"]:
                    return render("/admin_user.html")
                elif str(mimetype).lower() in ["text/plain", "application/json"]:
                    response.content_type = 'application/json; charset="UTF-8"'
                    response.status_int = 200
                    response.status = "200 OK"
                    return simplejson.dumps(c.user)
                try:
                    mimetype = accept_list.pop(0)
                except IndexError:
                    mimetype = None
            #Whoops nothing satisfies - return text/html            
            response.content_type = 'application/json; charset="UTF-8"'
            response.status_int = 200
            response.status = "200 OK"
            return simplejson.dumps(c.user)
        elif http_method == "POST":
            params = request.POST
            if not('password' in params or 'name' in params or \
                   'email' in params or 'firstname' in params or 'lastname' in params):
                abort(400, "No valid parameters found")
            params['username'] = username
            update_user(params)
            response.status_int = 204
            response.status = "204 Updated"
            response_message = None
            # conneg return
            accept_list = None
            if 'HTTP_ACCEPT' in request.environ:
                try:
                    accept_list = conneg_parse(request.environ['HTTP_ACCEPT'])
                except:
                    accept_list= [MT("text", "html")]
            if not accept_list:
                accept_list= [MT("text", "html")]
            mimetype = accept_list.pop(0)
            while(mimetype):
                if str(mimetype).lower() in ["text/html", "text/xhtml"]:
                    redirect(url(controller="users", action="userview", username=username))
                elif str(mimetype).lower() in ["text/plain", "application/json"]:
                    response.content_type = "text/plain"
                    return response_message
                try:
                    mimetype = accept_list.pop(0)
                except IndexError:
                    mimetype = None
            # Whoops - nothing satisfies - return text/plain
            response.content_type = "text/plain"
            return response_message
        elif http_method == "DELETE":
            user_groups = list_user_groups(username)
            if user_groups:
                abort(403, "User is member of silos. Remove user from all silos before deleting them")
            #Delete user from database
            delete_user(username)
            #Get all the silos user belomgs to, remove them from each silo and sync silo metadata
            # conneg return
            accept_list = None
            response.content_type = "text/plain"
            response.status_int = 200
            response.status = "200 OK"
            return "{'ok':'true'}"