views.py 6.08 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
9
from django.contrib import messages
stef's avatar
stef committed
10 11
from django.utils.translation import ugettext_lazy as _
from models import Violation, Attachment, Comment, Confirmation
stef's avatar
stef committed
12 13
from tempfile import mkstemp
from datetime import datetime
14 15 16
import hashlib, os, re, json, smtplib
from random import randint
from email.mime.text import MIMEText
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
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
44

45 46 47 48
def activate(request):
    v=Violation.objects.get(activationid=request.GET.get('key','asdf'))
    v.activationid=''
    v.save()
stef's avatar
stef committed
49
    messages.add_message(request, messages.INFO, _('Thank you for verifying your submission.'))
50 51
    return HttpResponseRedirect('/') # Redirect after POST

stef's avatar
stef committed
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
def confirm(request, id, name=None):
    if name:
        if Confirmation.objects.filter(email=name, violation=id).count()==0:
            actid=sendverifymail('confirm/',name)
            c=Confirmation(key=actid, email=name, violation=Violation.objects.get(pk=id))
            c.save()
        return HttpResponse('<div class="confirm_thanks">Thank you for your confirmation</div>')
    c=Confirmation.objects.get(key=id)
    if c:
        c.key=''
        c.save()
    return HttpResponse('<div class="confirm_thanks">Thank you for verifying your confirmation</div>')

def sendverifymail(service,to):
    actid = hashlib.sha1(''.join([chr(randint(32, 122)) for x in range(12)])).hexdigest()
    msg = MIMEText(_("Your verification key is %s/%s%s\n") % (settings.ROOT_URL or 'http://localhost:8001/', service, actid))
    msg['Subject'] = _('NNMon submission verification')
    msg['From'] = 'nnmon@nnmon.lqdn.fr'
    msg['To'] = to
    s = smtplib.SMTP('localhost')
    s.sendmail('nnmon@nnmon.lqdn.fr', [to], msg.as_string())
    s.quit()
    return actid

stef's avatar
stef committed
76
def add(request):
stef's avatar
stef committed
77 78 79
    if request.method == 'POST':
        form = AddViolation(request.POST)
        if form.is_valid():
stef's avatar
stef committed
80
            actid=sendverifymail('activate?key=',form.cleaned_data['email'])
stef's avatar
stef committed
81 82 83 84 85
            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
86
                resource_name = form.cleaned_data['resource_name'],
stef's avatar
stef committed
87 88 89 90
                type = form.cleaned_data['type'],
                media = form.cleaned_data['media'],
                temporary = form.cleaned_data['temporary'],
                contractual = form.cleaned_data['contractual'],
91
                contract_excerpt = sanitizeHtml(form.cleaned_data['contract_excerpt']),
92 93
                loophole = form.cleaned_data['loophole'],
                activationid = actid
stef's avatar
stef committed
94 95 96 97
                )
            v.save()
            c = Comment(
                comment=form.cleaned_data['comment'],
98 99
                submitter_email=form.cleaned_data['email'],
                submitter_name=form.cleaned_data['nick'],
stef's avatar
stef committed
100 101 102 103 104
                timestamp=datetime.now(),
                violation=v,
                )
            c.save()
            for f in request.FILES.getlist('attachments[]'):
105 106 107 108 109 110
                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
111
                a.save()
112

stef's avatar
stef committed
113
            messages.add_message(request, messages.INFO, _('Thank you for submitting this report, you will receive a verification email shortly.'))
stef's avatar
stef committed
114 115
            return HttpResponseRedirect('/') # Redirect after POST
    else:
stef's avatar
stef committed
116
        form = AddViolation()
stef's avatar
stef committed
117

stef's avatar
stef committed
118 119 120 121
    return render_to_response(
        'add.html',
        { 'form': form, },
        context_instance=RequestContext(request))
stef's avatar
stef committed
122

123 124
def ajax(request, country=None, operator=None):
    if not operator:
125
        return HttpResponse(json.dumps(sorted(list(set([x.operator for x in Violation.objects.filter(country=country,activationid='')])))))
126
    else:
127
        return HttpResponse(json.dumps(sorted(list(set([x.contract for x in Violation.objects.filter(country=country,activationid='',operator=operator)])))))
stef's avatar
stef committed
128 129

def index(request):
130
    v_list = Violation.objects.filter(activationid='')
stef's avatar
stef committed
131 132 133 134 135 136 137 138 139 140
    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)

141
    return render_to_response('list.html', {"violations": violations},context_instance=RequestContext(request))
142 143 144

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