Example #1
0
def submit_poll(request, year=None, slug=None):
    if request.method != 'POST':
        return HttpResponse('POST or gtfo')
    else:
        print repr(request.POST['option'])
        poll = get_object_or_404(Poll, time_start__year=year, slug=slug)
        
        ip = get_ip(request)
        user = get_user_profile(request)
        
        option_pk = request.POST['option']
        try:
            option = poll.options.get(pk=option_pk)
        except:
            return HttpResponse('error: invalid option "%s"' % option_pk)
        
        try:
            poll.vote(option=option, user=user, ip=ip)
        except gazjango.polls.exceptions.NotVoting:
            return HttpResponse("This poll is not accepting votes at this time.")
        except gazjango.polls.exceptions.AlreadyVoted:
            return HttpResponse("You've already voted in this poll.")
        except gazjango.polls.exceptions.PermissionDenied:
            return HttpResponse("You're not allowed to vote in this poll.")
        except Exception, e:
            return HttpResponse("Unknown problem: " + repr(e))
        else:
Example #2
0
def show_article(request, story, form, print_view=False):
    "Shows the requested article."
    d = story.pub_date
    template = ("stories/view_%s_%s_%s_%s.html" %
                (d.year, d.month, d.day, story.slug),
                "stories/view_from_sub_%s.html" %
                story.subsection.slug if story.subsection else '',
                "stories/view_from_sec_%s.html" % story.section.slug,
                "stories/view.html")

    cs = PublicComment.visible.order_by('-time').exclude(article=story)

    user = get_user_profile(request)
    ip = get_ip(request)
    comments = PublicComment.objects.for_article(story, user, ip)

    context = RequestContext(
        request, {
            'story': story,
            'comments': comments,
            'print_view': print_view,
            'comment_form': form,
            'poster': Poster.published.get_running(),
            'recent_stories': Article.published.order_by('-pub_date')[:3],
            'related': story.related_list(3),
            'top_banner': BannerAd.article_top.pick(allow_zero_priority=False),
            'side_banner':
            BannerAd.article_side.pick(allow_zero_priority=False),
        })
    return render_to_response(template, context_instance=context)
Example #3
0
def submit_poll(request, year=None, slug=None):
    if request.method != 'POST':
        return HttpResponse('POST or gtfo')
    else:
        print repr(request.POST['option'])
        poll = get_object_or_404(Poll, time_start__year=year, slug=slug)

        ip = get_ip(request)
        user = get_user_profile(request)

        option_pk = request.POST['option']
        try:
            option = poll.options.get(pk=option_pk)
        except:
            return HttpResponse('error: invalid option "%s"' % option_pk)

        try:
            poll.vote(option=option, user=user, ip=ip)
        except gazjango.polls.exceptions.NotVoting:
            return HttpResponse(
                "This poll is not accepting votes at this time.")
        except gazjango.polls.exceptions.AlreadyVoted:
            return HttpResponse("You've already voted in this poll.")
        except gazjango.polls.exceptions.PermissionDenied:
            return HttpResponse("You're not allowed to vote in this poll.")
        except Exception, e:
            return HttpResponse("Unknown problem: " + repr(e))
        else:
Example #4
0
def show_article(request, story, form, print_view=False):
    "Shows the requested article."
    d = story.pub_date
    template = (
        "stories/view_%s_%s_%s_%s.html" % (d.year, d.month, d.day, story.slug),
        "stories/view_from_sub_%s.html" % story.subsection.slug if story.subsection else '',
        "stories/view_from_sec_%s.html" % story.section.slug,
        "stories/view.html"
    )
    
    cs = PublicComment.visible.order_by('-time').exclude(article=story)
    
    user = get_user_profile(request)
    ip = get_ip(request)
    comments = PublicComment.objects.for_article(story, user, ip)
    
    context = RequestContext(request, {
        'story': story,
        'comments': comments,
        'print_view': print_view,
        'comment_form': form,
        'poster': Poster.published.get_running(),
        'recent_stories': Article.published.order_by('-pub_date')[:3],
        'related': story.related_list(3),
        
        'top_banner': BannerAd.article_top.pick(allow_zero_priority=False),
        'side_banner': BannerAd.article_side.pick(allow_zero_priority=False),
    })
    return render_to_response(template, context_instance=context)
Example #5
0
    def process_request(self, request):
        try:
            # Set the facebook message to empty. This message can be used to
            # display info from the middleware on a Web page.
            request.facebook_message = None
            request.facebook_user = None

            if request.user.is_authenticated():
                if API_KEY in request.COOKIES:  # using FB Connect
                    if 'fb_ip' not in request.COOKIES:  # we haven't been associated yet
                        if not self.verify_facebook_cookies(request):
                            return self.logout(request)
                        self.associate_profile(request)

                    elif request.COOKIES['fb_ip'] == self.hash(
                            get_ip(request) + API_SECRET):
                        if not self.verify_facebook_cookies(request):
                            return self.logout(request)
                        self.associate_profile(request)

                    else:  # invalid ip! either some proxy stuff or a haxor
                        return self.logout(request)

                else:  # not using FB Connect
                    pass

            else:  # not logged in
                if API_KEY in request.COOKIES:  # using FB Connect
                    if not self.verify_facebook_cookies(request):
                        return self.logout(request)

                    try:
                        fid = self.cookie(request, '_user')
                        profile = UserProfile.objects.get(facebook_id=fid)
                        user = profile.user
                    except UserProfile.DoesNotExist:
                        user, profile = self.create_user(request)

                    # TODO: fix up the crappy backend annotation
                    from django.contrib.auth import get_backends
                    backend = get_backends()[0]
                    user.backend = "%s.%s" % (backend.__module__,
                                              backend.__class__.__name__)

                    if user is None:
                        request.facebook_message = ACCOUNT_PROBLEM_ERROR
                        self.delete_fb_cookies = True
                    else:
                        if user.is_active:
                            login(request, user)
                            self.facebook_user_is_authenticated = True
                            request.facebook_user = user
                        else:
                            request.facebook_message = ACCOUNT_DISABLED_ERROR
                            self.delete_fb_cookies = True

        # something went wrong. make sure user doesn't have site access until problem is fixed.
        except:
            request.facebook_message = PROBLEM_ERROR
            self.logout(request)
Example #6
0
def show_captcha(request, year, month, day, slug):
    story = get_by_date_or_404(Article, year, month, day, slug=slug)
    key = 'comment:%s' % story.get_absolute_url()
    try:
        comment = request.session[key]
    except KeyError:
        raise Http404

    url = "http://api.recaptcha.net/%s?k=" + settings.RECAPTCHA_PUBLIC_KEY
    if "recaptcha_response_field" in request.POST:
        result = recaptcha.submit(
            request.POST.get('recaptcha_challenge_field', None),
            request.POST.get('recaptcha_response_field', None),
            settings.RECAPTCHA_PRIVATE_KEY, get_ip(request))
        if result.is_valid:
            del request.session[key]
            comment.mark_as_ham()
            comment.save()
            if request.is_ajax():
                # we're not (yet) doing this via ajax, so it's ok
                raise NotImplemented
            else:
                return HttpResponseRedirect(comment.get_absolute_url())
        else:
            url += "&error=%s" % response.error_code

    rc = RequestContext(
        request, {
            'challenge_captcha_url': url % 'challenge',
            'noscript_captcha_url': url % 'noscript'
        })
    return render_to_response('stories/captcha_form.html', context_instance=rc)
Example #7
0
def show_captcha(request, year, month, day, slug):
    story = get_by_date_or_404(Article, year, month, day, slug=slug)
    key = 'comment:%s' % story.get_absolute_url()
    try:
        comment = request.session[key]
    except KeyError:
        raise Http404
    
    url = "http://api.recaptcha.net/%s?k=" + settings.RECAPTCHA_PUBLIC_KEY
    if "recaptcha_response_field" in request.POST:
        result = recaptcha.submit(request.POST.get('recaptcha_challenge_field', None),
                                  request.POST.get('recaptcha_response_field',  None),
                                  settings.RECAPTCHA_PRIVATE_KEY,
                                  get_ip(request))
        if result.is_valid:
            del request.session[key]
            comment.mark_as_ham()
            comment.save()
            if request.is_ajax():
                # we're not (yet) doing this via ajax, so it's ok 
                raise NotImplemented
            else:
                return HttpResponseRedirect(comment.get_absolute_url())
        else:
            url += "&error=%s" % response.error_code
    
    rc = RequestContext(request, { 'challenge_captcha_url': url % 'challenge',
                                   'noscript_captcha_url':  url % 'noscript' })
    return render_to_response('stories/captcha_form.html', context_instance=rc)
Example #8
0
 def process_request(self, request):
     try:
         # Set the facebook message to empty. This message can be used to
         # display info from the middleware on a Web page.
         request.facebook_message = None
         request.facebook_user = None
         
         if request.user.is_authenticated():
             if API_KEY in request.COOKIES: # using FB Connect
                 if 'fb_ip' not in request.COOKIES: # we haven't been associated yet
                     if not self.verify_facebook_cookies(request):
                         return self.logout(request)
                     self.associate_profile(request)
                 
                 elif request.COOKIES['fb_ip'] == self.hash(get_ip(request) + API_SECRET):
                     if not self.verify_facebook_cookies(request):
                         return self.logout(request)
                     self.associate_profile(request)
                 
                 else: # invalid ip! either some proxy stuff or a haxor
                     return self.logout(request)
             
             else: # not using FB Connect
                 pass
         
         else: # not logged in
             if API_KEY in request.COOKIES: # using FB Connect
                 if not self.verify_facebook_cookies(request):
                     return self.logout(request)
                 
                 try:
                     fid = self.cookie(request, '_user')
                     profile = UserProfile.objects.get(facebook_id=fid)
                     user = profile.user
                 except UserProfile.DoesNotExist:
                     user, profile = self.create_user(request)
                 
                 # TODO: fix up the crappy backend annotation
                 from django.contrib.auth import get_backends
                 backend = get_backends()[0]
                 user.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__)
                 
                 if user is None:
                     request.facebook_message = ACCOUNT_PROBLEM_ERROR
                     self.delete_fb_cookies = True
                 else:
                     if user.is_active:
                         login(request, user)
                         self.facebook_user_is_authenticated = True
                         request.facebook_user = user
                     else:
                         request.facebook_message = ACCOUNT_DISABLED_ERROR
                         self.delete_fb_cookies = True
     
     # something went wrong. make sure user doesn't have site access until problem is fixed.
     except:
         request.facebook_message = PROBLEM_ERROR
         self.logout(request)
Example #9
0
def vote_on_comment(request, slug, year, month, day, num, val):
    if is_robot(request):
        return HttpResponse('sorry, you seem to be a robot, no voting for you!')
    
    comment = _get_comment_or_404(year, month, day, slug, num)
    positive = (val == 'up') if val in ('up', 'down') else None
    result = comment.vote(positive, ip=get_ip(request), user=get_user_profile(request))
    
    if request.is_ajax():
        return HttpResponse("success" if result else "failure")
    else:
        return HttpResponseRedirect(comment.get_absolute_url())
Example #10
0
def show_photospread_page(request,
                          spread,
                          num=None,
                          form=None,
                          whole_page=None):
    if num is None:
        num = 1

    page = spread.get_photo_number(num)
    if not page:
        raise Http404('This photospread does not have a photo number "%s".' %
                      num)

    data = {
        'story': spread,
        'page': page,
        'next': page.next(),
        'prev': page.prev()
    }

    if whole_page is None:
        whole_page = not request.is_ajax()

    user = get_user_profile(request)
    ip = get_ip(request)

    if whole_page:
        data.update(
            comments=PublicComment.objects.for_article(spread, user, ip),
            comment_form=form,
            poster=Poster.published.get_running(),
            recent_stories=Article.published.order_by('-pub_date')[:3],
            related=spread.related_list(3),
            top_banner=BannerAd.article_top.pick(allow_zero_priority=False),
            side_banner=BannerAd.article_side.pick(allow_zero_priority=False),
        )

        d = spread.pub_date
        template = ("stories/photospread_%s_%s_%s_%s.html" %
                    (d.year, d.month, d.day, spread.slug),
                    "stories/photospread_from_sub_%s.html" %
                    spread.subsection.slug if spread.subsection else '',
                    "stories/photospread_from_sec_%s.html" %
                    spread.section.slug, "stories/photospread.html")
    else:
        template = "stories/photo.html"

    rc = RequestContext(request, data)
    return render_to_response(template, context_instance=rc)
Example #11
0
def vote_on_comment(request, slug, year, month, day, num, val):
    if is_robot(request):
        return HttpResponse(
            'sorry, you seem to be a robot, no voting for you!')

    comment = _get_comment_or_404(year, month, day, slug, num)
    positive = (val == 'up') if val in ('up', 'down') else None
    result = comment.vote(positive,
                          ip=get_ip(request),
                          user=get_user_profile(request))

    if request.is_ajax():
        return HttpResponse("success" if result else "failure")
    else:
        return HttpResponseRedirect(comment.get_absolute_url())
Example #12
0
def post_comment(request, slug, year, month, day):
    story = get_by_date_or_404(Article, year, month, day, slug=slug)
    if not story.comments_allowed:
        raise Http404  # semantically incorrect, but whatever

    logged_in = request.user.is_authenticated()
    staff = logged_in and get_user_profile(request).staff_status()
    form = make_comment_form(data=request.POST,
                             logged_in=logged_in,
                             staff=staff)

    if form.is_valid():
        data = form.cleaned_data
        args = {
            'subject': story,
            'text': escape(data['text']).replace("\n", "<br/>"),
            'ip_address': get_ip(request),
            'user_agent': request.META.get('HTTP_USER_AGENT', '')
        }

        if logged_in:
            args['user'] = get_user_profile(request)
            if data['anonymous']:  # and data['name'] != request.user.get_full_name():
                args['name'] = data['name']
            args['speaking_officially'] = data['speaking_officially']
        else:
            args['name'] = data['name']
            args['email'] = data['email']

        try:
            comment = PublicComment.objects.new(**args)
        except CommentIsSpam, e:
            # put data in the session, because we're silly like that
            url = e.comment.subject.get_absolute_url()
            request.session.set_expiry(0)
            request.session['comment:%s' % url] = e.comment

            # NOTE: coupling with url for comment captchas
            redirect = request.build_absolute_uri(url + 'comment/captcha')
            if request.is_ajax():
                return HttpResponse('redirect: %s' % redirect)
            else:
                return HttpResponseRedirect(redirect)

        if request.is_ajax():
            return HttpResponse('success')
        else:
            return HttpResponseRedirect(comment.get_absolute_url())
Example #13
0
def comments_for_article(request, slug, year, month, day, num=None):
    """
    Returns the comments for the specified article, rendered as they are
    on article view pages, starting after number `num`. Used for after
    you've posted an AJAX comment.
    """
    story = get_by_date_or_404(Article, year, month, day, slug=slug)
    
    user = get_user_profile(request)
    ip = get_ip(request)
    
    spec = Q(number__gt=num) if num else Q()
    comments = PublicComment.objects.for_article(story, user, ip, spec=spec)
    
    rc = RequestContext(request, { 'comments': comments, 'new': True })
    return render_to_response("stories/comments.html", context_instance=rc)
Example #14
0
def comments_for_article(request, slug, year, month, day, num=None):
    """
    Returns the comments for the specified article, rendered as they are
    on article view pages, starting after number `num`. Used for after
    you've posted an AJAX comment.
    """
    story = get_by_date_or_404(Article, year, month, day, slug=slug)

    user = get_user_profile(request)
    ip = get_ip(request)

    spec = Q(number__gt=num) if num else Q()
    comments = PublicComment.objects.for_article(story, user, ip, spec=spec)

    rc = RequestContext(request, {'comments': comments, 'new': True})
    return render_to_response("stories/comments.html", context_instance=rc)
Example #15
0
def post_comment(request, slug, year, month, day):
    story = get_by_date_or_404(Article, year, month, day, slug=slug)
    if not story.comments_allowed:
        raise Http404 # semantically incorrect, but whatever
    
    logged_in = request.user.is_authenticated()
    staff = logged_in and get_user_profile(request).staff_status()
    form = make_comment_form(data=request.POST, logged_in=logged_in, staff=staff)
    
    if form.is_valid():
        data = form.cleaned_data
        args = {
            'subject': story,
            'text': escape(data['text']).replace("\n", "<br/>"),
            'ip_address': get_ip(request),
            'user_agent': request.META.get('HTTP_USER_AGENT', '')
        }
        
        if logged_in:
            args['user'] = get_user_profile(request)
            if data['anonymous']:# and data['name'] != request.user.get_full_name():
                args['name'] = data['name']
            args['speaking_officially'] = data['speaking_officially']
        else:
            args['name']  = data['name']
            args['email'] = data['email']
        
        try:
            comment = PublicComment.objects.new(**args)    
        except CommentIsSpam, e:
            # put data in the session, because we're silly like that
            url = e.comment.subject.get_absolute_url()
            request.session.set_expiry(0)
            request.session['comment:%s' % url] = e.comment
            
            # NOTE: coupling with url for comment captchas
            redirect = request.build_absolute_uri(url + 'comment/captcha')
            if request.is_ajax():
                return HttpResponse('redirect: %s' % redirect)
            else:
                return HttpResponseRedirect(redirect)
        
        if request.is_ajax():
            return HttpResponse('success')
        else:
            return HttpResponseRedirect(comment.get_absolute_url())
Example #16
0
def show_photospread_page(request, spread, num=None, form=None, whole_page=None):
    if num is None:
        num = 1
    
    page = spread.get_photo_number(num)
    if not page:
        raise Http404('This photospread does not have a photo number "%s".' % num)
    
    data = {
        'story': spread,
        'page': page,
        'next': page.next(),
        'prev': page.prev()
    }
    
    if whole_page is None:
        whole_page = not request.is_ajax()
    
    user = get_user_profile(request)
    ip = get_ip(request)
    
    if whole_page:
        data.update(
            comments=PublicComment.objects.for_article(spread, user, ip),
            comment_form=form,

            poster=Poster.published.get_running(),
            recent_stories=Article.published.order_by('-pub_date')[:3],
            related=spread.related_list(3),

            top_banner=BannerAd.article_top.pick(allow_zero_priority=False),
            side_banner=BannerAd.article_side.pick(allow_zero_priority=False),
        )

        d = spread.pub_date
        template = (
            "stories/photospread_%s_%s_%s_%s.html" % (d.year, d.month, d.day, spread.slug),
            "stories/photospread_from_sub_%s.html" % spread.subsection.slug if spread.subsection else '',
            "stories/photospread_from_sec_%s.html" % spread.section.slug,
            "stories/photospread.html"
        )
    else:
        template = "stories/photo.html"
    
    rc = RequestContext(request, data)
    return render_to_response(template, context_instance=rc)
Example #17
0
 def process_response(self, request, response):
     # delete FB Connect cookies -- the js might add them again, but
     # we want them gone if not
     if self.delete_fb_cookies is True:
         response.delete_cookie(API_KEY + '_user')
         response.delete_cookie(API_KEY + '_session_key')
         response.delete_cookie(API_KEY + '_expires')
         response.delete_cookie(API_KEY + '_ss')
         response.delete_cookie(API_KEY)
         response.delete_cookie('fbsetting_' + API_KEY)
     
     self.delete_fb_cookies = False
     
     if self.facebook_user_is_authenticated is True:
         response.set_cookie('fb_ip', self.hash(get_ip(request) + API_SECRET))
     
     return response
Example #18
0
    def process_response(self, request, response):
        # delete FB Connect cookies -- the js might add them again, but
        # we want them gone if not
        if self.delete_fb_cookies is True:
            response.delete_cookie(API_KEY + '_user')
            response.delete_cookie(API_KEY + '_session_key')
            response.delete_cookie(API_KEY + '_expires')
            response.delete_cookie(API_KEY + '_ss')
            response.delete_cookie(API_KEY)
            response.delete_cookie('fbsetting_' + API_KEY)

        self.delete_fb_cookies = False

        if self.facebook_user_is_authenticated is True:
            response.set_cookie('fb_ip',
                                self.hash(get_ip(request) + API_SECRET))

        return response
Example #19
0
def specific_article(request, story, num=None, form=None, print_view=False):
    "Displays an article without searching the db for it."
    
    logged_in = request.user.is_authenticated()
    if form is None:
        initial = { 'text': 'Have your say.' }
        if logged_in:
            initial['name'] = request.user.get_full_name()
        staff = logged_in and get_user_profile(request).staff_status()
        form = make_comment_form(logged_in=logged_in, initial=initial, staff=staff)

    if story.is_swat_only():
        if not is_from_swat(user=get_user_profile(request), ip=get_ip(request)):
            return show_swat_only(request, story)
    
    try:
        photospread = story.photospread
    except PhotoSpread.DoesNotExist:
        return show_article(request, story, form, print_view)
    else:
        return show_photospread_page(request, photospread, num, form)
Example #20
0
def specific_article(request, story, num=None, form=None, print_view=False):
    "Displays an article without searching the db for it."

    logged_in = request.user.is_authenticated()
    if form is None:
        initial = {'text': 'Have your say.'}
        if logged_in:
            initial['name'] = request.user.get_full_name()
        staff = logged_in and get_user_profile(request).staff_status()
        form = make_comment_form(logged_in=logged_in,
                                 initial=initial,
                                 staff=staff)

    if story.is_swat_only():
        if not is_from_swat(user=get_user_profile(request),
                            ip=get_ip(request)):
            return show_swat_only(request, story)

    try:
        photospread = story.photospread
    except PhotoSpread.DoesNotExist:
        return show_article(request, story, form, print_view)
    else:
        return show_photospread_page(request, photospread, num, form)