Пример #1
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'):
        raise Http404  # TODO: Shouldn't be 404! More like 400, 403 or sth more specific

    user = request.user

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

    if request.method == "GET":
        response = __generate_comments_json(obj, user)
    elif request.method == "POST":
        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)
            user.post_comment(parent_post=obj, body_text=request.POST.get('comment'))
            response = __generate_comments_json(obj, user)
        except exceptions.PermissionDenied, e:
            response = HttpResponseForbidden(unicode(e), mimetype="application/json")
Пример #2
0
def bounce_email(email, subject, reason=None, body_text=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": askbot_settings.APP_SHORT_NAME}
        error_message = string_concat(error_message, USAGE)
    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": askbot_settings.APP_SHORT_NAME, "url": url_utils.get_login_url()}
    elif reason == "permission_denied":
        error_message = _(
            "<p>Sorry, your question could not be posted " "due to insufficient privileges of your user account</p>"
        )
    else:
        raise ValueError('unknown reason to bounce an email: "%s"' % reason)

    if body_text != None:
        error_message = string_concat(error_message, body_text)

    # print 'sending email'
    # print email
    # print subject
    # print error_message
    mail.send_mail(recipient_list=(email,), subject_line="Re: " + subject, body_text=error_message)
Пример #3
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_id = request.POST['comment_id']
            comment = get_object_or_404(models.Post, post_type='comment', id=comment_id)
            request.user.assert_can_delete_comment(comment)

            parent = comment.parent
            comment.delete()
            #attn: recalc denormalized field
            parent.comment_count = parent.comment_count - 1
            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'
                )
Пример #4
0
def feedback(request):
    data = {'page_class': 'meta'}
    form = None

    if askbot_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)
Пример #5
0
def application_settings(request):
    """The context processor function"""
    if not request.path.startswith('/' + settings.ASKBOT_URL):
        #todo: this is a really ugly hack, will only work
        #when askbot is installed not at the home page.
        #this will not work for the
        #heavy modders of askbot, because their custom pages
        #will not receive the askbot settings in the context
        #to solve this properly we should probably explicitly
        #add settings to the context per page
        return {}
    my_settings = askbot_settings.as_dict()
    my_settings['LANGUAGE_CODE'] = getattr(request, 'LANGUAGE_CODE', settings.LANGUAGE_CODE)
    my_settings['ASKBOT_URL'] = settings.ASKBOT_URL
    my_settings['STATIC_URL'] = settings.STATIC_URL
    my_settings['ASKBOT_CSS_DEVEL'] = getattr(settings, 'ASKBOT_CSS_DEVEL', False)
    my_settings['DEBUG'] = settings.DEBUG
    my_settings['USING_RUNSERVER'] = 'runserver' in sys.argv
    my_settings['ASKBOT_VERSION'] = askbot.get_version()
    my_settings['LOGIN_URL'] = url_utils.get_login_url()
    my_settings['LOGOUT_URL'] = url_utils.get_logout_url()
    my_settings['LOGOUT_REDIRECT_URL'] = url_utils.get_logout_redirect_url()
    my_settings['USE_ASKBOT_LOGIN_SYSTEM'] = 'askbot.deps.django_authopenid' \
        in settings.INSTALLED_APPS
    return {
        'settings': my_settings,
        'skin': get_skin(request),
        'moderation_items': api.get_info_on_moderation_items(request.user),
        'noscript_url': const.DEPENDENCY_URLS['noscript'],
    }
Пример #6
0
def subscribe_for_tags(request):
    """process subscription of users by tags"""
    #todo - use special separator to split tags
    tag_names = request.REQUEST.get('tags','').strip().split()
    pure_tag_names, wildcards = forms.clean_marked_tagnames(tag_names)
    if request.user.is_authenticated():
        if request.method == 'POST':
            if 'ok' in request.POST:
                request.user.mark_tags(
                            pure_tag_names,
                            wildcards,
                            reason = 'good',
                            action = 'add'
                        )
                request.user.message_set.create(
                    message = _('Your tag subscription was saved, thanks!')
                )
            else:
                message = _(
                    'Tag subscription was canceled (<a href="%(url)s">undo</a>).'
                ) % {'url': request.path + '?tags=' + request.REQUEST['tags']}
                request.user.message_set.create(message = message)
            return HttpResponseRedirect(reverse('index'))
        else:
            data = {'tags': tag_names}
            return render_into_skin('subscribe_for_tags.html', data, request)
    else:
        all_tag_names = pure_tag_names + wildcards
        message = _('Please sign in to subscribe for: %(tags)s') \
                    % {'tags': ', '.join(all_tag_names)}
        request.user.message_set.create(message = message)
        request.session['subscribe_for_tags'] = (pure_tag_names, wildcards)
        return HttpResponseRedirect(url_utils.get_login_url())
Пример #7
0
def subscribe_for_tags(request):
    """process subscription of users by tags"""
    # todo - use special separator to split tags
    tag_names = request.REQUEST.get("tags", "").strip().split()
    pure_tag_names, wildcards = forms.clean_marked_tagnames(tag_names)
    if request.user.is_authenticated():
        if request.method == "POST":
            if "ok" in request.POST:
                request.user.mark_tags(pure_tag_names, wildcards, reason="good", action="add")
                request.user.message_set.create(message=_("Your tag subscription was saved, thanks!"))
            else:
                message = _('Tag subscription was canceled (<a href="%(url)s">undo</a>).') % {
                    "url": request.path + "?tags=" + request.REQUEST["tags"]
                }
                request.user.message_set.create(message=message)
            return HttpResponseRedirect(reverse("index"))
        else:
            data = {"tags": tag_names}
            return render_into_skin("subscribe_for_tags.html", data, request)
    else:
        all_tag_names = pure_tag_names + wildcards
        message = _("Please sign in to subscribe for: %(tags)s") % {"tags": ", ".join(all_tag_names)}
        request.user.message_set.create(message=message)
        request.session["subscribe_for_tags"] = (pure_tag_names, wildcards)
        return HttpResponseRedirect(url_utils.get_login_url())
Пример #8
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_id = request.POST['comment_id']
            comment = get_object_or_404(models.Comment, id=comment_id)
            request.user.assert_can_delete_comment(comment)

            obj = comment.content_object
            #todo: are the removed comments actually deleted?
            obj.comments.remove(comment)
            #attn: recalc denormalized field
            obj.comment_count = obj.comment_count - 1
            obj.save()

            return __generate_comments_json(obj, request.user)

        raise exceptions.PermissionDenied(
                    _('sorry, we seem to have some technical difficulties')
                )
    except exceptions.PermissionDenied, e:
        return HttpResponseForbidden(
                    unicode(e),
                    mimetype = 'application/json'
                )
Пример #9
0
def application_settings(request):
    """The context processor function"""
    if not request.path.startswith("/" + settings.ASKBOT_URL):
        # todo: this is a really ugly hack, will only work
        # when askbot is installed not at the home page.
        # this will not work for the
        # heavy modders of askbot, because their custom pages
        # will not receive the askbot settings in the context
        # to solve this properly we should probably explicitly
        # add settings to the context per page
        return {}
    my_settings = askbot_settings.as_dict()
    my_settings["LANGUAGE_CODE"] = getattr(request, "LANGUAGE_CODE", settings.LANGUAGE_CODE)
    my_settings["ASKBOT_URL"] = settings.ASKBOT_URL
    my_settings["STATIC_URL"] = settings.STATIC_URL
    my_settings["ASKBOT_CSS_DEVEL"] = getattr(settings, "ASKBOT_CSS_DEVEL", False)
    my_settings["USE_LOCAL_FONTS"] = getattr(settings, "ASKBOT_USE_LOCAL_FONTS", False)
    my_settings["DEBUG"] = settings.DEBUG
    my_settings["USING_RUNSERVER"] = "runserver" in sys.argv
    my_settings["ASKBOT_VERSION"] = askbot.get_version()
    my_settings["LOGIN_URL"] = url_utils.get_login_url()
    my_settings["LOGOUT_URL"] = url_utils.get_logout_url()
    my_settings["LOGOUT_REDIRECT_URL"] = url_utils.get_logout_redirect_url()
    my_settings["USE_ASKBOT_LOGIN_SYSTEM"] = "askbot.deps.django_authopenid" in settings.INSTALLED_APPS
    return {
        "settings": my_settings,
        "skin": get_skin(request),
        "moderation_items": api.get_info_on_moderation_items(request.user),
        "noscript_url": const.DEPENDENCY_URLS["noscript"],
    }
Пример #10
0
def post_comments(request):#generic ajax handler to load comments to an object
    # only support get post comments by ajax now
    user = request.user
    if request.is_ajax():
        post_type = request.REQUEST['post_type']
        id = request.REQUEST['post_id']
        if post_type == 'question':
            post_model = models.Question
        elif post_type == 'answer':
            post_model = models.Answer
        else:
            raise Http404

        obj = get_object_or_404(post_model, id=id)
        if request.method == "GET":
            response = __generate_comments_json(obj, user)
        elif request.method == "POST":
            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)
                user.post_comment(
                            parent_post = obj,
                            body_text = request.POST.get('comment')
                        )
                response = __generate_comments_json(obj, user)
            except exceptions.PermissionDenied, e:
                response = HttpResponseForbidden(
                                        unicode(e),
                                        mimetype="application/json"
                                    )
        return response
Пример #11
0
def post_comments(request):#generic ajax handler to load comments to an object
    """todo: fixme: post_comments is ambigous:
    means either get comments for post or
    add a new comment to post
    """
    # 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'):
        raise Http404  # TODO: Shouldn't be 404! More like 400, 403 or sth more specific

    user = request.user

    if request.method == 'POST':
        form = forms.NewCommentForm(request.POST)
    elif request.method == 'GET':
        form = forms.GetDataForPostForm(request.GET)

    if form.is_valid() == False:
        return HttpResponseBadRequest(
            _('This content is forbidden'),
            mimetype='application/json'
        )

    post_id = form.cleaned_data['post_id']
    try:
        post = models.Post.objects.get(id=post_id)
    except models.Post.DoesNotExist:
        return HttpResponseBadRequest(
            _('Post not found'), mimetype='application/json'
        )

    if request.method == "GET":
        response = __generate_comments_json(post, user)
    elif request.method == "POST":
        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)

            if askbot_settings.READ_ONLY_MODE_ENABLED:
                raise exceptions.PermissionDenied(askbot_settings.READ_ONLY_MESSAGE)

            comment = user.post_comment(
                parent_post=post, 
                body_text=form.cleaned_data['comment'],
                ip_addr=request.META.get('REMOTE_ADDR')
            )
            signals.new_comment_posted.send(None,
                comment=comment,
                user=user,
                form_data=form.cleaned_data
            )
            response = __generate_comments_json(post, user)
        except exceptions.PermissionDenied, e:
            response = HttpResponseForbidden(unicode(e), content_type="application/json")
Пример #12
0
def repost_answer_as_comment(request, destination=None):
    assert destination in ("comment_under_question", "comment_under_previous_answer")
    if request.user.is_anonymous():
        msg = _(
            "Sorry, only logged in users can convert answers to comments. "
            'Please <a href="%(sign_in_url)s">sign in</a>.'
        ) % {"sign_in_url": url_utils.get_login_url()}
        raise exceptions.PermissionDenied(msg)
    answer_id = request.POST.get("answer_id")
    if answer_id:
        try:
            answer_id = int(answer_id)
        except (ValueError, TypeError):
            raise Http404
        answer = get_object_or_404(models.Post, post_type="answer", id=answer_id)

        if askbot_settings.READ_ONLY_MODE_ENABLED:
            return HttpResponseRedirect(answer.get_absolute_url())
        request.user.assert_can_convert_post(post=answer)

        if destination == "comment_under_question":
            destination_post = answer.thread._question_post()
        else:
            # comment_under_previous_answer
            destination_post = answer.get_previous_answer(user=request.user)
        # todo: implement for comment under other answer

        if destination_post is None:
            message = _("Error - could not find the destination post")
            request.user.message_set.create(message=message)
            return HttpResponseRedirect(answer.get_absolute_url())

        if len(answer.text) <= askbot_settings.MAX_COMMENT_LENGTH:
            answer.post_type = "comment"
            answer.parent = destination_post

            new_comment_count = answer.comments.count() + 1
            answer.comment_count = 0

            answer_comments = models.Post.objects.get_comments().filter(parent=answer)
            answer_comments.update(parent=destination_post)

            # why this and not just "save"?
            answer.parse_and_save(author=answer.author)
            answer.thread.update_answer_count()

            answer.parent.comment_count += new_comment_count
            answer.parent.save()

            answer.thread.invalidate_cached_data()
        else:
            message = _(
                "Cannot convert, because text has more characters than " "%(max_chars)s - maximum allowed for comments"
            ) % {"max_chars": askbot_settings.MAX_COMMENT_LENGTH}
            request.user.message_set.create(message=message)

        return HttpResponseRedirect(answer.get_absolute_url())
    else:
        raise Http404
Пример #13
0
def answer(request, id, form_class=forms.AnswerForm):#process a new answer
    """view that posts new answer

    anonymous users post into anonymous storage
    and redirected to login page

    authenticated users post directly
    """
    question = get_object_or_404(models.Post, post_type='question', id=id)

    if askbot_settings.READ_ONLY_MODE_ENABLED:
        return HttpResponseRedirect(question.get_absolute_url())

    if request.method == "POST":

        #this check prevents backward compatilibility
        if form_class == forms.AnswerForm:
            custom_class_path = getattr(settings, 'ASKBOT_NEW_ANSWER_FORM', None)
            if custom_class_path:
                form_class = load_module(custom_class_path)
            else:
                form_class = forms.AnswerForm

        form = form_class(request.POST, user=request.user)

        if form.is_valid():
            if request.user.is_authenticated():
                drafts = models.DraftAnswer.objects.filter(
                                                author=request.user,
                                                thread=question.thread
                                            )
                drafts.delete()
                user = form.get_post_user(request.user)
                try:
                    answer = form.save(question, user)

                    signals.new_answer_posted.send(None,
                        answer=answer,
                        user=user,
                        form_data=form.cleaned_data
                    )

                    return HttpResponseRedirect(answer.get_absolute_url())
                except askbot_exceptions.AnswerAlreadyGiven, e:
                    request.user.message_set.create(message = unicode(e))
                    answer = question.thread.get_answers_by_user(user)[0]
                    return HttpResponseRedirect(answer.get_absolute_url())
                except exceptions.PermissionDenied, e:
                    request.user.message_set.create(message = unicode(e))
            else:
                request.session.flush()
                models.AnonymousAnswer.objects.create(
                    question=question,
                    wiki=form.cleaned_data['wiki'],
                    text=form.cleaned_data['text'],
                    session_key=request.session.session_key,
                    ip_addr=request.META['REMOTE_ADDR'],
                )
                return HttpResponseRedirect(url_utils.get_login_url())
Пример #14
0
 def wrapper(request, *args, **kwargs):
     if request.user.is_anonymous():
         #todo: expand for handling ajax responses
         if askbot_settings.ALLOW_POSTING_BEFORE_LOGGING_IN == False:
             request.user.message_set.create(message=unicode(message))
             params = 'next=%s' % request.path
             return HttpResponseRedirect(url_utils.get_login_url() + '?' + params)
     return view_func(request, *args, **kwargs)
Пример #15
0
def ask(request):#view used to ask a new question
    """a view to ask a new question
    gives space for q title, body, tags and checkbox for to post as wiki

    user can start posting a question anonymously but then
    must login/register in order for the question go be shown
    """
    if request.method == "POST":
        form = forms.AskForm(request.POST)
        if form.is_valid():
            timestamp = datetime.datetime.now()
            title = form.cleaned_data['title']
            wiki = form.cleaned_data['wiki']
            tagnames = form.cleaned_data['tags']
            text = form.cleaned_data['text']
            ask_anonymously = form.cleaned_data['ask_anonymously']
            is_charged = form.cleaned_data['is_charged']
            cost = form.cleaned_data['cost']
            featurepic = form.cleaned_data['featurepic']
            if is_charged == None :
                is_charged =False
            if cost == None :
                cost =0
            if request.user.is_authenticated():
                try:
                    question = request.user.post_question(
                        title = title,
                        body_text = text,
                        tags = tagnames,
                        wiki = wiki,
                        is_anonymous = ask_anonymously,
                        timestamp = timestamp,
                        is_charged = is_charged,
                        cost = cost,
                        featurepic= featurepic, 
                    )
                    return HttpResponseRedirect(question.get_absolute_url())
                except exceptions.PermissionDenied, e:
                    request.user.message_set.create(message = unicode(e))
                    return HttpResponseRedirect(reverse('index'))

            else:
                request.session.flush()
                session_key = request.session.session_key
                summary = strip_tags(text)[:120]
                models.AnonymousQuestion.objects.create(
                    session_key = session_key,
                    title       = title,
                    tagnames = tagnames,
                    wiki = wiki,
                    is_anonymous = ask_anonymously,
                    text = text,
                    summary = summary,
                    added_at = timestamp,
                    ip_addr = request.META['REMOTE_ADDR'],
                    featurepic= featurepic, 
                )
                return HttpResponseRedirect(url_utils.get_login_url())
Пример #16
0
def ask(request):#view used to ask a new question
    """a view to ask a new question
    gives space for q title, body, tags and checkbox for to post as wiki

    user can start posting a question anonymously but then
    must login/register in order for the question go be shown
    """
    form = forms.AskForm(request.REQUEST)
    if request.method == 'POST':
        if form.is_valid():
            timestamp = datetime.datetime.now()
            title = form.cleaned_data['title']
            wiki = form.cleaned_data['wiki']
            tagnames = form.cleaned_data['tags']
            text = form.cleaned_data['text']
            ask_anonymously = form.cleaned_data['ask_anonymously']
            post_privately = form.cleaned_data['post_privately']
            group_id = form.cleaned_data.get('group_id', None)

            if request.user.is_authenticated():
                drafts = models.DraftQuestion.objects.filter(
                                                author=request.user
                                            )
                drafts.delete()

                user = form.get_post_user(request.user)
                try:
                    question = user.post_question(
                        title = title,
                        body_text = text,
                        tags = tagnames,
                        wiki = wiki,
                        is_anonymous = ask_anonymously,
                        is_private = post_privately,
                        timestamp = timestamp,
                        group_id = group_id
                    )
                    return HttpResponseRedirect(question.get_absolute_url())
                except exceptions.PermissionDenied, e:
                    request.user.message_set.create(message = unicode(e))
                    return HttpResponseRedirect(reverse('index'))

            else:
                request.session.flush()
                session_key = request.session.session_key
                summary = strip_tags(text)[:120]
                models.AnonymousQuestion.objects.create(
                    session_key = session_key,
                    title       = title,
                    tagnames = tagnames,
                    wiki = wiki,
                    is_anonymous = ask_anonymously,
                    text = text,
                    summary = summary,
                    added_at = timestamp,
                    ip_addr = request.META['REMOTE_ADDR'],
                )
                return HttpResponseRedirect(url_utils.get_login_url())
Пример #17
0
 def wrapper(request, *args, **kwargs):
     if request.user.is_anonymous():
         # TODO: expand for handling ajax responses
         if not askbot_settings.ALLOW_POSTING_BEFORE_LOGGING_IN:
             # request.user.message_set.create(message=message)
             django_messages.info(request, message)
             params = 'next=%s' % request.path
             return redirect(url_utils.get_login_url() + '?' + params)
     return view_func(request, *args, **kwargs)
Пример #18
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:
         params = '?next=%s' % request.path
         return HttpResponseRedirect(url_utils.get_login_url() + params)
     return f(request, profile_owner, context)
Пример #19
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": askbot_settings.APP_SHORT_NAME}

        if askbot_settings.TAGS_ARE_REQUIRED:
            error_message = string_concat(
                INSTRUCTIONS_PREAMBLE,
                "<ul>",
                QUESTION_TITLE_INSTRUCTION,
                REQUIRED_TAGS_INSTRUCTION,
                QUESTION_DETAILS_INSTRUCTION,
                "</ul>",
                TAGS_INSTRUCTION_FOOTNOTE,
            )
        else:
            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": askbot_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)

    # print 'sending email'
    # print email
    # print subject
    # print error_message
    headers = {}
    if reply_to:
        headers["Reply-To"] = reply_to

    send_mail(recipient_list=(email,), subject_line="Re: " + subject, body_text=error_message, headers=headers)
Пример #20
0
def post_new_answer(request, mid, pid):#process a new problem
    """view that posts new problem

    anonymous users post into anonymous storage
    and redirected to login page

    authenticated users post directly
    """
    exercise = get_object_or_404(models.Post, post_type='exercise', id=mid)
    problem = get_object_or_404(models.Post, post_type='problem', id=pid)
    if request.method == "POST":
        form = forms.AnswerForm(request.POST)
        if form.is_valid():
            wiki = form.cleaned_data['wiki']
            text = form.cleaned_data['text']
            update_time = datetime.datetime.now()

            if request.user.is_authenticated():
                drafts = models.DraftSolution.objects.filter(
                                                author=request.user,
                                                #thread=exercise.thread
                                            )
                drafts.delete()
                try:
                    follow = form.cleaned_data['email_notify']
                    is_private = form.cleaned_data['post_privately']

                    user = form.get_post_user(request.user)
                    print dir(user.post_solution)
                    solution = user.post_solution(
                                        exercise = exercise,
                                        parent = problem,
                                        body_text = text,
                                        follow = follow,
                                        wiki = wiki,
                                        is_private = is_private,
                                        timestamp = update_time,
                                    )
                    return HttpResponseRedirect(exercise.get_absolute_url())
                except askbot_exceptions.SolutionAlreadyGiven, e:
                    request.user.message_set.create(message = unicode(e))
                    answer = exercise.thread.get_solutions_by_user(request.user)[0]
                    return HttpResponseRedirect(exercise.get_absolute_url())
                except exceptions.PermissionDenied, e:
                    request.user.message_set.create(message = unicode(e))
            else:
                request.session.flush()
                models.AnonymousSolution.objects.create(
                    exercise=exercise,
                    wiki=wiki,
                    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())
Пример #21
0
def application_settings(request):
    """The context processor function"""
    if not request.path.startswith('/' + settings.ASKBOT_URL):
        #todo: this is a really ugly hack, will only work
        #when askbot is installed not at the home page.
        #this will not work for the
        #heavy modders of askbot, because their custom pages
        #will not receive the askbot settings in the context
        #to solve this properly we should probably explicitly
        #add settings to the context per page
        return {}
    my_settings = askbot_settings.as_dict()
    my_settings['LANGUAGE_CODE'] = getattr(request, 'LANGUAGE_CODE', settings.LANGUAGE_CODE)
    my_settings['ALLOWED_UPLOAD_FILE_TYPES'] = \
            settings.ASKBOT_ALLOWED_UPLOAD_FILE_TYPES
    my_settings['ASKBOT_URL'] = settings.ASKBOT_URL
    my_settings['STATIC_URL'] = settings.STATIC_URL
    my_settings['ASKBOT_CSS_DEVEL'] = getattr(
                                        settings,
                                        'ASKBOT_CSS_DEVEL',
                                        False
                                    )
    my_settings['USE_LOCAL_FONTS'] = getattr(
                                        settings,
                                        'ASKBOT_USE_LOCAL_FONTS',
                                        False
                                    )
    my_settings['DEBUG'] = settings.DEBUG
    my_settings['USING_RUNSERVER'] = 'runserver' in sys.argv
    my_settings['ASKBOT_VERSION'] = askbot.get_version()
    my_settings['LOGIN_URL'] = url_utils.get_login_url()
    my_settings['LOGOUT_URL'] = url_utils.get_logout_url()
    my_settings['LOGOUT_REDIRECT_URL'] = url_utils.get_logout_redirect_url()
    my_settings['USE_ASKBOT_LOGIN_SYSTEM'] = 'askbot.deps.django_authopenid' \
        in settings.INSTALLED_APPS
    context = {
        'settings': my_settings,
        'skin': get_skin(request),
        'moderation_items': api.get_info_on_moderation_items(request.user),
        'noscript_url': const.DEPENDENCY_URLS['noscript'],
    }

    if askbot_settings.GROUPS_ENABLED:
        groups = models.Group.objects.exclude(
                                              name__startswith='_internal_'
                                             ).values('id', 'name')
        group_list = []
        for group in groups:
            group_slug = slugify(group['name'])
            link = reverse('users_by_group',
                    kwargs={'group_id': group['id'],
                        'group_slug': group_slug})
            group_list.append({'name': group['name'], 'link': link})
        context['group_list'] = simplejson.dumps(group_list)

    return context
Пример #22
0
def answer(request, id):#process a new answer
    """view that posts new answer

    anonymous users post into anonymous storage
    and redirected to login page

    authenticated users post directly
    """
    question = get_object_or_404(models.Post, post_type='question', id=id)
    if request.method == "POST":
        form = forms.AnswerForm(request.POST, user=request.user)
        if form.is_valid():
            wiki = form.cleaned_data['wiki']
            text = form.cleaned_data['text']
            update_time = datetime.datetime.now()

            if request.user.is_authenticated():
                drafts = models.DraftAnswer.objects.filter(
                                                author=request.user,
                                                thread=question.thread
                                            )
                drafts.delete()
                try:
                    follow = form.cleaned_data['email_notify']
                    is_private = form.cleaned_data['post_privately']

                    user = form.get_post_user(request.user)

                    answer = user.post_answer(
                                        question = question,
                                        body_text = text,
                                        follow = follow,
                                        wiki = wiki,
                                        is_private = is_private,
                                        timestamp = update_time,
                                    )
                    # by Jun
                    __save_presentation(question, answer, text, user)
                    
                    return HttpResponseRedirect(answer.get_absolute_url())
                except askbot_exceptions.AnswerAlreadyGiven, e:
                    request.user.message_set.create(message = unicode(e))
                    answer = question.thread.get_answers_by_user(request.user)[0]
                    return HttpResponseRedirect(answer.get_absolute_url())
                except exceptions.PermissionDenied, e:
                    request.user.message_set.create(message = unicode(e))
            else:
                request.session.flush()
                models.AnonymousAnswer.objects.create(
                    question=question,
                    wiki=wiki,
                    text=text,
                    session_key=request.session.session_key,
                    ip_addr=request.META['REMOTE_ADDR'],
                )
                return HttpResponseRedirect(url_utils.get_login_url())
Пример #23
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)
Пример #24
0
def feedback(request):
    data = {'page_class': 'meta'}
    form = None

    if askbot_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)
            else:
                data['email'] = request.user.email

            data['message'] = form.cleaned_data['message']
            data['name'] = form.cleaned_data.get('name', None)
            template = get_template('email/feedback_email.txt')
            message = template.render(RequestContext(request, data))

            headers = {}
            if data['email']:
                headers = {'Reply-To': data['email']}
            subject = _('Q&A forum feedback')
            if askbot_settings.FEEDBACK_EMAILS:
                recipients = re.split('\s*,\s*', askbot_settings.FEEDBACK_EMAILS)
                send_mail(
                    subject_line=subject,
                    body_text=message,
                    headers=headers,
                    recipient_list=recipients,
                )
            else:
                mail_moderators(
                    subject_line=subject,
                    body_text=message,
                    headers=headers
                )
            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(request, 'feedback.html', data)
Пример #25
0
def post_comments(request):  # generic ajax handler to load comments to an object
    """todo: fixme: post_comments is ambigous:
    means either get comments for post or
    add a new comment to post
    """
    # 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"):
        raise Http404  # TODO: Shouldn't be 404! More like 400, 403 or sth more specific

    if post_type == "question" and askbot_settings.QUESTION_COMMENTS_ENABLED == False:
        raise Http404
    elif post_type == "answer" and askbot_settings.ANSWER_COMMENTS_ENABLED == False:
        raise Http404

    user = request.user

    if request.method == "POST":
        form = forms.NewCommentForm(request.POST)
    elif request.method == "GET":
        form = forms.GetCommentDataForPostForm(request.GET)

    if form.is_valid() == False:
        return HttpResponseBadRequest(_("This content is forbidden"), mimetype="application/json")

    post_id = form.cleaned_data["post_id"]
    avatar_size = form.cleaned_data["avatar_size"]
    try:
        post = models.Post.objects.get(id=post_id)
    except models.Post.DoesNotExist:
        return HttpResponseBadRequest(_("Post not found"), mimetype="application/json")

    if request.method == "GET":
        response = __generate_comments_json(post, user, avatar_size)
    elif request.method == "POST":
        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)

            if askbot_settings.READ_ONLY_MODE_ENABLED:
                raise exceptions.PermissionDenied(askbot_settings.READ_ONLY_MESSAGE)

            comment = user.post_comment(
                parent_post=post, body_text=form.cleaned_data["comment"], ip_addr=request.META.get("REMOTE_ADDR")
            )
            signals.new_comment_posted.send(None, comment=comment, user=user, form_data=form.cleaned_data)
            response = __generate_comments_json(post, user, avatar_size)
        except exceptions.PermissionDenied, e:
            response = HttpResponseForbidden(unicode(e), content_type="application/json")
Пример #26
0
def ask(request):  # view used to ask a new question
    """a view to ask a new question
    gives space for q title, body, tags and checkbox for to post as wiki

    user can start posting a question anonymously but then
    must login/register in order for the question go be shown
    """
    if request.method == "POST":
        form = forms.AskForm(request.POST)
        if form.is_valid():
            timestamp = datetime.datetime.now()
            # todo: move this to clean_title
            title = form.cleaned_data["title"].strip()
            wiki = form.cleaned_data["wiki"]
            # todo: move this to clean_tagnames
            tagnames = form.cleaned_data["tags"].strip()
            text = form.cleaned_data["text"]
            ask_anonymously = form.cleaned_data["ask_anonymously"]

            if request.user.is_authenticated():
                try:
                    question = request.user.post_question(
                        title=title,
                        body_text=text,
                        tags=tagnames,
                        wiki=wiki,
                        is_anonymous=ask_anonymously,
                        timestamp=timestamp,
                    )
                    return HttpResponseRedirect(question.get_absolute_url())
                except exceptions.PermissionDenied, e:
                    request.user.message_set.create(message=unicode(e))
                    return HttpResponseRedirect(reverse("index"))

            else:
                request.session.flush()
                session_key = request.session.session_key
                summary = strip_tags(text)[:120]
                question = models.AnonymousQuestion(
                    session_key=session_key,
                    title=title,
                    tagnames=tagnames,
                    wiki=wiki,
                    is_anonymous=ask_anonymously,
                    text=text,
                    summary=summary,
                    added_at=timestamp,
                    ip_addr=request.META["REMOTE_ADDR"],
                )
                question.save()
                return HttpResponseRedirect(url_utils.get_login_url())
Пример #27
0
def application_settings(request):
    """The context processor function"""
    my_settings = askbot_settings.as_dict()
    my_settings['LANGUAGE_CODE'] = settings.LANGUAGE_CODE
    my_settings['ASKBOT_URL'] = settings.ASKBOT_URL
    my_settings['DEBUG'] = settings.DEBUG
    my_settings['ASKBOT_VERSION'] = askbot.get_version()
    my_settings['LOGIN_URL'] = url_utils.get_login_url()
    my_settings['LOGOUT_URL'] = url_utils.get_logout_url()
    my_settings['LOGOUT_REDIRECT_URL'] = url_utils.get_logout_redirect_url()
    return {
        'settings': my_settings,
        'skin': get_skin(request),
        'moderation_items': api.get_info_on_moderation_items(request.user)
    }
Пример #28
0
 def wrapped_func(request, profile_owner, context):
     if profile_owner == request.user:
         pass
     elif request.user.is_authenticated():
         if request.user.can_moderate_user(profile_owner):
             pass
         else:
             #redirect to the user profile homepage
             #as this one should be accessible to all
             return HttpResponseRedirect(request.path)
     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)
Пример #29
0
def feedback(request):
    if askbot_settings.FEEDBACK_MODE == 'auth-only':
        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)
    elif askbot_settings.FEEDBACK_MODE == 'disabled':
        raise Http404

    data = {'page_class': 'meta'}
    form = None

    if request.method == "POST":
        form = FeedbackForm(user=request.user, data=request.POST)
        if form.is_valid():

            data = {
                'message': form.cleaned_data['message'],
                'name': form.cleaned_data.get('name'),
                'ip_addr': request.META.get('REMOTE_ADDR', _('unknown')),
                'user': request.user
            }

            if request.user.is_authenticated():
                data['email'] = request.user.email
            else:
                data['email'] = form.cleaned_data.get('email', None)

            email = FeedbackEmail(data)

            if askbot_settings.FEEDBACK_EMAILS:
                recipients = re.split('\s*,\s*', askbot_settings.FEEDBACK_EMAILS)
                email.send(recipients)
            else:
                email.send(get_moderators())

            message = _('Thanks for the feedback!')
            request.user.message_set.create(message=message)
            return HttpResponseRedirect(get_next_url(request))
    else:
        form = FeedbackForm(
                    user=request.user,
                    initial={'next':get_next_url(request)}
                )

    data['form'] = form
    return render(request, 'feedback.html', data)
Пример #30
0
def comment_to_answer(request):
    if request.user.is_anonymous():
        msg = _('Sorry, only logged in users can convert comments to answers. '
                'Please <a href="%(sign_in_url)s">sign in</a>.') % {
                    'sign_in_url': url_utils.get_login_url()}
        raise exceptions.PermissionDenied(msg)

    form = forms.ConvertCommentForm(request.POST)
    if not form.is_valid():
        raise Http404

    comment = get_object_or_404(models.Post, post_type='comment', id=form.cleaned_data['comment_id'])

    if not askbot_settings.READ_ONLY_MODE_ENABLED:
        request.user.repost_comment_as_answer(comment)

    return redirect(comment)
Пример #31
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():

            form = forms.ProcessCommentForm(request.POST)

            if form.is_valid() == False:
                return HttpResponseBadRequest()

            comment_id = form.cleaned_data['comment_id']
            comment = get_object_or_404(models.Post, post_type='comment', id=comment_id)
            request.user.assert_can_delete_comment(comment)

            if askbot_settings.READ_ONLY_MODE_ENABLED:
                raise exceptions.PermissionDenied(askbot_settings.READ_ONLY_MESSAGE)

            parent = comment.parent
            comment.delete()
            #attn: recalc denormalized field
            parent.comment_count = parent.comments.count()
            parent.save()
            parent.thread.reset_cached_data()

            avatar_size = form.cleaned_data['avatar_size']
            return __generate_comments_json(parent, request.user, avatar_size)

        raise exceptions.PermissionDenied(
                    _('sorry, we seem to have some technical difficulties')
                )
    except exceptions.PermissionDenied as e:
        return HttpResponseForbidden(
                    unicode(e),
                    content_type='application/json'
                )
Пример #32
0
def bounce_email(email, subject, reason = None, body_text = 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': askbot_settings.APP_SHORT_NAME}
        error_message = string_concat(error_message, ASK_BY_EMAIL_USAGE)
    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': askbot_settings.APP_SHORT_NAME,
            'url': url_utils.get_login_url()
        }
    elif reason == 'permission_denied':
        error_message = _(
            '<p>Sorry, your question could not be posted '
            'due to insufficient privileges of your user account</p>'
        )
    else:
        raise ValueError('unknown reason to bounce an email: "%s"' % reason)

    if body_text != None:
        error_message = string_concat(error_message, body_text)

    #print 'sending email'
    #print email
    #print subject
    #print error_message
    send_mail(
        recipient_list = (email,),
        subject_line = 'Re: ' + subject,
        body_text = error_message
    )
Пример #33
0
def comment_to_answer(request):
    if request.user.is_anonymous():
        msg = _('Sorry, only logged in users can convert comments to answers. '
                'Please <a href="%(sign_in_url)s">sign in</a>.') % {
                    'sign_in_url': url_utils.get_login_url()
                }
        raise exceptions.PermissionDenied(msg)

    form = forms.ConvertCommentForm(request.POST)
    if not form.is_valid():
        raise Http404

    comment = get_object_or_404(models.Post,
                                post_type='comment',
                                id=form.cleaned_data['comment_id'])

    if not askbot_settings.READ_ONLY_MODE_ENABLED:
        request.user.repost_comment_as_answer(comment)

    return redirect(comment)
Пример #34
0
def feedback(request):
    if askbot_settings.FEEDBACK_MODE == 'auth-only':
        if request.user.is_anonymous:
            message = _('Please sign in or register to send your feedback')
            request.user.message_set.create(message=message)
            next_jwt = encode_jwt({'next_url': request.path})
            return HttpResponseRedirect(get_login_url() + '?next=' + next_jwt)
    elif askbot_settings.FEEDBACK_MODE == 'disabled':
        raise Http404

    data = {'page_class': 'meta'}
    form = None

    if request.method == "POST":
        form = FeedbackForm(user=request.user, data=request.POST)
        if form.is_valid():

            data = {
                'message': form.cleaned_data['message'],
                'name': form.cleaned_data.get('name'),
                'ip_addr': request.META.get('REMOTE_ADDR', _('unknown')),
                'user': request.user
            }

            if request.user.is_authenticated:
                data['email'] = request.user.email
            else:
                data['email'] = form.cleaned_data.get('email', None)

            email = FeedbackEmail(data)
            email.send(get_users_by_role('recv_feedback'))

            message = _('Thanks for the feedback!')
            request.user.message_set.create(message=message)
            return HttpResponseRedirect(get_next_url(request))
    else:
        form = FeedbackForm(user=request.user,
                            initial={'next': get_next_jwt(request)})

    data['form'] = form
    return render(request, 'feedback.html', data)
Пример #35
0
def answer(request, id):  #process a new answer
    """view that posts new answer

    anonymous users post into anonymous storage
    and redirected to login page

    authenticated users post directly
    """
    question = get_object_or_404(models.Question, id=id)
    if request.method == "POST":
        form = forms.AnswerForm(question, request.user, request.POST)
        if form.is_valid():
            wiki = form.cleaned_data['wiki']
            text = form.cleaned_data['text']
            update_time = datetime.datetime.now()

            if request.user.is_authenticated():
                try:
                    follow = form.cleaned_data['email_notify']
                    answer = request.user.post_answer(
                        question=question,
                        body_text=text,
                        follow=follow,
                        wiki=wiki,
                        timestamp=update_time,
                    )
                    return HttpResponseRedirect(answer.get_absolute_url())
                except exceptions.PermissionDenied, e:
                    request.user.message_set.create(message=unicode(e))
            else:
                request.session.flush()
                anon = models.AnonymousAnswer(
                    question=question,
                    wiki=wiki,
                    text=text,
                    summary=strip_tags(text)[:120],
                    session_key=request.session.session_key,
                    ip_addr=request.META['REMOTE_ADDR'],
                )
                anon.save()
                return HttpResponseRedirect(url_utils.get_login_url())
Пример #36
0
def feedback(request):
    data = {'page_class': 'meta'}
    form = None

    if askbot_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)
            else:
                data['email'] = request.user.email

            data['message'] = form.cleaned_data['message']
            data['name'] = form.cleaned_data.get('name', None)
            template = get_template('email/feedback_email.txt')
            message = template.render(RequestContext(request, data))

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

            mail_moderators(_('Q&A forum feedback'), message, headers=headers)
            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(request, 'feedback.html', data)
Пример #37
0
def subscribe_for_tags(request):
    """process subscription of users by tags"""
    # TODO - use special separator to split tags
    tag_names = request.REQUEST.get('tags', '').strip().split()
    pure_tag_names, wildcards = forms.clean_marked_tagnames(tag_names)
    if request.user.is_authenticated():
        if request.method == 'POST':
            if 'ok' in request.POST:
                request.user.mark_tags(pure_tag_names,
                                       wildcards,
                                       reason='good',
                                       action='add')
                # request.user.message_set.create(message=_('Your tag subscription was saved, thanks!'))
                django_messages.info(
                    request, _('Your tag subscription was saved, thanks!'))
            else:
                message = _(
                    'Tag subscription was canceled (<a href="%(url)s">undo</a>).'
                ) % {
                    'url':
                    escape(request.path) + '?tags=' + request.REQUEST['tags']
                }
                # request.user.message_set.create(message=message)
                django_messages.info(request, message)
            return redirect('index')
        else:
            data = {'tags': tag_names}
            return render(request, 'subscribe_for_tags.jinja', data)
    else:
        all_tag_names = pure_tag_names + wildcards
        message = _('Please sign in to subscribe for: %(tags)s') % {
            'tags': ', '.join(all_tag_names)
        }
        # request.user.message_set.create(message=message)
        django_messages.info(request, message)
        request.session['subscribe_for_tags'] = (pure_tag_names, wildcards)
        return redirect(url_utils.get_login_url())
Пример #38
0
def ask(request):#view used to ask a new question
    """a view to ask a new question
    gives space for q title, body, tags and checkbox for to post as wiki

    user can start posting a question anonymously but then
    must login/register in order for the question go be shown
    """
    form = forms.AskForm(request.REQUEST, user=request.user)

    if request.method == 'POST':
        if form.is_valid():
            logging.info(request.REQUEST)
            timestamp = datetime.datetime.now()
            title = form.cleaned_data['title']
            wiki = form.cleaned_data['wiki']
            tagnames = form.cleaned_data['tags']
            category = form.cleaned_data['category']
            text = form.cleaned_data['text']
            ask_anonymously = form.cleaned_data['ask_anonymously']
            post_privately = form.cleaned_data['post_privately']
            group_id = form.cleaned_data.get('group_id', None)
            if request.user.is_authenticated():
                drafts = models.DraftQuestion.objects.filter(
                                                author=request.user
                                            )
                drafts.delete()

                user = form.get_post_user(request.user)
                try:
                    question = user.post_question(
                        title = title,
                        body_text = text,
                        tags = tagnames,
                        category = category,
                        wiki = wiki,
                        is_anonymous = ask_anonymously,
                        is_private = post_privately,
                        timestamp = timestamp,
                        group_id = group_id
                    )
                    
                    __save_presentation(question, None, text, user)
                    
                    return HttpResponseRedirect(question.get_absolute_url())
                except exceptions.PermissionDenied, e:
                    request.user.message_set.create(message = unicode(e))
                    return HttpResponseRedirect(reverse('index'))

            else:
                request.session.flush()
                session_key = request.session.session_key
                category_instance = models.Category.objects.get(name = category)
                models.AnonymousQuestion.objects.create(
                    session_key = session_key,
                    title       = title,
                    tagnames = tagnames,
                    category_id = category_instance.id,
                    wiki = wiki,
                    is_anonymous = ask_anonymously,
                    text = text,
                    added_at = timestamp,
                    ip_addr = request.META['REMOTE_ADDR'],
                )
                return HttpResponseRedirect(url_utils.get_login_url())
Пример #39
0
def ask(request):  # view used to ask a new question
    """a view to ask a new question
    gives space for q title, body, tags and checkbox for to post as wiki

    user can start posting a question anonymously but then
    must login/register in order for the question go be shown
    """
    if request.user.is_authenticated():
        if request.user.is_read_only():
            referer = request.META.get("HTTP_REFERER", reverse('questions'))
            # request.user.message_set.create(message=_('Sorry, but you have only read access'))
            django_messages.info(request,
                                 _('Sorry, but you have only read access'))
            return redirect(referer)

    if askbot_settings.READ_ONLY_MODE_ENABLED:
        return redirect('index')

    if request.method == 'POST':
        form = forms.AskForm(request.POST, user=request.user)
        if form.is_valid():
            timestamp = timezone.now()
            title = form.cleaned_data['title']
            wiki = form.cleaned_data['wiki']
            tagnames = form.cleaned_data['tags']
            text = form.cleaned_data['text']
            ask_anonymously = form.cleaned_data['ask_anonymously']
            post_privately = form.cleaned_data['post_privately']
            group_id = form.cleaned_data.get('group_id', None)
            language = form.cleaned_data.get('language', None)

            if request.user.is_authenticated():
                drafts = models.DraftQuestion.objects.filter(
                    author=request.user)
                drafts.delete()
                user = form.get_post_user(request.user)
            elif request.user.is_anonymous(
            ) and askbot_settings.ALLOW_ASK_UNREGISTERED:
                user = models.get_or_create_anonymous_user()
                ask_anonymously = True
            else:
                user = None

            if user:
                try:
                    question = user.post_question(
                        title=title,
                        body_text=text,
                        tags=tagnames,
                        wiki=wiki,
                        is_anonymous=ask_anonymously,
                        is_private=post_privately,
                        timestamp=timestamp,
                        group_id=group_id,
                        language=language,
                        ip_addr=request.META.get('REMOTE_ADDR'))
                    signals.new_question_posted.send(
                        None,
                        question=question,
                        user=user,
                        form_data=form.cleaned_data)
                    return redirect(question)
                except exceptions.PermissionDenied as e:
                    traceback.print_exc()
                    # request.user.message_set.create(message=force_text(e))
                    django_messages.info(request, force_text(e))
                    return redirect('index')
            else:
                request.session.flush()
                session_key = request.session.session_key
                models.AnonymousQuestion.objects.create(
                    session_key=session_key,
                    title=title,
                    tagnames=tagnames,
                    wiki=wiki,
                    is_anonymous=ask_anonymously,
                    text=text,
                    added_at=timestamp,
                    ip_addr=request.META.get('REMOTE_ADDR'),
                )
                return redirect(url_utils.get_login_url())

    if request.method == 'GET':
        form = forms.AskForm(user=request.user)

    draft_title = ''
    draft_text = ''
    draft_tagnames = ''
    if request.user.is_authenticated():
        drafts = models.DraftQuestion.objects.filter(author=request.user)
        if len(drafts) > 0:
            draft = drafts[0]
            draft_title = draft.title
            draft_text = draft.text
            draft_tagnames = draft.tagnames

    form.initial = {
        'ask_anonymously': request.REQUEST.get('ask_anonymously', False),
        'tags': request.REQUEST.get('tags', draft_tagnames),
        'text': request.REQUEST.get('text', draft_text),
        'title': request.REQUEST.get('title', draft_title),
        'post_privately': request.REQUEST.get('post_privately', False),
        'language': get_language(),
        'wiki': request.REQUEST.get('wiki', False),
    }
    if 'group_id' in request.REQUEST:
        try:
            group_id = int(request.GET.get('group_id', None))
            form.initial['group_id'] = group_id
        except Exception:
            pass

    editor_is_folded = \
        askbot_settings.QUESTION_BODY_EDITOR_MODE == 'folded' and \
        askbot_settings.MIN_QUESTION_BODY_LENGTH == 0 and \
        form.initial['text'] == ''

    data = {
        'active_tab': 'ask',
        'page_class': 'ask-page',
        'form': form,
        'editor_is_folded': editor_is_folded,
        'mandatory_tags': models.tag.get_mandatory_tags(),
        'email_validation_faq_url': reverse('faq') + '# validate',
        'category_tree_data': askbot_settings.CATEGORY_TREE,
        'tag_names': list(
        ),  # need to keep context in sync with edit_question for tag editor
    }
    data.update(context.get_for_tag_editor())
    return render(request, 'ask.jinja', data)
Пример #40
0
def answer(request, id, form_class=forms.AnswerForm):  # process a new answer
    """view that posts new answer

    anonymous users post into anonymous storage
    and redirected to login page

    authenticated users post directly
    """
    question = get_object_or_404(models.Post, post_type='question', id=id)

    if askbot_settings.READ_ONLY_MODE_ENABLED:
        return redirect(question)

    if request.method == "POST":
        # this check prevents backward compatilibility
        if form_class == forms.AnswerForm:
            custom_class_path = getattr(settings, 'ASKBOT_NEW_ANSWER_FORM',
                                        None)
            if custom_class_path:
                form_class = load_module(custom_class_path)
            else:
                form_class = forms.AnswerForm

        form = form_class(request.POST, user=request.user)

        if form.is_valid():
            if request.user.is_authenticated():
                drafts = models.DraftAnswer.objects.filter(
                    author=request.user, thread=question.thread)
                drafts.delete()
                user = form.get_post_user(request.user)
                try:
                    answer = form.save(question,
                                       user,
                                       ip_addr=request.META.get('REMOTE_ADDR'))
                    signals.new_answer_posted.send(None,
                                                   answer=answer,
                                                   user=user,
                                                   form_data=form.cleaned_data)
                    return redirect(answer)
                except askbot_exceptions.AnswerAlreadyGiven as e:
                    traceback.print_exc()
                    # request.user.message_set.create(message=force_text(e))
                    django_messages.info(request, force_text(e))
                    answer = question.thread.get_answers_by_user(user)[0]
                    return redirect(answer)
                except exceptions.PermissionDenied as e:
                    traceback.print_exc()
                    # request.user.message_set.create(message=force_text(e))
                    django_messages.info(request, force_text(e))
            else:
                request.session.flush()
                models.AnonymousAnswer.objects.create(
                    question=question,
                    wiki=form.cleaned_data['wiki'],
                    text=form.cleaned_data['text'],
                    session_key=request.session.session_key,
                    ip_addr=request.META.get('REMOTE_ADDR'),
                )
                return redirect(url_utils.get_login_url())

    return redirect(question)
Пример #41
0
def ask(request):  #view used to ask a new question
    """a view to ask a new question
    gives space for q title, body, tags and checkbox for to post as wiki

    user can start posting a question anonymously but then
    must login/register in order for the question go be shown
    """
    if request.user.is_authenticated():
        if request.user.is_read_only():
            referer = request.META.get("HTTP_REFERER", reverse('questions'))
            request.user.message_set.create(
                message=_('Sorry, but you have only read access'))
            return HttpResponseRedirect(referer)

    if askbot_settings.READ_ONLY_MODE_ENABLED:
        return HttpResponseRedirect(reverse('index'))

    if request.method == 'POST':
        form = forms.AskForm(request.POST, user=request.user)
        if form.is_valid():
            timestamp = timezone.now()
            title = form.cleaned_data['title']
            wiki = form.cleaned_data['wiki']
            tagnames = form.cleaned_data['tags']
            text = form.cleaned_data['text']
            ask_anonymously = form.cleaned_data['ask_anonymously']
            post_privately = form.cleaned_data['post_privately']
            group_id = form.cleaned_data.get('group_id', None)
            language = form.cleaned_data.get('language', None)

            content = '{}\n\n{}\n\n{}'.format(title, tagnames, text)
            if akismet_check_spam(content, request):
                message = _(
                    'Spam was detected on your post, sorry if it was a mistake'
                )
                raise exceptions.PermissionDenied(message)

            if request.user.is_authenticated():
                drafts = models.DraftQuestion.objects.filter(
                    author=request.user)
                drafts.delete()
                user = form.get_post_user(request.user)
            elif request.user.is_anonymous(
            ) and askbot_settings.ALLOW_ASK_UNREGISTERED:
                user = models.get_or_create_anonymous_user()
                ask_anonymously = True
            else:
                user = None

            if user:
                try:
                    question = user.post_question(
                        title=title,
                        body_text=text,
                        tags=tagnames,
                        wiki=wiki,
                        is_anonymous=ask_anonymously,
                        is_private=post_privately,
                        timestamp=timestamp,
                        group_id=group_id,
                        language=language,
                        ip_addr=request.META.get('REMOTE_ADDR'))
                    signals.new_question_posted.send(
                        None,
                        question=question,
                        user=user,
                        form_data=form.cleaned_data)
                    return HttpResponseRedirect(question.get_absolute_url())
                except exceptions.PermissionDenied as e:
                    request.user.message_set.create(message=unicode(e))
                    return HttpResponseRedirect(reverse('index'))

            else:
                session_key = request.session.session_key
                if session_key is None:
                    return HttpResponseForbidden()

                models.AnonymousQuestion.objects.create(
                    session_key=session_key,
                    title=title,
                    tagnames=tagnames,
                    wiki=wiki,
                    is_anonymous=ask_anonymously,
                    text=text,
                    added_at=timestamp,
                    ip_addr=request.META.get('REMOTE_ADDR'),
                )
                return HttpResponseRedirect(url_utils.get_login_url())

    if request.method == 'GET':
        form = forms.AskForm(user=request.user)
        #session key used only to enable anonymous asking
        #as django will autodelete empty sessions
        request.session['askbot_write_intent'] = True

    draft_title = ''
    draft_text = ''
    draft_tagnames = ''
    if request.user.is_authenticated():
        drafts = models.DraftQuestion.objects.filter(author=request.user)
        if len(drafts) > 0:
            draft = drafts[0]
            draft_title = draft.title
            draft_text = draft.get_text()
            draft_tagnames = draft.tagnames

    form.initial = {
        'ask_anonymously': request.REQUEST.get('ask_anonymously', False),
        'tags': request.REQUEST.get('tags', draft_tagnames),
        'text': request.REQUEST.get('text', draft_text),
        'title': request.REQUEST.get('title', draft_title),
        'post_privately': request.REQUEST.get('post_privately', False),
        'language': get_language(),
        'wiki': request.REQUEST.get('wiki', False),
    }
    if 'group_id' in request.REQUEST:
        try:
            group_id = int(request.GET.get('group_id', None))
            form.initial['group_id'] = group_id
        except Exception:
            pass

    editor_is_folded = (askbot_settings.QUESTION_BODY_EDITOR_MODE=='folded' and \
                        askbot_settings.MIN_QUESTION_BODY_LENGTH==0 and \
                        form.initial['text'] == '')

    data = {
        'active_tab': 'ask',
        'page_class': 'ask-page',
        'form': form,
        'editor_is_folded': editor_is_folded,
        'mandatory_tags': models.tag.get_mandatory_tags(),
        'email_validation_faq_url': reverse('faq') + '#validate',
        'category_tree_data': askbot_settings.CATEGORY_TREE,
        'tag_names': forms.split_tags(form.initial['tags'])
    }
    data.update(context.get_for_tag_editor())
    return render(request, 'ask.html', data)
Пример #42
0
def ask(request):  #view used to ask a new question
    """a view to ask a new question
    gives space for q title, body, tags and checkbox for to post as wiki

    user can start posting a question anonymously but then
    must login/register in order for the question go be shown
    """
    if request.user.is_authenticated():
        if request.user.is_read_only():
            referer = request.META.get("HTTP_REFERER", reverse('questions'))
            request.user.message_set.create(
                message=_('Sorry, but you have only read access'))
            return HttpResponseRedirect(referer)

    form = forms.AskForm(request.REQUEST, user=request.user)
    if request.method == 'POST':
        if form.is_valid():
            timestamp = datetime.datetime.now()
            title = form.cleaned_data['title']
            wiki = form.cleaned_data['wiki']
            tagnames = form.cleaned_data['tags']
            text = form.cleaned_data['text']
            ask_anonymously = form.cleaned_data['ask_anonymously']
            post_privately = form.cleaned_data['post_privately']
            group_id = form.cleaned_data.get('group_id', None)
            language = form.cleaned_data.get('language', None)

            if request.user.is_authenticated():
                drafts = models.DraftQuestion.objects.filter(
                    author=request.user)
                drafts.delete()

                user = form.get_post_user(request.user)
                try:
                    question = user.post_question(title=title,
                                                  body_text=text,
                                                  tags=tagnames,
                                                  wiki=wiki,
                                                  is_anonymous=ask_anonymously,
                                                  is_private=post_privately,
                                                  timestamp=timestamp,
                                                  group_id=group_id,
                                                  language=language)
                    signals.new_question_posted.send(
                        None,
                        question=question,
                        user=user,
                        form_data=form.cleaned_data)
                    return HttpResponseRedirect(question.get_absolute_url())
                except exceptions.PermissionDenied, e:
                    request.user.message_set.create(message=unicode(e))
                    return HttpResponseRedirect(reverse('index'))

            else:
                request.session.flush()
                session_key = request.session.session_key
                models.AnonymousQuestion.objects.create(
                    session_key=session_key,
                    title=title,
                    tagnames=tagnames,
                    wiki=wiki,
                    is_anonymous=ask_anonymously,
                    text=text,
                    added_at=timestamp,
                    ip_addr=request.META['REMOTE_ADDR'],
                )
                return HttpResponseRedirect(url_utils.get_login_url())
Пример #43
0
def ask(request, offering_id):  #view used to ask a new question
    """a view to ask a new question
    gives space for q title, body, tags and checkbox for to post as wiki

    user can start posting a question anonymously but then
    must login/register in order for the question go be shown
    """
    offering = get_object_or_404(Offering, id=offering_id)
    if request.user.is_authenticated():
        if request.user.is_read_only():
            referer = request.META.get("HTTP_REFERER", reverse('questions'))
            request.user.message_set.create(
                message=_('Sorry, but you have only read access'))
            return HttpResponseRedirect(referer)

    if askbot_settings.READ_ONLY_MODE_ENABLED:
        return HttpResponseRedirect(reverse('index'))

    if request.method == 'POST':
        form = forms.AskForm(request.POST, user=request.user)
        if form.is_valid():
            timestamp = timezone.now()
            title = form.cleaned_data['title']
            wiki = form.cleaned_data['wiki']
            tagnames = form.cleaned_data['tags']
            text = form.cleaned_data['text']
            ask_anonymously = form.cleaned_data['ask_anonymously']
            post_privately = form.cleaned_data['post_privately']
            group_id = form.cleaned_data.get('group_id', None)
            language = form.cleaned_data.get('language', None)

            if request.user.is_authenticated():
                drafts = models.DraftQuestion.objects.filter(
                    author=request.user)
                drafts.delete()
                user = form.get_post_user(request.user)
            elif request.user.is_anonymous(
            ) and askbot_settings.ALLOW_ASK_UNREGISTERED:
                user = models.get_or_create_anonymous_user()
                ask_anonymously = True
            else:
                user = None

            if user:
                try:

                    question = user.post_question(
                        offering=offering,
                        title=title,
                        body_text=text,
                        tags=tagnames,
                        wiki=wiki,
                        is_anonymous=ask_anonymously,
                        is_private=post_privately,
                        timestamp=timestamp,
                        group_id=group_id,
                        language=language,
                        ip_addr=request.META.get('REMOTE_ADDR'),
                    )
                    signals.new_question_posted.send(
                        None,
                        question=question,
                        user=user,
                        form_data=form.cleaned_data)
                    return HttpResponseRedirect(question.get_absolute_url())
                except exceptions.PermissionDenied, e:
                    request.user.message_set.create(message=unicode(e))
                    return HttpResponseRedirect(reverse('index'))

            else:
                session_key = request.session.session_key
                if session_key is None:
                    return HttpResponseForbidden()

                models.AnonymousQuestion.objects.create(
                    session_key=session_key,
                    title=title,
                    tagnames=tagnames,
                    wiki=wiki,
                    is_anonymous=ask_anonymously,
                    text=text,
                    added_at=timestamp,
                    ip_addr=request.META.get('REMOTE_ADDR'),
                )
                return HttpResponseRedirect(url_utils.get_login_url())
Пример #44
0
def ask(request):  #view used to ask a new question
    """a view to ask a new question
    gives space for q title, body, tags and checkbox for to post as wiki

    user can start posting a question anonymously but then
    must login/register in order for the question go be shown
    """
    if request.method == "POST":
        form = forms.AskForm(request.POST)
        if form.is_valid():
            timestamp = datetime.datetime.now()
            #todo: move this to clean_title
            title = form.cleaned_data['title'].strip()
            wiki = form.cleaned_data['wiki']
            #todo: move this to clean_tagnames
            tagnames = form.cleaned_data['tags'].strip()
            text = form.cleaned_data['text']
            ask_anonymously = form.cleaned_data['ask_anonymously']

            if request.user.is_authenticated():
                try:
                    question = request.user.post_question(
                        title=title,
                        body_text=text,
                        tags=tagnames,
                        wiki=wiki,
                        is_anonymous=ask_anonymously,
                        timestamp=timestamp)
                    return HttpResponseRedirect(question.get_absolute_url())
                except exceptions.PermissionDenied, e:
                    request.user.message_set.create(message=unicode(e))
                    return HttpResponseRedirect(reverse('index'))

            else:
                request.session.flush()
                session_key = request.session.session_key
                summary = strip_tags(text)[:120]
                question = models.AnonymousQuestion(
                    session_key=session_key,
                    title=title,
                    tagnames=tagnames,
                    wiki=wiki,
                    is_anonymous=ask_anonymously,
                    text=text,
                    summary=summary,
                    added_at=timestamp,
                    ip_addr=request.META['REMOTE_ADDR'],
                )
                question.save()
                return HttpResponseRedirect(url_utils.get_login_url())
        else:
            form = forms.AskForm(request.POST)
            if 'title' in request.GET:
                #normally this title is inherited from search query
                #but it is possible to ask with a parameter title in the url query
                form.initial['title'] = request.GET['title']
            else:
                #attempt to extract title from previous search query
                search_state = request.session.get('search_state', None)
                if search_state:
                    query = search_state.query
                    form.initial['title'] = query
Пример #45
0
def answer(request, id, form_class=forms.AnswerForm):  #process a new answer
    """view that posts new answer

    anonymous users post into anonymous storage
    and redirected to login page

    authenticated users post directly
    """
    question = get_object_or_404(models.Post, post_type='question', id=id)

    if askbot_settings.READ_ONLY_MODE_ENABLED:
        return HttpResponseRedirect(question.get_absolute_url())

    if request.method == 'GET':
        #session key used only to enable anonymous asking
        #as django will autodelete empty sessions
        request.session['askbot_write_intent'] = True
    elif request.method == 'POST':

        #this check prevents backward compatilibility
        if form_class == forms.AnswerForm:
            custom_class_path = getattr(settings, 'ASKBOT_NEW_ANSWER_FORM',
                                        None)
            if custom_class_path:
                form_class = load_module(custom_class_path)
            else:
                form_class = forms.AnswerForm

        form = form_class(request.POST, user=request.user)

        if form.is_valid():
            if request.user.is_authenticated():
                drafts = models.DraftAnswer.objects.filter(
                    author=request.user, thread=question.thread)
                drafts.delete()
                user = form.get_post_user(request.user)
                try:
                    answer = form.save(question,
                                       user,
                                       ip_addr=request.META.get('REMOTE_ADDR'))

                    signals.new_answer_posted.send(None,
                                                   answer=answer,
                                                   user=user,
                                                   form_data=form.cleaned_data)

                    return HttpResponseRedirect(answer.get_absolute_url())
                except askbot_exceptions.AnswerAlreadyGiven, e:
                    request.user.message_set.create(message=unicode(e))
                    answer = question.thread.get_answers_by_user(user)[0]
                    return HttpResponseRedirect(answer.get_absolute_url())
                except exceptions.PermissionDenied, e:
                    request.user.message_set.create(message=unicode(e))
            else:
                if request.session.session_key is None:
                    return HttpResponseForbidden()

                models.AnonymousAnswer.objects.create(
                    question=question,
                    wiki=form.cleaned_data['wiki'],
                    text=form.cleaned_data['text'],
                    session_key=request.session.session_key,
                    ip_addr=request.META.get('REMOTE_ADDR'),
                )
                return HttpResponseRedirect(url_utils.get_login_url())
Пример #46
0
def application_settings(request):
    """The context processor function"""
    # if not request.path.startswith('/' + settings.ASKBOT_URL):
    #     #todo: this is a really ugly hack, will only work
    #     #when askbot is installed not at the home page.
    #     #this will not work for the
    #     #heavy modders of askbot, because their custom pages
    #     #will not receive the askbot settings in the context
    #     #to solve this properly we should probably explicitly
    #     #add settings to the context per page
    #     return {}
    my_settings = askbot_settings.as_dict()
    my_settings['LANGUAGE_CODE'] = getattr(request, 'LANGUAGE_CODE',
                                           settings.LANGUAGE_CODE)
    my_settings['LANGUAGE_MODE'] = askbot.get_lang_mode()
    my_settings['MULTILINGUAL'] = askbot.is_multilingual()
    my_settings['LANGUAGES_DICT'] = dict(getattr(settings, 'LANGUAGES', []))
    my_settings[
        'ALLOWED_UPLOAD_FILE_TYPES'] = settings.ASKBOT_ALLOWED_UPLOAD_FILE_TYPES
    my_settings['ASKBOT_URL'] = settings.ASKBOT_URL
    my_settings['STATIC_URL'] = settings.STATIC_URL
    my_settings['IP_MODERATION_ENABLED'] = getattr(
        settings, 'ASKBOT_IP_MODERATION_ENABLED', False)
    my_settings['USE_LOCAL_FONTS'] = getattr(settings,
                                             'ASKBOT_USE_LOCAL_FONTS', False)
    my_settings['CSRF_COOKIE_NAME'] = settings.CSRF_COOKIE_NAME
    my_settings['DEBUG'] = settings.DEBUG
    my_settings['USING_RUNSERVER'] = 'runserver' in sys.argv
    my_settings['ASKBOT_VERSION'] = askbot.get_version()
    my_settings['LOGIN_URL'] = url_utils.get_login_url()
    my_settings['LOGOUT_URL'] = url_utils.get_logout_url()

    if my_settings['EDITOR_TYPE'] == 'tinymce':
        tinymce_plugins = settings.TINYMCE_DEFAULT_CONFIG.get('plugins',
                                                              '').split(',')
        my_settings['TINYMCE_PLUGINS'] = [v.strip() for v in tinymce_plugins]
        my_settings[
            'TINYMCE_EDITOR_DESELECTOR'] = settings.TINYMCE_DEFAULT_CONFIG[
                'editor_deselector']
        my_settings['TINYMCE_CONFIG_JSON'] = json.dumps(
            settings.TINYMCE_DEFAULT_CONFIG)
    else:
        my_settings['TINYMCE_PLUGINS'] = []
        my_settings['TINYMCE_EDITOR_DESELECTOR'] = ''

    my_settings['LOGOUT_REDIRECT_URL'] = url_utils.get_logout_redirect_url()

    current_language = get_language()

    # for some languages we will start searching for shorter words
    if current_language == 'ja':
        # we need to open the search box and show info message about
        # the japanese lang search
        min_search_word_length = 1
    else:
        min_search_word_length = my_settings['MIN_SEARCH_WORD_LENGTH']

    need_scope_links = askbot_settings.ALL_SCOPE_ENABLED or \
        askbot_settings.UNANSWERED_SCOPE_ENABLED or \
        (request.user.is_authenticated and askbot_settings.FOLLOWED_SCOPE_ENABLED)

    context = {
        'base_url': site_url(''),
        'csrf_token': csrf.get_token(request),
        'empty_search_state': SearchState.get_empty(),
        'min_search_word_length': min_search_word_length,
        'current_language_code': current_language,
        'settings': my_settings,
        'moderation_items': api.get_info_on_moderation_items(request.user),
        'need_scope_links': need_scope_links,
        'noscript_url': const.DEPENDENCY_URLS['noscript'],
    }

    use_askbot_login = '******' in settings.INSTALLED_APPS
    my_settings['USE_ASKBOT_LOGIN_SYSTEM'] = use_askbot_login
    if use_askbot_login and request.user.is_anonymous:
        from askbot.deps.django_authopenid import context as login_context
        context.update(login_context.login_context(request))

    context['group_list'] = json.dumps(make_group_list())

    if askbot_settings.EDITOR_TYPE == 'tinymce':
        from tinymce.widgets import TinyMCE
        context['tinymce'] = TinyMCE()

    return context
Пример #47
0
def post_comments(
        request):  #generic ajax handler to load comments to an object
    """todo: fixme: post_comments is ambigous:
    means either get comments for post or
    add a new comment to post
    """
    # 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'):
        raise Http404  # TODO: Shouldn't be 404! More like 400, 403 or sth more specific

    if post_type == 'question' \
        and askbot_settings.QUESTION_COMMENTS_ENABLED == False:
        raise Http404
    elif post_type == 'answer' \
        and askbot_settings.ANSWER_COMMENTS_ENABLED == False:
        raise Http404

    user = request.user

    if request.method == 'POST':
        form = forms.NewCommentForm(request.POST)
    elif request.method == 'GET':
        form = forms.GetCommentDataForPostForm(request.GET)

    if form.is_valid() == False:
        return HttpResponseBadRequest(_('This content is forbidden'),
                                      content_type='application/json')

    post_id = form.cleaned_data['post_id']
    avatar_size = form.cleaned_data['avatar_size']
    try:
        post = models.Post.objects.get(id=post_id)
    except models.Post.DoesNotExist:
        return HttpResponseBadRequest(_('Post not found'),
                                      content_type='application/json')

    if request.method == "GET":
        response = __generate_comments_json(post, user, avatar_size)
    elif request.method == "POST":
        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)

            if askbot_settings.READ_ONLY_MODE_ENABLED:
                raise exceptions.PermissionDenied(
                    askbot_settings.READ_ONLY_MESSAGE)

            comment = user.post_comment(
                parent_post=post,
                body_text=form.cleaned_data['comment'],
                ip_addr=request.META.get('REMOTE_ADDR'))
            signals.new_comment_posted.send(None,
                                            comment=comment,
                                            user=user,
                                            form_data=form.cleaned_data)
            response = __generate_comments_json(post, user, avatar_size)
        except exceptions.PermissionDenied, e:
            response = HttpResponseForbidden(unicode(e),
                                             content_type="application/json")
Пример #48
0
def application_settings(request):
    """The context processor function"""
    if not request.path.startswith('/' + settings.ASKBOT_URL):
        #todo: this is a really ugly hack, will only work
        #when askbot is installed not at the home page.
        #this will not work for the
        #heavy modders of askbot, because their custom pages
        #will not receive the askbot settings in the context
        #to solve this properly we should probably explicitly
        #add settings to the context per page
        return {}
    my_settings = askbot_settings.as_dict()
    my_settings['LANGUAGE_CODE'] = getattr(request, 'LANGUAGE_CODE', settings.LANGUAGE_CODE)
    my_settings['MULTILINGUAL'] = getattr(settings, 'ASKBOT_MULTILINGUAL', False)
    my_settings['LANGUAGES_DICT'] = dict(getattr(settings, 'LANGUAGES', []))
    my_settings['ALLOWED_UPLOAD_FILE_TYPES'] = \
            settings.ASKBOT_ALLOWED_UPLOAD_FILE_TYPES
    my_settings['ASKBOT_URL'] = settings.ASKBOT_URL
    my_settings['STATIC_URL'] = settings.STATIC_URL
    my_settings['IP_MODERATION_ENABLED'] = getattr(settings, 'ASKBOT_IP_MODERATION_ENABLED', False)
    my_settings['ASKBOT_CSS_DEVEL'] = getattr(
                                        settings,
                                        'ASKBOT_CSS_DEVEL',
                                        False
                                    )
    my_settings['USE_LOCAL_FONTS'] = getattr(
                                        settings,
                                        'ASKBOT_USE_LOCAL_FONTS',
                                        False
                                    )
    my_settings['CSRF_COOKIE_NAME'] = settings.CSRF_COOKIE_NAME
    my_settings['DEBUG'] = settings.DEBUG
    my_settings['USING_RUNSERVER'] = 'runserver' in sys.argv
    my_settings['ASKBOT_VERSION'] = askbot.get_version()
    my_settings['LOGIN_URL'] = url_utils.get_login_url()
    my_settings['LOGOUT_URL'] = url_utils.get_logout_url()

    if my_settings['EDITOR_TYPE'] == 'tinymce':
        tinymce_plugins = settings.TINYMCE_DEFAULT_CONFIG.get('plugins', '').split(',')
        my_settings['TINYMCE_PLUGINS'] = map(lambda v: v.strip(), tinymce_plugins)
    else:
        my_settings['TINYMCE_PLUGINS'] = [];

    my_settings['LOGOUT_REDIRECT_URL'] = url_utils.get_logout_redirect_url()
    my_settings['USE_ASKBOT_LOGIN_SYSTEM'] = 'askbot.deps.django_authopenid' \
        in settings.INSTALLED_APPS
    
    current_language = get_language()

    #for some languages we will start searching for shorter words
    if current_language == 'ja':
        #we need to open the search box and show info message about
        #the japanese lang search
        min_search_word_length = 1
    else:   
        min_search_word_length = my_settings['MIN_SEARCH_WORD_LENGTH']

    need_scope_links = askbot_settings.ALL_SCOPE_ENABLED or \
                    askbot_settings.UNANSWERED_SCOPE_ENABLED or \
                    (request.user.is_authenticated() and askbot_settings.FOLLOWED_SCOPE_ENABLED)

    context = {
        'base_url': site_url(''),
        'empty_search_state': SearchState.get_empty(),
        'min_search_word_length': min_search_word_length,
        'current_language_code': current_language,
        'settings': my_settings,
        'skin': get_skin(),
        'moderation_items': api.get_info_on_moderation_items(request.user),
        'need_scope_links': need_scope_links,
        'noscript_url': const.DEPENDENCY_URLS['noscript'],
    }

    if askbot_settings.GROUPS_ENABLED:
        #calculate context needed to list all the groups
        def _get_group_url(group):
            """calculates url to the group based on its id and name"""
            group_slug = slugify(group['name'])
            return reverse(
                'users_by_group',
                kwargs={'group_id': group['id'], 'group_slug': group_slug}
            )

        #load id's and names of all groups
        global_group = models.Group.objects.get_global_group()
        groups = models.Group.objects.exclude_personal()
        groups = groups.exclude(id=global_group.id)
        groups_data = list(groups.values('id', 'name'))

        #sort groups_data alphanumerically, but case-insensitive
        groups_data = sorted(
                        groups_data,
                        lambda x, y: cmp(x['name'].lower(), y['name'].lower())
                    )

        #insert data for the global group at the first position
        groups_data.insert(0, {'id': global_group.id, 'name': global_group.name})

        #build group_list for the context
        group_list = list()
        for group in groups_data:
            link = _get_group_url(group)
            group_list.append({'name': group['name'], 'link': link})
        context['group_list'] = simplejson.dumps(group_list)

    return context
Пример #49
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': askbot_settings.APP_SHORT_NAME}

        if askbot_settings.TAGS_ARE_REQUIRED:
            error_message = string_concat(
                                    INSTRUCTIONS_PREAMBLE,
                                    '<ul>',
                                    QUESTION_TITLE_INSTRUCTION,
                                    REQUIRED_TAGS_INSTRUCTION,
                                    QUESTION_DETAILS_INSTRUCTION,
                                    '</ul>',
                                    TAGS_INSTRUCTION_FOOTNOTE
                                )
        else:
            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': askbot_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)


    #print 'sending email'
    #print email
    #print subject
    #print error_message
    headers = {}
    if reply_to:
        headers['Reply-To'] = reply_to

    send_mail(
        recipient_list = (email,),
        subject_line = 'Re: ' + subject,
        body_text = error_message,
        headers = headers
    )
Пример #50
0
def application_settings(request):
    """The context processor function"""
    if not request.path.startswith('/' + settings.ASKBOT_URL):
        #todo: this is a really ugly hack, will only work
        #when askbot is installed not at the home page.
        #this will not work for the
        #heavy modders of askbot, because their custom pages
        #will not receive the askbot settings in the context
        #to solve this properly we should probably explicitly
        #add settings to the context per page
        return {}
    my_settings = askbot_settings.as_dict()
    my_settings['LANGUAGE_CODE'] = getattr(request, 'LANGUAGE_CODE',
                                           settings.LANGUAGE_CODE)
    my_settings['ALLOWED_UPLOAD_FILE_TYPES'] = \
            settings.ASKBOT_ALLOWED_UPLOAD_FILE_TYPES
    my_settings['ASKBOT_URL'] = settings.ASKBOT_URL
    my_settings['STATIC_URL'] = settings.STATIC_URL
    my_settings['ASKBOT_CSS_DEVEL'] = getattr(settings, 'ASKBOT_CSS_DEVEL',
                                              False)
    my_settings['USE_LOCAL_FONTS'] = getattr(settings,
                                             'ASKBOT_USE_LOCAL_FONTS', False)
    my_settings['DEBUG'] = settings.DEBUG
    my_settings['USING_RUNSERVER'] = 'runserver' in sys.argv
    my_settings['ASKBOT_VERSION'] = askbot.get_version()
    my_settings['LOGIN_URL'] = url_utils.get_login_url()
    my_settings['LOGOUT_URL'] = url_utils.get_logout_url()
    my_settings['LOGOUT_REDIRECT_URL'] = url_utils.get_logout_redirect_url()
    my_settings['USE_ASKBOT_LOGIN_SYSTEM'] = 'askbot.deps.django_authopenid' \
        in settings.INSTALLED_APPS
    context = {
        'settings': my_settings,
        'skin': get_skin(request),
        'moderation_items': api.get_info_on_moderation_items(request.user),
        'noscript_url': const.DEPENDENCY_URLS['noscript'],
    }

    if askbot_settings.GROUPS_ENABLED:
        #calculate context needed to list all the groups
        def _get_group_url(group):
            """calculates url to the group based on its id and name"""
            group_slug = slugify(group['name'])
            return reverse('users_by_group',
                           kwargs={
                               'group_id': group['id'],
                               'group_slug': group_slug
                           })

        #load id's and names of all groups
        global_group = models.Group.objects.get_global_group()
        groups = models.Group.objects.exclude_personal()
        groups = groups.exclude(id=global_group.id)
        groups_data = list(groups.values('id', 'name'))

        #sort groups_data alphanumerically, but case-insensitive
        groups_data = sorted(
            groups_data,
            lambda x, y: cmp(x['name'].lower(), y['name'].lower()))

        #insert data for the global group at the first position
        groups_data.insert(0, {
            'id': global_group.id,
            'name': global_group.name
        })

        #build group_list for the context
        group_list = list()
        for group in groups_data:
            link = _get_group_url(group)
            group_list.append({'name': group['name'], 'link': link})
        context['group_list'] = simplejson.dumps(group_list)

    return context
Пример #51
0
def get_login_link(text=None):
    from askbot.utils.url_utils import get_login_url
    text = text or _('please login')
    return '<a href="%s">%s</a>' % (get_login_url(), text)
Пример #52
0
def repost_answer_as_comment(request, destination=None):
    assert (destination
            in ('comment_under_question', 'comment_under_previous_answer'))
    if request.user.is_anonymous():
        msg = _('Sorry, only logged in users can convert answers to comments. '
                'Please <a href="%(sign_in_url)s">sign in</a>.') % \
                {'sign_in_url': url_utils.get_login_url()}
        raise exceptions.PermissionDenied(msg)
    answer_id = request.POST.get('answer_id')
    if answer_id:
        try:
            answer_id = int(answer_id)
        except (ValueError, TypeError):
            raise Http404
        answer = get_object_or_404(models.Post,
                                   post_type='answer',
                                   id=answer_id)

        if askbot_settings.READ_ONLY_MODE_ENABLED:
            return HttpResponseRedirect(answer.get_absolute_url())
        request.user.assert_can_convert_post(post=answer)

        if destination == 'comment_under_question':
            destination_post = answer.thread._question_post()
        else:
            #comment_under_previous_answer
            destination_post = answer.get_previous_answer(user=request.user)
        #todo: implement for comment under other answer

        if destination_post is None:
            message = _('Error - could not find the destination post')
            request.user.message_set.create(message=message)
            return HttpResponseRedirect(answer.get_absolute_url())

        if len(answer.text) <= askbot_settings.MAX_COMMENT_LENGTH:
            answer.post_type = 'comment'
            answer.parent = destination_post

            new_comment_count = answer.comments.count() + 1
            answer.comment_count = 0

            answer_comments = models.Post.objects.get_comments().filter(
                parent=answer)
            answer_comments.update(parent=destination_post)

            #why this and not just "save"?
            answer.parse_and_save(author=answer.author)
            answer.thread.update_answer_count()

            answer.parent.comment_count += new_comment_count
            answer.parent.save()

            answer.thread.invalidate_cached_data()
        else:
            message = _(
                'Cannot convert, because text has more characters than '
                '%(max_chars)s - maximum allowed for comments') % {
                    'max_chars': askbot_settings.MAX_COMMENT_LENGTH
                }
            request.user.message_set.create(message=message)

        return HttpResponseRedirect(answer.get_absolute_url())
    else:
        raise Http404