Exemplo n.º 1
0
def all_downloads(request, channel):
    if channel is None:
        channel = "release"
    if channel == "developer":
        channel = "alpha"
    if channel == "organizations":
        channel = "esr"

    version = firefox_desktop.latest_version(channel)
    query = request.GET.get("q")

    channel_names = {
        "release": _("Firefox"),
        "beta": _("Firefox Beta"),
        "alpha": _("Developer Edition"),
        "esr": _("Firefox Extended Support Release"),
    }

    context = {
        "full_builds_version": version.split(".", 1)[0],
        "full_builds": firefox_desktop.get_filtered_full_builds(channel, version, query),
        "test_builds": firefox_desktop.get_filtered_test_builds(channel, version, query),
        "query": query,
        "channel": channel,
        "channel_name": channel_names[channel],
    }

    if channel == "esr":
        next_version = firefox_desktop.latest_version("esr_next")
        if next_version:
            context["full_builds_next_version"] = next_version.split(".", 1)[0]
            context["full_builds_next"] = firefox_desktop.get_filtered_full_builds("esr_next", next_version, query)
            context["test_builds_next"] = firefox_desktop.get_filtered_test_builds("esr_next", next_version, query)
    return l10n_utils.render(request, "firefox/all.html", context)
Exemplo n.º 2
0
class PrivacyContactForm(forms.Form):
    name = forms.CharField(
        required=True,
        error_messages={
            'required': _('This field is required, please enter your name.')
        },
        widget=forms.TextInput(attrs={'required': 'required'}))
    sender = forms.EmailField(
        required=True,
        error_messages={
            'required':
            _('This field is required, please enter your email address.')
        },
        widget=EmailInput(attrs={
            'required': 'required',
            'placeholder': '*****@*****.**'
        }))
    comments = forms.CharField(
        required=True,
        error_messages={
            'required':
            _('This field is required, please enter your comments or questions.'
              )
        },
        widget=forms.Textarea(
            attrs={
                'required': 'required',
                'placeholder': 'Enter your comments...',
                'rows': '10',
                'cols': '77'
            }))
    superpriority = forms.BooleanField(widget=HoneyPotWidget, required=False)
Exemplo n.º 3
0
def format_tweet_timestamp(tweet):
    """
    Return an HTML time element filled with a tweet timestamp.

    @param tweet: A Tweepy Status object retrieved with the Twitter REST API.

    For a tweet posted within the last 24 hours, the timestamp label should be
    a relative format like "20s", "3m" or 5h", otherwise it will be a simple
    date like "6 Jun". See the Display Requirements for details:
    https://dev.twitter.com/terms/display-requirements
    """
    now = datetime.utcnow()
    created = tweet.created_at  # A datetime object
    diff = now - created  # A timedelta Object

    if diff.days == 0:
        if diff.seconds < 60:
            label = _('%ds') % diff.seconds
        elif diff.seconds < 60 * 60:
            label = _('%dm') % round(diff.seconds / 60)
        else:
            label = _('%dh') % round(diff.seconds / 60 / 60)
    else:
        label = created.strftime("%-d %b")

    full = created.strftime("%Y-%m-%d %H:%M")

    return ('<time datetime="%s" title="%s" itemprop="dateCreated">%s '
            '<span class="full">(%s)</span></time>'
            % (created.isoformat(), full, label, full))
Exemplo n.º 4
0
def newsletter_subscribe(request):
    if request.method == 'POST':
        newsletters = request.POST.get('newsletters', None)
        form = NewsletterFooterForm(newsletters,
                                    l10n_utils.get_locale(request),
                                    request.POST)
        errors = []
        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',
                                                      'first_name',
                                                      'last_name', ]
                               if data[k]))
            try:
                basket.subscribe(data['email'], data['newsletters'],
                                 **kwargs)
            except basket.BasketException as e:
                if e.code == basket.errors.BASKET_INVALID_EMAIL:
                    errors.append(unicode(invalid_email_address))
                else:
                    log.exception("Error subscribing %s to newsletter %s" %
                                  (data['email'], data['newsletters']))
                    errors.append(unicode(general_error))

        else:
            if 'email' in form.errors:
                errors.append(_('Please enter a valid email address'))
            if 'privacy' in form.errors:
                errors.append(_('You must agree to the privacy notice'))
            for fieldname in ('fmt', 'lang', 'country'):
                if fieldname in form.errors:
                    errors.extend(form.errors[fieldname])

        # form error messages may contain unsanitized user input
        errors = map(escape, errors)

        if request.is_ajax():
            # return JSON
            if errors:
                resp = {
                    'success': False,
                    'errors': errors,
                }
            else:
                resp = {'success': True}

            return HttpResponseJSON(resp)
        else:
            ctx = {'newsletter_form': form}
            if not errors:
                ctx['success'] = True

            return l10n_utils.render(request, 'newsletter/mozilla-and-you.html', ctx)

    return l10n_utils.render(request, 'newsletter/mozilla-and-you.html')
Exemplo n.º 5
0
class PrivacyContactForm(forms.Form):
    sender = forms.EmailField(
        required=True,
        error_messages={
            'required': _('This field is required, please enter your email address.')
        },
        widget=EmailInput(
            attrs={
                'required': 'required',
                'placeholder': _('*****@*****.**')
            }))
    comments = forms.CharField(
        required=True,
        error_messages={
            'required': _('This field is required, please enter your comments or questions.')
        },
        widget=forms.Textarea(
            attrs={
                'required': 'required',
                'placeholder': _('Enter your comments...'),
                'rows': '10',
                'cols': '77'
            }))
    # honeypot
    office_fax = forms.CharField(
        widget=HoneyPotWidget,
        required=False)
Exemplo n.º 6
0
def all_downloads(request, channel):
    if channel is None:
        channel = 'release'

    if channel == 'organizations':
        channel = 'esr'

    version = get_latest_version('firefox', channel)
    query = request.GET.get('q')

    channel_names = {
        'release': _('Firefox'),
        'beta': _('Firefox Beta'),
        'aurora': _('Firefox Aurora'),
        'esr': _('Firefox Extended Support Release'),
    }

    context = {
        'full_builds_version': version.split('.', 1)[0],
        'full_builds': firefox_details.get_filtered_full_builds(version, query),
        'test_builds': firefox_details.get_filtered_test_builds(version, query),
        'query': query,
        'channel': channel,
        'channel_name': channel_names[channel]
    }

    if channel == 'esr':
        next_version = get_latest_version('firefox', 'esr_next')
        if next_version:
            context['full_builds_next_version'] = next_version.split('.', 1)[0]
            context['full_builds_next'] = firefox_details.get_filtered_full_builds(next_version,
                                                                                   query)
            context['test_builds_next'] = firefox_details.get_filtered_test_builds(next_version,
                                                                                   query)
    return l10n_utils.render(request, 'firefox/all.html', context)
Exemplo n.º 7
0
def all_downloads(request, channel):
    if channel is None:
        channel = "release"

    if channel == "organizations":
        channel = "esr"

    version = get_latest_version("firefox", channel)
    query = request.GET.get("q")

    channel_names = {
        "release": _("Firefox"),
        "beta": _("Firefox Beta"),
        "aurora": _("Firefox Aurora"),
        "esr": _("Firefox Extended Support Release"),
    }

    return l10n_utils.render(
        request,
        "firefox/all.html",
        {
            "full_builds": firefox_details.get_filtered_full_builds(version, query),
            "test_builds": firefox_details.get_filtered_test_builds(version, query),
            "query": query,
            "channel": channel,
            "channel_name": channel_names[channel],
        },
    )
Exemplo n.º 8
0
def all_downloads(request, channel):
    if channel is None:
        channel = 'release'

    if channel == 'organizations':
        channel = 'esr'

    version = get_latest_version('firefox', channel)
    query = request.GET.get('q')

    channel_names = {
        'release': _('Firefox'),
        'beta': _('Firefox Beta'),
        'aurora': _('Firefox Aurora'),
        'esr': _('Firefox Extended Support Release'),
    }

    return l10n_utils.render(
        request, 'firefox/all.html', {
            'full_builds': firefox_details.get_filtered_full_builds(
                version, query),
            'test_builds': firefox_details.get_filtered_test_builds(
                version, query),
            'query': query,
            'channel': channel,
            'channel_name': channel_names[channel],
        })
Exemplo n.º 9
0
def newsletter_subscribe(request):
    if request.method == 'POST':
        newsletters = request.POST.get('newsletters', None)
        form = NewsletterFooterForm(newsletters,
                                    l10n_utils.get_locale(request),
                                    request.POST)
        errors = []
        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',
                                                      'first_name',
                                                      'last_name', ]
                               if data[k]))
            try:
                basket.subscribe(data['email'], data['newsletters'],
                                 **kwargs)
            except basket.BasketException as e:
                if e.code == basket.errors.BASKET_INVALID_EMAIL:
                    errors.append(unicode(invalid_email_address))
                else:
                    log.exception("Error subscribing %s to newsletter %s" %
                                  (data['email'], data['newsletters']))
                    errors.append(unicode(general_error))

        else:
            if 'email' in form.errors:
                errors.append(_('Please enter a valid email address'))
            if 'privacy' in form.errors:
                errors.append(_('You must agree to the privacy notice'))
            for fieldname in ('fmt', 'lang', 'country'):
                if fieldname in form.errors:
                    errors.extend(form.errors[fieldname])

        # form error messages may contain unsanitized user input
        errors = map(escape, errors)

        if request.is_ajax():
            # return JSON
            if errors:
                resp = {
                    'success': False,
                    'errors': errors,
                }
            else:
                resp = {'success': True}

            return HttpResponseJSON(resp)
        else:
            ctx = {'newsletter_form': form}
            if not errors:
                ctx['success'] = True

            return l10n_utils.render(request, 'newsletter/mozilla-and-you.html', ctx)

    return l10n_utils.render(request, 'newsletter/mozilla-and-you.html')
Exemplo n.º 10
0
def format_tweet_timestamp(tweet):
    """
    Return an HTML time element filled with a tweet timestamp.

    @param tweet: A Tweepy Status object retrieved with the Twitter REST API.

    For a tweet posted within the last 24 hours, the timestamp label should be
    a relative format like "20s", "3m" or 5h", otherwise it will be a simple
    date like "6 Jun". See the Display Requirements for details:
    https://dev.twitter.com/terms/display-requirements
    """
    now = datetime.utcnow()
    created = tweet.created_at  # A datetime object
    diff = now - created  # A timedelta Object

    if diff.days == 0:
        if diff.seconds < 60:
            label = _('%ds') % diff.seconds
        elif diff.seconds < 60 * 60:
            label = _('%dm') % round(diff.seconds / 60)
        else:
            label = _('%dh') % round(diff.seconds / 60 / 60)
    else:
        label = created.strftime("%-d %b")

    full = created.strftime("%Y-%m-%d %H:%M")

    return ('<time datetime="%s" title="%s" itemprop="dateCreated">%s '
            '<span class="full">(%s)</span></time>' %
            (created.isoformat(), full, label, full))
Exemplo n.º 11
0
 def test_new_lang_files_do_not_modify_settings(self, trans_patch):
     """
     Test to make sure that building the new lang files list does not
     modify `settings.DOTLANG_FILES`.
     """
     old_setting = settings.DOTLANG_FILES[:]
     trans_str = 'Translate me'
     _(trans_str)
     call_lang_files = [LANG_FILES] + settings.DOTLANG_FILES
     trans_patch.assert_called_with(trans_str, call_lang_files)
     eq_(old_setting, settings.DOTLANG_FILES)
Exemplo n.º 12
0
 def test_new_lang_files_do_not_modify_settings(self, trans_patch):
     """
     Test to make sure that building the new lang files list does not
     modify `settings.DOTLANG_FILES`.
     """
     old_setting = settings.DOTLANG_FILES[:]
     trans_str = 'Translate me'
     _(trans_str)
     call_lang_files = [LANG_FILES] + settings.DOTLANG_FILES
     trans_patch.assert_called_with(trans_str, call_lang_files)
     eq_(old_setting, settings.DOTLANG_FILES)
Exemplo n.º 13
0
    def form_valid(self, form):
        try:
            basket.request('post', 'get-involved', self.get_basket_data(form))
        except basket.BasketException as e:
            if e.code == basket.errors.BASKET_INVALID_EMAIL:
                msg = _(u'Whoops! Be sure to enter a valid email address.')
                field = 'email'
            else:
                msg = _(u'We apologize, but an error occurred in our system. '
                        u'Please try again later.')
                field = '__all__'
            form.errors[field] = form.error_class([msg])
            return self.form_invalid(form)

        return super(ContributeTasksSurvey, self).form_valid(form)
Exemplo n.º 14
0
    def platforms(self, channel='release'):
        platforms = self.platform_labels.copy()
        major_version = int(self.latest_version(channel).split('.', 1)[0])

        # Android Gingerbread (2.3) is no longer supported as of Firefox 48
        if major_version >= 48:
            platforms['android'] = _('ARM devices\n(Android 4.0.3+)')
            platforms['android-x86'] = _('Intel devices\n(Android 4.0.3+ x86 CPU)')
            del platforms['android-api-9']

        # Android Honeycomb (3.x) was supported on Firefox 45 and below
        if major_version <= 45:
            platforms['android'] = _('Modern devices\n(Android 3.0+)')

        return platforms.items()
Exemplo n.º 15
0
    def form_valid(self, form):
        try:
            basket.request('post', 'get-involved', self.get_basket_data(form))
        except basket.BasketException as e:
            if e.code == basket.errors.BASKET_INVALID_EMAIL:
                msg = _(u'Whoops! Be sure to enter a valid email address.')
                field = 'email'
            else:
                msg = _(u'We apologize, but an error occurred in our system. '
                        u'Please try again later.')
                field = '__all__'
            form.errors[field] = form.error_class([msg])
            return self.form_invalid(form)

        return super(ContributeTasksSurvey, self).form_valid(form)
Exemplo n.º 16
0
    def clean_office_fax(self):
        cleaned_data = super(SpeakerRequestForm, self).clean()
        honeypot = cleaned_data.pop('office_fax', None)

        if honeypot:
            raise forms.ValidationError(
                _('Your submission could not be processed'))
Exemplo n.º 17
0
    def clean_office_fax(self):
        cleaned_data = super(PressInquiryForm, self).clean()
        honeypot = cleaned_data.pop('office_fax', None)

        if honeypot:
            raise forms.ValidationError(
                _('Your submission could not be processed'))
Exemplo n.º 18
0
 def clean(self, *args, **kwargs):
     super(ContributeUniversityAmbassadorForm, self).clean(*args, **kwargs)
     if self.cleaned_data.get("current_status", "") == "student" and not self.cleaned_data.get(
         "expected_graduation_year", ""
     ):
         self._errors["expected_graduation_year"] = self.error_class([_("This field is required.")])
     return self.cleaned_data
Exemplo n.º 19
0
    def clean_superpriority(self):
        cleaned_data = super(FraudReportForm, self).clean()
        honeypot = cleaned_data.pop('superpriority', None)

        if honeypot:
            raise forms.ValidationError(
                _('Your submission could not be processed'))
Exemplo n.º 20
0
class USPhoneNumberField(forms.CharField):
    """
    A form field that validates input as a U.S. phone number.
    """
    default_error_messages = {
        'invalid':
        _("Sorry. This number isn't valid. Please enter a U.S. phone "
          'number or <a href="%s">'
          'download directly from Google Play.</a>') % 'http://mzl.la/OgZo6k',
    }

    def __init__(self, *args, **kwargs):
        kwargs.setdefault('max_length', 14)
        super(USPhoneNumberField, self).__init__(*args, **kwargs)

    def clean(self, value):
        super(USPhoneNumberField, self).clean(value)
        if value in EMPTY_VALUES:
            return ''

        value = re.sub(r'\D+', '', smart_text(value))
        if len(value) == 10:
            value = '1' + value
        elif len(value) != 11 or value[0] != '1':
            raise forms.ValidationError(self.error_messages['invalid'])

        return value
Exemplo n.º 21
0
def sms_send(request):
    form = SMSSendForm(request.POST or None)
    if request.method == "POST":
        error_msg = _("An error occurred in our system. Please try again later.")
        error = None
        if form.is_valid():
            try:
                basket.send_sms(form.cleaned_data["number"], SMS_MESSAGES["android"], form.cleaned_data["optin"])
            except basket.BasketException:
                error = error_msg

        else:
            number_errors = form.errors.get("number")
            if number_errors:
                # form error messages may contain unsanitized user input
                error = escape(number_errors[0])
            else:
                error = error_msg

        if request.is_ajax():
            # return JSON
            if error:
                resp = {"success": False, "error": error}
            else:
                resp = {"success": True}

            return HttpResponseJSON(resp)
        else:
            if error:
                form.errors["__all__"] = form.error_class([error])
            else:
                return HttpResponseRedirect(reverse("firefox.android.sms-thankyou"))

    return l10n_utils.render(request, "firefox/android/sms-send.html", {"sms_form": form})
Exemplo n.º 22
0
 def __init__(self, *args, **kwargs):
     locale = kwargs.get("locale", "en-US")
     super(ContributeUniversityAmbassadorForm, self).__init__(*args, **kwargs)
     country_list = product_details.get_regions(locale).items()
     country_list = sorted(country_list, key=lambda country: country[1])
     country_list.insert(0, ("", _("Country")))
     self.fields["country"].choices = country_list
Exemplo n.º 23
0
    def platforms(self, channel='release'):
        platforms = self.platform_labels.copy()
        major_version = int(self.latest_version(channel).split('.', 1)[0])

        # Android Gingerbread (2.3) is no longer supported as of Firefox 48
        if major_version >= 48:
            platforms['android'] = _('ARM devices\n(Android 4.0.3+)')
            platforms['android-x86'] = _(
                'Intel devices\n(Android 4.0.3+ x86 CPU)')
            del platforms['android-api-9']

        # Android Honeycomb (3.x) was supported on Firefox 45 and below
        if major_version <= 45:
            platforms['android'] = _('Modern devices\n(Android 3.0+)')

        return platforms.items()
Exemplo n.º 24
0
 def clean(self, *args, **kwargs):
     super(ContributeUniversityAmbassadorForm, self).clean(*args, **kwargs)
     if (self.cleaned_data.get('current_status', '') == 'student'
             and not self.cleaned_data.get('expected_graduation_year', '')):
         self._errors['expected_graduation_year'] = (
             self.error_class([_('This field is required.')]))
     return self.cleaned_data
Exemplo n.º 25
0
 def clean(self):
     valid_newsletters = utils.get_newsletters()
     for newsletter in self.newsletters:
         if newsletter not in valid_newsletters:
             msg = _("%s is not a valid newsletter") % newsletter
             raise ValidationError(msg)
     return super(ManageSubscriptionsForm, self).clean()
Exemplo n.º 26
0
 def __init__(self, *args, **kwargs):
     locale = kwargs.get('locale', 'en-US')
     super(ContributeUniversityAmbassadorForm, self).__init__(*args, **kwargs)
     country_list = product_details.get_regions(locale).items()
     country_list = sorted(country_list, key=lambda country: country[1])
     country_list.insert(0, ('', _('Country')))
     self.fields['country'].choices = country_list
Exemplo n.º 27
0
 def clean(self, *args, **kwargs):
     super(ContributeStudentAmbassadorForm, self).clean(*args, **kwargs)
     if (self.cleaned_data.get('status', '') == 'student'
             and not self.cleaned_data.get('grad_year', '')):
         self._errors['grad_year'] = (
             self.error_class([_('This field is required.')]))
     return self.cleaned_data
Exemplo n.º 28
0
 def clean(self, *args, **kwargs):
     super(ContributeUniversityAmbassadorForm, self).clean(*args, **kwargs)
     if (self.cleaned_data.get('current_status', '') == 'student'
             and not self.cleaned_data.get('expected_graduation_year', '')):
         self._errors['expected_graduation_year'] = (self.error_class(
             [_('This field is required.')]))
     return self.cleaned_data
Exemplo n.º 29
0
 def clean(self, *args, **kwargs):
     super(ContributeStudentAmbassadorForm, self).clean(*args, **kwargs)
     if (self.cleaned_data.get('status', '') == 'student'
             and not self.cleaned_data.get('grad_year', '')):
         self._errors['grad_year'] = (self.error_class(
             [_('This field is required.')]))
     return self.cleaned_data
Exemplo n.º 30
0
def autorespond(request, data):
    """Send an auto-respond email based on chosen field of interest and locale.

    You can add localized responses by creating email messages in
    mozorg/emails/<category.txt>
    """
    functional_area = FUNCTIONAL_AREAS_DICT[data['interest']]

    subject = _('Welcome to Mozilla!')
    to = [data['email']]
    from_ = '*****@*****.**'
    reply_to = ['*****@*****.**']
    headers = {}
    msg = ''

    template = 'mozorg/emails/%s.txt' % functional_area.id
    if request.locale != 'en-US' and request.locale in LOCALE_CONTACTS:
        template = '%s/templates/%s' % (request.locale, template)
        reply_to += LOCALE_CONTACTS[request.locale]
    else:
        reply_to += functional_area.contacts

    try:
        msg = jingo.render_to_string(request, template, data)
    except TemplateNotFound:
        # No template found means no auto-response
        return False

    # FIXME Why ?
    msg = msg.replace('\n', '\r\n')
    headers = {'Reply-To': ','.join(reply_to)}

    email = EmailMessage(subject, msg, from_, to, headers=headers)
    email.send()
Exemplo n.º 31
0
    def _get_filtered_builds(self, builds, channel, version=None, query=None):
        """
        Get a list of builds, sorted by english locale name, for a specific
        Firefox version.
        :param builds: a build dict from the JSON
        :param channel: one of self.version_map.keys().
        :param version: a firefox version. one of self.latest_versions.
        :param query: a string to match against native or english locale name
        :return: list
        """
        product = self.product_map.get(channel, 'fennec-latest')
        locales = [build['locale']['code'] for build in builds]
        f_builds = []

        # Prepend multi-locale build
        locales.sort()
        locales.insert(0, 'multi')

        for locale in locales:
            if locale == 'multi':
                name_en = _('Multi-locale')
                name_native = ''
            elif locale in self.languages:
                name_en = self.languages[locale]['English']
                name_native = self.languages[locale]['native']
            else:
                continue

            build_info = {
                'locale': locale,
                'name_en': name_en,
                'name_native': name_native,
                'platforms': {},
            }

            # only include builds that match a search query
            if query is not None and not self._matches_query(
                    build_info, query):
                continue

            for arch, label in self.platform_labels.iteritems():
                # x86 builds are not localized yet
                if arch == 'android-x86' and locale not in ['multi', 'en-US']:
                    continue

                params = urlencode([
                    ('product', product),
                    ('os', arch),
                    # Order matters, lang must be last for bouncer.
                    ('lang', locale),
                ])

                build_info['platforms'][arch] = {
                    'download_url': '?'.join([self.bouncer_url, params])
                }

            f_builds.append(build_info)

        return f_builds
Exemplo n.º 32
0
    def test_gettext_searches_kwarg_specified_lang_files(self, trans_patch):
        """
        The `l10n_utils.dotlang._` function should search .lang files
        specified in the `lang_files` keyword arg, and not the ones from the
        module.
        """
        # test the case when LANG_FILES is a string
        trans_str = 'Translate me'
        _(trans_str, lang_files='maude')
        call_lang_files = ['maude'] + settings.DOTLANG_FILES
        trans_patch.assert_called_with(trans_str, call_lang_files)

        # test the case when LANG_FILES is a list
        lang_files_list = ['maude', 'bunny', 'uli']
        _(trans_str, lang_files=lang_files_list)
        call_lang_files = lang_files_list + settings.DOTLANG_FILES
        trans_patch.assert_called_with(trans_str, call_lang_files)
Exemplo n.º 33
0
 def __init__(self, *args, **kwargs):
     locale = kwargs.get('locale', 'en-US')
     super(ContributeUniversityAmbassadorForm,
           self).__init__(*args, **kwargs)
     country_list = product_details.get_regions(locale).items()
     country_list = sorted(country_list, key=lambda country: country[1])
     country_list.insert(0, ('', _('Country')))
     self.fields['country'].choices = country_list
Exemplo n.º 34
0
    def test_gettext_searches_kwarg_specified_lang_files(self, trans_patch):
        """
        The `l10n_utils.dotlang._` function should search .lang files
        specified in the `lang_files` keyword arg, and not the ones from the
        module.
        """
        # test the case when LANG_FILES is a string
        trans_str = 'Translate me'
        _(trans_str, lang_files='maude')
        call_lang_files = ['maude'] + settings.DOTLANG_FILES
        trans_patch.assert_called_with(trans_str, call_lang_files)

        # test the case when LANG_FILES is a list
        lang_files_list = ['maude', 'bunny', 'uli']
        _(trans_str, lang_files=lang_files_list)
        call_lang_files = lang_files_list + settings.DOTLANG_FILES
        trans_patch.assert_called_with(trans_str, call_lang_files)
Exemplo n.º 35
0
    def platforms(self, channel='release'):
        platforms = self.platform_labels.copy()

        # Android Honeycomb (3.x) was supported on Firefox 45 and below
        if int(self.latest_version(channel).split('.', 1)[0]) < 46:
            platforms['android'] = _('Modern devices\n(Android 3.0+)')

        return platforms.items()
Exemplo n.º 36
0
    def platforms(self, channel='release'):
        platforms = self.platform_labels.copy()

        # Android Honeycomb (3.x) was supported on Firefox 45 and below
        if int(self.latest_version(channel).split('.', 1)[0]) < 46:
            platforms['android'] = _('Modern devices\n(Android 3.0+)')

        return platforms.items()
Exemplo n.º 37
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
        })
Exemplo n.º 38
0
    def _get_filtered_builds(self, builds, channel, version=None, query=None):
        """
        Get a list of builds, sorted by english locale name, for a specific
        Firefox version.
        :param builds: a build dict from the JSON
        :param channel: one of self.version_map.keys().
        :param version: a firefox version. one of self.latest_versions.
        :param query: a string to match against native or english locale name
        :return: list
        """
        product = self.product_map.get(channel, 'fennec-latest')
        locales = [build['locale']['code'] for build in builds]
        f_builds = []

        # Prepend multi-locale build
        locales.sort()
        locales.insert(0, 'multi')

        for locale in locales:
            if locale == 'multi':
                name_en = _('Multi-locale')
                name_native = ''
            elif locale in self.languages:
                name_en = self.languages[locale]['English']
                name_native = self.languages[locale]['native']
            else:
                continue

            build_info = {
                'locale': locale,
                'name_en': name_en,
                'name_native': name_native,
                'platforms': {},
            }

            # only include builds that match a search query
            if query is not None and not self._matches_query(build_info, query):
                continue

            for arch, label in self.platform_labels.iteritems():
                # x86 builds are not localized yet
                if arch == 'android-x86' and locale not in ['multi', 'en-US']:
                    continue

                params = urlencode([
                    ('product', product),
                    ('os', arch),
                    # Order matters, lang must be last for bouncer.
                    ('lang', locale),
                ])

                build_info['platforms'][arch] = {
                    'download_url': '?'.join([self.bouncer_url, params])
                }

            f_builds.append(build_info)

        return f_builds
Exemplo n.º 39
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})
Exemplo n.º 40
0
    def test_gettext_ignores_default_lang_files(self, trans_patch):
        """
        The `l10n_utils.dotlang._` function should search .lang files
        specified in the module from which it's called before the
        default files, but it should not include the defaults twice.
        """
        # use LANG_FILES global in this module
        global LANG_FILES
        old_lang_files = LANG_FILES

        trans_str = 'Translate me'
        LANG_FILES = [settings.DOTLANG_FILES[0], 'dude', 'donnie', 'walter']
        _(trans_str)
        call_lang_files = LANG_FILES[1:] + settings.DOTLANG_FILES
        trans_patch.assert_called_with(trans_str, call_lang_files)

        # restore original value to avoid test leakage
        LANG_FILES = old_lang_files
Exemplo n.º 41
0
    def clean_input_attachment(self):
        attachment = self.cleaned_data.get("input_attachment")

        if attachment:
            if attachment.size > FRAUD_REPORT_FILE_SIZE_LIMIT:
                raise forms.ValidationError(
                    _("Attachment must not exceed 5MB"))

        return attachment
Exemplo n.º 42
0
    def test_gettext_ignores_default_lang_files(self, trans_patch):
        """
        The `l10n_utils.dotlang._` function should search .lang files
        specified in the module from which it's called before the
        default files, but it should not include the defaults twice.
        """
        # use LANG_FILES global in this module
        global LANG_FILES
        old_lang_files = LANG_FILES

        trans_str = 'Translate me'
        LANG_FILES = [settings.DOTLANG_FILES[0], 'dude', 'donnie', 'walter']
        _(trans_str)
        call_lang_files = LANG_FILES[1:] + settings.DOTLANG_FILES
        trans_patch.assert_called_with(trans_str, call_lang_files)

        # restore original value to avoid test leakage
        LANG_FILES = old_lang_files
Exemplo n.º 43
0
    def clean_sr_attachment(self):
        cleaned_data = super().clean()
        attachment = cleaned_data.get("sr_attachment")

        if attachment:
            if attachment.size > SPEAKER_REQUEST_FILE_SIZE_LIMIT:
                raise forms.ValidationError(_("Attachment must not exceed 5MB"))

        return attachment
Exemplo n.º 44
0
    def clean_input_attachment(self):
        attachment = self.cleaned_data.get("input_attachment")

        if attachment:
            if attachment.size > FRAUD_REPORT_FILE_SIZE_LIMIT:
                raise forms.ValidationError(
                    _("Attachment must not exceed 5MB"))

        return attachment
Exemplo n.º 45
0
def all_downloads(request, channel):
    if channel is None:
        channel = 'release'
    if channel == 'developer':
        channel = 'alpha'
    if channel == 'organizations':
        channel = 'esr'

    version = firefox_desktop.latest_version(channel)
    query = request.GET.get('q')

    channel_names = {
        'release': _('Firefox'),
        'beta': _('Firefox Beta'),
        'alpha': _('Developer Edition'),
        'esr': _('Firefox Extended Support Release'),
    }

    context = {
        'full_builds_version':
        version.split('.', 1)[0],
        'full_builds':
        firefox_desktop.get_filtered_full_builds(channel, version, query),
        'test_builds':
        firefox_desktop.get_filtered_test_builds(channel, version, query),
        'query':
        query,
        'channel':
        channel,
        'channel_name':
        channel_names[channel]
    }

    if channel == 'esr':
        next_version = firefox_desktop.latest_version('esr_next')
        if next_version:
            context['full_builds_next_version'] = next_version.split('.', 1)[0]
            context[
                'full_builds_next'] = firefox_desktop.get_filtered_full_builds(
                    'esr_next', next_version, query)
            context[
                'test_builds_next'] = firefox_desktop.get_filtered_test_builds(
                    'esr_next', next_version, query)
    return l10n_utils.render(request, 'firefox/all.html', context)
Exemplo n.º 46
0
 def render(self, name, value, attrs=None):
     honeypot_txt = _(u'Check this box if you are not human.')
     # semi-randomized in case we have more than one per page.
     # this is maybe/probably overthought
     honeypot_id = 'super-priority-' + str(randrange(1001)) + '-' + str(datetime.now().strftime("%Y%m%d%H%M%S%f"))
     return mark_safe(
         '<div class="super-priority-field">'
         '<label for="%s" class="super-priority-check-label">%s</label>'
         '<input type="checkbox" name="superpriority" id="%s">'
         '</div>' % (honeypot_id, honeypot_txt, honeypot_id))
Exemplo n.º 47
0
    def clean_input_attachment(self):
        cleaned_data = super(FraudReportForm, self).clean()
        attachment = cleaned_data.get("input_attachment")

        if attachment:
            if attachment._size > FRAUD_REPORT_FILE_SIZE_LIMIT:
                raise forms.ValidationError(
                    _("Attachment must not exceed 5MB"))

        return attachment
Exemplo n.º 48
0
 def render(self, name, value, attrs=None):
     honeypot_txt = _(u'Check this box if you are not human.')
     # semi-randomized in case we have more than one per page.
     # this is maybe/probably overthought
     honeypot_id = 'super-priority-' + str(randrange(1001)) + '-' + str(datetime.now().strftime("%Y%m%d%H%M%S%f"))
     return mark_safe(
         '<div class="super-priority-field">'
         '<label for="%s" class="super-priority-check-label">%s</label>'
         '<input type="checkbox" name="superpriority" id="%s">'
         '</div>' % (honeypot_id, honeypot_txt, honeypot_id))
Exemplo n.º 49
0
    def clean_sr_attachment(self):
        cleaned_data = super(SpeakerRequestForm, self).clean()
        attachment = cleaned_data.get("sr_attachment")

        if attachment:
            if attachment._size > SPEAKER_REQUEST_FILE_SIZE_LIMIT:
                raise forms.ValidationError(
                    _("Attachment must not exceed 5MB"))

        return attachment
Exemplo n.º 50
0
 def render(self, name, value, attrs=None):
     honeypot_txt = _(u'Leave this field empty.')
     # semi-randomized in case we have more than one per page.
     # this is maybe/probably overthought
     honeypot_id = 'office-fax-' + str(randrange(1001)) + '-' + str(
         datetime.now().strftime("%Y%m%d%H%M%S%f"))
     return mark_safe('<div class="super-priority-field">'
                      '<label for="%s">%s</label>'
                      '<input type="text" name="office_fax" id="%s">'
                      '</div>' % (honeypot_id, honeypot_txt, honeypot_id))
Exemplo n.º 51
0
 def render(self, name, value, attrs=None):
     honeypot_txt = _(u'Leave this field empty.')
     # semi-randomized in case we have more than one per page.
     # this is maybe/probably overthought
     honeypot_id = 'office-fax-' + str(randrange(1001)) + '-' + str(datetime.now().strftime("%Y%m%d%H%M%S%f"))
     return mark_safe(
         '<div class="super-priority-field">'
         '<label for="%s">%s</label>'
         '<input type="text" name="office_fax" id="%s">'
         '</div>' % (honeypot_id, honeypot_txt, honeypot_id))
Exemplo n.º 52
0
 def get_context_data(self, **kwargs):
     cxt = super(ContributeSignup, self).get_context_data(**kwargs)
     cxt['category_info'] = {
         'coding': _('More about coding'),
         'testing': _('More about testing'),
         'writing': _('More about writing'),
         'teaching': _('More about teaching'),
         'helping': _('More about helping'),
         'translating': _('More about translating'),
         'activism': _('More about activism'),
         'dontknow': _('More about how you can contribute'),
     }
     return cxt
Exemplo n.º 53
0
def sms_send(request):
    form = SMSSendForm(request.POST or None)
    if request.method == "POST" and form.is_valid():
        try:
            basket.send_sms(form.cleaned_data["number"], "SMS_Android", form.cleaned_data["optin"])
        except basket.BasketException:
            msg = form.error_class([_("An error occurred in our system. " "Please try again later.")])
            form.errors["__all__"] = msg
        else:
            return HttpResponseRedirect(reverse("firefox.mobile.sms-thankyou"))
    return l10n_utils.render(request, "firefox/mobile/sms-send.html", {"sms_form": form})
Exemplo n.º 54
0
    def render(self, name, value, attrs=None):
        attrs['required'] = 'required'
        input_txt = super(PrivacyWidget, self).render(name, value, attrs)

        policy_txt = _(u'I’m okay with you handling this info as you explain '
                       u'in your <a href="%s">Privacy Policy</a>')
        return mark_safe(
            '<label for="%s" class="privacy-check-label">'
            '%s '
            '<span class="title">%s</span></label>' %
            (attrs['id'], input_txt, policy_txt % '/en-US/privacy-policy'))
Exemplo n.º 55
0
 def get_context_data(self, **kwargs):
     cxt = super(ContributeSignup, self).get_context_data(**kwargs)
     cxt['category_info'] = {
         'coding': _('More about coding'),
         'testing': _('More about testing'),
         'writing': _('More about writing'),
         'teaching': _('More about teaching'),
         'helping': _('More about helping'),
         'translating': _('More about translating'),
         'activism': _('More about activism'),
         'dontknow': _('More about how you can contribute'),
     }
     return cxt
Exemplo n.º 56
0
    def render(self, name, value, attrs=None):
        attrs['required'] = 'required'
        input_txt = super(PrivacyWidget, self).render(name, value, attrs)

        policy_txt = _(u'I’m okay with Mozilla handling my info as explained '
                       u'in <a href="%s">this Privacy Notice</a>')
        return mark_safe('<label for="%s" class="privacy-check-label">'
                         '%s '
                         '<span class="title">%s</span></label>' %
                         (attrs['id'], input_txt,
                          policy_txt % reverse('privacy.notices.websites')))