<commit_before># -*- coding: utf-8  -*-
from datetime import timedelta
from django.contrib.auth.decorators import permission_required, login_required
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.core.urlresolvers import reverse
from django.core.exceptions import PermissionDenied, ObjectDoesNotExist

from post_office import mail
import unicodecsv

from activities.models import Activity, Review, Participation, Episode
from activities.forms import ActivityForm, DirectActivityForm, DisabledActivityForm, ReviewForm
from accounts.models import get_gender
from activities.utils import get_pending_activities, get_approved_activities, get_rejected_activities, has_submitted_any_activity
from clubs.models import Club
from clubs.utils import get_presidency, is_coordinator_or_member, is_coordinator_of_any_club, get_media_center, \
    is_member_of_any_club, is_employee_of_any_club
from core.utilities import FVP_EMAIL, MVP_EMAIL, DHA_EMAIL
from media.utils import MAX_OVERDUE_REPORTS


def list_activities(request):
    """
    Return a list of the current year's activities displayed as a calendar as well as a table.
    (For the front-end, only the calendar is visible.)
    * For superusers, SC Presidency members (Chairman, Deputies, and Assistants), all activities should be visible.
    * For Deanship of Student Affairs reviewers, only activities approved by SC Presidency should be visible.
    * For club coordinators, only activities approved by SC-P and DSA in addition to pending and rejected activities
      of their own club.
    * For Deanship of Student Affairs employees and other users, only activities approved by SC-P and DSA should be
      visible.
    """
    context = {}
    template = 'activities/list_privileged.html'
    if request.user.is_superuser or is_coordinator_or_member(get_presidency(), request.user)\
            or request.user.has_perm('activities.add_presidency_review'):
        # If the user is a super user or part of the presidency, then show all activities
        context['approved'] = get_approved_activities()
        context['pending'] = get_pending_activities()
        context['rejected'] = get_rejected_activities()

    # elif request.user.groups.filter(name="deanship_master").exists():
    elif request.user.has_perm('activities.add_deanship_review'):
        # If the user is part of the deanship of student affairs, only show activities approved by presidency
        context['approved'] = get_approved_activities()
        context['pending'] = get_pending_activities().filter(review__review_type="P", review__is_approved=True)
        context['rejected'] = get_rejected_activities().filter(review__review_type="P", review__is_approved=True)

    elif (is_coordinator_of_any_club(request.user) or is_member_of_any_club(request.user) or has_submitted_any_activity(request.user)) and \
         not is_coordinator_or_member(get_presidency(), request.user) and \
         not is_coordinator_or_member(get_media_center(), request.user):
        # For club coordinators (and members?), show approved activities as well as their own club's pending and
        # rejected activities
        context['approved'] = get_approved_activities()
        context['pending'] = get_pending_activities().filter(primary_club__in=request.user.coordination.all()
                                                             | request.user.memberships.all()) | \
                             get_pending_activities().filter(submitter=request.user)
        context['rejected'] = get_rejected_activities().filter(primary_club__in=request.user.coordination.all()
                                                               | request.user.memberships.all()) | \
                              get_rejected_activities().filter(submitter=request.user)

        # Media-related
        # Only display to coordinators
        if is_coordinator_of_any_club(request.user):
            context['due_report_count'] = request.user.coordination.all()[0].get_due_report_count()
            context['overdue_report_count'] = request.user.coordination.all()[0].get_overdue_report_count()
            context['MAX_OVERDUE_REPORTS'] = MAX_OVERDUE_REPORTS

    elif is_employee_of_any_club(request.user):
        # For employees, display all approved activities, as well as their clubs' approved activities in
        # a separate table
        # An employee is basically similar to a normal user, the only difference is having another table that
        # includes the employee's relevant activities
        context['approved'] = get_approved_activities()
        context['pending'] = Activity.objects.none()
        context['rejected'] = Activity.objects.none()
        context['club_approved'] = get_approved_activities().filter(primary_club__in=request.user.employee.all())

        template = 'activities/list_employee.html'
    else:
        context['approved'] = get_approved_activities()
        context['pending'] = Activity.objects.none()
        context['rejected'] = Activity.objects.none()

        if request.user.is_authenticated():
            template = 'activities/list_normal.html'
        else:
            template = 'activities/front/list.html'

    return render(request, template, context)

@login_required
def show(request, activity_id):
    # If the activity is approved, everyone can see it.  If it is not,
    # only the head of the Student Club, the Media Team, the members
    # of the related clubs and the person who submitted it can see it.
    activity = get_object_or_404(Activity, pk=activity_id)
    
    context = {'activity': activity}
    # The activity object is the only thing that should be in the context  [Saeed, 17 Jun 2014]
    
    if request.user.is_authenticated():
        user_clubs = request.user.memberships.all() | request.user.coordination.all()
        is_coordinator = activity.primary_club in request.user.coordination.all()
        is_submitter = activity.submitter == request.user

#        By definition, the coordinator should have all the below-mentioned
#        permissions; all we need is use {{ perms }} from within the template
#        [Saeed, 17 Jun 2014]

#        {{ perms }} cannot figure out whether or not someone is a
#        coordinator of this specific club.  In addition, Django
#        templates are limited when dealing with combined and/or
#        conditions. [Osama, 27 Jun 2014]

        if request.user.has_perm('activities.change_activity') or \
            is_coordinator or is_submitter:
            context['can_edit'] = True
        if request.user.has_perm('activities.view_participation') or \
            is_coordinator or is_submitter:
            context['can_view_participation'] = True
        if request.user.has_perm('activities.view_deanship_review') or \
            is_coordinator or is_submitter:
            context['can_view_deanship_review'] = True
        if request.user.has_perm('activities.view_presidency_review') or \
            is_coordinator or is_submitter:
            context['can_view_presidency_review'] = True
        if request.user.has_perm('media.add_followupreport') or \
            is_coordinator or is_submitter:
            context['can_add_followupreport'] = True
        if request.user.has_perm('niqati.view_order') or \
            is_coordinator or is_submitter:
            context['can_view_niqati_orders'] = True

    else:
        user_clubs = Club.objects.none()

    activity_primary_club = activity.primary_club
    activity_secondary_clubs = activity.secondary_clubs.all()
    activity_clubs = [activity_primary_club] + [club for club in activity_secondary_clubs]

    # The third test condition, that is:
    #   any([club in activity_clubs for club in user_clubs])
    #  checks if any of the clubs the user is a member of is also
    #  orginizing the activity that the user is trying to see.  If
    #  will be True if any club is one of the organizers and it will
    #  be False if none is.
    if not activity.is_approved() and \
       not request.user.has_perm('activities.view_activity') and \
       not any([club in activity_clubs for club in user_clubs]) and \
       not request.user == activity.submitter:
        raise PermissionDenied

    return render(request, 'activities/show.html', context)

@login_required
def create(request):
    
    # --- Permission checks ---<commit_msg>Corrected permissions Deanship reviewers can view activity page when the activity is approved by presidency and not (yet) approved by deanship<commit_after># -*- coding: utf-8  -*-
from datetime import timedelta
from django.contrib.auth.decorators import permission_required, login_required
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.core.urlresolvers import reverse
from django.core.exceptions import PermissionDenied, ObjectDoesNotExist

from post_office import mail
import unicodecsv

from activities.models import Activity, Review, Participation, Episode
from activities.forms import ActivityForm, DirectActivityForm, DisabledActivityForm, ReviewForm
from accounts.models import get_gender
from activities.utils import get_pending_activities, get_approved_activities, get_rejected_activities, has_submitted_any_activity
from clubs.models import Club
from clubs.utils import get_presidency, is_coordinator_or_member, is_coordinator_of_any_club, get_media_center, \
    is_member_of_any_club, is_employee_of_any_club
from core.utilities import FVP_EMAIL, MVP_EMAIL, DHA_EMAIL
from media.utils import MAX_OVERDUE_REPORTS


def list_activities(request):
    """
    Return a list of the current year's activities displayed as a calendar as well as a table.
    (For the front-end, only the calendar is visible.)
    * For superusers, SC Presidency members (Chairman, Deputies, and Assistants), all activities should be visible.
    * For Deanship of Student Affairs reviewers, only activities approved by SC Presidency should be visible.
    * For club coordinators, only activities approved by SC-P and DSA in addition to pending and rejected activities
      of their own club.
    * For Deanship of Student Affairs employees and other users, only activities approved by SC-P and DSA should be
      visible.
    """
    context = {}
    template = 'activities/list_privileged.html'
    if request.user.is_superuser or is_coordinator_or_member(get_presidency(), request.user)\
            or request.user.has_perm('activities.add_presidency_review'):
        # If the user is a super user or part of the presidency, then show all activities
        context['approved'] = get_approved_activities()
        context['pending'] = get_pending_activities()
        context['rejected'] = get_rejected_activities()

    # elif request.user.groups.filter(name="deanship_master").exists():
    elif request.user.has_perm('activities.add_deanship_review'):
        # If the user is part of the deanship of student affairs, only show activities approved by presidency
        context['approved'] = get_approved_activities()
        context['pending'] = get_pending_activities().filter(review__review_type="P", review__is_approved=True)
        context['rejected'] = get_rejected_activities().filter(review__review_type="P", review__is_approved=True)

    elif (is_coordinator_of_any_club(request.user) or is_member_of_any_club(request.user) or has_submitted_any_activity(request.user)) and \
         not is_coordinator_or_member(get_presidency(), request.user) and \
         not is_coordinator_or_member(get_media_center(), request.user):
        # For club coordinators (and members?), show approved activities as well as their own club's pending and
        # rejected activities
        context['approved'] = get_approved_activities()
        context['pending'] = get_pending_activities().filter(primary_club__in=request.user.coordination.all()
                                                             | request.user.memberships.all()) | \
                             get_pending_activities().filter(submitter=request.user)
        context['rejected'] = get_rejected_activities().filter(primary_club__in=request.user.coordination.all()
                                                               | request.user.memberships.all()) | \
                              get_rejected_activities().filter(submitter=request.user)

        # Media-related
        # Only display to coordinators
        if is_coordinator_of_any_club(request.user):
            context['due_report_count'] = request.user.coordination.all()[0].get_due_report_count()
            context['overdue_report_count'] = request.user.coordination.all()[0].get_overdue_report_count()
            context['MAX_OVERDUE_REPORTS'] = MAX_OVERDUE_REPORTS

    elif is_employee_of_any_club(request.user):
        # For employees, display all approved activities, as well as their clubs' approved activities in
        # a separate table
        # An employee is basically similar to a normal user, the only difference is having another table that
        # includes the employee's relevant activities
        context['approved'] = get_approved_activities()
        context['pending'] = Activity.objects.none()
        context['rejected'] = Activity.objects.none()
        context['club_approved'] = get_approved_activities().filter(primary_club__in=request.user.employee.all())

        template = 'activities/list_employee.html'
    else:
        context['approved'] = get_approved_activities()
        context['pending'] = Activity.objects.none()
        context['rejected'] = Activity.objects.none()

        if request.user.is_authenticated():
            template = 'activities/list_normal.html'
        else:
            template = 'activities/front/list.html'

    return render(request, template, context)

@login_required
def show(request, activity_id):
    # If the activity is approved, everyone can see it.  If it is not,
    # only the head of the Student Club, the Media Team, the members
    # of the related clubs and the person who submitted it can see it.
    activity = get_object_or_404(Activity, pk=activity_id)
    
    context = {'activity': activity}
    # The activity object is the only thing that should be in the context  [Saeed, 17 Jun 2014]
    
    if request.user.is_authenticated():
        user_clubs = request.user.memberships.all() | request.user.coordination.all()
        is_coordinator = activity.primary_club in request.user.coordination.all()
        is_submitter = activity.submitter == request.user

#        By definition, the coordinator should have all the below-mentioned
#        permissions; all we need is use {{ perms }} from within the template
#        [Saeed, 17 Jun 2014]

#        {{ perms }} cannot figure out whether or not someone is a
#        coordinator of this specific club.  In addition, Django
#        templates are limited when dealing with combined and/or
#        conditions. [Osama, 27 Jun 2014]

        if request.user.has_perm('activities.change_activity') or \
            is_coordinator or is_submitter:
            context['can_edit'] = True
        if request.user.has_perm('activities.view_participation') or \
            is_coordinator or is_submitter:
            context['can_view_participation'] = True
        if request.user.has_perm('activities.view_deanship_review') or \
            is_coordinator or is_submitter:
            context['can_view_deanship_review'] = True
        if request.user.has_perm('activities.view_presidency_review') or \
            is_coordinator or is_submitter:
            context['can_view_presidency_review'] = True
        if request.user.has_perm('media.add_followupreport') or \
            is_coordinator or is_submitter:
            context['can_add_followupreport'] = True
        if request.user.has_perm('niqati.view_order') or \
            is_coordinator or is_submitter:
            context['can_view_niqati_orders'] = True

    else:
        user_clubs = Club.objects.none()

    activity_primary_club = activity.primary_club
    activity_secondary_clubs = activity.secondary_clubs.all()
    activity_clubs = [activity_primary_club] + [club for club in activity_secondary_clubs]

    # --- Permission checks ---

    # If the user is a superuser or part of presidency or user is the activity's club coordinator or
    #  a coordinator of a secondary club in the activity, show the activity regardless of status
    # Elseif user is a DSA reviewer, show the activity if it's approved by presidency
    # Else (employees or others), show activity only if approved
    if request.user.is_superuser or request.user.has_perm('activities.add_presidency_review') \
        or any([club in activity_clubs for club in user_clubs]):
        # Don't raise any errors
        pass
    elif request.user.has_perm('activities.add_deanship_review'):
        if not activity.is_approved_by_presidency():
            raise PermissionDenied
    else:
        if not activity.is_approved():
            raise PermissionDenied

    return render(request, 'activities/show.html', context)

@login_required
def create(request):
    
    # --- Permission checks ---
{'fraction_non_alphanumeric': 0.08068530416160213, 'fraction_numerical': 0.0034728251432540372, 'mean_word_length': 3.3433886375062847, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 10, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '613822', 'n_tokens_mistral': 4824, 'n_tokens_neox': 4618, 'n_words': 1328}