<commit_before># Django imports
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.shortcuts import render_to_response, get_object_or_404
from django.db.models import Q
from django.db import transaction
from django.contrib.auth import login
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.db import connection
from django import forms
from django.core.mail import send_mail
from django.utils.html import escape

# Mako imports
from mako.template import Template
from mako import exceptions
from mako.lookup import TemplateLookup

# Standard library imports
import time, datetime, os, timeit, string, random
from itertools import *

# Project-specific imports
from models import *
from tsa.config import *
import tsa.settings

def get_template(name):
    mylookup = TemplateLookup(directories=[TEMPLATE_DIR])
    return mylookup.get_template(name)

def render_template(name,request,**kwds):
    if 'ENABLE_ADMIN' in request.GET and request.user.is_superuser:
        request.session['DISABLE_ADMIN'] = False
    '''if 'ENABLE_ADMIN' in request.GET and request.session.get('ADMIN_ID'):
        user = User.objects.get(id=int(request.session.get('ADMIN_ID')))
        user.backend = 'django.contrib.auth.backends.ModelBackend'
        login(request, user)
        return HttpResponseRedirect('/')'''
    if 'DISABLE_ADMIN' in request.GET or request.session.get('DISABLE_ADMIN'):
        request.user.is_superuser = False
        request.user.admin_disabled = True
        request.session['DISABLE_ADMIN'] = True
    try:
        kwds.update(dict(
            user=request.user,
            messages=request.user.get_and_delete_messages(),
            MODE = tsa.settings.MODE,
            DEPLOYED = DEPLOYED
        ))
        t = get_template(name)
        txt = t.render(**kwds)
    except:
        return HttpResponse(exceptions.html_error_template().render() )
    return HttpResponse(txt)
    
def message(request, msg):
    request.user.message_set.create(message=msg)

def log(request, type, text, affected=None):
    SystemLog(user=request.user, type=type, text=text, affected=(affected or request.user)).save()

def name(user):
    return '%s %s' % (user.first_name, user.last_name)

def login_url(user):
    return '/quick_login?user=%s&auth=%s' % (user.id, user.password.split('$')[2])
    
def generate_password():
    c, v = '<PASSWORD>ghjklmnpqrstvwxz', '<PASSWORD>'
    r = random.choice
    return r(c) + r(v) + r(c) + r(v) + r(c) + str(random.randint(100,999))
    



@login_required
def index(request):
    for user in User.objects.all():
        try:
            user.profile
        except UserProfile.DoesNotExist:
            UserProfile(user=user, is_member=True, senior=False).save()
    return render_template('index.mako',request, events=Event.objects.all())

def quick_login(request):
    user = User.objects.get(id=int(request.GET['user']))
    if user.is_superuser and DEPLOYED:
        return HttpResponse('Error: Admins cannot login using the quick links for security reasons.')
    if user.password.split('$')[2] == request.GET['auth']:
        user.backend = 'django.contrib.auth.backends.ModelBackend'
        login(request, user)
        return HttpResponseRedirect(request.GET.get('next','/'))
    else:
        return HttpResponse('Error: Authentication token is invalid. Either you\'re trying to login as someone else using your authentication token (nice try), or your password has been reset since this link was generated.')

@login_required
def update_indi(request):
    if request.method == 'POST':
        eid = int(request.POST['add_indi_event'])
        if eid != -1:
            e = Event.objects.get(id=eid)
            if e.is_locked(request.user):
                message(request, 'Error: Event is locked')
            elif request.user in e.entrants.all():
                message(request, 'Error: You are already in that event.')
            else:
                e.entrants.add(request.user)
                message(request, 'Individual event "%s" added.' % e.name)
                log(request, 'event_add', '%s added the individual event %s.' % (name(request.user), e.name))
    if 'delete_event' in request.GET:
        eid = int(request.GET['delete_event'])
        e = Event.objects.get(id=eid)
        e.entrants.remove(request.user)
        message(request, 'Individual event "%s" removed.' % e.name)
        log(request, 'event_remove', '%s removed the individual event %s.' % (name(request.user), e.name))
    return index(request)

@login_required
def join_team(request):
    eid = request.REQUEST['event_id']
    e = Event.objects.get(id=eid)
    if request.method == 'POST':
        t = Team(event=e)
        t.captain = request.user
        t.senior = request.user.profile.senior
        t.save()
        t.members.add(request.user)
        message(request, 'New team created.')
        log(request, 'team_create', '%s created a new <a href="/teams/%d">%s team</a>.' % (name(request.user), t.id, e.name))
        return HttpResponseRedirect('/teams/%d' % t.id)
    return render_template('join_team.mako',request, teams=Team.objects.filter(event=e).order_by('senior'), event=e)

@login_required
def view_team(request, tid):
    return render_template('view_team.mako',request, team=Team.objects.get(id=tid))

@login_required
def update_team(request, tid):
    action = request.REQUEST['action']
    team = Team.objects.get(id=tid)
    
    redirect =  HttpResponseRedirect('/teams/%d/' % team.id)       
    
    if action == 'join':
        if team.entry_locked:
            return HttpResponse('Error: Team is locked; nobody may join')
        team.members.add(request.user)
        team.save()
        message(request, 'You have joined this team.')
        log(request, 'team_join', '%s joined a %s.' % (name(request.user), team.link()))
        return redirect
        
    if action == 'remove_member' and int(request.REQUEST['user_id']) == request.user.id:
        # The logged in user is leaving the team
        team.members.remove(request.user)
        message(request, 'You have left the team.')
        log(request, 'team_leave', '%s left their %s.' % (name(request.user), team.link()))
        if team.members.count() == 0:
            event = team.event.name
            team.delete()
            message(request, 'The team has been deleted because you were the last member.')
            log(request, 'team_delete', 'A %s team has been deleted.' % event)
        elif request.user == team.captain:
            team.captain = team.members.all()[0]
            team.save()
            message(request, '%s %s is the new team captain.' % (team.captain.first_name, team.captain.last_name))
            log(request, 'team_promote', '%s has been promoted to captain of %s.' % (name(team.captain), team.link()), affected=team.captain)
        return HttpResponseRedirect('/')
        
    if action == 'delete_post':
        post = TeamPost.objects.get(id=int(request.REQUEST['id']))
        if request.user == post.author or request.user == team.captain or request.user.is_superuser:
            post.delete()
            message(request, 'The post has been deleted.')
            log(request, 'team_post_delete', '%s deleted a post in a %s.' % (name(request.user), team.link()))
        else:
            message(request, 'Error: you do not have permission to delete the post.')
        return redirect
        
    if request.user not in team.members.all() and not request.user.is_superuser:
        message(request, 'Error: you are not in this team.')
        return redirect
    # All actions beyond this point require team membership
    
    if action == 'Post':
        text = request.REQUEST['message']
        post = TeamPost(team=team, author=request.user, text=text)
        post.save()
        for member in team.members.all():
            if member.id == request.user.id:
                continue
            if member.profile.posts_email == 2:
                t = get_template('email/posts_email.mako')
                body = t.render(name=member.first_name, poster=request.user.first_name, team=team, text=text, login_url=login_url(member))
                send_mail('%s Post' % team.event.name, body, 'State High TSA <<EMAIL>>', [member.email])
        message(request, 'Message posted.')
        log(request, 'team_post', '%s posted to their %s' % (name(request.user), team.link()))
        return redirect
        
    if action == 'Add Member':
        u = User.objects.get(id=int(request.REQUEST['user_id']))
        if u.teams.filter(event=team.event).count() != 0:
            message(request, 'Error: %s is already in a team for that event.' % u.first_name)
            return redirect
        team.members.add(u)
        team.save()
        message(request, '%s %s has been added to the team.' % (u.first_name, u.last_name))
        log(request, 'team_join', '%s has been added to a %s.' % (name(u), team.link()), affected=u)
        return redirect
        
    if request.user != team.captain and not request.user.is_superuser:
        message(request, 'Error: you are not the team captain.')
        return redirect
    # All actions beyond this point require team captain
    
    if action == 'lock_team':
        team.entry_locked = not team.entry_locked
        team.save()
        if team.entry_locked:
            message(request, 'The team is now locked.')
        else:
            message(request, 'The team is now unlocked.')
    if action == 'remove_member':
        u = User.objects.get(id=int(request.REQUEST['user_id']))
        team.members.remove(u)
        team.save()
        message(request, '%s %s has been removed from the team.' % (u.first_name, u.last_name))
        log(request, 'team_remove', '%s has been removed from their %s.' % (name(u), team.link()), affected=u)
    if action == 'promote_member':
        u = User.objects.get(id=int(request.REQUEST['user_id']))
        team.captain = u
        team.save()
        message(request, '%s %s has been promoted to team captain.' % (u.first_name, u.last_name))
        log(request, 'team_promote', '%s has been promoted to captain of their %s.' % (name(u), team.link()), affected=u)
    if action == 'delete_team':
        event = team.event.name
        team.delete()
        return HttpResponseRedirect('/')
        message(request, 'The team has been deleted.')
        log(request, 'team_delete', 'A %s team has been deleted.' % event)

    return redirect

@login_required
def event_list(request):
    if request.method == 'POST':
        i = 0
        for event in Event.objects.all():
            if event.entry_locked and not 'lock_%d' % event.id in request.POST:
                event.entry_locked = False
                event.save()
                i += 1
            elif not event.entry_locked and 'lock_%d' % event.id in request.POST:
                event.entry_locked = True
                event.save()
                i += 1
            if event.entry_locked_senior and not 'senior_lock_%d' % event.id in request.POST:
                event.entry_locked_senior = False
                event.save()
                i += 1
            elif not event.entry_locked_senior and 'senior_lock_%d' % event.id in request.POST:
                event.entry_locked_senior = True
                event.save()
                i += 1
        message(request, '%d events updated.' % i)
        if i > 0:
            log(request, 'admin_lock', '%s updated the lock status of %d events.' % (name(request.user), i))
    return render_template('event_list.mako',request,events=Event.objects.all())
    
class NewUserForm(forms.Form):
        username = forms.CharField()<commit_msg>Minor bugfix with team deletion<commit_after># Django imports
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.shortcuts import render_to_response, get_object_or_404
from django.db.models import Q
from django.db import transaction
from django.contrib.auth import login
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.db import connection
from django import forms
from django.core.mail import send_mail
from django.utils.html import escape

# Mako imports
from mako.template import Template
from mako import exceptions
from mako.lookup import TemplateLookup

# Standard library imports
import time, datetime, os, timeit, string, random
from itertools import *

# Project-specific imports
from models import *
from tsa.config import *
import tsa.settings

def get_template(name):
    mylookup = TemplateLookup(directories=[TEMPLATE_DIR])
    return mylookup.get_template(name)

def render_template(name,request,**kwds):
    if 'ENABLE_ADMIN' in request.GET and request.user.is_superuser:
        request.session['DISABLE_ADMIN'] = False
    '''if 'ENABLE_ADMIN' in request.GET and request.session.get('ADMIN_ID'):
        user = User.objects.get(id=int(request.session.get('ADMIN_ID')))
        user.backend = 'django.contrib.auth.backends.ModelBackend'
        login(request, user)
        return HttpResponseRedirect('/')'''
    if 'DISABLE_ADMIN' in request.GET or request.session.get('DISABLE_ADMIN'):
        request.user.is_superuser = False
        request.user.admin_disabled = True
        request.session['DISABLE_ADMIN'] = True
    try:
        kwds.update(dict(
            user=request.user,
            messages=request.user.get_and_delete_messages(),
            MODE = tsa.settings.MODE,
            DEPLOYED = DEPLOYED
        ))
        t = get_template(name)
        txt = t.render(**kwds)
    except:
        return HttpResponse(exceptions.html_error_template().render() )
    return HttpResponse(txt)
    
def message(request, msg):
    request.user.message_set.create(message=msg)

def log(request, type, text, affected=None):
    SystemLog(user=request.user, type=type, text=text, affected=(affected or request.user)).save()

def name(user):
    return '%s %s' % (user.first_name, user.last_name)

def login_url(user):
    return '/quick_login?user=%s&auth=%s' % (user.id, user.password.split('$')[2])
    
def generate_password():
    c, v = '<PASSWORD>', '<PASSWORD>'
    r = random.choice
    return r(c) + r(v) + r(c) + r(v) + r(c) + str(random.randint(100,999))
    



@login_required
def index(request):
    for user in User.objects.all():
        try:
            user.profile
        except UserProfile.DoesNotExist:
            UserProfile(user=user, is_member=True, senior=False).save()
    return render_template('index.mako',request, events=Event.objects.all())

def quick_login(request):
    user = User.objects.get(id=int(request.GET['user']))
    if user.is_superuser and DEPLOYED:
        return HttpResponse('Error: Admins cannot login using the quick links for security reasons.')
    if user.password.split('$')[2] == request.GET['auth']:
        user.backend = 'django.contrib.auth.backends.ModelBackend'
        login(request, user)
        return HttpResponseRedirect(request.GET.get('next','/'))
    else:
        return HttpResponse('Error: Authentication token is invalid. Either you\'re trying to login as someone else using your authentication token (nice try), or your password has been reset since this link was generated.')

@login_required
def update_indi(request):
    if request.method == 'POST':
        eid = int(request.POST['add_indi_event'])
        if eid != -1:
            e = Event.objects.get(id=eid)
            if e.is_locked(request.user):
                message(request, 'Error: Event is locked')
            elif request.user in e.entrants.all():
                message(request, 'Error: You are already in that event.')
            else:
                e.entrants.add(request.user)
                message(request, 'Individual event "%s" added.' % e.name)
                log(request, 'event_add', '%s added the individual event %s.' % (name(request.user), e.name))
    if 'delete_event' in request.GET:
        eid = int(request.GET['delete_event'])
        e = Event.objects.get(id=eid)
        e.entrants.remove(request.user)
        message(request, 'Individual event "%s" removed.' % e.name)
        log(request, 'event_remove', '%s removed the individual event %s.' % (name(request.user), e.name))
    return index(request)

@login_required
def join_team(request):
    eid = request.REQUEST['event_id']
    e = Event.objects.get(id=eid)
    if request.method == 'POST':
        t = Team(event=e)
        t.captain = request.user
        t.senior = request.user.profile.senior
        t.save()
        t.members.add(request.user)
        message(request, 'New team created.')
        log(request, 'team_create', '%s created a new <a href="/teams/%d">%s team</a>.' % (name(request.user), t.id, e.name))
        return HttpResponseRedirect('/teams/%d' % t.id)
    return render_template('join_team.mako',request, teams=Team.objects.filter(event=e).order_by('senior'), event=e)

@login_required
def view_team(request, tid):
    return render_template('view_team.mako',request, team=Team.objects.get(id=tid))

@login_required
def update_team(request, tid):
    action = request.REQUEST['action']
    team = Team.objects.get(id=tid)
    
    redirect =  HttpResponseRedirect('/teams/%d/' % team.id)       
    
    if action == 'join':
        if team.entry_locked:
            return HttpResponse('Error: Team is locked; nobody may join')
        team.members.add(request.user)
        team.save()
        message(request, 'You have joined this team.')
        log(request, 'team_join', '%s joined a %s.' % (name(request.user), team.link()))
        return redirect
        
    if action == 'remove_member' and int(request.REQUEST['user_id']) == request.user.id:
        # The logged in user is leaving the team
        team.members.remove(request.user)
        message(request, 'You have left the team.')
        log(request, 'team_leave', '%s left their %s.' % (name(request.user), team.link()))
        if team.members.count() == 0:
            event = team.event.name
            team.delete()
            message(request, 'The team has been deleted because you were the last member.')
            log(request, 'team_delete', 'A %s team has been deleted.' % event)
        elif request.user == team.captain:
            team.captain = team.members.all()[0]
            team.save()
            message(request, '%s %s is the new team captain.' % (team.captain.first_name, team.captain.last_name))
            log(request, 'team_promote', '%s has been promoted to captain of %s.' % (name(team.captain), team.link()), affected=team.captain)
        return HttpResponseRedirect('/')
        
    if action == 'delete_post':
        post = TeamPost.objects.get(id=int(request.REQUEST['id']))
        if request.user == post.author or request.user == team.captain or request.user.is_superuser:
            post.delete()
            message(request, 'The post has been deleted.')
            log(request, 'team_post_delete', '%s deleted a post in a %s.' % (name(request.user), team.link()))
        else:
            message(request, 'Error: you do not have permission to delete the post.')
        return redirect
        
    if request.user not in team.members.all() and not request.user.is_superuser:
        message(request, 'Error: you are not in this team.')
        return redirect
    # All actions beyond this point require team membership
    
    if action == 'Post':
        text = request.REQUEST['message']
        post = TeamPost(team=team, author=request.user, text=text)
        post.save()
        for member in team.members.all():
            if member.id == request.user.id:
                continue
            if member.profile.posts_email == 2:
                t = get_template('email/posts_email.mako')
                body = t.render(name=member.first_name, poster=request.user.first_name, team=team, text=text, login_url=login_url(member))
                send_mail('%s Post' % team.event.name, body, 'State High TSA <<EMAIL>>', [member.email])
        message(request, 'Message posted.')
        log(request, 'team_post', '%s posted to their %s' % (name(request.user), team.link()))
        return redirect
        
    if action == 'Add Member':
        u = User.objects.get(id=int(request.REQUEST['user_id']))
        if u.teams.filter(event=team.event).count() != 0:
            message(request, 'Error: %s is already in a team for that event.' % u.first_name)
            return redirect
        team.members.add(u)
        team.save()
        message(request, '%s %s has been added to the team.' % (u.first_name, u.last_name))
        log(request, 'team_join', '%s has been added to a %s.' % (name(u), team.link()), affected=u)
        return redirect
        
    if request.user != team.captain and not request.user.is_superuser:
        message(request, 'Error: you are not the team captain.')
        return redirect
    # All actions beyond this point require team captain
    
    if action == 'lock_team':
        team.entry_locked = not team.entry_locked
        team.save()
        if team.entry_locked:
            message(request, 'The team is now locked.')
        else:
            message(request, 'The team is now unlocked.')
    if action == 'remove_member':
        u = User.objects.get(id=int(request.REQUEST['user_id']))
        team.members.remove(u)
        team.save()
        message(request, '%s %s has been removed from the team.' % (u.first_name, u.last_name))
        log(request, 'team_remove', '%s has been removed from their %s.' % (name(u), team.link()), affected=u)
    if action == 'promote_member':
        u = User.objects.get(id=int(request.REQUEST['user_id']))
        team.captain = u
        team.save()
        message(request, '%s %s has been promoted to team captain.' % (u.first_name, u.last_name))
        log(request, 'team_promote', '%s has been promoted to captain of their %s.' % (name(u), team.link()), affected=u)
    if action == 'delete_team':
        event = team.event.name
        team.delete()
        message(request, 'The team has been deleted.')
        log(request, 'team_delete', 'A %s team has been deleted.' % event)
        return HttpResponseRedirect('/')

    return redirect

@login_required
def event_list(request):
    if request.method == 'POST':
        i = 0
        for event in Event.objects.all():
            if event.entry_locked and not 'lock_%d' % event.id in request.POST:
                event.entry_locked = False
                event.save()
                i += 1
            elif not event.entry_locked and 'lock_%d' % event.id in request.POST:
                event.entry_locked = True
                event.save()
                i += 1
            if event.entry_locked_senior and not 'senior_lock_%d' % event.id in request.POST:
                event.entry_locked_senior = False
                event.save()
                i += 1
            elif not event.entry_locked_senior and 'senior_lock_%d' % event.id in request.POST:
                event.entry_locked_senior = True
                event.save()
                i += 1
        message(request, '%d events updated.' % i)
        if i > 0:
            log(request, 'admin_lock', '%s updated the lock status of %d events.' % (name(request.user), i))
    return render_template('event_list.mako',request,events=Event.objects.all())
    
class NewUserForm(forms.Form):
        username = forms.CharField()
{'fraction_non_alphanumeric': 0.12605328113030898, 'fraction_numerical': 0.0021278406672908335, 'mean_word_length': 2.695392357288882, 'pattern_counts': {'":': 0, '<': 15, '<?xml version=': 0, '>': 17, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '755171', 'n_tokens_mistral': 7006, 'n_tokens_neox': 6889, 'n_words': 1841}