views.py 4.26 KB
Newer Older
stef's avatar
stef committed
1
2
from forms import AddViolation
from django.http import HttpResponse, HttpResponseRedirect, Http404
3
from django.shortcuts import render_to_response, get_object_or_404
4
from django.template import RequestContext
stef's avatar
stef committed
5
6
from django.core.files import File
from django.conf import settings
stef's avatar
stef committed
7
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
8
from django.core.exceptions import ObjectDoesNotExist
stef's avatar
stef committed
9
10
11
from models import Violation, Attachment, Comment
from tempfile import mkstemp
from datetime import datetime
12
import hashlib, os, re, json, hashlib
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
from urlparse import urljoin
from BeautifulSoup import BeautifulSoup, Comment as BComment

def sanitizeHtml(value, base_url=None):
    rjs = r'[\s]*(&#x.{1,7})?'.join(list('javascript:'))
    rvb = r'[\s]*(&#x.{1,7})?'.join(list('vbscript:'))
    re_scripts = re.compile('(%s)|(%s)' % (rjs, rvb), re.IGNORECASE)
    validTags = 'p i strong b u a h1 h2 h3 pre br img'.split()
    validAttrs = 'href src width height'.split()
    urlAttrs = 'href src'.split() # Attributes which should have a URL
    soup = BeautifulSoup(value)
    for comment in soup.findAll(text=lambda text: isinstance(text, BComment)):
        # Get rid of comments
        comment.extract()
    for tag in soup.findAll(True):
        if tag.name not in validTags:
            tag.hidden = True
        attrs = tag.attrs
        tag.attrs = []
        for attr, val in attrs:
            if attr in validAttrs:
                val = re_scripts.sub('', val) # Remove scripts (vbs & js)
                if attr in urlAttrs:
                    val = urljoin(base_url, val) # Calculate the absolute url
                tag.attrs.append((attr, val))

    return soup.renderContents().decode('utf8')
stef's avatar
stef committed
40
41

def add(request):
stef's avatar
stef committed
42
43
44
45
46
47
48
49
    if request.method == 'POST':
        form = AddViolation(request.POST)
        if form.is_valid():
            v=Violation(
                country = form.cleaned_data['country'],
                operator = form.cleaned_data['operator'],
                contract = form.cleaned_data['contract'],
                resource = form.cleaned_data['resource'],
stef's avatar
stef committed
50
                resource_name = form.cleaned_data['resource_name'],
stef's avatar
stef committed
51
52
53
54
                type = form.cleaned_data['type'],
                media = form.cleaned_data['media'],
                temporary = form.cleaned_data['temporary'],
                contractual = form.cleaned_data['contractual'],
55
                contract_excerpt = sanitizeHtml(form.cleaned_data['contract_excerpt']),
stef's avatar
stef committed
56
57
58
59
60
                loophole = form.cleaned_data['loophole']
                )
            v.save()
            c = Comment(
                comment=form.cleaned_data['comment'],
61
62
                submitter_email=form.cleaned_data['email'],
                submitter_name=form.cleaned_data['nick'],
stef's avatar
stef committed
63
64
65
66
67
                timestamp=datetime.now(),
                violation=v,
                )
            c.save()
            for f in request.FILES.getlist('attachments[]'):
68
69
70
71
72
73
                a=Attachment(comment=c, name=f.name)
                m = hashlib.sha256()
                for chunk in f.chunks():
                    m.update(chunk)
                sname=m.hexdigest()
                a.storage.save(sname,f)
stef's avatar
stef committed
74
                a.save()
stef's avatar
stef committed
75
76
            return HttpResponseRedirect('/') # Redirect after POST
    else:
stef's avatar
stef committed
77
        form = AddViolation()
stef's avatar
stef committed
78

stef's avatar
stef committed
79
80
81
82
    return render_to_response(
        'add.html',
        { 'form': form, },
        context_instance=RequestContext(request))
stef's avatar
stef committed
83

84
85
def ajax(request, country=None, operator=None):
    if not operator:
86
        return HttpResponse(json.dumps(sorted(list(set([x.operator for x in Violation.objects.filter(country=country)])))))
87
    else:
88
        return HttpResponse(json.dumps(sorted(list(set([x.contract for x in Violation.objects.filter(country=country).filter(operator=operator)])))))
stef's avatar
stef committed
89
90

def index(request):
stef's avatar
stef committed
91
92
93
94
95
96
97
98
99
100
101
102
    v_list = Violation.objects.all()
    paginator = Paginator(v_list, 25)

    page = request.GET.get('page','1')
    try:
        violations = paginator.page(page)
    except PageNotAnInteger:
        violations = paginator.page(1)
    except EmptyPage:
        violations = paginator.page(paginator.num_pages)

    return render_to_response('list.html', {"violations": violations})
103
104
105

def view(request,id):
    v = get_object_or_404(Violation, pk=id)
stef's avatar
stef committed
106
    return render_to_response('view.html', { 'v': v, },context_instance=RequestContext(request))