views.py 9.01 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
10
from django.contrib.auth.models import User
stef's avatar
stef committed
11
from django.utils.translation import ugettext_lazy as _
stef's avatar
stef committed
12
from models import Violation, Attachment, Comment, Confirmation
stef's avatar
stef committed
13 14
from tempfile import mkstemp
from datetime import datetime
15 16 17
import hashlib, os, re, json, smtplib
from random import randint
from email.mime.text import MIMEText
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 44
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
45

46
def activate(request):
47 48 49
    try:
        v=Violation.objects.get(activationid=request.GET.get('key','asdf'))
    except:
50
        return HttpResponse(_("Thank you, this has been already activated"))
51 52 53
    if v:
        actid = hashlib.sha1(''.join([chr(randint(32, 122)) for x in range(12)])).hexdigest()
        to=[x.email for x in User.objects.filter(groups__name='moderator')]
Benjamin Sonntag's avatar
Benjamin Sonntag committed
54 55
        msg = MIMEText(_("A new report was submitted. To approve click here: %s/moderate/?key=%s\n") % (settings.ROOT_URL or 'http://localhost:8001/', actid), _charset="utf-8")
        msg['Subject'] = _('NNMon submission approval').encode("Utf-8")
56 57 58 59 60 61 62
        msg['From'] = 'nnmon@nnmon.lqdn.fr'
        msg['To'] = ', '.join(to)
        s = smtplib.SMTP('localhost')
        s.sendmail('nnmon@nnmon.lqdn.fr', to, msg.as_string())
        s.quit()
        v.activationid=actid
        v.save()
Benjamin Sonntag's avatar
Benjamin Sonntag committed
63
        messages.add_message(request, messages.INFO, _('Thank you for verifying your submission. It will be listed shortly, after we\'ve checked that the report is valid.').encode("Utf-8"))
64 65
    return HttpResponseRedirect('/') # Redirect after POST

66
def moderate(request):
67 68 69
    try:
        v=Violation.objects.get(activationid=request.GET.get('key','asdf'))
    except:
stef's avatar
stef committed
70
        return HttpResponse(_("Thank you, this has been already activated"))
71 72 73 74 75
    if not v:
        messages.add_message(request, messages.INFO, _('No such key'))
        return HttpResponseRedirect('/') # Redirect after POST
    if request.GET.get('action','')=='approve':
        if settings.TWITTER_API:
stef's avatar
stef committed
76
            try:
stef's avatar
stef committed
77
                settings.TWITTER_API.PostUpdate(_("New infringement reported for %s (%s) %s") % (v.operator, v.country, v.contract))
stef's avatar
stef committed
78 79
            except:
                pass
80 81 82 83 84 85 86 87 88 89
        v.activationid=''
        v.save()
        messages.add_message(request, messages.INFO, _('Thank you for approving the submission.'))
        return HttpResponseRedirect('/') # Redirect after POST
    if request.GET.get('action','')=='delete':
        v.delete()
        messages.add_message(request, messages.INFO, _('Thank you for deleting the submission.'))
        return HttpResponseRedirect('/') # Redirect after POST
    return render_to_response('view.html', { 'v': v, 'key': request.GET.get('key') },context_instance=RequestContext(request))

stef's avatar
stef committed
90 91 92 93
def confirm(request, id, name=None):
    if name:
        if Confirmation.objects.filter(email=name, violation=id).count()==0:
            actid=sendverifymail('confirm/',name)
94 95 96
            try:
                c=Confirmation(key=actid, email=name, violation=Violation.objects.get(pk=id))
            except:
stef's avatar
stef committed
97
                return HttpResponse(unicode(_("Thank you, this has been already confirmed")))
stef's avatar
stef committed
98
            c.save()
stef's avatar
stef committed
99
        return HttpResponse('<div class="confirm_thanks">%s</div>' % unicode(_('Thank you for your confirmation')) )
stef's avatar
stef committed
100 101 102 103 104 105
    try:
        c = get_object_or_404(Confirmation, key=id)
    except:
        return HttpResponse(unicode(_("Thank you, this has been already confirmed")))
    c.key=''
    c.save()
stef's avatar
stef committed
106
    messages.add_message(request, messages.INFO, unicode(_('Thank you for verifying your confirmation')))
107
    return HttpResponseRedirect('/') # Redirect after POST
stef's avatar
stef committed
108 109 110

def sendverifymail(service,to):
    actid = hashlib.sha1(''.join([chr(randint(32, 122)) for x in range(12)])).hexdigest()
Benjamin Sonntag's avatar
Benjamin Sonntag committed
111 112
    msg = MIMEText(_("Thank you for submitting a new report. To finalize your submission please confirm using your validation key.\nYour verification key is %s/%s%s\nPlease note that reports are moderated, it might take some time before your report appears online. Thank you for your patience.") % (settings.ROOT_URL or 'http://localhost:8001/', service, actid), _charset="utf-8")
    msg['Subject'] = _('NNMon submission verification').encode("Utf-8")
stef's avatar
stef committed
113 114 115 116 117 118 119
    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
120
def add(request):
stef's avatar
stef committed
121 122 123
    if request.method == 'POST':
        form = AddViolation(request.POST)
        if form.is_valid():
stef's avatar
stef committed
124
            actid=sendverifymail('activate?key=',form.cleaned_data['email'])
stef's avatar
stef committed
125 126 127 128 129
            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
130
                resource_name = form.cleaned_data['resource_name'],
stef's avatar
stef committed
131 132 133 134
                type = form.cleaned_data['type'],
                media = form.cleaned_data['media'],
                temporary = form.cleaned_data['temporary'],
                contractual = form.cleaned_data['contractual'],
135
                contract_excerpt = sanitizeHtml(form.cleaned_data['contract_excerpt']),
136 137
                loophole = form.cleaned_data['loophole'],
                activationid = actid
stef's avatar
stef committed
138 139
                )
            v.save()
stef's avatar
stef committed
140 141
            c=Confirmation(key='', email=form.cleaned_data['email'], violation=v)
            c.save()
stef's avatar
stef committed
142 143
            c = Comment(
                comment=form.cleaned_data['comment'],
144 145
                submitter_email=form.cleaned_data['email'],
                submitter_name=form.cleaned_data['nick'],
stef's avatar
stef committed
146 147 148 149 150
                timestamp=datetime.now(),
                violation=v,
                )
            c.save()
            for f in request.FILES.getlist('attachments[]'):
151 152 153 154 155 156
                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
157
                a.save()
158

stef's avatar
stef committed
159
            messages.add_message(request, messages.INFO, _('Thank you for submitting this report, you will receive a verification email shortly.'))
stef's avatar
stef committed
160 161
            return HttpResponseRedirect('/') # Redirect after POST
    else:
stef's avatar
stef committed
162
        form = AddViolation()
stef's avatar
stef committed
163

164
    v_list = Violation.objects.filter(activationid='',featuredcase__isnull=False).order_by('id').reverse()[:3]
stef's avatar
stef committed
165
    return render_to_response(
166
        'index.html',
167 168
        { 'form': form,
          'violations': v_list },
stef's avatar
stef committed
169
        context_instance=RequestContext(request))
stef's avatar
stef committed
170

171 172
def ajax(request, country=None, operator=None):
    if not operator:
173
        return HttpResponse(json.dumps(sorted(list(set([x.operator for x in Violation.objects.filter(country=country,activationid='')])))))
174
    else:
175
        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
176 177

def index(request):
178
    v_list = Violation.objects.filter(activationid='',featuredcase__isnull=False).order_by('id').reverse()[:3]
stef's avatar
stef committed
179 180 181 182 183 184 185 186 187
    form = AddViolation()

    return render_to_response(
        'index.html',
        { 'form': form,
          'violations': v_list },
        context_instance=RequestContext(request))

def list_violations(request):
188
    violations = Violation.objects.filter(activationid='')
189
    return render_to_response('list.html', {"violations": violations},context_instance=RequestContext(request))
190 191 192

def view(request,id):
    v = get_object_or_404(Violation, pk=id)
193 194
    if v.activationid:
        raise Http404
stef's avatar
stef committed
195
    return render_to_response('view.html', { 'v': v, },context_instance=RequestContext(request))