Exemple #1
0
def send_email_reminder(request):
    """Send reminder email."""
    statsd_waffle_incr("users.send_email_reminder", "signin_metrics")
    if request.method == "POST":
        statsd_waffle_incr("users.send_email_reminder.POST", "signin_metrics")
        form = EmailReminderForm(request.POST)
        if form.is_valid():
            error = None
            username = form.cleaned_data["username"]
            try:
                user = User.objects.get(username=username, is_active=True)
                if user.email:
                    # TODO: should this be on a model or manager instead?
                    statsd_waffle_incr("users.send_email_reminder.SUCCESS", "signin_metrics")
                    send_reminder_email(user)
                else:
                    statsd_waffle_incr("users.send_email_reminder.NOEMAIL", "signin_metrics")
                    error = "no_email"
            except User.DoesNotExist:
                # Don't leak existence of email addresses.
                statsd_waffle_incr("users.send_email_reminder.NOUSER", "signin_metrics")
            return jingo.render(request, "users/send_email_reminder_done.html", {"username": username, "error": error})
    else:
        form = EmailConfirmationForm()
    return jingo.render(request, "users/resend_confirmation.html", {"form": form})
Exemple #2
0
def register(request):
    """Register a new user."""
    form = handle_register(request)
    if form.is_valid():
        return jingo.render(request, 'users/register_done.html')
    return jingo.render(request, 'users/register.html',
                        {'form': form})
Exemple #3
0
def activity_page(request, slug, page=1):
    """Fetch a page of project activity. Useful for xhr."""
    project = get_object_or_404(Project, slug=slug)
    start = int(page) * ACTIVITY_PAGE_SIZE
    end = start + ACTIVITY_PAGE_SIZE
    all_activities = Activity.objects.filter(
        entry__link__project=project).select_related(
        'entry', 'entry__link', 'entry__link__project').order_by(
        '-published_on')
    activities = all_activities[start:end]
    if not activities:
        raise Http404
    if request.is_ajax():
        return jingo.render(request, 'activity/ajax/activity.html', {
            'activities': activities,
            'show_meta': False,
         })
    else:
        has_more = len(all_activities) > end
        return jingo.render(request, 'projects/activity.html', {
            'project': project,
            'activities': activities,
            'has_more': has_more,
            'next_page': int(page) + 1
        })
Exemple #4
0
def edit(request):
    webapp = settings.APP_PREVIEW
    # Don't use request.amo_user since it has too much caching.
    amouser = UserProfile.objects.get(pk=request.user.id)
    if request.method == 'POST':
        # ModelForm alters the instance you pass in.  We need to keep a copy
        # around in case we need to use it below (to email the user)
        original_email = amouser.email
        form = forms.UserEditForm(request.POST, request.FILES, request=request,
                                  instance=amouser, webapp=webapp)
        if form.is_valid():
            messages.success(request, _('Profile Updated'))
            if amouser.email != original_email:
                # Temporarily block email changes.
                if settings.APP_PREVIEW:
                    messages.error(request, 'Error',
                                   'You cannot change your email on the '
                                   'developer preview site.')
                    return jingo.render(request, 'users/edit.html',
                                        {'form': form, 'amouser': amouser})

                l = {'user': amouser,
                     'mail1': original_email,
                     'mail2': amouser.email}
                log.info(u"User (%(user)s) has requested email change from"
                          "(%(mail1)s) to (%(mail2)s)" % l)
                messages.info(request, _('Email Confirmation Sent'),
                    _(u'An email has been sent to {0} to confirm your new '
                       'email address. For the change to take effect, you '
                       'need to click on the link provided in this email. '
                       'Until then, you can keep logging in with your '
                       'current email address.').format(amouser.email))

                domain = settings.DOMAIN
                token, hash = EmailResetCode.create(amouser.id, amouser.email)
                url = "%s%s" % (settings.SITE_URL,
                                reverse('users.emailchange', args=[amouser.id,
                                                                token, hash]))
                t = loader.get_template('users/email/emailchange.ltxt')
                c = {'domain': domain, 'url': url}
                send_mail(_('Please confirm your email address '
                            'change at %s' % domain),
                    t.render(Context(c)), None, [amouser.email],
                    use_blacklist=False, real_email=True)

                # Reset the original email back.  We aren't changing their
                # address until they confirm the new one
                amouser.email = original_email
            form.save()
            return redirect('users.edit')
        else:

            messages.error(request, _('Errors Found'),
                                    _('There were errors in the changes '
                                      'you made. Please correct them and '
                                      'resubmit.'))
    else:
        form = forms.UserEditForm(instance=amouser, webapp=webapp)
    return jingo.render(request, 'users/edit.html',
                        {'form': form, 'amouser': amouser, 'webapp': webapp})
Exemple #5
0
def edit_answer(request, question_id, answer_id):
    """Edit an answer."""
    answer = get_object_or_404(Answer, pk=answer_id, question=question_id)
    answer_preview = None
    if answer.question.is_locked:
        raise PermissionDenied

    # NOJS: upload images, if any
    upload_imageattachment(request, answer)

    if request.method == 'GET':
        form = AnswerForm({'content': answer.content})
        return jingo.render(request, 'questions/edit_answer.html',
                            {'form': form, 'answer': answer})

    form = AnswerForm(request.POST)

    if form.is_valid():
        answer.content = form.cleaned_data['content']
        answer.updated_by = request.user
        if 'preview' in request.POST:
            answer.updated = datetime.now()
            answer_preview = answer
        else:
            log.warning('User %s is editing answer with id=%s' %
                        (request.user, answer.id))
            answer.save()
            return HttpResponseRedirect(answer.get_absolute_url())

    return jingo.render(request, 'questions/edit_answer.html',
                        {'form': form, 'answer': answer,
                         'answer_preview': answer_preview})
Exemple #6
0
def add_tag(request, question_id):
    """Add a (case-insensitive) tag to question.

    If the question already has the tag, do nothing.

    """
    # If somebody hits Return in the address bar after provoking an error from
    # the add form, nicely send them back to the question:
    if request.method == 'GET':
        return HttpResponseRedirect(
            reverse('questions.answers', args=[question_id]))

    try:
        question, canonical_name = _add_tag(request, question_id)
    except Tag.DoesNotExist:
        template_data = _answers_data(request, question_id)
        template_data['tag_adding_error'] = UNAPPROVED_TAG
        template_data['tag_adding_value'] = request.POST.get('tag-name', '')
        return jingo.render(request, 'questions/answers.html', template_data)

    if canonical_name:  # success
        question.clear_cached_tags()
        return HttpResponseRedirect(
            reverse('questions.answers', args=[question_id]))

    # No tag provided
    template_data = _answers_data(request, question_id)
    template_data['tag_adding_error'] = NO_TAG
    return jingo.render(request, 'questions/answers.html', template_data)
Exemple #7
0
def edit_thread(request, forum_slug, thread_id):
    """Edit a thread."""
    forum = get_object_or_404(Forum, slug=forum_slug)
    thread = get_object_or_404(Thread, pk=thread_id, forum=forum)

    if thread.is_locked:
        raise PermissionDenied

    if request.method == 'GET':
        form = EditThreadForm(instance=thread)
        return jingo.render(request, 'forums/edit_thread.html',
                            {'form': form, 'forum': forum, 'thread': thread})

    form = EditThreadForm(request.POST)

    if form.is_valid():
        log.warning('User %s is editing thread with id=%s' %
                    (request.user, thread.id))
        thread.title = form.cleaned_data['title']
        thread.save()

        url = reverse('forums.posts', args=[forum_slug, thread_id])
        return HttpResponseRedirect(url)

    return jingo.render(request, 'forums/edit_thread.html',
                        {'form': form, 'forum': forum, 'thread': thread})
Exemple #8
0
def edit_post(request, forum_slug, thread_id, post_id):
    """Edit a post."""
    forum = get_object_or_404(Forum, slug=forum_slug)
    thread = get_object_or_404(Thread, pk=thread_id, forum=forum)
    post = get_object_or_404(Post, pk=post_id, thread=thread)

    if thread.is_locked:
        raise PermissionDenied

    if request.method == 'GET':
        form = EditPostForm({'content': post.content})
        return jingo.render(request, 'forums/edit_post.html',
                            {'form': form, 'forum': forum,
                             'thread': thread, 'post': post})

    form = EditPostForm(request.POST)
    post_preview = None
    if form.is_valid():
        post.content = form.cleaned_data['content']
        post.updated_by = request.user
        if 'preview' in request.POST:
            post.updated = datetime.now()
            post_preview = post
        else:
            log.warning('User %s is editing post with id=%s' %
                        (request.user, post.id))
            post.save()
            return HttpResponseRedirect(post.get_absolute_url())

    return jingo.render(request, 'forums/edit_post.html',
                        {'form': form, 'forum': forum,
                         'thread': thread, 'post': post,
                         'post_preview': post_preview})
Exemple #9
0
def edit_thread(request, document_slug, thread_id):
    """Edit a thread."""
    doc = get_document(document_slug, request)
    thread = get_object_or_404(Thread, pk=thread_id, document=doc)

    perm = request.user.has_perm('kbforums.change_thread')
    if not (perm or (thread.creator == request.user and
                     not thread.is_locked)):
        raise PermissionDenied

    if request.method == 'GET':
        form = EditThreadForm(instance=thread)
        return jingo.render(request, 'kbforums/edit_thread.html',
                            {'form': form, 'document': doc, 'thread': thread})

    form = EditThreadForm(request.POST)

    if form.is_valid():
        log.warning('User %s is editing KB thread with id=%s' %
                    (request.user, thread.id))
        thread.title = form.cleaned_data['title']
        thread.save()

        url = reverse('wiki.discuss.posts', args=[document_slug, thread_id])
        return HttpResponseRedirect(url)

    return jingo.render(request, 'kbforums/edit_thread.html',
                        {'form': form, 'document': doc, 'thread': thread})
Exemple #10
0
def edit_post(request, document_slug, thread_id, post_id):
    """Edit a post."""
    doc = get_document(document_slug, request)
    thread = get_object_or_404(Thread, pk=thread_id, document=doc)
    post = get_object_or_404(Post, pk=post_id, thread=thread)

    perm = request.user.has_perm('kbforums.change_post')
    if not (perm or (request.user == post.creator and not thread.is_locked)):
        raise PermissionDenied

    if request.method == 'GET':
        form = EditPostForm({'content': post.content})
        return jingo.render(request, 'kbforums/edit_post.html',
                            {'form': form, 'document': doc,
                             'thread': thread, 'post': post})

    form = EditPostForm(request.POST)
    post_preview = None
    if form.is_valid():
        post.content = form.cleaned_data['content']
        post.updated_by = request.user
        if 'preview' in request.POST:
            post.updated = datetime.now()
            post_preview = post
        else:
            log.warning('User %s is editing KB post with id=%s' %
                        (request.user, post.id))
            post.save()
            return HttpResponseRedirect(post.get_absolute_url())

    return jingo.render(request, 'kbforums/edit_post.html',
                        {'form': form, 'document': doc,
                         'thread': thread, 'post': post,
                         'post_preview': post_preview})
Exemple #11
0
def dashboard(request, page=0):
    """Display first page of activities for a users dashboard."""
    start = int(page) * ACTIVITY_PAGE_SIZE
    end = start + ACTIVITY_PAGE_SIZE
    profile = request.user.get_profile()
    all_activities = Activity.objects.filter(
        entry__link__project__in=profile.projects_following.all()
    ).select_related('entry', 'entry__link', 'entry__link__project').order_by(
        '-published_on'
    )
    activities = all_activities[start:end]
    if request.is_ajax():
        if not all_activities:
            raise Http404
        return jingo.render(request, 'activity/ajax/activity.html', {
            'activities': activities,
            'show_meta': True
        })
    return jingo.render(request, 'users/dashboard.html', {
        'profile': profile,
        'activities': activities,
        'has_more': len(all_activities) > end,
        'next_page': int(page) + 1,
        'total': len(all_activities)
    })
Exemple #12
0
def new_thread(request, document_slug):
    """Start a new thread."""
    doc = get_document(document_slug, request)

    if request.method == 'GET':
        form = NewThreadForm()
        return jingo.render(request, 'kbforums/new_thread.html',
                            {'form': form, 'document': doc})

    form = NewThreadForm(request.POST)
    post_preview = None
    if form.is_valid():
        if 'preview' in request.POST:
            thread = Thread(creator=request.user,
                            title=form.cleaned_data['title'])
            post_preview = Post(thread=thread, creator=request.user,
                                content=form.cleaned_data['content'])
        else:
            thread = doc.thread_set.create(creator=request.user,
                                             title=form.cleaned_data['title'])
            thread.save()
            post = thread.new_post(creator=request.user,
                                   content=form.cleaned_data['content'])
            post.save()

            # Send notifications to forum watchers.
            NewThreadEvent(post).fire(exclude=post.creator)

            return HttpResponseRedirect(
                reverse('wiki.discuss.posts', args=[document_slug, thread.id]))

    return jingo.render(request, 'kbforums/new_thread.html',
                        {'form': form, 'document': doc,
                         'post_preview': post_preview})
Exemple #13
0
def new_document(request):
    """Create a new wiki document."""
    if request.method == 'GET':
        doc_form = DocumentForm(
            can_create_tags=request.user.has_perm('taggit.add_tag'))
        rev_form = RevisionForm()
        return jingo.render(request, 'wiki/new_document.html',
                            {'document_form': doc_form,
                             'revision_form': rev_form})

    post_data = request.POST.copy()
    post_data.update({'locale': request.locale})
    doc_form = DocumentForm(post_data,
        can_create_tags=request.user.has_perm('taggit.add_tag'))
    rev_form = RevisionForm(post_data)

    if doc_form.is_valid() and rev_form.is_valid():
        doc = doc_form.save(None)
        _save_rev_and_notify(rev_form, request.user, doc)
        return HttpResponseRedirect(reverse('wiki.document_revisions',
                                    args=[doc.slug]))

    return jingo.render(request, 'wiki/new_document.html',
                        {'document_form': doc_form,
                         'revision_form': rev_form})
Exemple #14
0
def edit_image(request, image_id):
    g = get_object_or_404(Image, pk=image_id)

    if request.user != g.creator:
        return http.HttpResponseForbidden()

    if request.method == 'GET':
        gal_form = ImageForm(instance=g)
        gal_form.fields['gallery'].queryset = Gallery.objects.filter(creator=request.user)
        return jingo.render(request, 'portfolio/edit_image.html',
                            {'gallery_form': gal_form,
                             'id': g.id,
                             'imgpath': g.file.file})

    gal_form = ImageForm(request.POST, instance=g)
    gal_form.fields['gallery'].queryset = Gallery.objects.filter(creator=request.user)

    if gal_form.is_valid():
        gal = gal_form.save()
        return http.HttpResponseRedirect(reverse('portfolio.viewentry',
                                    args=[gal.id]))

    return jingo.render(request, 'portfolio/edit_image.html',
                        {'gallery_form': gal_form,
                         'id': g.id,
                         'imgpath': g.file.file})
Exemple #15
0
def render(request, template, context={}, **kwargs):
    """
    Same as jingo's render() shortcut, but with l10n template support.
    If used like this::

        return l10n_utils.render(request, 'myapp/mytemplate.html')

    ... this helper will render the following template::

        l10n/LANG/myapp/mytemplate.html

    if present, otherwise, it'll render the specified (en-US) template.
    """
    # Look for localized template if not default lang.
    if request.locale != settings.LANGUAGE_CODE:
        localized_tmpl = '%s/templates/%s' % (request.locale, template)
        try:
            return jingo.render(request, localized_tmpl, context, **kwargs)
        except TemplateNotFound:
            # If not found, just go on and try rendering the parent template.
            pass

    # Every template gets its own .lang file, so figure out what it is
    # and pass it in the context
    path = get_lang_path(template)
    (base, ext) = os.path.splitext(path)
    context['langfile'] = base

    return jingo.render(request, template, context, **kwargs)
Exemple #16
0
def pay_start(request, signed_req, pay_req):
    cfg = pay_req['_config']
    pr = None
    has_preapproval = False
    if request.amo_user:
        pr = request.amo_user.get_preapproval()
        has_preapproval = request.amo_user.has_preapproval_key()
    tier, price, currency = _get_price(pay_req, preapproval=pr)
    webapp = cfg.addon
    InappPayLog.log(request, 'PAY_START', config=cfg)
    tasks.fetch_product_image.delay(cfg.pk,
                                    _serializable_req(pay_req))
    data = dict(price=price,
                product=webapp,
                currency=currency,
                item=pay_req['request']['name'],
                img=cfg.image_url(pay_req['request'].get('imageURL')),
                description=pay_req['request']['description'],
                signed_request=signed_req)

    if not request.user.is_authenticated():
        return jingo.render(request, 'inapp_pay/login.html', data)
    if not has_preapproval:
        return jingo.render(request, 'inapp_pay/nowallet.html', data)
    return jingo.render(request, 'inapp_pay/pay_start.html', data)
Exemple #17
0
def edit(request):
    webapp = settings.APP_PREVIEW
    # Don't use request.amo_user since it has too much caching.
    amouser = UserProfile.objects.get(pk=request.user.id)
    if request.method == "POST":
        # ModelForm alters the instance you pass in.  We need to keep a copy
        # around in case we need to use it below (to email the user)
        original_email = amouser.email
        form = forms.UserEditForm(request.POST, request.FILES, request=request, instance=amouser, webapp=webapp)
        if form.is_valid():
            messages.success(request, _("Profile Updated"))
            if amouser.email != original_email:
                # Temporarily block email changes.
                if settings.APP_PREVIEW:
                    messages.error(request, "Error", "You cannot change your email on the " "developer preview site.")
                    return jingo.render(request, "users/edit.html", {"form": form, "amouser": amouser})

                l = {"user": amouser, "mail1": original_email, "mail2": amouser.email}
                log.info(u"User (%(user)s) has requested email change from" "(%(mail1)s) to (%(mail2)s)" % l)
                messages.info(
                    request,
                    _("Email Confirmation Sent"),
                    _(
                        u"An email has been sent to {0} to confirm your new "
                        "email address. For the change to take effect, you "
                        "need to click on the link provided in this email. "
                        "Until then, you can keep logging in with your "
                        "current email address."
                    ).format(amouser.email),
                )

                domain = settings.DOMAIN
                token, hash = EmailResetCode.create(amouser.id, amouser.email)
                url = "%s%s" % (settings.SITE_URL, reverse("users.emailchange", args=[amouser.id, token, hash]))
                t = loader.get_template("users/email/emailchange.ltxt")
                c = {"domain": domain, "url": url}
                send_mail(
                    _("Please confirm your email address " "change at %s" % domain),
                    t.render(Context(c)),
                    None,
                    [amouser.email],
                    use_blacklist=False,
                    real_email=True,
                )

                # Reset the original email back.  We aren't changing their
                # address until they confirm the new one
                amouser.email = original_email
            form.save()
            return redirect("users.edit")
        else:

            messages.error(
                request,
                _("Errors Found"),
                _("There were errors in the changes " "you made. Please correct them and " "resubmit."),
            )
    else:
        form = forms.UserEditForm(instance=amouser, webapp=webapp)
    return jingo.render(request, "users/edit.html", {"form": form, "amouser": amouser, "webapp": webapp})
Exemple #18
0
def send_email_reminder(request):
    """Send reminder email."""
    statsd_waffle_incr('users.send_email_reminder', 'signin_metrics')
    if request.method == 'POST':
        statsd_waffle_incr('users.send_email_reminder.POST', 'signin_metrics')
        form = EmailReminderForm(request.POST)
        if form.is_valid():
            error = None
            username = form.cleaned_data['username']
            try:
                user = User.objects.get(username=username, is_active=True)
                if user.email:
                    # TODO: should this be on a model or manager instead?
                    statsd_waffle_incr('users.send_email_reminder.SUCCESS',
                                      'signin_metrics')
                    send_reminder_email(user)
                else:
                    statsd_waffle_incr('users.send_email_reminder.NOEMAIL',
                                      'signin_metrics')
                    error = 'no_email'
            except User.DoesNotExist:
                # Don't leak existence of email addresses.
                statsd_waffle_incr('users.send_email_reminder.NOUSER',
                                  'signin_metrics')
            return jingo.render(request,
                                'users/send_email_reminder_done.html',
                                {'username': username, 'error': error})
    else:
        form = EmailConfirmationForm()
    return jingo.render(request, 'users/resend_confirmation.html',
                        {'form': form})
Exemple #19
0
def update(request):
    form = UpdateForm(request.GET)

    if form.is_valid():
        data = form.cleaned_data
        version, file = data['id'].get_current_version_for_client(
                            data['version'], form.version_int,
                            data['appID'], data['appOS'])
        if version and file:
            app = amo.APP_IDS[data['appID'].id]
            application_version = version.compatible_apps[app]
            addon_type = amo.ADDON_SLUGS_UPDATE[data['id'].type]
            url = file.get_mirror(data['id'])
            return jingo.render(request, 'addons/update.rdf', {
                                    'addon': data['id'],
                                    'application': data['appID'],
                                    'application_version': application_version,
                                    'appversion': data['appVersion'],
                                    'file': file,
                                    'type': addon_type,
                                    'url': url,
                                    'version': version,
                                }, content_type="text/xml")

    return jingo.render(request, 'addons/update.rdf',
                        {}, content_type="text/xml")
Exemple #20
0
def edit_post(request, document_slug, thread_id, post_id):
    """Edit a post."""
    doc = get_document(document_slug, request)
    thread = get_object_or_404(Thread, pk=thread_id, document=doc)
    post = get_object_or_404(Post, pk=post_id, thread=thread)

    perm = request.user.has_perm("kbforums.change_post")
    if not (perm or (request.user == post.creator and not thread.is_locked)):
        raise PermissionDenied

    if request.method == "GET":
        form = EditPostForm({"content": post.content})
        return jingo.render(
            request, "kbforums/edit_post.html", {"form": form, "document": doc, "thread": thread, "post": post}
        )

    form = EditPostForm(request.POST)
    post_preview = None
    if form.is_valid():
        post.content = form.cleaned_data["content"]
        post.updated_by = request.user
        if "preview" in request.POST:
            post.updated = datetime.now()
            post_preview = post
        else:
            log.warning("User %s is editing KB post with id=%s" % (request.user, post.id))
            post.save()
            return HttpResponseRedirect(post.get_absolute_url())

    return jingo.render(
        request,
        "kbforums/edit_post.html",
        {"form": form, "document": doc, "thread": thread, "post": post, "post_preview": post_preview},
    )
Exemple #21
0
def new_document(request):
    """Create a new wiki document."""
    if request.method == 'GET':
        doc_form = DocumentForm(
            can_create_tags=request.user.has_perm('taggit.add_tag'))
        rev_form = RevisionForm(initial={'review_tags': [t[0] for t in REVIEW_FLAG_TAGS]})
        return jingo.render(request, 'wiki/new_document.html',
                            {'document_form': doc_form,
                             'revision_form': rev_form})

    post_data = request.POST.copy()
    post_data.update({'locale': request.locale})
    doc_form = DocumentForm(post_data,
        can_create_tags=request.user.has_perm('taggit.add_tag'))
    rev_form = RevisionForm(post_data)

    if doc_form.is_valid() and rev_form.is_valid():
        doc = doc_form.save(None)
        _save_rev_and_notify(rev_form, request.user, doc)
        if doc.current_revision.is_approved:
            view = 'wiki.document'
        else:
            view = 'wiki.document_revisions'
        return HttpResponseRedirect(reverse(view,
                                    args=[doc.slug]))

    return jingo.render(request, 'wiki/new_document.html',
                        {'document_form': doc_form,
                         'revision_form': rev_form})
Exemple #22
0
def new_thread(request, forum_slug):
    """Start a new thread."""
    forum = get_object_or_404(Forum, slug=forum_slug)
    user = request.user
    if not forum.allows_posting_by(user):
        if forum.allows_viewing_by(user):
            raise PermissionDenied
        else:
            raise Http404

    if request.method == "GET":
        form = NewThreadForm()
        return jingo.render(request, "forums/new_thread.html", {"form": form, "forum": forum})

    form = NewThreadForm(request.POST)
    post_preview = None
    if form.is_valid():
        if "preview" in request.POST:
            thread = Thread(creator=request.user, title=form.cleaned_data["title"])
            post_preview = Post(thread=thread, author=request.user, content=form.cleaned_data["content"])
        else:
            thread = forum.thread_set.create(creator=request.user, title=form.cleaned_data["title"])
            thread.save()
            post = thread.new_post(author=request.user, content=form.cleaned_data["content"])
            post.save()

            # Send notifications to forum watchers.
            build_thread_notification.delay(post)

            return HttpResponseRedirect(reverse("forums.posts", args=[forum_slug, thread.id]))

    return jingo.render(request, "forums/new_thread.html", {"form": form, "forum": forum, "post_preview": post_preview})
Exemple #23
0
def _collections(request):
    """Handle the request for collections."""
    form = SecondarySearchForm(request.GET)
    form.is_valid()

    query = form.cleaned_data.get("q", "")

    search_opts = {}
    search_opts["limit"] = form.cleaned_data.get("pp", DEFAULT_NUM_RESULTS)
    page = form.cleaned_data.get("page") or 1
    search_opts["offset"] = (page - 1) * search_opts["limit"]
    search_opts["sort"] = form.cleaned_data.get("sortby")

    try:
        results = CollectionsClient().query(query, **search_opts)
    except SearchError:
        return jingo.render(request, "search/down.html", {}, status=503)

    pager = amo.utils.paginate(request, results, search_opts["limit"])
    c = dict(
        pager=pager,
        form=form,
        query=query,
        opts=search_opts,
        filter=bandwagon.views.get_filter(request),
        search_placeholder="collections",
    )
    return jingo.render(request, "search/collections.html", c)
Exemple #24
0
def pay_status(request, config_pk, status):
    tpl_path = 'inapp_pay/'
    with transaction.commit_on_success():
        cfg = get_object_or_404(InappConfig, pk=config_pk)
        uuid_ = None
        try:
            uuid_ = str(request.GET['uuid'])
            cnt = Contribution.objects.get(uuid=uuid_)
        except (KeyError, UnicodeEncodeError, ValueError,
                Contribution.DoesNotExist):
            log.error('PayPal returned invalid uuid %r from in-app payment'
                      % uuid_, exc_info=True)
            return jingo.render(request, 'inapp_pay/error.html')
        payment = InappPayment.objects.get(config=cfg, contribution=cnt)
        if status == 'complete':
            cnt.update(type=amo.CONTRIB_INAPP)
            tpl = tpl_path + 'complete.html'
            action = 'PAY_COMPLETE'
        elif status == 'cancel':
            tpl = tpl_path + 'payment_cancel.html'
            action = 'PAY_CANCEL'
        else:
            raise ValueError('Unexpected status: %r' % status)

    _payment_done(request, payment, action=action)

    return jingo.render(request, tpl, {'product': cnt.addon})
Exemple #25
0
def new_document(request):
    """Create a new wiki document."""
    if request.method == 'GET':
        doc_form = DocumentForm()
        rev_form = RevisionForm()
        return jingo.render(request, 'wiki/new_document.html',
                            {'document_form': doc_form,
                             'revision_form': rev_form})

    doc_form = DocumentForm(request.POST)
    rev_form = RevisionForm(request.POST)

    if doc_form.is_valid() and rev_form.is_valid():
        doc = doc_form.save()

        doc.firefox_versions = doc_form.cleaned_data['firefox_versions']
        doc.operating_systems = doc_form.cleaned_data['operating_systems']

        rev = rev_form.save(commit=False)
        rev.document = doc
        rev.creator = request.user
        rev.save()

        return HttpResponseRedirect(reverse('wiki.document_revisions',
                                    args=[doc.id]))

    return jingo.render(request, 'wiki/new_document.html',
                        {'document_form': doc_form,
                         'revision_form': rev_form})
Exemple #26
0
def edit_post(request, forum_slug, thread_id, post_id):
    """Edit a post."""
    forum = get_object_or_404(Forum, slug=forum_slug)
    thread = get_object_or_404(Thread, pk=thread_id, forum=forum)
    post = get_object_or_404(Post, pk=post_id, thread=thread)

    if thread.is_locked:
        raise PermissionDenied

    if request.method == "GET":
        form = EditPostForm({"content": post.content})
        return jingo.render(
            request, "forums/edit_post.html", {"form": form, "forum": forum, "thread": thread, "post": post}
        )

    form = EditPostForm(request.POST)
    post_preview = None
    if form.is_valid():
        post.content = form.cleaned_data["content"]
        post.updated_by = request.user
        if "preview" in request.POST:
            post.updated = datetime.now()
            post_preview = post
        else:
            log.warning("User %s is editing post with id=%s" % (request.user, post.id))
            post.save()
            return HttpResponseRedirect(post.get_absolute_url())

    return jingo.render(
        request,
        "forums/edit_post.html",
        {"form": form, "forum": forum, "thread": thread, "post": post, "post_preview": post_preview},
    )
Exemple #27
0
def login_user(request):
    """Verify user login and password work."""
    msg = []
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            username = request.POST['username']
            password = request.POST['password']
            user = authenticate(username=username, password=password)
            if user is not None:
                if user.is_active:
                    login(request, user)
                    return HttpResponseRedirect(reverse('users.user_page',
                                                args=[request.user.username]))
                else:
                    msg.append("You have entered a disabled account")
                    return jingo.render(request, 'users/login.html',
                                       {'errors': msg, 'form': form})
        else:
            msg.append("Invalid form")
            return jingo.render(request, 'users/login.html',
                               {'errors': msg, 'form': form})
    else:
        form = LoginForm()
    return jingo.render(request, 'users/login.html',
                       {'errors': msg, 'form': form})
Exemple #28
0
def new_thread(request, document_slug):
    """Start a new thread."""
    doc = get_document(document_slug, request)

    if request.method == "GET":
        form = NewThreadForm()
        return jingo.render(request, "kbforums/new_thread.html", {"form": form, "document": doc})

    form = NewThreadForm(request.POST)
    post_preview = None
    if form.is_valid():
        if "preview" in request.POST:
            thread = Thread(creator=request.user, title=form.cleaned_data["title"])
            post_preview = Post(thread=thread, creator=request.user, content=form.cleaned_data["content"])
        else:
            thread = doc.thread_set.create(creator=request.user, title=form.cleaned_data["title"])
            thread.save()
            statsd.incr("kbforums.thread")
            post = thread.new_post(creator=request.user, content=form.cleaned_data["content"])
            post.save()

            # Send notifications to forum watchers.
            NewThreadEvent(post).fire(exclude=post.creator)

            # Add notification automatically if needed.
            if Setting.get_for_user(request.user, "kbforums_watch_new_thread"):
                NewPostEvent.notify(request.user, thread)

            return HttpResponseRedirect(reverse("wiki.discuss.posts", args=[document_slug, thread.id]))

    return jingo.render(
        request, "kbforums/new_thread.html", {"form": form, "document": doc, "post_preview": post_preview}
    )
Exemple #29
0
def resend_confirmation(request):
    """Resend confirmation email."""
    if request.method == 'POST':
        form = EmailConfirmationForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data['email']
            try:
                reg_prof = RegistrationProfile.objects.get(
                    user__email=email, user__is_active=False)
                form = try_send_email_with_form(
                    RegistrationProfile.objects.send_confirmation_email,
                    form, 'email',
                    reg_prof)
            except RegistrationProfile.DoesNotExist:
                # Don't leak existence of email addresses.
                pass
            # Form may now be invalid if email failed to send.
            if form.is_valid():
                return jingo.render(request,
                                    'users/resend_confirmation_done.html',
                                    {'email': email})
    else:
        form = EmailConfirmationForm()
    return jingo.render(request, 'users/resend_confirmation.html',
                        {'form': form})
Exemple #30
0
def edit_settings(request):
    """Edit user settings"""
    if request.method == 'POST':
        form = SettingsForm(request.POST)
        if form.is_valid():
            form.save_for_user(request.user)
            messages.add_message(request, messages.INFO,
                                 _(u'Your settings have been saved.'))
            return HttpResponseRedirect(reverse('users.edit_settings'))
        # Invalid form
        return jingo.render(request, 'users/edit_settings.html',
                        {'form': form})

    # Pass the current user's settings as the initial values.
    values = request.user.settings.values()
    initial = dict()
    for v in values:
        try:
            # Uses ast.literal_eval to convert 'False' => False etc.
            # TODO: Make more resilient.
            initial[v['name']] = literal_eval(v['value'])
        except (SyntaxError, ValueError):
            # Attempted to convert the string value to a Python value
            # but failed so leave it a string.
            initial[v['name']] = v['value']
    form = SettingsForm(initial=initial)
    return jingo.render(request, 'users/edit_settings.html',
                        {'form': form})
Exemple #31
0
def action_unavailable_response(request, message=None,
                                template_name="action_unavailable.html"):
    """Generic page for unavailable actions"""
    context = {'message': message}
    return jingo.render(request, template_name, context, status=403)
Exemple #32
0
def app_fail(request, template_name='500.html'):
    return jingo.render(request, template_name, {}, status=500)
Exemple #33
0
def home(request):
    tx_form = TransactionSearchForm()

    return jingo.render(request, 'lookup/home.html', {'tx_form': tx_form})
Exemple #34
0
def payments(request, addon_id, addon, webapp=False):
    premium_form = forms_payments.PremiumForm(
        request.POST or None, request=request, addon=addon,
        user=request.amo_user)

    region_form = forms.RegionForm(
        request.POST or None, product=addon)

    upsell_form = forms_payments.UpsellForm(
        request.POST or None, addon=addon, user=request.amo_user)

    bango_account_list_form = forms_payments.BangoAccountListForm(
        request.POST or None, addon=addon, user=request.amo_user)

    if request.method == 'POST':

        success = all(form.is_valid() for form in
                      [premium_form, region_form, upsell_form,
                       bango_account_list_form])

        if success:
            region_form.save()

            try:
                premium_form.save()
            except client.Error as err:
                success = False
                log.error('Error setting payment information (%s)' % err)
                messages.error(
                    request, _(u'We encountered a problem connecting to the '
                               u'payment server.'))
                raise  # We want to see these exceptions!

            is_now_paid = addon.premium_type in amo.ADDON_PREMIUMS

            # If we haven't changed to a free app, check the upsell.
            if is_now_paid and success:
                try:
                    upsell_form.save()
                    bango_account_list_form.save()
                except client.Error as err:
                    log.error('Error saving payment information (%s)' % err)
                    messages.error(
                        request, _(u'We encountered a problem connecting to '
                                   u'the payment server.'))
                    success = False
                    raise  # We want to see all the solitude errors now.

            # Test again in case a call to Solitude failed.
            if is_now_paid and success:
                # Update the product's price if we need to.
                try:
                    apa = AddonPaymentAccount.objects.get(addon=addon)
                    apa.update_price(addon.addonpremium.price.price)
                except AddonPaymentAccount.DoesNotExist:
                    pass
                except client.Error:
                    log.error('Error updating AddonPaymentAccount (%s) price' %
                                  apa.pk)
                    messages.error(
                        request, _(u'We encountered a problem while updating '
                                   u'the payment server.'))
                    success = False
                    raise  # We want to see all the solitude errors now.

        # If everything happened successfully, give the user a pat on the back.
        if success:
            messages.success(request, _('Changes successfully saved.'))
            return redirect(addon.get_dev_url('payments'))

    # TODO: This needs to be updated as more platforms support payments.
    cannot_be_paid = (
        addon.premium_type == amo.ADDON_FREE and
        any(premium_form.device_data['free-%s' % x] == y for x, y in
            [('android-mobile', True), ('android-tablet', True),
             ('desktop', True), ('firefoxos', False)]))

    return jingo.render(
        request, 'developers/payments/premium.html',
        {'addon': addon, 'webapp': webapp, 'premium': addon.premium,
         'form': premium_form, 'upsell_form': upsell_form,
         'region_form': region_form,
         'DEVICE_LOOKUP': DEVICE_LOOKUP,
         'is_paid': addon.premium_type in amo.ADDON_PREMIUMS,
         'no_paid': cannot_be_paid,
         'is_incomplete': addon.status == amo.STATUS_NULL,
         'is_packaged': addon.is_packaged,
         # Bango values
         'bango_account_form': forms_payments.BangoPaymentAccountForm(),
         'bango_account_list_form': bango_account_list_form,
         # Waffles
         'payments_enabled':
             waffle.flag_is_active(request, 'allow-b2g-paid-submission') and
             not waffle.switch_is_active('disabled-payments')})
Exemple #35
0
def payment_accounts_form(request):
    bango_account_form = forms_payments.BangoAccountListForm(
        user=request.amo_user, addon=None)
    return jingo.render(
        request, 'developers/payments/includes/bango_accounts_form.html',
        {'bango_account_list_form': bango_account_form})
Exemple #36
0
def post_preview_async(request, document_slug):
    """Ajax preview of posts."""
    statsd.incr('forums.preview')
    post = Post(creator=request.user, content=request.POST.get('content', ''))
    return jingo.render(request, 'kbforums/includes/post_preview.html',
                        {'post_preview': post})
Exemple #37
0
def _error_page(request, status):
    """Render error pages with jinja2."""
    return jingo.render(request, '%d.html' % status, status=status)
Exemple #38
0
from django.conf.urls.defaults import url, patterns, include
from django.conf import settings
from django.contrib import admin
from django.shortcuts import redirect

import jingo
from django_arecibo.tasks import post as arecibo_post


def _error_page(request, status):
    """Render error pages with jinja2."""
    return jingo.render(request, '%d.html' % status, status=status)


handler404 = lambda r: _error_page(r, 404)
handler_csrf = lambda r, reason: jingo.render(r, 'csrf_error.html')


def handler500(request):
    arecibo = getattr(settings, 'ARECIBO_SERVER_URL', '')

    if arecibo:
        arecibo_post(request, 500)

    return _error_page(request, 500)


admin.autodiscover()


def unchannel(request):
Exemple #39
0
def select_locale(request, document_slug):
    """Select a locale to translate the document to."""
    doc = get_object_or_404(Document,
                            locale=settings.WIKI_DEFAULT_LANGUAGE,
                            slug=document_slug)
    return jingo.render(request, 'wiki/select_locale.html', {'document': doc})
Exemple #40
0
def transaction_refund(request, tx_uuid):
    contrib = get_object_or_404(Contribution,
                                uuid=tx_uuid,
                                type=amo.CONTRIB_PURCHASE)
    refund_contribs = contrib.get_refund_contribs()
    refund_contrib = refund_contribs[0] if refund_contribs.exists() else None

    if refund_contrib:
        messages.error(request, _('A refund has already been processed.'))
        return redirect(reverse('lookup.transaction_summary', args=[tx_uuid]))

    form = TransactionRefundForm(request.POST)
    if not form.is_valid():
        return jingo.render(
            request, 'lookup/transaction_summary.html',
            dict({
                'uuid': tx_uuid,
                'tx_refund_form': form,
                'tx_form': TransactionSearchForm()
            }.items() + _transaction_summary(tx_uuid).items()))

    data = {'uuid': contrib.transaction_id}
    if settings.BANGO_FAKE_REFUNDS:
        data['fake_response_status'] = {
            'responseCode': form.cleaned_data['fake']
        }

    try:
        res = client.api.bango.refund.post(data)
    except (HttpClientError, HttpServerError):
        # Either doing something not supposed to or Solitude had an issue.
        log.exception('Refund error: %s' % tx_uuid)
        messages.error(
            request,
            _('You cannot make a refund request for this transaction.'))
        return redirect(reverse('lookup.transaction_summary', args=[tx_uuid]))

    if res['status'] in [PENDING, COMPLETED]:
        # Create refund Contribution by cloning the payment Contribution.
        refund_contrib = Contribution.objects.get(id=contrib.id)
        refund_contrib.id = None
        refund_contrib.save()
        refund_contrib.update(
            type=amo.CONTRIB_REFUND,
            related=contrib,
            uuid=hashlib.md5(str(uuid.uuid4())).hexdigest(),
            amount=-refund_contrib.amount if refund_contrib.amount else None,
            transaction_id=client.get(res['transaction'])['uuid'])

    if res['status'] == PENDING:
        # Create pending Refund.
        refund_contrib.enqueue_refund(
            amo.REFUND_PENDING,
            request.amo_user,
            refund_reason=form.cleaned_data['refund_reason'])
        log.info('Refund pending: %s' % tx_uuid)
        email_buyer_refund_pending(contrib)
        messages.success(request,
                         _('Refund for this transaction now pending.'))
    elif res['status'] == COMPLETED:
        # Create approved Refund.
        refund_contrib.enqueue_refund(
            amo.REFUND_APPROVED,
            request.amo_user,
            refund_reason=form.cleaned_data['refund_reason'])
        log.info('Refund approved: %s' % tx_uuid)
        email_buyer_refund_approved(contrib)
        messages.success(
            request, _('Refund for this transaction successfully approved.'))
    elif res['status'] == FAILED:
        # Bango no like.
        log.error('Refund failed: %s' % tx_uuid)
        messages.error(request,
                       _('Refund request for this transaction failed.'))

    return redirect(reverse('lookup.transaction_summary', args=[tx_uuid]))
Exemple #41
0
def logout(request, template_name='cas/logout.html'):
    url = request.GET.get('url', None)
    auth_logout(request)
    return jingo.render(request, template_name, {'return_url': url})
Exemple #42
0
def _login(request,
           template_name='cas/login.html',
           success_redirect=settings.LOGIN_REDIRECT_URL):
    """
    Standard CAS login form.

    Instead of running this directly, we enforce a service whitelist first.
    See whitelist_login().
    """

    service = request.GET.get('service', None)
    # renew=true indicates that we should force the user to log in.
    if False == request.GET.get('renew',
                                False) and request.user.is_authenticated():
        if service is not None:
            ticket = utils.create_service_ticket(request.user, service)
            # TODO Parsing and rebuilding the URL here is a much better idea.
            if service.find('?') == -1:
                return HttpResponseRedirect(service + '?ticket=' +
                                            ticket.ticket)
            else:
                return HttpResponseRedirect(service + '&ticket=' +
                                            ticket.ticket)
        else:
            return HttpResponseRedirect(success_redirect)

    # gateway=true indicates that we should silently try to authenticate (no
    # login screen).
    if request.GET.get('gateway', False):
        return HttpResponseRedirect(service)
    errors = []
    if request.method == 'POST':
        username = request.POST.get('username', None)
        password = request.POST.get('password', None)
        service = request.POST.get('service', None)
        lt = request.POST.get('lt', None)

        try:
            login_ticket = LoginTicket.objects.get(ticket=lt)
        except:
            errors.append('Login ticket expired. Please try again.')
        else:
            login_ticket.delete()
            user = authenticate(username=username, password=password)
            if user is not None:
                if user.is_active:
                    auth_login(request, user)
                    if service is not None:
                        ticket = utils.create_service_ticket(user, service)
                        return HttpResponseRedirect(service + '?ticket=' +
                                                    ticket.ticket)
                    else:
                        return HttpResponseRedirect(success_redirect)
                else:
                    errors.append('This account is disabled.')
            else:
                errors.append('Incorrect username and/or password.')
    form = LoginForm(service)
    return jingo.render(request, template_name, {
        'form': form,
        'errors': errors
    })
Exemple #43
0
def handler403(request):
    if request.path_info.startswith('/api/'):
        # Pass over to handler403 view in api if api was targeted.
        return api.views.handler403(request)
    else:
        return jingo.render(request, 'amo/403.html', status=403)
Exemple #44
0
def request_token_ready(request, token):
    error = request.GET.get('error', '')
    ctx = {'error': error, 'token': token}
    return jingo.render(request, 'piston/request_token_ready.html', ctx)
Exemple #45
0
def reissue(request, addon):
    reissue = not addon.is_premium()
    if addon.is_premium() and addon.has_purchased(request.amo_user):
        reissue = True
    return jingo.render(request, 'receipts/reissue.html',
                        {'reissue': reissue, 'app': addon})
Exemple #46
0
def csrf_failure(request, reason=''):
    return jingo.render(request,
                        'amo/403.html', {'because_csrf': 'CSRF' in reason},
                        status=403)
Exemple #47
0
def apps_reviewing(request):

    return jingo.render(request, 'reviewers/apps_reviewing.html',
                        context(request, **{
                            'apps': AppsReviewing(request).get_apps(),
                            'tab': 'reviewing'}))
Exemple #48
0
def index(request):
    log = ActivityLog.objects.admin_events()[:5]
    return jingo.render(request, 'zadmin/index.html', {'log': log})
Exemple #49
0
def _review(request, addon, version):

    if (not settings.ALLOW_SELF_REVIEWS and
        not acl.action_allowed(request, 'Admin', '%') and
        addon.has_author(request.amo_user)):
        messages.warning(request, _('Self-reviews are not allowed.'))
        return redirect(reverse('reviewers.home'))

    if (addon.status == amo.STATUS_BLOCKED and
        not acl.action_allowed(request, 'Apps', 'ReviewEscalated')):
        messages.warning(
            request, _('Only senior reviewers can review blocklisted apps.'))
        return redirect(reverse('reviewers.home'))

    attachment_formset = forms.AttachmentFormSet(data=request.POST or None,
                                                 files=request.FILES or None,
                                                 prefix='attachment')
    form = forms.get_review_form(data=request.POST or None,
                                 files=request.FILES or None, request=request,
                                 addon=addon, version=version,
                                 attachment_formset=attachment_formset)
    postdata = request.POST if request.method == 'POST' else None
    all_forms = [form, attachment_formset]

    if waffle.switch_is_active('buchets') and version:
        features_list = [unicode(f) for f in version.features.to_list()]
        appfeatures_form = AppFeaturesForm(data=postdata,
                                           instance=version.features)
        all_forms.append(appfeatures_form)
    else:
        appfeatures_form = None
        features_list = None

    queue_type = form.helper.review_type
    redirect_url = reverse('reviewers.apps.queue_%s' % queue_type)
    is_admin = acl.action_allowed(request, 'Addons', 'Edit')

    if request.method == 'POST' and all(f.is_valid() for f in all_forms):

        old_types = set(o.id for o in addon.device_types)
        new_types = set(form.cleaned_data.get('device_override'))

        if waffle.switch_is_active('buchets'):
            old_features = set(features_list)
            new_features = set(unicode(f) for f
                               in appfeatures_form.instance.to_list())

        if form.cleaned_data.get('action') == 'public':
            if old_types != new_types:
                # The reviewer overrode the device types. We need to not
                # publish this app immediately.
                if addon.make_public == amo.PUBLIC_IMMEDIATELY:
                    addon.update(make_public=amo.PUBLIC_WAIT)

                # And update the device types to what the reviewer set.
                AddonDeviceType.objects.filter(addon=addon).delete()
                for device in form.cleaned_data.get('device_override'):
                    addon.addondevicetype_set.create(device_type=device)

                # Log that the reviewer changed the device types.
                added_devices = new_types - old_types
                removed_devices = old_types - new_types
                msg = _(u'Device(s) changed by '
                         'reviewer: {0}').format(', '.join(
                    [_(u'Added {0}').format(unicode(amo.DEVICE_TYPES[d].name))
                     for d in added_devices] +
                    [_(u'Removed {0}').format(
                     unicode(amo.DEVICE_TYPES[d].name))
                     for d in removed_devices]))
                amo.log(amo.LOG.REVIEW_DEVICE_OVERRIDE, addon,
                        addon.current_version, details={'comments': msg})

            if (waffle.switch_is_active('buchets') and
                 old_features != new_features):
                # The reviewer overrode the requirements. We need to not
                # publish this app immediately.
                if addon.make_public == amo.PUBLIC_IMMEDIATELY:
                    addon.update(make_public=amo.PUBLIC_WAIT)

                appfeatures_form.save(mark_for_rereview=False)

                # Log that the reviewer changed the minimum requirements.
                added_features = new_features - old_features
                removed_features = old_features - new_features

                fmt = ', '.join(
                      [_(u'Added {0}').format(f) for f in added_features] +
                      [_(u'Removed {0}').format(f) for f in removed_features])
                # L10n: {0} is the list of requirements changes.
                msg = _(u'Requirements changed by reviewer: {0}').format(fmt)
                amo.log(amo.LOG.REVIEW_FEATURES_OVERRIDE, addon,
                        addon.current_version, details={'comments': msg})

        form.helper.process()

        if form.cleaned_data.get('notify'):
            EditorSubscription.objects.get_or_create(user=request.amo_user,
                                                     addon=addon)

        messages.success(request, _('Review successfully processed.'))
        return redirect(redirect_url)

    canned = AppCannedResponse.objects.all()
    actions = form.helper.actions.items()

    try:
        if not version:
            raise Version.DoesNotExist
        show_diff = (addon.versions.exclude(id=version.id)
                                   .filter(files__isnull=False,
                                           created__lt=version.created,
                                           files__status=amo.STATUS_PUBLIC)
                                   .latest())
    except Version.DoesNotExist:
        show_diff = None

    # The actions we should show a minimal form from.
    actions_minimal = [k for (k, a) in actions if not a.get('minimal')]

    # We only allow the user to check/uncheck files for "pending"
    allow_unchecking_files = form.helper.review_type == "pending"

    versions = (Version.with_deleted.filter(addon=addon)
                                    .order_by('-created')
                                    .transform(Version.transformer_activity)
                                    .transform(Version.transformer))

    product_attrs = {
        'product': json.dumps(
            product_as_dict(request, addon, False, 'reviewer'),
            cls=JSONEncoder),
        'manifest_url': addon.manifest_url,
    }

    pager = paginate(request, versions, 10)

    num_pages = pager.paginator.num_pages
    count = pager.paginator.count

    ctx = context(request, version=version, product=addon, pager=pager,
                  num_pages=num_pages, count=count,
                  flags=Review.objects.filter(addon=addon, flag=True),
                  form=form, canned=canned, is_admin=is_admin,
                  status_types=amo.STATUS_CHOICES, show_diff=show_diff,
                  allow_unchecking_files=allow_unchecking_files,
                  actions=actions, actions_minimal=actions_minimal,
                  tab=queue_type, product_attrs=product_attrs,
                  attachment_formset=attachment_formset,
                  appfeatures_form=appfeatures_form,
                  default_visibility=DEFAULT_ACTION_VISIBILITY)

    if features_list is not None:
        ctx['feature_list'] = features_list

    return jingo.render(request, 'reviewers/review.html', ctx)
Exemple #50
0
def leaderboard(request):

    return jingo.render(request, 'reviewers/leaderboard.html', context(request,
        **{'scores': ReviewerScore.all_users_by_score()}))
Exemple #51
0
def handler500(request):
    if request.path_info.startswith('/api/'):
        return api.views.handler500(request)
    else:
        return jingo.render(request, 'site/500.html', status=500)
Exemple #52
0
def robots(request):
    """Generate a robots.txt"""
    template = jingo.render(request, 'site/robots.txt')
    return HttpResponse(template, mimetype="text/plain")
Exemple #53
0
def document(request, document_slug, template=None):
    """View a wiki document."""
    fallback_reason = None
    # If a slug isn't available in the requested locale, fall back to en-US:
    try:
        doc = Document.objects.get(locale=request.locale, slug=document_slug)
        if (not doc.current_revision and doc.parent
                and doc.parent.current_revision):
            # This is a translation but its current_revision is None
            # and OK to fall back to parent (parent is approved).
            fallback_reason = 'translation_not_approved'
        elif not doc.current_revision:
            # No current_revision, no parent with current revision, so
            # nothing to show.
            fallback_reason = 'no_content'
    except Document.DoesNotExist:
        # Look in default language:
        doc = get_object_or_404(Document,
                                locale=settings.WIKI_DEFAULT_LANGUAGE,
                                slug=document_slug)
        # If there's a translation to the requested locale, take it:
        translation = doc.translated_to(request.locale)
        if translation:
            url = translation.get_absolute_url()
            url = urlparams(url, query_dict=request.GET)
            return HttpResponseRedirect(url)
        elif doc.current_revision:
            # There is no translation
            # and OK to fall back to parent (parent is approved).
            fallback_reason = 'no_translation'

    # Obey explicit redirect pages:
    # Don't redirect on redirect=no (like Wikipedia), so we can link from a
    # redirected-to-page back to a "Redirected from..." link, so you can edit
    # the redirect.
    redirect_url = (None if request.GET.get('redirect') == 'no' else
                    doc.redirect_url())
    if redirect_url:
        url = urlparams(redirect_url,
                        query_dict=request.GET,
                        redirectslug=doc.slug,
                        redirectlocale=doc.locale)
        return HttpResponseRedirect(url)

    # Get "redirected from" doc if we were redirected:
    redirect_slug = request.GET.get('redirectslug')
    redirect_locale = request.GET.get('redirectlocale')
    redirected_from = None
    if redirect_slug and redirect_locale:
        try:
            redirected_from = Document.objects.get(locale=redirect_locale,
                                                   slug=redirect_slug)
        except Document.DoesNotExist:
            pass

    related = doc.related_documents.order_by('-related_to__in_common')[0:5]

    # Get the contributors. (To avoid this query, we could render the
    # the contributors right into the Document's html field.)
    contributors = set([
        r.creator for r in doc.revisions.filter(
            is_approved=True).select_related('creator')
    ])

    data = {
        'document': doc,
        'redirected_from': redirected_from,
        'related': related,
        'contributors': contributors,
        'fallback_reason': fallback_reason,
        'is_aoa_referral': request.GET.get('ref') == 'aoa'
    }
    data.update(SHOWFOR_DATA)
    return jingo.render(request, template, data)
Exemple #54
0
def handler404(request):
    if request.path_info.startswith('/api/'):
        # Pass over to API handler404 view if API was targeted.
        return api.views.handler404(request)
    else:
        return jingo.render(request, 'site/404.html', status=404)
Exemple #55
0
def about(request, project, slug, template_name='ignite/about.html'):
    if waffle.switch_is_active('announce_winners'):
        template_name = 'ignite/about-winners.html'
    return jingo.render(request, template_name)
Exemple #56
0
def translate(request, document_slug, revision_id=None):
    """Create a new translation of a wiki document.

    * document_slug is for the default locale
    * translation is to the request locale

    """
    # TODO: Refactor this view into two views? (new, edit)
    # That might help reduce the headache-inducing branchiness.
    parent_doc = get_object_or_404(Document,
                                   locale=settings.WIKI_DEFAULT_LANGUAGE,
                                   slug=document_slug)
    user = request.user

    if settings.WIKI_DEFAULT_LANGUAGE == request.locale:
        # Don't translate to the default language.
        return HttpResponseRedirect(
            reverse('wiki.edit_document',
                    locale=settings.WIKI_DEFAULT_LANGUAGE,
                    args=[parent_doc.slug]))

    if not parent_doc.is_localizable:
        message = _lazy(u'You cannot translate this document.')
        return jingo.render(request,
                            'handlers/400.html', {'message': message},
                            status=400)

    based_on_rev = get_current_or_latest_revision(parent_doc,
                                                  reviewed_only=False)

    disclose_description = bool(request.GET.get('opendescription'))

    try:
        doc = parent_doc.translations.get(locale=request.locale)
    except Document.DoesNotExist:
        doc = None
        disclose_description = True

    user_has_doc_perm = ((not doc) or (doc and doc.allows_editing_by(user)))
    user_has_rev_perm = ((not doc) or (doc and doc.allows_revision_by(user)))
    if not user_has_doc_perm and not user_has_rev_perm:
        # User has no perms, bye.
        raise PermissionDenied

    doc_form = rev_form = None

    if user_has_doc_perm:
        doc_initial = _document_form_initial(doc) if doc else None
        doc_form = DocumentForm(
            initial=doc_initial,
            can_create_tags=user.has_perm('taggit.add_tag'))
    if user_has_rev_perm:
        initial = {'based_on': based_on_rev.id, 'comment': ''}
        if revision_id:
            r = Revision.objects.get(pk=revision_id)
            initial.update(content=r.content,
                           summary=r.summary,
                           keywords=r.keywords)
        elif not doc:
            initial.update(content=based_on_rev.content,
                           summary=based_on_rev.summary,
                           keywords=based_on_rev.keywords)
        instance = doc and get_current_or_latest_revision(doc)
        rev_form = RevisionForm(instance=instance, initial=initial)

    if request.method == 'POST':
        which_form = request.POST.get('form', 'both')
        doc_form_invalid = False

        if user_has_doc_perm and which_form in ['doc', 'both']:
            disclose_description = True
            post_data = request.POST.copy()
            post_data.update({'locale': request.locale})
            doc_form = DocumentForm(
                post_data,
                instance=doc,
                can_create_tags=user.has_perm('taggit.add_tag'))
            doc_form.instance.locale = request.locale
            doc_form.instance.parent = parent_doc
            if which_form == 'both':
                rev_form = RevisionForm(request.POST)

            # If we are submitting the whole form, we need to check that
            # the Revision is valid before saving the Document.
            if doc_form.is_valid() and (which_form == 'doc'
                                        or rev_form.is_valid()):
                doc = doc_form.save(parent_doc)

                # Possibly schedule a rebuild.
                _maybe_schedule_rebuild(doc_form)

                if which_form == 'doc':
                    url = urlparams(reverse('wiki.edit_document',
                                            args=[doc.slug]),
                                    opendescription=1)
                    return HttpResponseRedirect(url)

                doc_slug = doc_form.cleaned_data['slug']
            else:
                doc_form_invalid = True
        else:
            doc_slug = doc.slug

        if doc and user_has_rev_perm and which_form in ['rev', 'both']:
            rev_form = RevisionForm(request.POST)
            rev_form.instance.document = doc  # for rev_form.clean()
            if rev_form.is_valid() and not doc_form_invalid:
                _save_rev_and_notify(rev_form, request.user, doc)
                url = reverse('wiki.document_revisions', args=[doc_slug])
                return HttpResponseRedirect(url)

    return jingo.render(
        request, 'wiki/translate.html', {
            'parent': parent_doc,
            'document': doc,
            'document_form': doc_form,
            'revision_form': rev_form,
            'locale': request.locale,
            'based_on': based_on_rev,
            'disclose_description': disclose_description
        })
Exemple #57
0
def addon_detail(request, addon):
    reviews = Review.objects.latest().filter(addon=addon)
    src = request.GET.get('src', 'discovery-details')
    return jingo.render(request, 'discovery/addons/detail.html',
                        {'addon': addon, 'reviews': reviews,
                         'get_replies': Review.get_replies, 'src': src})
Exemple #58
0
def fail(request, template_name='404.html'):
    return jingo.render(request, template_name, {}, status=404)
Exemple #59
0
def terms_development(request, project, slug, template_name='static/terms_conditions_development.html'):
    return jingo.render(request, template_name, {})
Exemple #60
0
def edit_document(request, document_slug, revision_id=None):
    """Create a new revision of a wiki document, or edit document metadata."""
    doc = get_object_or_404(Document,
                            locale=request.locale,
                            slug=document_slug)
    user = request.user

    # If this document has a parent, then the edit is handled by the
    # translate view. Pass it on.
    if doc.parent:
        return translate(request, doc.parent.slug, revision_id)
    if revision_id:
        rev = get_object_or_404(Revision, pk=revision_id, document=doc)
    else:
        rev = doc.current_revision or doc.revisions.order_by(
            '-created', '-id')[0]

    disclose_description = bool(request.GET.get('opendescription'))
    doc_form = rev_form = None
    if doc.allows_revision_by(user):
        rev_form = RevisionForm(instance=rev,
                                initial={
                                    'based_on': rev.id,
                                    'comment': ''
                                })
    if doc.allows_editing_by(user):
        doc_form = DocumentForm(
            initial=_document_form_initial(doc),
            can_create_tags=user.has_perm('taggit.add_tag'))

    if request.method == 'GET':
        if not (rev_form or doc_form):
            # You can't do anything on this page, so get lost.
            raise PermissionDenied
    else:  # POST
        # Comparing against localized names for the Save button bothers me, so
        # I embedded a hidden input:
        which_form = request.POST.get('form')

        if which_form == 'doc':
            if doc.allows_editing_by(user):
                post_data = request.POST.copy()
                post_data.update({'locale': request.locale})
                doc_form = DocumentForm(
                    post_data,
                    instance=doc,
                    can_create_tags=user.has_perm('taggit.add_tag'))
                if doc_form.is_valid():
                    # Get the possibly new slug for the imminent redirection:
                    doc = doc_form.save(None)

                    # Do we need to rebuild the KB?
                    _maybe_schedule_rebuild(doc_form)

                    return HttpResponseRedirect(
                        urlparams(reverse('wiki.edit_document',
                                          args=[doc.slug]),
                                  opendescription=1))
                disclose_description = True
            else:
                raise PermissionDenied
        elif which_form == 'rev':
            if doc.allows_revision_by(user):
                rev_form = RevisionForm(request.POST)
                rev_form.instance.document = doc  # for rev_form.clean()
                if rev_form.is_valid():
                    _save_rev_and_notify(rev_form, user, doc)
                    return HttpResponseRedirect(
                        reverse('wiki.document_revisions',
                                args=[document_slug]))
            else:
                raise PermissionDenied

    return jingo.render(
        request, 'wiki/edit_document.html', {
            'revision_form': rev_form,
            'document_form': doc_form,
            'disclose_description': disclose_description,
            'document': doc
        })