Example #1
0
    def process_request(self, request):
        success = False

        is_footer_form = (request.method == 'POST' and
                          'newsletter-footer' in request.POST)
        if is_footer_form:
            form = NewsletterFooterForm(request.locale, request.POST or None)
            if form.is_valid():
                data = form.cleaned_data
                kwargs = {
                    'format': data['fmt'],
                }
                # add optional data
                kwargs.update(dict((k, data[k]) for k in ['country',
                                                          'lang',
                                                          'source_url']
                                   if data[k]))
                result = newsletter_subscribe(data['email'])
                request.newsletter_subscriber = data['email']
                request.new_subscription = result
                success = True
            request.newsletter_form = form
        else:
            request.newsletter_form = NewsletterFooterForm(request.locale, None)
        request.newsletter_success = success
Example #2
0
def one_newsletter_subscribe(request, template_name, target=None):
    success = False

    # not in a footer, but we use the same form
    form = NewsletterFooterForm(request.locale, request.POST or None)

    if form.is_valid():
        data = form.cleaned_data
        request.newsletter_lang = data.get('lang', 'en') or 'en'
        kwargs = {
            'format': data['fmt'],
        }
        # add optional data
        kwargs.update(dict((k, data[k]) for k in ['country',
                                                  'lang',
                                                  'source_url']
                           if data[k]))
        newsletter_subscribe(data['email'])
        success = True

    request.newsletter_form = form
    request.newsletter_success = success

    return l10n_utils.render(request,
                             template_name,
                             {'target': target})
Example #3
0
    def process_request(self, request):
        success = False
        form = NewsletterFooterForm(request.locale, request.POST or None)

        is_footer_form = (request.method == 'POST' and
                          'newsletter-footer' in request.POST)
        if is_footer_form:
            if form.is_valid():
                data = form.cleaned_data
                kwargs = {
                    'format': data['fmt'],
                }
                # add optional data
                kwargs.update(dict((k, data[k]) for k in ['country',
                                                          'lang',
                                                          'source_url']
                                   if data[k]))
                try:
                    basket.subscribe(data['email'], data['newsletter'],
                                     **kwargs)
                    success = True
                except basket.BasketException:
                    msg = _lazy("We are sorry, but there was a problem "
                                "with our system. Please try again later!")
                    form.errors['__all__'] = form.error_class([msg])

        request.newsletter_form = form
        request.newsletter_success = success
Example #4
0
    def test_invalid_newsletter_is_error(self):
        """Invalid newsletter should not raise exception. Bug 1072302.

        Instead, an invalid newsletter name should manifest as a normal
        form error.
        """
        data = {
            'email': '*****@*****.**',
            'lang': 'fr',
            'privacy': True,
            'fmt': 'H',
            'newsletters': '',
        }
        form = NewsletterFooterForm('', locale='en-US', data=data.copy())
        self.assertFalse(form.is_valid())
        self.assertIn('newsletters', form.errors)
        self.assertEqual(form.errors['newsletters'], [u'This field is required.'])

        invalid_newsletter = '!nv@l1d'
        data = {
            'email': '*****@*****.**',
            'lang': 'fr',
            'privacy': True,
            'fmt': 'H',
            'newsletters': invalid_newsletter,
        }
        form = NewsletterFooterForm(invalid_newsletter, locale='en-US', data=data.copy())
        self.assertFalse(form.is_valid())
        self.assertIn('newsletters', form.errors)
        self.assertEqual(form.errors['newsletters'], [u'Invalid Newsletter'])
Example #5
0
def contribute(request, template, return_to_form):
    newsletter_id = 'about-mozilla'
    has_contribute_form = (request.method == 'POST' and
                           'contribute-form' in request.POST)

    has_newsletter_form = (request.method == 'POST' and
                           'newsletter-form' in request.POST)

    locale = getattr(request, 'locale', 'en-US')

    contribute_success = False
    newsletter_success = False

    # This is ugly, but we need to handle two forms. I would love if
    # these forms could post to separate pages and get redirected
    # back, but we're forced to keep the error/success workflow on the
    # same page. Please change this.
    if has_contribute_form:
        form = ContributeForm(request.POST)
        contribute_success = email_contribute.handle_form(request, form)
        if contribute_success:
            # If form was submitted successfully, return a new, empty
            # one.
            form = ContributeForm()
    else:
        form = ContributeForm()

    if has_newsletter_form:
        newsletter_form = NewsletterFooterForm(newsletter_id, locale,
                                               request.POST,
                                               prefix='newsletter')
        if newsletter_form.is_valid():
            data = newsletter_form.cleaned_data

            try:
                basket.subscribe(data['email'],
                                 newsletter_id,
                                 format=data['fmt'],
                                 country=data['country'])
                newsletter_success = True
            except basket.BasketException:
                msg = newsletter_form.error_class(
                    [_('We apologize, but an error occurred in our system. '
                       'Please try again later.')]
                )
                newsletter_form.errors['__all__'] = msg
    else:
        newsletter_form = NewsletterFooterForm(newsletter_id, locale, prefix='newsletter')

    return l10n_utils.render(request,
                             template,
                             {'form': form,
                              'contribute_success': contribute_success,
                              'newsletter_form': newsletter_form,
                              'newsletter_success': newsletter_success,
                              'return_to_form': return_to_form,
                              'hide_form': hide_contrib_form(request.locale),
                              'has_moz15': locale in settings.LOCALES_WITH_MOZ15})
Example #6
0
    def test_lang_choices_per_newsletter(self):
        """Lang choices should be based on the newsletter."""
        form = NewsletterFooterForm('beta', 'en-US')
        choices = [lang[0] for lang in form.fields['lang'].choices]
        self.assertEqual(choices, ['en'])

        form = NewsletterFooterForm('join-mozilla', 'en-US')
        choices = [lang[0] for lang in form.fields['lang'].choices]
        self.assertEqual(choices, ['en', 'es'])
Example #7
0
 def test_lang_not_required(self):
     """lang not required since field not always displayed"""
     data = {"email": "*****@*****.**", "privacy": True, "fmt": "H", "newsletters": self.newsletter_name}
     form = NewsletterFooterForm(self.newsletter_name, locale="en-US", data=data.copy())
     self.assertTrue(form.is_valid(), form.errors)
     # Form returns '' for lang, so we don't accidentally change the user's
     # preferred language thinking they entered something here that they
     # didn't.
     self.assertEqual(u"", form.cleaned_data["lang"])
Example #8
0
    def test_lang_choices_per_newsletter(self):
        """Lang choices should be based on the newsletter."""
        form = NewsletterFooterForm("beta", "en-US")
        choices = [lang[0] for lang in form.fields["lang"].choices]
        self.assertEqual(choices, ["en"])

        form = NewsletterFooterForm("join-mozilla", "en-US")
        choices = [lang[0] for lang in form.fields["lang"].choices]
        self.assertEqual(choices, ["en", "es"])
Example #9
0
 def test_privacy_required(self):
     """they have to check the privacy box"""
     data = {
         'email': '*****@*****.**',
         'privacy': False,
         'newsletters': self.newsletter_name,
     }
     form = NewsletterFooterForm(self.newsletter_name, locale='en-US', data=data)
     self.assertFalse(form.is_valid())
     self.assertIn('privacy', form.errors)
Example #10
0
    def test_country_default(self):
        """country defaults based on the locale.

        But only for country based locales (e.g. pt-BR)"""
        form = NewsletterFooterForm(self.newsletter_name, locale='fr')
        self.assertEqual('', form.fields['country'].initial)
        form = NewsletterFooterForm(self.newsletter_name, locale='pt-BR')
        self.assertEqual('br', form.fields['country'].initial)
        form = NewsletterFooterForm(self.newsletter_name, locale='zh-TW')
        self.assertEqual('tw', form.fields['country'].initial)
Example #11
0
    def test_country_default(self):
        """country defaults based on the locale.

        But only for country based locales (e.g. pt-BR)"""
        form = NewsletterFooterForm(self.newsletter_name, locale="fr")
        self.assertEqual("", form.fields["country"].initial)
        form = NewsletterFooterForm(self.newsletter_name, locale="pt-BR")
        self.assertEqual("br", form.fields["country"].initial)
        form = NewsletterFooterForm(self.newsletter_name, locale="zh-TW")
        self.assertEqual("tw", form.fields["country"].initial)
Example #12
0
 def test_privacy_required(self):
     """they have to check the privacy box"""
     data = {
         'email': '*****@*****.**',
         'privacy': False,
         'fmt': 'H',
         'newsletters': self.newsletter_name,
     }
     form = NewsletterFooterForm(self.newsletter_name, locale='en-US', data=data)
     self.assertFalse(form.is_valid())
     self.assertIn('privacy', form.errors)
Example #13
0
 def test_privacy_required(self):
     """they have to check the privacy box"""
     data = {
         "email": "*****@*****.**",
         "privacy": False,
         "fmt": "H",
         "newsletters": self.newsletter_name,
     }
     form = NewsletterFooterForm(self.newsletter_name, locale="en-US", data=data)
     self.assertFalse(form.is_valid())
     self.assertIn("privacy", form.errors)
Example #14
0
    def test_multiple_newsletters(self):
        """Should allow to subscribe to multiple newsletters at a time."""
        newsletters = "mozilla-and-you,beta"
        data = {"email": "*****@*****.**", "lang": "en", "privacy": "Y", "fmt": "H", "newsletters": newsletters}
        form = NewsletterFooterForm(newsletters, "en-US", data=data.copy())
        self.assertTrue(form.is_valid())
        self.assertEqual(form.cleaned_data["newsletters"], newsletters)

        # whitespace shouldn't matter
        form = NewsletterFooterForm("mozilla-and-you , beta ", "en-US", data=data.copy())
        self.assertTrue(form.is_valid())
        self.assertEqual(form.cleaned_data["newsletters"], newsletters)
Example #15
0
def email_newsletter_form(ctx,
                          newsletters='mozilla-and-you',
                          title=None,
                          include_country=True,
                          include_language=True,
                          use_thankyou=True,
                          footer=True,
                          process_form=True):
    request = ctx['request']
    context = ctx.get_all()
    context.update(
        dict(
            id=newsletters,
            title=title,
            include_country=include_country,
            include_language=include_language,
            use_thankyou=use_thankyou,
            footer=footer,
        ))
    success = False
    form = NewsletterFooterForm(newsletters, get_locale(request), request.POST
                                or None)

    if process_form and request.method == 'POST':
        if form.is_valid():
            data = form.cleaned_data

            # If data['lang'] is set, pass it to the template.
            # If it's None, empty, or nonexistent, pass 'en'.
            context['lang'] = data.get('lang', 'en').strip() or 'en'

            kwargs = {'format': data['fmt']}
            # add optional data
            kwargs.update(
                dict((k, data[k]) for k in ['country', 'lang', 'source_url']
                     if data[k]))
            try:
                basket.subscribe(data['email'], form.newsletters, **kwargs)
            except basket.BasketException:
                log.exception("Error subscribing %s to newsletter %s" %
                              (data['email'], newsletters))
                msg = _lazy("We are sorry, but there was a problem "
                            "with our system. Please try again later!")
                form.errors['__all__'] = form.error_class([msg])
            else:
                success = True

    request.newsletter_success = success
    context.update(dict(form=form, success=success))
    html = jingo.render_to_string(request, 'newsletter/includes/form.html',
                                  context)
    if not (success and not use_thankyou):
        return jinja2.Markup(html)
Example #16
0
 def test_lang_not_required(self):
     """lang not required since field not always displayed"""
     data = {
         'email': '*****@*****.**',
         'privacy': True,
         'fmt': 'H',
     }
     form = NewsletterFooterForm(self.newsletter_name, locale='en-US', data=data.copy())
     self.assertTrue(form.is_valid(), form.errors)
     # Form returns '' for lang, so we don't accidentally change the user's
     # preferred language thinking they entered something here that they
     # didn't.
     self.assertEqual(u'', form.cleaned_data['lang'])
Example #17
0
 def test_form(self):
     """Form works normally"""
     data = {
         'email': '*****@*****.**',
         'lang': 'fr',
         'privacy': True,
         'fmt': 'H',
     }
     form = NewsletterFooterForm(self.newsletter_name, locale='en-US', data=data.copy())
     self.assertTrue(form.is_valid(), form.errors)
     cleaned_data = form.cleaned_data
     self.assertEqual(data['fmt'], cleaned_data['fmt'])
     self.assertEqual(data['lang'], cleaned_data['lang'])
Example #18
0
 def test_lang_not_required(self):
     """lang not required since field not always displayed"""
     data = {
         'email': '*****@*****.**',
         'privacy': True,
         'fmt': 'H',
     }
     form = NewsletterFooterForm(self.newsletter_name, locale='en-US', data=data)
     self.assertTrue(form.is_valid(), form.errors)
     # Form returns '' for lang, so we don't accidentally change the user's
     # preferred language thinking they entered something here that they
     # didn't.
     self.assertEqual(u'', form.cleaned_data['lang'])
Example #19
0
 def test_form(self):
     """Form works normally"""
     data = {
         'email': '*****@*****.**',
         'lang': 'fr',
         'privacy': True,
         'fmt': 'H',
     }
     form = NewsletterFooterForm(self.newsletter_name, locale='en-US', data=data)
     self.assertTrue(form.is_valid(), form.errors)
     cleaned_data = form.cleaned_data
     self.assertEqual(data['fmt'], cleaned_data['fmt'])
     self.assertEqual(data['lang'], cleaned_data['lang'])
Example #20
0
 def test_form(self):
     """Form works normally"""
     data = {
         "email": "*****@*****.**",
         "lang": "fr",
         "privacy": True,
         "fmt": "H",
         "newsletters": self.newsletter_name,
     }
     form = NewsletterFooterForm(self.newsletter_name, locale="en-US", data=data.copy())
     self.assertTrue(form.is_valid(), form.errors)
     cleaned_data = form.cleaned_data
     self.assertEqual(data["fmt"], cleaned_data["fmt"])
     self.assertEqual(data["lang"], cleaned_data["lang"])
Example #21
0
 def test_lang_not_required(self):
     """lang not required since field not always displayed"""
     data = {
         "email": "*****@*****.**",
         "privacy": True,
         "fmt": "H",
         "newsletters": self.newsletter_name,
     }
     form = NewsletterFooterForm(self.newsletter_name, locale="en-US", data=data.copy())
     self.assertTrue(form.is_valid(), form.errors)
     # Form returns '' for lang, so we don't accidentally change the user's
     # preferred language thinking they entered something here that they
     # didn't.
     self.assertEqual("", form.cleaned_data["lang"])
Example #22
0
def email_newsletter_form(ctx, newsletters='mozilla-and-you', title=None,
                          include_country=True, include_language=True,
                          use_thankyou=True, footer=True, process_form=True):
    request = ctx['request']
    context = ctx.get_all()
    context.update(dict(
        id=newsletters,
        title=title,
        include_country=include_country,
        include_language=include_language,
        use_thankyou=use_thankyou,
        footer=footer,
    ))
    success = False
    form = NewsletterFooterForm(newsletters, get_locale(request),
                                request.POST or None)

    if process_form and request.method == 'POST':
        if form.is_valid():
            data = form.cleaned_data

            # If data['lang'] is set, pass it to the template.
            # If it's None, empty, or nonexistent, pass 'en'.
            context['lang'] = data.get('lang', 'en').strip() or 'en'

            kwargs = {'format': data['fmt']}
            # add optional data
            kwargs.update(dict((k, data[k]) for k in ['country',
                                                      'lang',
                                                      'source_url']
                               if data[k]))
            try:
                basket.subscribe(data['email'], form.newsletters,
                                 **kwargs)
            except basket.BasketException:
                log.exception("Error subscribing %s to newsletter %s" %
                              (data['email'], newsletters))
                msg = _lazy("We are sorry, but there was a problem "
                            "with our system. Please try again later!")
                form.errors['__all__'] = form.error_class([msg])
            else:
                success = True

    request.newsletter_success = success
    context.update(dict(form=form, success=success))
    html = jingo.render_to_string(request, 'newsletter/includes/form.html', context)
    if not (success and not use_thankyou):
        return jinja2.Markup(html)
Example #23
0
def email_newsletter_form(ctx, newsletters='mozilla-and-you', title=None,
                          include_country=True, include_language=True,
                          use_thankyou=True, footer=True, process_form=True):
    request = ctx['request']
    context = ctx.get_all()

    success = bool(ctx.get('success'))
    if success and not use_thankyou:
        return

    form = ctx.get('newsletter_form', None)
    if not form:
        form = NewsletterFooterForm(newsletters, get_locale(request))

    context.update(dict(
        id=newsletters,
        title=title,
        include_country=include_country,
        include_language=include_language,
        use_thankyou=use_thankyou,
        footer=footer,
        form=form,
        success=success,
    ))

    html = jingo.render_to_string(request, 'newsletter/includes/form.html', context)
    return jinja2.Markup(html)
Example #24
0
def email_newsletter_form(
    ctx,
    newsletters="mozilla-and-you",
    title=None,
    subtitle=None,
    desc=None,
    include_country=True,
    include_language=True,
    details=None,
    use_thankyou=True,
    thankyou_head=None,
    thankyou_content=None,
    footer=True,
    process_form=True,
    include_title=None,
    submit_text=None,
    button_class=None,
    spinner_color=None,
    email_label=None,
    email_placeholder=None,
):
    request = ctx["request"]
    context = ctx.get_all()

    success = bool(ctx.get("success"))
    if success and not use_thankyou:
        return

    form = ctx.get("newsletter_form", None)
    if not form:
        form = NewsletterFooterForm(newsletters, get_locale(request))

    context.update(
        dict(
            id=newsletters,
            title=title,
            subtitle=subtitle,  # nested in/depends on include_title
            desc=desc,  # nested in/depends on include_title
            include_country=include_country,
            include_language=include_language,
            details=details,
            use_thankyou=use_thankyou,
            thankyou_head=thankyou_head,
            thankyou_content=thankyou_content,
            footer=footer,
            include_title=include_title
            if include_title is not None else footer,
            form=form,
            submit_text=submit_text,
            button_class=button_class,
            spinner_color=spinner_color,
            success=success,
            email_label=email_label,
            email_placeholder=email_placeholder,
        ))

    html = render_to_string("newsletter/includes/form.html",
                            context,
                            request=request)
    return jinja2.Markup(html)
Example #25
0
    def test_multiple_newsletters(self):
        """Should allow to subscribe to multiple newsletters at a time."""
        data = {
            'email': '*****@*****.**',
            'lang': 'en',
            'privacy': 'Y',
            'fmt': 'H',
        }
        form = NewsletterFooterForm('mozilla-and-you,beta', 'en-US', data=data.copy())
        self.assertTrue(form.is_valid())
        self.assertEqual(form.newsletters, 'mozilla-and-you,beta')

        # whitespace shouldn't matter
        form = NewsletterFooterForm('mozilla-and-you , beta ', 'en-US', data=data.copy())
        self.assertTrue(form.is_valid())
        self.assertEqual(form.newsletters, 'mozilla-and-you,beta')
Example #26
0
 def test_source_url_too_long(self):
     """Form works normally"""
     data = {
         "email": "*****@*****.**",
         "lang": "fr",
         "first_name": "Walter",
         "last_name": "Sobchak",
         "privacy": True,
         "fmt": "H",
         "source_url": "about:devtools" * 20,
         "newsletters": self.newsletter_name,
     }
     form = NewsletterFooterForm(self.newsletter_name, locale="en-US", data=data.copy())
     self.assertTrue(form.is_valid(), form.errors)
     cleaned_data = form.cleaned_data
     self.assertEqual(data["source_url"][:255], cleaned_data["source_url"])
Example #27
0
 def test_source_url_too_long(self):
     """Form works normally"""
     data = {
         'email': '*****@*****.**',
         'lang': 'fr',
         'first_name': 'Walter',
         'last_name': 'Sobchak',
         'privacy': True,
         'fmt': 'H',
         'source_url': 'about:devtools' * 20,
         'newsletters': self.newsletter_name,
     }
     form = NewsletterFooterForm(self.newsletter_name, locale='en-US', data=data.copy())
     self.assertTrue(form.is_valid(), form.errors)
     cleaned_data = form.cleaned_data
     self.assertEqual(data['source_url'][:255], cleaned_data['source_url'])
Example #28
0
def ios_testflight(request):
    # no country field, so no need to send locale
    newsletter_form = NewsletterFooterForm('ios-beta-test-flight', '')

    return l10n_utils.render(request,
                             'firefox/testflight.html',
                             {'newsletter_form': newsletter_form})
Example #29
0
 def test_source_url_too_long(self):
     """Form works normally"""
     data = {
         'email': '*****@*****.**',
         'lang': 'fr',
         'first_name': 'Walter',
         'last_name': 'Sobchak',
         'privacy': True,
         'fmt': 'H',
         'source_url': 'about:devtools' * 20,
         'newsletters': self.newsletter_name,
     }
     form = NewsletterFooterForm(self.newsletter_name, locale='en-US', data=data.copy())
     self.assertTrue(form.is_valid(), form.errors)
     cleaned_data = form.cleaned_data
     self.assertEqual(data['source_url'][:255], cleaned_data['source_url'])
Example #30
0
def contribute(request, template, return_to_form):
    newsletter_form = NewsletterFooterForm('about-mozilla',
                                           l10n_utils.get_locale(request))

    contribute_success = False

    form = ContributeForm(request.POST or None, auto_id=u'id_contribute-%s')
    if form.is_valid():
        data = form.cleaned_data.copy()

        honeypot = data.pop('office_fax')

        if not honeypot:
            contribute_success = email_contribute.handle_form(request, form)
            if contribute_success:
                # If form was submitted successfully, return a new, empty
                # one.
                form = ContributeForm()
        else:
            # send back a clean form if honeypot was filled in
            form = ContributeForm()

    return l10n_utils.render(
        request, template, {
            'form': form,
            'newsletter_form': newsletter_form,
            'contribute_success': contribute_success,
            'return_to_form': return_to_form,
            'hide_form': hide_contrib_form(request.locale)
        })
Example #31
0
 def test_form(self):
     """Form works normally"""
     data = {
         'email': '*****@*****.**',
         'lang': 'fr',
         'first_name': 'Walter',
         'last_name': 'Sobchak',
         'privacy': True,
         'fmt': 'H',
         'source_url': 'https://accounts.firefox.com',
         'newsletters': self.newsletter_name,
     }
     form = NewsletterFooterForm(self.newsletter_name, locale='en-US', data=data.copy())
     self.assertTrue(form.is_valid(), form.errors)
     cleaned_data = form.cleaned_data
     self.assertEqual(data['fmt'], cleaned_data['fmt'])
     self.assertEqual(data['lang'], cleaned_data['lang'])
     self.assertEqual(data['source_url'], cleaned_data['source_url'])
Example #32
0
def email_newsletter_form(ctx,
                          newsletters='mozilla-and-you',
                          title=None,
                          subtitle=None,
                          include_country=True,
                          include_language=True,
                          details=None,
                          use_thankyou=True,
                          thankyou_head=None,
                          thankyou_content=None,
                          footer=True,
                          process_form=True,
                          include_title=None,
                          submit_text=None,
                          button_class=None,
                          spinner_color=None,
                          protocol_component=False,
                          email_label=None,
                          email_placeholder=None):
    request = ctx['request']
    context = ctx.get_all()

    success = bool(ctx.get('success'))
    if success and not use_thankyou:
        return

    form = ctx.get('newsletter_form', None)
    if not form:
        form = NewsletterFooterForm(newsletters, get_locale(request))

    context.update(
        dict(
            id=newsletters,
            title=title,
            subtitle=subtitle,  # nested in/depends on include_title
            include_country=include_country,
            include_language=include_language,
            details=details,
            use_thankyou=use_thankyou,
            thankyou_head=thankyou_head,
            thankyou_content=thankyou_content,
            footer=footer,
            include_title=include_title
            if include_title is not None else footer,
            form=form,
            submit_text=submit_text,
            button_class=button_class,
            spinner_color=spinner_color,
            success=success,
            email_label=email_label,
            email_placeholder=email_placeholder,
        ))

    template_name = 'newsletter/includes/form-protocol.html' if protocol_component else 'newsletter/includes/form.html'

    html = render_to_string(template_name, context, request=request)
    return jinja2.Markup(html)
Example #33
0
 def test_form(self):
     """Form works normally"""
     data = {
         'email': '*****@*****.**',
         'lang': 'fr',
         'first_name': 'Walter',
         'last_name': 'Sobchak',
         'privacy': True,
         'fmt': 'H',
         'source_url': 'https://accounts.firefox.com',
         'newsletters': self.newsletter_name,
     }
     form = NewsletterFooterForm(self.newsletter_name, locale='en-US', data=data.copy())
     self.assertTrue(form.is_valid(), form.errors)
     cleaned_data = form.cleaned_data
     self.assertEqual(data['fmt'], cleaned_data['fmt'])
     self.assertEqual(data['lang'], cleaned_data['lang'])
     self.assertEqual(data['source_url'], cleaned_data['source_url'])
Example #34
0
 def test_form(self):
     """Form works normally"""
     data = {
         "email": "*****@*****.**",
         "lang": "fr",
         "first_name": "Walter",
         "last_name": "Sobchak",
         "privacy": True,
         "fmt": "H",
         "source_url": "https://accounts.firefox.com",
         "newsletters": self.newsletter_name,
     }
     form = NewsletterFooterForm(self.newsletter_name, locale="en-US", data=data.copy())
     self.assertTrue(form.is_valid(), form.errors)
     cleaned_data = form.cleaned_data
     self.assertEqual(data["fmt"], cleaned_data["fmt"])
     self.assertEqual(data["lang"], cleaned_data["lang"])
     self.assertEqual(data["source_url"], cleaned_data["source_url"])
Example #35
0
def contribute(request, template, return_to_form):
    has_contribute_form = (request.method == 'POST' and
                           'contribute-form' in request.POST)

    has_newsletter_form = (request.method == 'POST' and
                           'newsletter-form' in request.POST)

    locale = getattr(request, 'locale', 'en-US')

    contribute_success = False
    newsletter_success = False

    # This is ugly, but we need to handle two forms. I would love if
    # these forms could post to separate pages and get redirected
    # back, but we're forced to keep the error/success workflow on the
    # same page. Please change this.
    if has_contribute_form:
        form = ContributeForm(request.POST)
        contribute_success = email_contribute.handle_form(request, form)
        if contribute_success:
            # If form was submitted successfully, return a new, empty
            # one.
            form = ContributeForm()
    else:
        form = ContributeForm()

    if has_newsletter_form:
        newsletter_form = NewsletterFooterForm(locale, request.POST)
        if newsletter_form.is_valid():
            data = newsletter_form.cleaned_data
            newsletter_subscribe(data['email'])
            newsletter_success = True
    else:
        newsletter_form = NewsletterFooterForm(locale, None)

    return l10n_utils.render(request,
                             template,
                             {'form': form,
                              'contribute_success': contribute_success,
                              'newsletter_form': newsletter_form,
                              'newsletter_success': newsletter_success,
                              'return_to_form': return_to_form,
                              'hide_form': hide_contrib_form(request.locale),
                              'has_moz15': locale in settings.LOCALES_WITH_MOZ15})
Example #36
0
def contribute(request, template, return_to_form):
    has_contribute_form = (request.method == 'POST'
                           and 'contribute-form' in request.POST)

    has_newsletter_form = (request.method == 'POST'
                           and 'newsletter-form' in request.POST)

    locale = getattr(request, 'locale', 'en-US')

    contribute_success = False
    newsletter_success = False

    # This is ugly, but we need to handle two forms. I would love if
    # these forms could post to separate pages and get redirected
    # back, but we're forced to keep the error/success workflow on the
    # same page. Please change this.
    if has_contribute_form:
        form = ContributeForm(request.POST)
        contribute_success = email_contribute.handle_form(request, form)
        if contribute_success:
            # If form was submitted successfully, return a new, empty
            # one.
            form = ContributeForm()
    else:
        form = ContributeForm()

    if has_newsletter_form:
        newsletter_form = NewsletterFooterForm(locale,
                                               request.POST,
                                               prefix='newsletter')
        if newsletter_form.is_valid():
            data = newsletter_form.cleaned_data

            try:
                basket.subscribe(data['email'],
                                 'about-mozilla',
                                 format=data['fmt'],
                                 country=data['country'])
                newsletter_success = True
            except basket.BasketException:
                msg = newsletter_form.error_class([
                    _('We apologize, but an error occurred in our system. '
                      'Please try again later.')
                ])
                newsletter_form.errors['__all__'] = msg
    else:
        newsletter_form = NewsletterFooterForm(locale, prefix='newsletter')

    return l10n_utils.render(
        request, template, {
            'form': form,
            'contribute_success': contribute_success,
            'newsletter_form': newsletter_form,
            'newsletter_success': newsletter_success,
            'return_to_form': return_to_form,
            'hide_form': hide_contrib_form(request.locale),
            'has_moz15': locale in settings.LOCALES_WITH_MOZ15
        })
Example #37
0
    def test_invalid_newsletter_is_error(self):
        """Invalid newsletter should not raise exception. Bug 1072302.

        Instead, an invalid newsletter name should manifest as a normal
        form error.
        """
        data = {
            "email": "*****@*****.**",
            "lang": "fr",
            "privacy": True,
            "fmt": "H",
            "newsletters": "",
        }
        form = NewsletterFooterForm("", locale="en-US", data=data.copy())
        self.assertFalse(form.is_valid())
        self.assertIn("newsletters", form.errors)
        self.assertEqual(form.errors["newsletters"], ["This field is required."])

        invalid_newsletter = "!nv@l1d"
        data = {
            "email": "*****@*****.**",
            "lang": "fr",
            "privacy": True,
            "fmt": "H",
            "newsletters": invalid_newsletter,
        }
        form = NewsletterFooterForm(invalid_newsletter, locale="en-US", data=data.copy())
        self.assertFalse(form.is_valid())
        self.assertIn("newsletters", form.errors)
        self.assertEqual(form.errors["newsletters"], ["Invalid Newsletter"])
Example #38
0
    def test_invalid_newsletter_is_error(self):
        """Invalid newsletter should not raise exception. Bug 1072302.

        Instead, an invalid newsletter name should manifest as a normal
        form error.
        """
        data = {
            'email': '*****@*****.**',
            'lang': 'fr',
            'privacy': True,
            'fmt': 'H',
            'newsletters': '',
        }
        form = NewsletterFooterForm('', locale='en-US', data=data.copy())
        self.assertFalse(form.is_valid())
        self.assertIn('newsletters', form.errors)
        self.assertEqual(form.errors['newsletters'],
                         [u'This field is required.'])

        invalid_newsletter = '!nv@l1d'
        data = {
            'email': '*****@*****.**',
            'lang': 'fr',
            'privacy': True,
            'fmt': 'H',
            'newsletters': invalid_newsletter,
        }
        form = NewsletterFooterForm(invalid_newsletter,
                                    locale='en-US',
                                    data=data.copy())
        self.assertFalse(form.is_valid())
        self.assertIn('newsletters', form.errors)
        self.assertEqual(form.errors['newsletters'], [u'Invalid Newsletter'])
Example #39
0
    def process_request(self, request):
        success = False
        form = NewsletterFooterForm(request.locale, request.POST or None)

        is_footer_form = (request.method == 'POST' and
                          'newsletter-footer' in request.POST)
        if is_footer_form:
            if form.is_valid():
                data = form.cleaned_data

                # If data['lang'] is set, pass it to the template.
                # If it's None, empty, or nonexistent, pass 'en'.
                request.newsletter_lang = data.get('lang', 'en').strip() \
                    or 'en'

                kwargs = {
                    'format': data['fmt'],
                }
                # add optional data
                kwargs.update(dict((k, data[k]) for k in ['country',
                                                          'lang',
                                                          'source_url']
                                   if data[k]))
                try:
                    basket.subscribe(data['email'], data['newsletter'],
                                     **kwargs)
                except basket.BasketException:
                    log.exception("Error subscribing %s to newsletter %s" %
                                  (data['email'], data['newsletter']))
                    msg = _lazy("We are sorry, but there was a problem "
                                "with our system. Please try again later!")
                    form.errors['__all__'] = form.error_class([msg])
                else:
                    success = True

        request.newsletter_form = form
        request.newsletter_success = success
Example #40
0
    def process_request(self, request):
        success = False
        form = NewsletterFooterForm(request.locale, request.POST or None)

        is_footer_form = (request.method == 'POST'
                          and 'newsletter-footer' in request.POST)
        if is_footer_form:
            if form.is_valid():
                data = form.cleaned_data

                # If data['lang'] is set, pass it to the template.
                # If it's None, empty, or nonexistent, pass 'en'.
                request.newsletter_lang = data.get('lang', 'en').strip() \
                    or 'en'

                kwargs = {
                    'format': data['fmt'],
                }
                # add optional data
                kwargs.update(
                    dict((k, data[k])
                         for k in ['country', 'lang', 'source_url']
                         if data[k]))
                try:
                    basket.subscribe(data['email'], data['newsletter'],
                                     **kwargs)
                except basket.BasketException:
                    log.exception("Error subscribing %s to newsletter %s" %
                                  (data['email'], data['newsletter']))
                    msg = _lazy("We are sorry, but there was a problem "
                                "with our system. Please try again later!")
                    form.errors['__all__'] = form.error_class([msg])
                else:
                    success = True

        request.newsletter_form = form
        request.newsletter_success = success
Example #41
0
def email_newsletter_form(ctx,
                          newsletters='mozilla-and-you',
                          title=None,
                          subtitle=None,
                          include_country=True,
                          include_language=True,
                          details=None,
                          use_thankyou=True,
                          thankyou_head=None,
                          thankyou_content=None,
                          footer=True,
                          process_form=True,
                          include_title=None,
                          submit_text=None,
                          button_class=None):
    request = ctx['request']
    context = ctx.get_all()

    success = bool(ctx.get('success'))
    if success and not use_thankyou:
        return

    form = ctx.get('newsletter_form', None)
    if not form:
        form = NewsletterFooterForm(newsletters, get_locale(request))

    context.update(
        dict(
            id=newsletters,
            title=title,
            subtitle=subtitle,  # nested in/depends on include_title
            include_country=include_country,
            include_language=include_language,
            details=details,
            use_thankyou=use_thankyou,
            thankyou_head=thankyou_head,
            thankyou_content=thankyou_content,
            footer=footer,
            include_title=include_title
            if include_title is not None else footer,
            form=form,
            submit_text=submit_text,
            button_class=button_class,
            success=success,
        ))

    html = jingo.render_to_string(request, 'newsletter/includes/form.html',
                                  context)
    return jinja2.Markup(html)
Example #42
0
    def test_invalid_newsletter_is_error(self):
        """Invalid newsletter should not raise exception. Bug 1072302.

        Instead, an invalid newsletter name should manifest as a normal
        form error.
        """
        data = {"email": "*****@*****.**", "lang": "fr", "privacy": True, "fmt": "H", "newsletters": ""}
        form = NewsletterFooterForm("", locale="en-US", data=data.copy())
        self.assertFalse(form.is_valid())
        self.assertIn("newsletters", form.errors)
        self.assertEqual(form.errors["newsletters"], [u"This field is required."])

        invalid_newsletter = "!nv@l1d"
        data = {
            "email": "*****@*****.**",
            "lang": "fr",
            "privacy": True,
            "fmt": "H",
            "newsletters": invalid_newsletter,
        }
        form = NewsletterFooterForm(invalid_newsletter, locale="en-US", data=data.copy())
        self.assertFalse(form.is_valid())
        self.assertIn("newsletters", form.errors)
        self.assertEqual(form.errors["newsletters"], [u"Invalid Newsletter"])
Example #43
0
    def test_multiple_newsletters(self):
        """Should allow to subscribe to multiple newsletters at a time."""
        newsletters = 'mozilla-and-you,beta'
        data = {
            'email': '*****@*****.**',
            'lang': 'en',
            'privacy': 'Y',
            'fmt': 'H',
        }
        form = NewsletterFooterForm(newsletters, 'en-US', data=data.copy())
        self.assertTrue(form.is_valid())
        self.assertEqual(form.cleaned_data['newsletters'], newsletters)

        # whitespace shouldn't matter
        form = NewsletterFooterForm('mozilla-and-you , beta ', 'en-US', data=data.copy())
        self.assertTrue(form.is_valid())
        self.assertEqual(form.cleaned_data['newsletters'], newsletters)
Example #44
0
    def test_multiple_newsletters(self):
        """Should allow to subscribe to multiple newsletters at a time."""
        newsletters = "mozilla-and-you,beta"
        data = {
            "email": "*****@*****.**",
            "lang": "en",
            "privacy": "Y",
            "fmt": "H",
            "newsletters": newsletters,
        }
        form = NewsletterFooterForm(newsletters, "en-US", data=data.copy())
        self.assertTrue(form.is_valid())
        self.assertEqual(form.cleaned_data["newsletters"], newsletters)

        # whitespace shouldn't matter
        form = NewsletterFooterForm("mozilla-and-you , beta ", "en-US", data=data.copy())
        self.assertTrue(form.is_valid())
        self.assertEqual(form.cleaned_data["newsletters"], newsletters)
Example #45
0
    def test_multiple_newsletters(self):
        newsletters = ["mozilla-and-you", "beta"]
        spacey_newsletters = [f" {n} " for n in newsletters]
        data = {
            "email": "*****@*****.**",
            "lang": "en",
            "privacy": "Y",
            "fmt": "H",
            "newsletters": newsletters,
        }
        form = NewsletterFooterForm(newsletters, "en-US", data=data.copy())
        self.assertTrue(form.is_valid(), form.errors)
        self.assertEqual(form.cleaned_data["newsletters"], newsletters)

        # whitespace shouldn't matter
        form = NewsletterFooterForm(spacey_newsletters, "en-US", data=data.copy())
        self.assertTrue(form.is_valid())
        self.assertEqual(form.cleaned_data["newsletters"], newsletters)
Example #46
0
 def test_privacy_required(self):
     """they have to check the privacy box"""
     data = {"email": "*****@*****.**", "privacy": False, "fmt": "H", "newsletters": self.newsletter_name}
     form = NewsletterFooterForm(self.newsletter_name, locale="en-US", data=data)
     self.assertFalse(form.is_valid())
     self.assertIn("privacy", form.errors)
Example #47
0
 def test_lang_default(self):
     """lang defaults based on the locale"""
     form = NewsletterFooterForm(self.newsletter_name, locale='pt-BR')
     self.assertEqual('pt', form.fields['lang'].initial)
Example #48
0
 def test_lang_default_not_supported(self):
     """lang defaults to blank if not supported by newsletter."""
     form = NewsletterFooterForm('beta', locale='pt-BR')
     self.assertEqual('', form.fields['lang'].initial)
Example #49
0
def contribute_friends(request):
    newsletter_form = NewsletterFooterForm('firefox-friends', l10n_utils.get_locale(request))

    return l10n_utils.render(request,
                             'mozorg/contribute/friends.html',
                             {'newsletter_form': newsletter_form})
Example #50
0
def contribute(request, template, return_to_form):
    newsletter_id = "about-mozilla"
    has_contribute_form = request.method == "POST" and "contribute-form" in request.POST

    has_newsletter_form = request.method == "POST" and "newsletter-form" in request.POST

    locale = getattr(request, "locale", "en-US")

    contribute_success = False
    newsletter_success = False

    # This is ugly, but we need to handle two forms. I would love if
    # these forms could post to separate pages and get redirected
    # back, but we're forced to keep the error/success workflow on the
    # same page. Please change this.
    if has_contribute_form:
        form = ContributeForm(request.POST)

        if form.is_valid():
            data = form.cleaned_data.copy()

            honeypot = data.pop("office_fax")

            if not honeypot:
                contribute_success = email_contribute.handle_form(request, form)
                if contribute_success:
                    # If form was submitted successfully, return a new, empty
                    # one.
                    form = ContributeForm()
            else:
                # send back a clean form if honeypot was filled in
                form = ContributeForm()
    else:
        form = ContributeForm()

    if has_newsletter_form:
        newsletter_form = NewsletterFooterForm(newsletter_id, locale, request.POST, prefix="newsletter")
        if newsletter_form.is_valid():
            data = newsletter_form.cleaned_data

            try:
                basket.subscribe(data["email"], newsletter_id, format=data["fmt"], country=data["country"])
                newsletter_success = True
            except basket.BasketException:
                msg = newsletter_form.error_class(
                    [_("We apologize, but an error occurred in our system. " "Please try again later.")]
                )
                newsletter_form.errors["__all__"] = msg
    else:
        newsletter_form = NewsletterFooterForm(newsletter_id, locale, prefix="newsletter")

    return l10n_utils.render(
        request,
        template,
        {
            "form": form,
            "contribute_success": contribute_success,
            "newsletter_form": newsletter_form,
            "newsletter_success": newsletter_success,
            "return_to_form": return_to_form,
            "hide_form": hide_contrib_form(request.locale),
        },
    )