<commit_before>#    Eve W-Space
#    Copyright (C) 2013  <NAME> and other contributors
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version. An additional term under section
#    7 of the GPL is included in the LICENSE file.
#
#    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 General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
from datetime import datetime
import pytz
from collections import defaultdict
from django.core.exceptions import PermissionDenied, ObjectDoesNotExist
from django.template.response import TemplateResponse
from django.contrib.auth.models import User, Group, Permission
from django.shortcuts import get_object_or_404
from django import forms
from core.utils import get_config
from core.models import Corporation
from core import tasks as core_tasks
from django.http import Http404, HttpResponse, HttpResponseRedirect
from django.core.paginator import Paginator
from django.core.urlresolvers import reverse
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import authenticate, login
from django.contrib.auth.decorators import permission_required, login_required
from models import *
from API.models import MemberAPIKey, APIKey
from API import cache_handler as handler
import eveapi

def applicant_register(request, app_type=None):
    email_required = get_config('RECRUIT_REQUIRE_EMAIL', None).value == "1"
    if not app_type:
        app_type = get_object_or_404(AppType, pk=request.POST.get('app_type'))
    if request.method == "POST":
        form = RecruitRegistrationForm(request.POST)
        valid = form.is_valid()
        email = request.POST.get('email', None)
        if email_required and not email:
            form.errors['__all__'] = form.error_class(
                    ['An email address is required.'])
            valid = False
        if valid:
            newUser = form.save()
            newUser.is_active = False
            if email:
                newUser.email = email
            newUser.save()
            log_user = authenticate(username=newUser.username,
                    password=request.POST.get('password1', ''))
            login(request, log_user)
            return HttpResponseRedirect(request.POST.get('next_page'))
    else:
        form = RecruitRegistrationForm()
    next_page = reverse('Recruitment.views.get_application',
            args=(app_type.pk,))
    return TemplateResponse(request, "recruit_register.html", {'form': form,
                            'email_required': email_required,
                            'next_page': next_page,
                            'app_type': app_type.pk})


def get_application(request, app_type_id):
    app_type = get_object_or_404(AppType, pk=app_type_id)
    if app_type.require_account and not request.user.is_authenticated():
        raise PermissionDenied
    if not app_type.require_account and not request.user.is_authenticated():
        return applicant_register(request, app_type)
    app = app_type.start_application(request.user)
    return HttpResponseRedirect(
            reverse('Recruitment.views.get_application_form', args=(app.pk,)))

@login_required
def get_application_form(request, app_id):
    app = get_object_or_404(Application, pk=app_id, app_type__visible=True)
    app_type = app.app_type
    if app.applicant != request.user:
        raise PermissionDenied
    status_view = False
    if app.submitted:
        status_view = True
    stages = AppStage.objects.filter(app_type=app_type.pk, visible=True)
    questions = {}
    for stage in stages:
        questions[stage.pk] = AppQuestion.objects.filter(app_stage=stage.pk, visible=True)
    return TemplateResponse(request, 'application.html', {'app': app_type,
        'application': app, 'status_view': status_view, 'stages': stages, 'questions': questions})

@login_required
def get_api_keys(request, app_id):
    app = get_object_or_404(Application, pk=app_id)
    if app.applicant != request.user or not request.is_ajax():
        raise PermissionDenied
    if request.method == "POST":
        error_list = []
        key_id = request.POST.get('key_id', 0)
        key_vcode = request.POST.get('vcode', '')
        if not key_id or not key_vcode:
            error_list.append('You must provide both Key ID and vCode!')
        else:
            try:
                key_id = int(key_id)
            except ValueError:
               error_list.append('The Key ID is invalid (not an integer)!')
            api_key = MemberAPIKey(keyid=key_id, vcode=key_vcode,
                    user=request.user)
            api_key.validate()
            if not api_key.validation_error:
                return HttpResponse()
            else:
                error_list.append(api_key.validation_error)
                api_key.delete()
        if error_list:
            error_text = ''
            for x in error_list:
                error_text += '%s<br />' % x
            return HttpResponse(error_text, status=400)
    else:

        return TemplateResponse(request, 'api_widget.html',
                {'application': app})

@login_required
def save_application(request, app_id):
    if not request.is_ajax():
        raise PermissionDenied
    app = get_object_or_404(Application, pk=app_id)
    if not app.required_response_present(request.POST.copy()):
        raise "Not all required questions were answered"
    try:
        app.save_from_dict(request.POST.copy())
        app.add_action_entries()
    except Exception as ex:
        raise
    return HttpResponse()

@permission_required('Recruitment.can_recruit')
def view_applications(request):
    apps = Application.objects.filter(submitted__isnull=False,
            disposition__isnull=True).all()
    return TemplateResponse(request, 'ro_panel.html', {'apps': apps})

@permission_required('Recruitment.can_recruit')
def search_applications(request):
    search = True
    filter_text = request.POST.get('filter', "")
    if request.method == "POST":
        if filter_text:
            apps = Application.objects.filter(submitted__isnull=False,
                    disposition__isnull=False, applicant__username__icontains=filter_text).order_by('-closetime').all()
        else:
            apps = Application.objects.filter(submitted__isnull=False,
                disposition__isnull=False).order_by('-closetime').all()[:20]
        return TemplateResponse(request, 'recruiter_applications.html', {'apps': apps, 'search': search})
    else:
        apps = Application.objects.filter(submitted__isnull=False,
                disposition__isnull=False).order_by('-closetime').all()[:20]
    	return TemplateResponse(request, 'ro_panel.html', {'apps': apps, 'search': search})
    
@permission_required('Recruitment.can_recruit')
def recruiter_api_key(request, app_id):
    if not request.is_ajax():
        raise PermissionDenied
    app = get_object_or_404(Application, pk=app_id)
    if app.closetime: 
        raise PermissionDenied
    api_keys = app.applicant.api_keys.all()
    return TemplateResponse(request, "recruiter_manage_keys.html",
            {'api_keys': api_keys, 'app': app})
            
@permission_required('Recruitment.can_recruit')
def recruiter_api_key_delete(request, app_id, key_id):
    if not request.is_ajax():
        raise PermissionDenied
    api_key = get_object_or_404(MemberAPIKey, keyid=key_id)
    auto_comment = "An API (%s) was deleted by %s" % (key_id, request.user)
    app_comment = AppComment(application=app, author=request.user, comment=auto_comment)
    api_key.delete()
    return HttpResponse()

@permission_required('Recruitment.can_recruit')
def recruiter_api_key_edit(request, app_id, key_id):
    if not request.is_ajax():
        raise PermissionDenied
    app = get_object_or_404(Application, pk=app_id)
    if request.method == 'GET':
        api_key = get_object_or_404(MemberAPIKey, keyid=key_id)
    else:
        key_id = int(request.POST.get('Recruiter_key_id', None).replace(' ',''))
        vcode = request.POST.get('Recruiter_vcode', None).replace(' ', '')
        try:
            api_key = MemberAPIKey.objects.get(keyid=key_id, user=app.applicant)
            api_key.keyid = key_id
            api_key.vcode = vcode
            api_key.user = app.applicant
            api_key.validate()
        except:
            api_key = MemberAPIKey(user=app.applicant,
                            keyid=key_id,
                            vcode=vcode)
            api_key.validate()
            auto_comment = "An API (%s) was added by %s" % (key_id, request.user)
            app_comment = AppComment(application=app, author=request.user, comment=auto_comment)
<commit_msg>Bug fix for deleting API keys<commit_after>#    Eve W-Space
#    Copyright (C) 2013  <NAME> and other contributors
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version. An additional term under section
#    7 of the GPL is included in the LICENSE file.
#
#    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 General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
from datetime import datetime
import pytz
from collections import defaultdict
from django.core.exceptions import PermissionDenied, ObjectDoesNotExist
from django.template.response import TemplateResponse
from django.contrib.auth.models import User, Group, Permission
from django.shortcuts import get_object_or_404
from django import forms
from core.utils import get_config
from core.models import Corporation
from core import tasks as core_tasks
from django.http import Http404, HttpResponse, HttpResponseRedirect
from django.core.paginator import Paginator
from django.core.urlresolvers import reverse
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import authenticate, login
from django.contrib.auth.decorators import permission_required, login_required
from models import *
from API.models import MemberAPIKey, APIKey
from API import cache_handler as handler
import eveapi

def applicant_register(request, app_type=None):
    email_required = get_config('RECRUIT_REQUIRE_EMAIL', None).value == "1"
    if not app_type:
        app_type = get_object_or_404(AppType, pk=request.POST.get('app_type'))
    if request.method == "POST":
        form = RecruitRegistrationForm(request.POST)
        valid = form.is_valid()
        email = request.POST.get('email', None)
        if email_required and not email:
            form.errors['__all__'] = form.error_class(
                    ['An email address is required.'])
            valid = False
        if valid:
            newUser = form.save()
            newUser.is_active = False
            if email:
                newUser.email = email
            newUser.save()
            log_user = authenticate(username=newUser.username,
                    password=request.POST.get('password1', ''))
            login(request, log_user)
            return HttpResponseRedirect(request.POST.get('next_page'))
    else:
        form = RecruitRegistrationForm()
    next_page = reverse('Recruitment.views.get_application',
            args=(app_type.pk,))
    return TemplateResponse(request, "recruit_register.html", {'form': form,
                            'email_required': email_required,
                            'next_page': next_page,
                            'app_type': app_type.pk})


def get_application(request, app_type_id):
    app_type = get_object_or_404(AppType, pk=app_type_id)
    if app_type.require_account and not request.user.is_authenticated():
        raise PermissionDenied
    if not app_type.require_account and not request.user.is_authenticated():
        return applicant_register(request, app_type)
    app = app_type.start_application(request.user)
    return HttpResponseRedirect(
            reverse('Recruitment.views.get_application_form', args=(app.pk,)))

@login_required
def get_application_form(request, app_id):
    app = get_object_or_404(Application, pk=app_id, app_type__visible=True)
    app_type = app.app_type
    if app.applicant != request.user:
        raise PermissionDenied
    status_view = False
    if app.submitted:
        status_view = True
    stages = AppStage.objects.filter(app_type=app_type.pk, visible=True)
    questions = {}
    for stage in stages:
        questions[stage.pk] = AppQuestion.objects.filter(app_stage=stage.pk, visible=True)
    return TemplateResponse(request, 'application.html', {'app': app_type,
        'application': app, 'status_view': status_view, 'stages': stages, 'questions': questions})

@login_required
def get_api_keys(request, app_id):
    app = get_object_or_404(Application, pk=app_id)
    if app.applicant != request.user or not request.is_ajax():
        raise PermissionDenied
    if request.method == "POST":
        error_list = []
        key_id = request.POST.get('key_id', 0)
        key_vcode = request.POST.get('vcode', '')
        if not key_id or not key_vcode:
            error_list.append('You must provide both Key ID and vCode!')
        else:
            try:
                key_id = int(key_id)
            except ValueError:
               error_list.append('The Key ID is invalid (not an integer)!')
            api_key = MemberAPIKey(keyid=key_id, vcode=key_vcode,
                    user=request.user)
            api_key.validate()
            if not api_key.validation_error:
                return HttpResponse()
            else:
                error_list.append(api_key.validation_error)
                api_key.delete()
        if error_list:
            error_text = ''
            for x in error_list:
                error_text += '%s<br />' % x
            return HttpResponse(error_text, status=400)
    else:

        return TemplateResponse(request, 'api_widget.html',
                {'application': app})

@login_required
def save_application(request, app_id):
    if not request.is_ajax():
        raise PermissionDenied
    app = get_object_or_404(Application, pk=app_id)
    if not app.required_response_present(request.POST.copy()):
        raise "Not all required questions were answered"
    try:
        app.save_from_dict(request.POST.copy())
        app.add_action_entries()
    except Exception as ex:
        raise
    return HttpResponse()

@permission_required('Recruitment.can_recruit')
def view_applications(request):
    apps = Application.objects.filter(submitted__isnull=False,
            disposition__isnull=True).all()
    return TemplateResponse(request, 'ro_panel.html', {'apps': apps})

@permission_required('Recruitment.can_recruit')
def search_applications(request):
    search = True
    filter_text = request.POST.get('filter', "")
    if request.method == "POST":
        if filter_text:
            apps = Application.objects.filter(submitted__isnull=False,
                    disposition__isnull=False, applicant__username__icontains=filter_text).order_by('-closetime').all()
        else:
            apps = Application.objects.filter(submitted__isnull=False,
                disposition__isnull=False).order_by('-closetime').all()[:20]
        return TemplateResponse(request, 'recruiter_applications.html', {'apps': apps, 'search': search})
    else:
        apps = Application.objects.filter(submitted__isnull=False,
                disposition__isnull=False).order_by('-closetime').all()[:20]
    	return TemplateResponse(request, 'ro_panel.html', {'apps': apps, 'search': search})
    
@permission_required('Recruitment.can_recruit')
def recruiter_api_key(request, app_id):
    if not request.is_ajax():
        raise PermissionDenied
    app = get_object_or_404(Application, pk=app_id)
    if app.closetime: 
        raise PermissionDenied
    api_keys = app.applicant.api_keys.all()
    return TemplateResponse(request, "recruiter_manage_keys.html",
            {'api_keys': api_keys, 'app': app})
            
@permission_required('Recruitment.can_recruit')
def recruiter_api_key_delete(request, app_id, key_id):
    if not request.is_ajax():
        raise PermissionDenied
    api_key = get_object_or_404(MemberAPIKey, keyid=key_id)
    app = get_object_or_404(Application, pk=app_id)
    auto_comment = "An API (%s) was deleted by %s" % (key_id, request.user)
    app_comment = AppComment(application=app, author=request.user, comment=auto_comment)
    api_key.delete()
    return HttpResponse()

@permission_required('Recruitment.can_recruit')
def recruiter_api_key_edit(request, app_id, key_id):
    if not request.is_ajax():
        raise PermissionDenied
    app = get_object_or_404(Application, pk=app_id)
    if request.method == 'GET':
        api_key = get_object_or_404(MemberAPIKey, keyid=key_id)
    else:
        key_id = int(request.POST.get('Recruiter_key_id', None).replace(' ',''))
        vcode = request.POST.get('Recruiter_vcode', None).replace(' ', '')
        try:
            api_key = MemberAPIKey.objects.get(keyid=key_id, user=app.applicant)
            api_key.keyid = key_id
            api_key.vcode = vcode
            api_key.user = app.applicant
            api_key.validate()
        except:
            api_key = MemberAPIKey(user=app.applicant,
                            keyid=key_id,
                            vcode=vcode)
            api_key.validate()
            auto_comment = "An API (%s) was added by %s" % (key_id, request.user)
            app_comment = AppComment(application=app, author=request.user, comment=auto_comment)

{'fraction_non_alphanumeric': 0.09490841692106411, 'fraction_numerical': 0.005505887483645879, 'mean_word_length': 3.0177398160315376, 'pattern_counts': {'":': 6, '<': 9, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, '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': '5976991', 'n_tokens_mistral': 5393, 'n_tokens_neox': 5224, 'n_words': 1282}