Esempio n. 1
0
def feedback(request):
    data = {'page_class': 'meta'}
    form = None

    if openode_settings.ALLOW_ANONYMOUS_FEEDBACK is False:
        if request.user.is_anonymous():
            message = _('Please sign in or register to send your feedback')
            request.user.message_set.create(message=message)
            redirect_url = get_login_url() + '?next=' + request.path
            return HttpResponseRedirect(redirect_url)

    if request.method == "POST":
        form = FeedbackForm(
            is_auth=request.user.is_authenticated(),
            data=request.POST
        )
        if form.is_valid():
            if not request.user.is_authenticated():
                data['email'] = form.cleaned_data.get('email',None)
            data['message'] = form.cleaned_data['message']
            data['name'] = form.cleaned_data.get('name',None)
            template = get_template('email/feedback_email.txt', request)
            message = template.render(RequestContext(request, data))
            mail_moderators(_('Q&A forum feedback'), message)
            msg = _('Thanks for the feedback!')
            request.user.message_set.create(message=msg)
            return HttpResponseRedirect(get_next_url(request))
    else:
        form = FeedbackForm(is_auth = request.user.is_authenticated(),
                            initial={'next':get_next_url(request)})

    data['form'] = form
    return render_into_skin('feedback.html', data, request)
Esempio n. 2
0
def feedback(request):
    data = {'page_class': 'meta'}
    form = None

    if openode_settings.ALLOW_ANONYMOUS_FEEDBACK is False:
        if request.user.is_anonymous():
            message = _('Please sign in or register to send your feedback')
            request.user.message_set.create(message=message)
            redirect_url = get_login_url() + '?next=' + request.path
            return HttpResponseRedirect(redirect_url)

    if request.method == "POST":
        form = FeedbackForm(is_auth=request.user.is_authenticated(),
                            data=request.POST)
        if form.is_valid():
            if not request.user.is_authenticated():
                data['email'] = form.cleaned_data.get('email', None)
            data['message'] = form.cleaned_data['message']
            data['name'] = form.cleaned_data.get('name', None)
            template = get_template('email/feedback_email.txt', request)
            message = template.render(RequestContext(request, data))
            mail_moderators(_('Q&A forum feedback'), message)
            msg = _('Thanks for the feedback!')
            request.user.message_set.create(message=msg)
            return HttpResponseRedirect(get_next_url(request))
    else:
        form = FeedbackForm(is_auth=request.user.is_authenticated(),
                            initial={'next': get_next_url(request)})

    data['form'] = form
    return render_into_skin('feedback.html', data, request)
Esempio n. 3
0
 def wrapper(request, *args, **kwargs):
     if request.user.is_anonymous():
         #todo: expand for handling ajax responses
         request.user.message_set.create(message=message)
         params = 'next=%s' % request.path
         return HttpResponseRedirect(url_utils.get_login_url() + '?' + params)
     return view_func(request, *args, **kwargs)
Esempio n. 4
0
def application_settings(request):
    """The context processor function"""
    if not request.path.startswith('/' + settings.OPENODE_URL):
        #todo: this is a really ugly hack, will only work
        #when openode is installed not at the home page.
        #this will not work for the
        #heavy modders of openode, because their custom pages
        #will not receive the openode settings in the context
        #to solve this properly we should probably explicitly
        #add settings to the context per page
        return {}

    my_settings = openode_settings.as_dict()
    my_settings['LANGUAGE_CODE'] = getattr(request, 'LANGUAGE_CODE',
                                           settings.LANGUAGE_CODE)
    my_settings[
        'ALLOWED_UPLOAD_FILE_TYPES'] = settings.OPENODE_ALLOWED_UPLOAD_FILE_TYPES
    my_settings['OPENODE_URL'] = settings.OPENODE_URL
    my_settings['STATIC_URL'] = settings.STATIC_URL
    my_settings['OPENODE_CSS_DEVEL'] = getattr(settings, 'OPENODE_CSS_DEVEL',
                                               False)
    my_settings['DEBUG'] = settings.DEBUG
    my_settings[
        'FORCE_STATIC_SERVE_WITH_DJANGO'] = settings.FORCE_STATIC_SERVE_WITH_DJANGO
    my_settings['USING_RUNSERVER'] = 'runserver' in sys.argv
    my_settings['OPENODE_VERSION'] = openode.get_version()
    my_settings['LOGIN_URL'] = url_utils.get_login_url()
    my_settings['USER_REGISTRATION_URL'] = url_utils.get_user_registration_url(
    )
    my_settings['LOGOUT_URL'] = url_utils.get_logout_url()
    my_settings['LOGOUT_REDIRECT_URL'] = url_utils.get_logout_redirect_url()
    my_settings['LANGUAGES'] = getattr(settings, 'LANGUAGES', ())

    # wysiwyg
    my_settings["WYSIWYG_SETTING_SIMPLE"] = settings.WYSIWYG_SETTING_SIMPLE
    my_settings["WYSIWYG_SETTING_COMMENT"] = settings.WYSIWYG_SETTING_COMMENT

    context = {
        'settings': my_settings,
        'skin': get_skin(request),
        'moderation_items': request.user.get_moderation_items(),
        'noscript_url': const.DEPENDENCY_URLS['noscript'],
        'THREAD_TYPE_QUESTION': const.THREAD_TYPE_QUESTION,
        'THREAD_TYPE_DISCUSSION': const.THREAD_TYPE_DISCUSSION,
        'THREAD_TYPE_DOCUMENT': const.THREAD_TYPE_DOCUMENT,
    }

    #calculate context needed to list all the organizations
    def _get_organization_url(organization):
        """calculates url to the organization based on its id and name"""
        organization_slug = slugify(organization['name'])
        return reverse('organization_detail',
                       kwargs={
                           'organization_id': organization['id'],
                           'organization_slug': organization_slug
                       })

    return context
Esempio n. 5
0
 def wrapped_func(request, profile_owner, context):
     if profile_owner == request.user:
         pass
     elif request.user.is_authenticated() and request.user.can_moderate_user(profile_owner):
         pass
     else:
         next_url = request.path + '?' + urllib.urlencode(request.REQUEST)
         params = '?next=%s' % urllib.quote(next_url)
         return HttpResponseRedirect(url_utils.get_login_url() + params)
     return f(request, profile_owner, context)
Esempio n. 6
0
 def wrapped_func(request, profile_owner, context):
     if profile_owner == request.user:
         pass
     elif request.user.is_authenticated() and request.user.can_moderate_user(profile_owner):
         pass
     else:
         next_url = request.path + '?' + urllib.urlencode(request.REQUEST)
         params = '?next=%s' % urllib.quote(next_url)
         return HttpResponseRedirect(url_utils.get_login_url() + params)
     return f(request, profile_owner, context)
Esempio n. 7
0
def bounce_email(
    email, subject, reason=None, body_text=None, reply_to=None
):
    """sends a bounce email at address ``email``, with the subject
    line ``subject``, accepts several reasons for the bounce:
    * ``'problem_posting'``, ``unknown_user`` and ``permission_denied``
    * ``body_text`` in an optional parameter that allows to append
      extra text to the message
    """
    if reason == 'problem_posting':
        error_message = _(
            '<p>Sorry, there was an error posting your question '
            'please contact the %(site)s administrator</p>'
        ) % {'site': openode_settings.APP_SHORT_NAME}

        error_message = string_concat(
                                INSTRUCTIONS_PREAMBLE,
                                '<ul>',
                                    QUESTION_TITLE_INSTRUCTION,
                                    QUESTION_DETAILS_INSTRUCTION,
                                    OPTIONAL_TAGS_INSTRUCTION,
                                '</ul>',
                                TAGS_INSTRUCTION_FOOTNOTE
                            )

    elif reason == 'unknown_user':
        error_message = _(
            '<p>Sorry, in order to post questions on %(site)s '
            'by email, please <a href="%(url)s">register first</a></p>'
        ) % {
            'site': openode_settings.APP_SHORT_NAME,
            'url': url_utils.get_login_url()
        }
    elif reason == 'permission_denied' and body_text is None:
        error_message = _(
            '<p>Sorry, your question could not be posted '
            'due to insufficient privileges of your user account</p>'
        )
    elif body_text:
        error_message = body_text
    else:
        raise ValueError('unknown reason to bounce an email: "%s"' % reason)

    headers = {}
    if reply_to:
        headers['Reply-To'] = reply_to

    send_mail(
        recipient_list=(email, ),
        subject_line='Re: ' + subject,
        body_text=error_message,
        headers=headers
    )
Esempio n. 8
0
def post_comments(request):
    # generic ajax handler to load comments to an object
    # only support get post comments by ajax now

    post_type = request.REQUEST.get('post_type', '')
    if not request.is_ajax() or post_type not in ('question', 'answer', 'discussion'):
        # TODO: Shouldn't be 404! More like 400, 403 or sth more specific
        raise Http404

    user = request.user
    obj = get_object_or_404(models.Post, pk=request.REQUEST['post_id'])

    if obj.thread and not user.has_openode_perm("%s_answer_comment_create" % obj.thread.thread_type, obj.thread):
        return HttpResponseForbidden(mimetype="application/json")

    if request.method == "GET":
        response = __generate_comments_json(obj, user)
    elif request.method == "POST":
        text = request.POST.get('comment')

        clean_text = strip_tags(text).replace("&nbsp;", "").strip()

        if not clean_text:
            return HttpResponse(
                simplejson.dumps({"errors": _("Comment is empty.")}),
                mimetype="application/json"
            )
        elif len(clean_text) < openode_settings.MIN_ANSWER_BODY_LENGTH:
            return HttpResponse(
                simplejson.dumps({
                    "errors": _("Comment must be at least %d character long." % openode_settings.MIN_ANSWER_BODY_LENGTH)
                }),
                mimetype="application/json"
            )

        try:
            if user.is_anonymous():
                msg = _('Sorry, you appear to be logged out and '
                        'cannot post comments. Please '
                        '<a href="%(sign_in_url)s">sign in</a>.') % \
                        {'sign_in_url': url_utils.get_login_url()}
                raise exceptions.PermissionDenied(msg)

            response = __generate_comments_json(
                obj,
                user,
                new_comment=user.post_comment(
                    parent_post=obj,
                    body_text=bleach_html(text)
                    )
                )
        except exceptions.PermissionDenied, e:
            response = HttpResponseForbidden(unicode(e), mimetype="application/json")
Esempio n. 9
0
def application_settings(request):
    """The context processor function"""
    if not request.path.startswith("/" + settings.OPENODE_URL):
        # todo: this is a really ugly hack, will only work
        # when openode is installed not at the home page.
        # this will not work for the
        # heavy modders of openode, because their custom pages
        # will not receive the openode settings in the context
        # to solve this properly we should probably explicitly
        # add settings to the context per page
        return {}

    my_settings = openode_settings.as_dict()
    my_settings["LANGUAGE_CODE"] = getattr(request, "LANGUAGE_CODE", settings.LANGUAGE_CODE)
    my_settings["ALLOWED_UPLOAD_FILE_TYPES"] = settings.OPENODE_ALLOWED_UPLOAD_FILE_TYPES
    my_settings["OPENODE_URL"] = settings.OPENODE_URL
    my_settings["STATIC_URL"] = settings.STATIC_URL
    my_settings["OPENODE_CSS_DEVEL"] = getattr(settings, "OPENODE_CSS_DEVEL", False)
    my_settings["DEBUG"] = settings.DEBUG
    my_settings["FORCE_STATIC_SERVE_WITH_DJANGO"] = settings.FORCE_STATIC_SERVE_WITH_DJANGO
    my_settings["USING_RUNSERVER"] = "runserver" in sys.argv
    my_settings["OPENODE_VERSION"] = openode.get_version()
    my_settings["LOGIN_URL"] = url_utils.get_login_url()
    my_settings["USER_REGISTRATION_URL"] = url_utils.get_user_registration_url()
    my_settings["LOGOUT_URL"] = url_utils.get_logout_url()
    my_settings["LOGOUT_REDIRECT_URL"] = url_utils.get_logout_redirect_url()
    my_settings["LANGUAGES"] = getattr(settings, "LANGUAGES", ())

    # wysiwyg
    my_settings["WYSIWYG_SETTING_SIMPLE"] = settings.WYSIWYG_SETTING_SIMPLE
    my_settings["WYSIWYG_SETTING_COMMENT"] = settings.WYSIWYG_SETTING_COMMENT

    context = {
        "settings": my_settings,
        "skin": get_skin(request),
        "moderation_items": request.user.get_moderation_items(),
        "noscript_url": const.DEPENDENCY_URLS["noscript"],
        "THREAD_TYPE_QUESTION": const.THREAD_TYPE_QUESTION,
        "THREAD_TYPE_DISCUSSION": const.THREAD_TYPE_DISCUSSION,
        "THREAD_TYPE_DOCUMENT": const.THREAD_TYPE_DOCUMENT,
    }

    # calculate context needed to list all the organizations
    def _get_organization_url(organization):
        """calculates url to the organization based on its id and name"""
        organization_slug = slugify(organization["name"])
        return reverse(
            "organization_detail",
            kwargs={"organization_id": organization["id"], "organization_slug": organization_slug},
        )

    return context
Esempio n. 10
0
def bounce_email(email, subject, reason=None, body_text=None, reply_to=None):
    """sends a bounce email at address ``email``, with the subject
    line ``subject``, accepts several reasons for the bounce:
    * ``'problem_posting'``, ``unknown_user`` and ``permission_denied``
    * ``body_text`` in an optional parameter that allows to append
      extra text to the message
    """
    if reason == 'problem_posting':
        error_message = _('<p>Sorry, there was an error posting your question '
                          'please contact the %(site)s administrator</p>') % {
                              'site': openode_settings.APP_SHORT_NAME
                          }

        error_message = string_concat(INSTRUCTIONS_PREAMBLE, '<ul>',
                                      QUESTION_TITLE_INSTRUCTION,
                                      QUESTION_DETAILS_INSTRUCTION,
                                      OPTIONAL_TAGS_INSTRUCTION, '</ul>',
                                      TAGS_INSTRUCTION_FOOTNOTE)

    elif reason == 'unknown_user':
        error_message = _(
            '<p>Sorry, in order to post questions on %(site)s '
            'by email, please <a href="%(url)s">register first</a></p>') % {
                'site': openode_settings.APP_SHORT_NAME,
                'url': url_utils.get_login_url()
            }
    elif reason == 'permission_denied' and body_text is None:
        error_message = _(
            '<p>Sorry, your question could not be posted '
            'due to insufficient privileges of your user account</p>')
    elif body_text:
        error_message = body_text
    else:
        raise ValueError('unknown reason to bounce an email: "%s"' % reason)

    headers = {}
    if reply_to:
        headers['Reply-To'] = reply_to

    send_mail(recipient_list=(email, ),
              subject_line='Re: ' + subject,
              body_text=error_message,
              headers=headers)
Esempio n. 11
0
def delete_comment(request):
    """ajax handler to delete comment
    """
    try:
        if request.user.is_anonymous():
            msg = _('Sorry, you appear to be logged out and '
                    'cannot delete comments. Please '
                    '<a href="%(sign_in_url)s">sign in</a>.') % \
                    {'sign_in_url': url_utils.get_login_url()}
            raise exceptions.PermissionDenied(msg)
        if request.is_ajax():

            comment = get_object_or_404(
                models.Post,
                post_type='comment',
                pk=request.POST['comment_id']
                )
            request.user.assert_can_delete_comment(comment)

            if not request.user.has_openode_perm("question_answer_comment_delete_any", comment.thread):
                raise exceptions.PermissionDenied("msg")

            parent = comment.parent
            comment.delete()
            #attn: recalc denormalized field
            parent.comment_count = max(parent.comment_count - 1, 0)
            parent.save()
            parent.thread.invalidate_cached_data()

            return __generate_comments_json(parent, request.user)

        raise exceptions.PermissionDenied(_('sorry, we seem to have some technical difficulties'))
    except exceptions.PermissionDenied, e:
        return HttpResponseForbidden(
            unicode(e),
            mimetype='application/json'
        )
Esempio n. 12
0
                except openode_exceptions.AnswerAlreadyGiven, e:
                    request.user.message_set.create(message=unicode(e))
                    answer = thread.get_answers_by_user(request.user)[0]
                    return HttpResponseRedirect(answer.get_absolute_url())
                except django_exceptions.PermissionDenied, e:
                    request.user.message_set.create(message=unicode(e))
            else:
                request.session.flush()
                models.AnonymousAnswer.objects.create(
                    question=main_post,
                    text=text,
                    summary=strip_tags(text)[:120],
                    session_key=request.session.session_key,
                    ip_addr=request.META['REMOTE_ADDR'],
                )
                return HttpResponseRedirect(url_utils.get_login_url())
    else:
        answer_form = AnswerForm(initial=initial, node=node)

    user_can_post_comment = (
        request.user.is_authenticated() and request.user.can_post_comment()
    )

    user_already_gave_answer = False
    previous_answer = None
    if request.user.is_authenticated():
        if openode_settings.LIMIT_ONE_ANSWER_PER_USER and module == const.NODE_MODULE_QA:
            for answer in answers:
                if answer.author == request.user:
                    user_already_gave_answer = True
                    previous_answer = answer
Esempio n. 13
0
                except openode_exceptions.AnswerAlreadyGiven, e:
                    request.user.message_set.create(message=unicode(e))
                    answer = thread.get_answers_by_user(request.user)[0]
                    return HttpResponseRedirect(answer.get_absolute_url())
                except django_exceptions.PermissionDenied, e:
                    request.user.message_set.create(message=unicode(e))
            else:
                request.session.flush()
                models.AnonymousAnswer.objects.create(
                    question=main_post,
                    text=text,
                    summary=strip_tags(text)[:120],
                    session_key=request.session.session_key,
                    ip_addr=request.META['REMOTE_ADDR'],
                )
                return HttpResponseRedirect(url_utils.get_login_url())
    else:
        answer_form = AnswerForm(initial=initial, node=node)

    user_can_post_comment = (request.user.is_authenticated()
                             and request.user.can_post_comment())

    user_already_gave_answer = False
    previous_answer = None
    if request.user.is_authenticated():
        if openode_settings.LIMIT_ONE_ANSWER_PER_USER and module == const.NODE_MODULE_QA:
            for answer in answers:
                if answer.author == request.user:
                    user_already_gave_answer = True
                    previous_answer = answer
                    break