Example #1
0
    def parse(self, fileorpath):
        data = self.get_json_data(fileorpath)
        loc = data.get('default_locale', translation.get_language())
        default_locale = self.trans_locale(loc)
        locales = data.get('locales', {})
        if type(locales) == list:
            raise forms.ValidationError(
                _('Your specified app locales are not in the correct format.'))

        localized_descr = self.extract_locale(locales, 'description',
                                              default='')
        if 'description' in data:
            localized_descr.update({default_locale: data['description']})

        localized_name = self.extract_locale(locales, 'name',
                                             default=data['name'])
        localized_name.update({default_locale: data['name']})

        developer_info = data.get('developer', {})
        developer_name = developer_info.get('name')
        if not developer_name:
            # Missing developer name shouldn't happen if validation took place,
            # but let's be explicit about this just in case.
            raise forms.ValidationError(
                _("Developer name is required in the manifest in order to "
                  "display it on the app's listing."))

        return {'guid': None,
                'type': amo.ADDON_WEBAPP,
                'name': self.trans_all_locales(localized_name),
                'developer_name': developer_name,
                'description': self.trans_all_locales(localized_descr),
                'version': data.get('version', '1.0'),
                'default_locale': default_locale,
                'origin': data.get('origin')}
Example #2
0
    def collections(self):
        features = self.features()
        lang = translation.to_language(translation.get_language())
        locale = Q(locale='') | Q(locale=lang)
        promos = (CollectionPromo.objects.filter(locale)
                  .filter(collection_feature__in=features)
                  .transform(CollectionPromo.transformer))
        groups = sorted_groupby(promos, 'collection_feature_id')

        # We key by feature_id and locale, so we can favor locale specific
        # promos.
        promo_dict = {}
        for feature_id, v in groups:
            promo = v.next()
            key = (feature_id, translation.to_language(promo.locale))
            promo_dict[key] = promo

        rv = {}
        # If we can, we favor locale specific collections.
        for feature in features:
            key = (feature.id, lang)
            if key not in promo_dict:
                key = (feature.id, '')
                if key not in promo_dict:
                    continue

            # We only want to see public add-ons on the front page.
            c = promo_dict[key].collection
            c.public_addons = c.addons.all() & Addon.objects.public()
            rv[feature] = c

        return rv
Example #3
0
def fetch_langpacks(path, **kw):
    log.info('[@None] Fetching language pack updates %s' % path)

    PLATFORMS = amo.PLATFORM_ALL,
    PLATFORMS = [Platform.objects.get(pk=p.id) for p in PLATFORMS]

    owner = UserProfile.objects.get(email=settings.LANGPACK_OWNER_EMAIL)
    orig_lang = translation.get_language()

    # Treat `path` as relative even if it begins with a leading /
    list_url = urlparse.urljoin(settings.LANGPACK_LIST_BASE, './' + path + '/')
    base_url = urlparse.urljoin(settings.LANGPACK_DOWNLOAD_BASE,
                                './' + path + '/')

    if not list_url.startswith(settings.LANGPACK_LIST_BASE):
        log.error('[@None] Not fetching language packs from invalid URL '
                  'path: %s' % path)
        raise ValueError('Invalid path')

    try:
        # urllib2 rather than requests since this is an FTP URL.
        req = urllib2.urlopen(list_url)
    except Exception, e:
        log.error('[@None] Error fetching language pack list %s: %s' %
                  (path, e))
        return
Example #4
0
    def collections(self):
        features = self.features()
        lang = translation.to_language(translation.get_language())
        locale = Q(locale='') | Q(locale=lang)
        promos = (CollectionPromo.objects.filter(locale)
                  .filter(collection_feature__in=features)
                  .transform(CollectionPromo.transformer))
        groups = sorted_groupby(promos, 'collection_feature_id')

        # We key by feature_id and locale, so we can favor locale specific
        # promos.
        promo_dict = {}
        for feature_id, v in groups:
            promo = v.next()
            key = (feature_id, translation.to_language(promo.locale))
            promo_dict[key] = promo

        rv = {}
        # If we can, we favor locale specific collections.
        for feature in features:
            key = (feature.id, lang)
            if key not in promo_dict:
                key = (feature.id, '')
                if key not in promo_dict:
                    continue

            # We only want to see public add-ons on the front page.
            c = promo_dict[key].collection
            c.public_addons = c.addons.all() & Addon.objects.public()
            rv[feature] = c

        return rv
 def render_additions(self, name, value, attrs=None):
     # id attribute is always present when rendering a widget
     ckeditor_selector = attrs['id']
     language = get_language().split('-')[0]
     configuration = deepcopy(self.configuration)
     # We are in a plugin -> we use toolbar_CMS or a custom defined toolbar
     if self.placeholder:
         configuration['toolbar'] = configuration.get('toolbar', 'CMS')
     # We are not in a plugin but toolbar is set to CMS (the default) ->
     # we force the use of toolbar_HTMLField
     elif configuration.get('toolbar', False) == 'CMS':
         configuration['toolbar'] = 'HTMLField'
     # Toolbar is not set or set to a custom value -> we use the custom
     # value or fallback to HTMLField
     else:
         configuration['toolbar'] = configuration.get('toolbar', 'HTMLField')
     context = {
         'ckeditor_class': self.ckeditor_class,
         'ckeditor_selector': ckeditor_selector,
         'ckeditor_function': ckeditor_selector.replace('-', '_'),
         'name': name,
         'language': language,
         'settings': language.join(json.dumps(configuration).split("{{ language }}")),
         'STATIC_URL': settings.STATIC_URL,
         'CKEDITOR_BASEPATH': text_settings.TEXT_CKEDITOR_BASE_PATH,
         'installed_plugins': self.installed_plugins,
         'plugin_pk': self.pk,
         'plugin_language': self.plugin_language,
         'placeholder': self.placeholder,
         'widget': self,
     }
     return mark_safe(render_to_string('cms/plugins/widgets/ckeditor.html', context))
Example #6
0
def clear_gettext_cache():
    gettext._translations = {}
    trans_real._translations = {}
    trans_real._default = None
    prev = trans_real.get_language()
    if prev:
        activate(prev)
Example #7
0
def fetch_langpacks(path, **kw):
    log.info('[@None] Fetching language pack updates %s' % path)

    PLATFORMS = amo.PLATFORM_ALL,
    PLATFORMS = [Platform.objects.get(pk=p.id) for p in PLATFORMS]

    owner = UserProfile.objects.get(email=settings.LANGPACK_OWNER_EMAIL)
    orig_lang = translation.get_language()

    # Treat `path` as relative even if it begins with a leading /
    base_url = urljoin(settings.LANGPACK_DOWNLOAD_BASE,
                       './' + path.strip('/') + '/')

    # Find the checksum manifest, 2 directories up.
    list_url = urljoin(base_url, settings.LANGPACK_MANIFEST_PATH)
    list_base = urljoin(list_url, './')

    log.info('[@None] Fetching language pack manifests from %s' % list_url)

    if not list_url.startswith(settings.LANGPACK_DOWNLOAD_BASE):
        log.error('[@None] Not fetching language packs from invalid URL: '
                  '%s' % base_url)
        raise ValueError('Invalid path')

    try:
        req = requests.get(list_url,
                           verify=settings.CA_CERT_BUNDLE_PATH)
    except Exception, e:
        log.error('[@None] Error fetching language pack list %s: %s'
                  % (path, e))
        return
 def render_additions(self, name, value, attrs=None):
     language = get_language().split('-')[0]
     context = {
         'ckeditor_class':
         self.ckeditor_class,
         'name':
         name,
         'language':
         language,
         'settings':
         language.join(
             json.dumps(
                 text_settings.CKEDITOR_SETTINGS).split("{{ language }}")),
         'STATIC_URL':
         settings.STATIC_URL,
         'installed_plugins':
         self.installed_plugins,
         'plugin_pk':
         self.pk,
         'plugin_language':
         self.plugin_language,
         'placeholder':
         self.placeholder
     }
     return mark_safe(
         render_to_string('cms/plugins/widgets/ckeditor.html', context))
 def render_additions(self, name, value, attrs=None):
     language = get_language().split('-')[0]
     configuration = deepcopy(self.configuration)
     # We are in a plugin -> we use toolbar_CMS or a custom defined toolbar
     if self.placeholder:
         configuration['toolbar'] = configuration.get('toolbar', 'CMS')
     # We are not in a plugin but toolbar is set to CMS (the default) ->
     # we force the use of toolbar_HTMLField
     elif configuration.get('toolbar', False) == 'CMS':
         configuration['toolbar'] = 'HTMLField'
     # Toolbar is not set or set to a custom value -> we use the custom
     # value or fallback to HTMLField
     else:
         configuration['toolbar'] = configuration.get('toolbar', 'HTMLField')
     context = {
         'ckeditor_class': self.ckeditor_class,
         'name': name,
         'language': language,
         'settings': language.join(json.dumps(configuration).split("{{ language }}")),
         'STATIC_URL': settings.STATIC_URL,
         'installed_plugins': self.installed_plugins,
         'plugin_pk': self.pk,
         'plugin_language': self.plugin_language,
         'placeholder': self.placeholder
     }
     return mark_safe(render_to_string('cms/plugins/widgets/ckeditor.html', context))
 def render_additions(self, name, value, attrs=None):
     # id attribute is always present when rendering a widget
     ckeditor_selector = attrs["id"]
     language = get_language().split("-")[0]
     configuration = deepcopy(self.configuration)
     # We are in a plugin -> we use toolbar_CMS or a custom defined toolbar
     if self.placeholder:
         configuration["toolbar"] = configuration.get("toolbar", "CMS")
     # We are not in a plugin but toolbar is set to CMS (the default) ->
     # we force the use of toolbar_HTMLField
     elif configuration.get("toolbar", False) == "CMS":
         configuration["toolbar"] = "HTMLField"
     # Toolbar is not set or set to a custom value -> we use the custom
     # value or fallback to HTMLField
     else:
         configuration["toolbar"] = configuration.get("toolbar", "HTMLField")
     context = {
         "ckeditor_class": self.ckeditor_class,
         "ckeditor_selector": ckeditor_selector,
         "ckeditor_function": ckeditor_selector.replace("-", "_"),
         "name": name,
         "language": language,
         "settings": language.join(json.dumps(configuration).split("{{ language }}")),
         "STATIC_URL": settings.STATIC_URL,
         "CKEDITOR_BASEPATH": text_settings.TEXT_CKEDITOR_BASE_PATH,
         "installed_plugins": self.installed_plugins,
         "plugin_pk": self.pk,
         "plugin_language": self.plugin_language,
         "placeholder": self.placeholder,
     }
     return mark_safe(render_to_string("cms/plugins/widgets/ckeditor.html", context))
Example #11
0
def fetch_langpacks(path, **kw):
    log.info('[@None] Fetching language pack updates %s' % path)

    PLATFORMS = amo.PLATFORM_ALL,
    PLATFORMS = [Platform.objects.get(pk=p.id) for p in PLATFORMS]

    owner = UserProfile.objects.get(email=settings.LANGPACK_OWNER_EMAIL)
    orig_lang = translation.get_language()

    # Treat `path` as relative even if it begins with a leading /
    base_url = urljoin(settings.LANGPACK_DOWNLOAD_BASE,
                       './' + path.strip('/') + '/')

    # Find the checksum manifest, 2 directories up.
    list_url = urljoin(base_url, settings.LANGPACK_MANIFEST_PATH)
    list_base = urljoin(list_url, './')

    log.info('[@None] Fetching language pack manifests from %s' % list_url)

    if not list_url.startswith(settings.LANGPACK_DOWNLOAD_BASE):
        log.error('[@None] Not fetching language packs from invalid URL: '
                  '%s' % base_url)
        raise ValueError('Invalid path')

    try:
        req = requests.get(list_url,
                           verify=settings.CA_CERT_BUNDLE_PATH)
    except Exception, e:
        log.error('[@None] Error fetching language pack list %s: %s'
                  % (path, e))
        return
Example #12
0
 def parse(self, fileorpath, addon=None):
     filename = get_filepath(fileorpath)
     with open(filename) as f:
         try:
             data = json.load(f)
         except ValueError:
             raise forms.ValidationError(
                 _('Could not parse webapp manifest file.'))
     loc = data.get('default_locale', translation.get_language())
     default_locale = self.trans_locale(loc)
     if type(data.get('locales')) == list:
         raise forms.ValidationError(
             _('Your specified app locales are not in the correct format.'))
     localized_descr = self.extract_locale(data.get('locales', {}),
                                           'description',
                                           default='')
     if 'description' in data:
         localized_descr.update({default_locale: data['description']})
     return {
         'guid': None,
         'type': amo.ADDON_WEBAPP,
         'name': {
             default_locale: data['name']
         },
         'summary': self.trans_all_locales(localized_descr),
         'version': '1.0',
         'default_locale': default_locale
     }
Example #13
0
    def parse(self, fileorpath):
        data = self.get_json_data(fileorpath)
        loc = data.get('default_locale', translation.get_language())
        default_locale = self.trans_locale(loc)
        locales = data.get('locales', {})
        if type(locales) == list:
            raise forms.ValidationError(
                _('Your specified app locales are not in the correct format.'))

        localized_descr = self.extract_locale(locales, 'description',
                                              default='')
        if 'description' in data:
            localized_descr.update({default_locale: data['description']})

        localized_name = self.extract_locale(locales, 'name',
                                             default=data['name'])
        localized_name.update({default_locale: data['name']})

        developer_info = data.get('developer', {})
        developer_name = developer_info.get('name')
        if not developer_name:
            # Missing developer name shouldn't happen if validation took place,
            # but let's be explicit about this just in case.
            raise forms.ValidationError(
                _("Developer name is required in the manifest in order to "
                  "display it on the app's listing."))

        return {'guid': None,
                'type': amo.ADDON_WEBAPP,
                'name': self.trans_all_locales(localized_name),
                'developer_name': developer_name,
                'description': self.trans_all_locales(localized_descr),
                'version': data.get('version', '1.0'),
                'default_locale': default_locale,
                'origin': data.get('origin')}
Example #14
0
 def get_address(self):
     if get_language() == 'en':
         if self.address_en:
             return self.address_en
         else:
             return self.address
     return self.address
Example #15
0
    def parse(self, fileorpath):
        data = self.get_json_data(fileorpath)
        loc = data.get("default_locale", translation.get_language())
        default_locale = self.trans_locale(loc)
        locales = data.get("locales", {})
        if type(locales) == list:
            raise forms.ValidationError(_("Your specified app locales are not in the correct format."))

        localized_descr = self.extract_locale(locales, "description", default="")
        if "description" in data:
            localized_descr.update({default_locale: data["description"]})

        localized_name = self.extract_locale(locales, "name", default=data["name"])
        localized_name.update({default_locale: data["name"]})

        developer_info = data.get("developer", {})
        developer_name = developer_info.get("name")
        if not developer_name:
            # Missing developer name shouldn't happen if validation took place,
            # but let's be explicit about this just in case.
            raise forms.ValidationError(
                _("Developer name is required in the manifest in order to " "display it on the app's listing.")
            )

        return {
            "guid": None,
            "type": amo.ADDON_WEBAPP,
            "name": self.trans_all_locales(localized_name),
            "developer_name": developer_name,
            "description": self.trans_all_locales(localized_descr),
            "version": data.get("version", "1.0"),
            "default_locale": default_locale,
            "origin": data.get("origin"),
        }
Example #16
0
def do_ntranslate(singular, plural, number, translation_function):
    language = trans_real.get_language()

    translation = trans_real.translation(language)
    number = translation.plural(number)

    kw = {'msgid': singular, 'plural': number, 'language': language,
            'domain': 'django'}
    try:
        message = Message.objects.get(**kw)
    except Message.DoesNotExist:
        # Miss
        msgstr = do_ntranslate_old(singular, plural, number,
                                   translation_function)
        kw['msgstr'] = msgstr
        message = Message(**kw)
        message.save()
        return msgstr

    # Hit
    translation = message.translation
    if not translation:
        return do_ntranslate_old(singular, plural, number,
                                 translation_function)

    return translation
Example #17
0
def fetch_langpacks(path, **kw):
    log.info('[@None] Fetching language pack updates %s' % path)

    PLATFORMS = amo.PLATFORM_ALL,
    PLATFORMS = [Platform.objects.get(pk=p.id) for p in PLATFORMS]

    owner = UserProfile.objects.get(email=settings.LANGPACK_OWNER_EMAIL)
    orig_lang = translation.get_language()

    # Treat `path` as relative even if it begins with a leading /
    list_url = urlparse.urljoin(settings.LANGPACK_LIST_BASE, './' + path + '/')
    base_url = urlparse.urljoin(settings.LANGPACK_DOWNLOAD_BASE, './' + path + '/')

    if not list_url.startswith(settings.LANGPACK_LIST_BASE):
        log.error('[@None] Not fetching language packs from invalid URL '
                  'path: %s' % path)
        raise ValueError('Invalid path')

    try:
        # urllib2 rather than requests since this is an FTP URL.
        req = urllib2.urlopen(list_url)
    except Exception, e:
        log.error('[@None] Error fetching language pack list %s: %s'
                  % (path, e))
        return
Example #18
0
 def get_name(self):
     try:
         if get_language() == 'en':
             if self.name_en:
                 return self.name_en
         return self.name
     except:
         return self.name
Example #19
0
 def get_description(self):
     try:
         if get_language() == 'en':
             if self.description_en:
                 return self.description_en
     except:
         pass
     return self.description
Example #20
0
 def get_name(self):
     try:
         if get_language() == 'en':
             if self.name_en:
                 return self.name_en
         return self.name
     except:
         return self.name
Example #21
0
 def get_description(self):
     try:
         if get_language() == 'en':
             if self.description_en:
                 return self.description_en
     except:
         pass
     return self.description
    def is_edit_mode(self, request):
        from django.utils.translation.trans_real import get_language, to_locale
        locale = to_locale(get_language())
        if 'en' in locale or request.path.find('/admin') > -1:
            return False

        #return request.GET.get('translate', 'False').lower() == 'true' and request.user.is_staff
        return request.user.is_staff and getattr(settings, 'ROSETTA_INPAGE', False)
Example #23
0
 def get_description(self):
     # noinspection PyBroadException
     try:
         if get_language() == 'en':
             if self.description_en:
                 return self.description_en
     except:
         pass
     return self.description
Example #24
0
class WebAppParser(object):

    def extract_locale(self, locales, key, default=None):
        """Gets a locale item based on key.

        For example, given this:

            locales = {'en': {'foo': 1, 'bar': 2},
                       'it': {'foo': 1, 'bar': 2}}

        You can get english foo like:

            self.extract_locale(locales, 'foo', 'en')

        """
        ex = {}
        for loc, data in locales.iteritems():
            ex[loc] = data.get(key, default)
        return ex

    def parse(self, fileorpath, addon=None):
        filename = get_filepath(fileorpath)
        with open(filename, 'rb') as f:
            data = f.read()
            enc_guess = chardet.detect(data)
            for bom in (codecs.BOM_UTF32_BE,
                        codecs.BOM_UTF32_LE,
                        codecs.BOM_UTF16_BE,
                        codecs.BOM_UTF16_LE,
                        codecs.BOM_UTF8):
                if data.startswith(bom):
                    data = data[len(bom):]
                    break
        try:
            data = json.loads(data.decode(enc_guess['encoding']))
        except (ValueError, UnicodeDecodeError), exc:
            msg = 'Error parsing webapp %r (encoding: %r %.2f%% sure): %s: %s'
            log.error(msg % (filename, enc_guess['encoding'],
                             enc_guess['confidence'] * 100.0,
                             exc.__class__.__name__, exc))
            raise forms.ValidationError(
                            _('Could not parse webapp manifest file.'))
        loc = data.get('default_locale', translation.get_language())
        default_locale = self.trans_locale(loc)
        if type(data.get('locales')) == list:
            raise forms.ValidationError(
                _('Your specified app locales are not in the correct format.'))
        localized_descr = self.extract_locale(data.get('locales', {}),
                                              'description', default='')
        if 'description' in data:
            localized_descr.update({default_locale: data['description']})
        return {'guid': None,
                'type': amo.ADDON_WEBAPP,
                'name': {default_locale: data['name']},
                'summary': self.trans_all_locales(localized_descr),
                'version': '1.0',
                'default_locale': default_locale}
Example #25
0
def extension_detail(request, addon):
    """Extensions details page."""

    # if current version is incompatible with this app, redirect
    comp_apps = addon.compatible_apps
    if comp_apps and request.APP not in comp_apps:
        prefixer = urlresolvers.get_url_prefix()
        prefixer.app = comp_apps.keys()[0].short
        return http.HttpResponsePermanentRedirect(reverse(
            'addons.detail', args=[addon.id]))

    # source tracking
    src = request.GET.get('src', 'addondetail')

    # get satisfaction only supports en-US
    lang = translation.to_locale(translation.get_language())
    addon.has_satisfaction = (lang == 'en_US' and
                              addon.get_satisfaction_company)

    # other add-ons from the same author(s)
    author_addons = order_by_translation(addon.authors_other_addons, 'name')

    # tags
    dev_tags, user_tags = addon.tags_partitioned_by_developer

    current_user_tags = []

    if request.user.is_authenticated():
        current_user_tags = user_tags.filter(
                addon_tags__user=request.amo_user)

    # addon recommendations
    recommended = Addon.objects.valid().only_translations().filter(
        recommended_for__addon=addon)[:5]

    # popular collections this addon is part of
    collections = Collection.objects.listed().filter(
        addons=addon, application__id=request.APP.id)

    data = {
        'addon': addon,
        'author_addons': author_addons,

        'src': src,

        'dev_tags': dev_tags,
        'user_tags': user_tags,
        'current_user_tags': current_user_tags,

        'recommendations': recommended,
        'review_form': ReviewForm(),
        'reviews': Review.objects.latest().filter(addon=addon),
        'get_replies': Review.get_replies,

        'collections': collections.order_by('-subscribers')[:3],
    }
    return jingo.render(request, 'addons/details.html', data)
Example #26
0
 def get_name(self):
     # noinspection PyBroadException
     try:
         if get_language() == 'en':
             if self.name_en:
                 return self.name_en
         return self.name
     except:
         return self.name
Example #27
0
 def get_name(self):
     # noinspection PyBroadException
     try:
         if get_language() == 'en':
             if self.name_en:
                 return self.name_en
         return self.name
     except:
         return self.name
Example #28
0
 def get_description(self):
     # noinspection PyBroadException
     try:
         if get_language() == 'en':
             if self.description_en:
                 return self.description_en
     except:
         pass
     return self.description
Example #29
0
 def get_name_add(self):
     try:
         if get_language() == 'en':
             if self.name_add_en:
                 return self.name_add_en
     except :
         pass
     if self.name_add:
         return self.name_add
     return self.get_name
Example #30
0
 def render_additions(self, name, value, attrs=None):
     language = get_language().split('-')[0]
     context = {
         'name': name,
         'language': language,
         'data': value,
         'table_settings_id': self.table_settings_id,
         'STATIC_URL': settings.STATIC_URL,
     }
     return mark_safe(render_to_string('djangocms_table/input-widget/table-widget.html', context))
Example #31
0
 def render_additions(self, name, value, attrs=None):
     language = get_language().split('-')[0]
     context = {
         'name': name,
         'language': language,
         'data': value,
         'STATIC_URL': settings.STATIC_URL,
     }
     return mark_safe(render_to_string(
         'cms/plugins/widgets/table.html', context))
Example #32
0
 def render_additions(self, name, value, attrs=None):
     language = get_language().split('-')[0]
     context = {
         'name': name,
         'language': language,
         'data': value,
         'chart_type': self.chart_type,
         'STATIC_URL': settings.STATIC_URL,
         'LABEL_VALUE_CHART_TYPES': json.dumps(CHART_TYPES.get_label_value_types)
     }
     return mark_safe(render_to_string('djangocms_charts/widgets/input-table.html', context))
Example #33
0
def extension_detail(request, addon):
    """Extensions details page."""
    # If current version is incompatible with this app, redirect.
    comp_apps = addon.compatible_apps
    if comp_apps and request.APP not in comp_apps:
        prefixer = urlresolvers.get_url_prefix()
        prefixer.app = comp_apps.keys()[0].short
        return redirect('addons.detail', addon.slug, permanent=True)

    # get satisfaction only supports en-US.
    lang = translation.to_locale(translation.get_language())
    addon.has_satisfaction = (lang == 'en_US' and
                              addon.get_satisfaction_company)

    # Addon recommendations.
    recommended = Addon.objects.listed(request.APP).filter(
        recommended_for__addon=addon)[:6]

    # Popular collections this addon is part of.
    collections = Collection.objects.listed().filter(
        addons=addon, application__id=request.APP.id)

    ctx = {
        'addon': addon,
        'src': request.GET.get('src', 'dp-btn-primary'),
        'version_src': request.GET.get('src', 'dp-btn-version'),
        'tags': addon.tags.not_blacklisted(),
        'grouped_ratings': GroupedRating.get(addon.id),
        'recommendations': recommended,
        'review_form': ReviewForm(),
        'reviews': Review.objects.latest().filter(addon=addon),
        'get_replies': Review.get_replies,
        'collections': collections.order_by('-subscribers')[:3],
        'abuse_form': AbuseForm(request=request),
    }

    # details.html just returns the top half of the page for speed. The bottom
    # does a lot more queries we don't want on the initial page load.
    if request.is_ajax():
        # Other add-ons/apps from the same author(s).
        if addon.is_webapp():
            others = Webapp.objects.listed().filter(type=amo.ADDON_WEBAPP)
        else:
            others = (Addon.objects.listed(request.APP)
                      .exclude(type=amo.ADDON_WEBAPP))
        others = (others.exclude(id=addon.id).distinct()
                        .filter(addonuser__listed=True,
                                authors__in=addon.listed_authors))
        ctx['author_addons'] = others[:6]
        return jingo.render(request, 'addons/impala/details-more.html', ctx)
    else:
        if addon.is_webapp():
            ctx['search_placeholder'] = 'apps'
        return jingo.render(request, 'addons/impala/details.html', ctx)
Example #34
0
 def get_name_add(self):
     # noinspection PyBroadException
     try:
         if get_language() == 'en':
             if self.name_add_en:
                 return self.name_add_en
     except:
         pass
     if self.name_add:
         return self.name_add
     return self.get_name
 def render_additions(self, name, value, attrs=None):
     language = get_language().split('-')[0]
     context = {
         'name': name,
         'language': language,
         'settings': language.join(simplejson.dumps(text_settings.CKEDITOR_SETTINGS).split("{{ language }}")),
         'STATIC_URL': settings.STATIC_URL,
         'installed_plugins': self.installed_plugins,
         'plugin_pk': self.pk,
     }
     return mark_safe(render_to_string('cms/plugins/widgets/ckeditor.html', context))
Example #36
0
def extension_detail(request, addon):
    """Extensions details page."""
    # If current version is incompatible with this app, redirect.
    comp_apps = addon.compatible_apps
    if comp_apps and request.APP not in comp_apps:
        prefixer = urlresolvers.get_url_prefix()
        prefixer.app = comp_apps.keys()[0].short
        return redirect('addons.detail', addon.slug, permanent=True)

    # get satisfaction only supports en-US.
    lang = translation.to_locale(translation.get_language())
    addon.has_satisfaction = (lang == 'en_US' and
                              addon.get_satisfaction_company)

    # Addon recommendations.
    recommended = Addon.objects.listed(request.APP).filter(
        recommended_for__addon=addon)[:6]

    # Popular collections this addon is part of.
    collections = Collection.objects.listed().filter(
        addons=addon, application__id=request.APP.id)

    ctx = {
        'addon': addon,
        'src': request.GET.get('src', 'dp-btn-primary'),
        'version_src': request.GET.get('src', 'dp-btn-version'),
        'tags': addon.tags.not_blacklisted(),
        'grouped_ratings': GroupedRating.get(addon.id),
        'recommendations': recommended,
        'review_form': ReviewForm(),
        'reviews': Review.objects.latest().filter(addon=addon),
        'get_replies': Review.get_replies,
        'collections': collections.order_by('-subscribers')[:3],
        'abuse_form': AbuseForm(request=request),
    }

    # details.html just returns the top half of the page for speed. The bottom
    # does a lot more queries we don't want on the initial page load.
    if request.is_ajax():
        # Other add-ons/apps from the same author(s).
        if addon.is_webapp():
            others = Webapp.objects.listed().filter(type=amo.ADDON_WEBAPP)
        else:
            others = (Addon.objects.listed(request.APP)
                      .exclude(type=amo.ADDON_WEBAPP))
        others = (others.exclude(id=addon.id).distinct()
                        .filter(addonuser__listed=True,
                                authors__in=addon.listed_authors))
        ctx['author_addons'] = others[:6]
        return jingo.render(request, 'addons/impala/details-more.html', ctx)
    else:
        if addon.is_webapp():
            ctx['search_placeholder'] = 'apps'
        return jingo.render(request, 'addons/impala/details.html', ctx)
Example #37
0
 def get_name_add(self):
     # noinspection PyBroadException
     try:
         if get_language() == 'en':
             if self.name_add_en:
                 return self.name_add_en
     except:
         pass
     if self.name_add:
         return self.name_add
     return self.get_name
Example #38
0
	def get_translation(self, lang = None):
		if not lang:
			from django.utils.translation import trans_real
			lang = trans_real.get_language()

		trans = self.translations.filter(language = lang)
		if not trans:
			trans = self.translations.filter(language = settings.LANGUAGE_CODE)
		if not trans:
			return None
		return TranslationWrapper(trans[0])
Example #39
0
def get_message(msgid, locale=None):
    """
    Fetch a message for a locale from the catalog

    @param msgid:
    @param locale:
    @return:
    """
    if not locale:
        locale = to_locale(get_language())
    catalog = get_locale_catalog(locale)
    return catalog.dict.get(msgid, None)
Example #40
0
def get_message(msgid, locale=None):
    """
    Fetch a message for a locale from the catalog

    @param msgid:
    @param locale:
    @return:
    """
    if not locale:
        locale = to_locale(get_language())
    catalog = get_locale_catalog(locale)
    return catalog.dict.get(msgid, None)
Example #41
0
 def from_upload(cls, upload, platforms):
     from files.utils import parse_addon
     data = parse_addon(upload.path)
     fields = cls._meta.get_all_field_names()
     addon = Addon(**dict((k, v) for k, v in data.items() if k in fields))
     addon.status = amo.STATUS_NULL
     addon.default_locale = to_language(translation.get_language())
     addon.save()
     Version.from_upload(upload, addon, platforms)
     amo.log(amo.LOG.CREATE_ADDON, addon)
     log.debug('New addon %r from %r' % (addon, upload))
     return addon
Example #42
0
def impala_extension_detail(request, addon):
    """Extensions details page."""

    # if current version is incompatible with this app, redirect
    comp_apps = addon.compatible_apps
    if comp_apps and request.APP not in comp_apps:
        prefixer = urlresolvers.get_url_prefix()
        prefixer.app = comp_apps.keys()[0].short
        return http.HttpResponsePermanentRedirect(reverse(
            'addons.detail', args=[addon.slug]))

    # source tracking
    src = request.GET.get('src', 'addon-detail')

    # get satisfaction only supports en-US
    lang = translation.to_locale(translation.get_language())
    addon.has_satisfaction = (lang == 'en_US' and
                              addon.get_satisfaction_company)

    # other add-ons from the same author(s)
    author_addons = order_by_translation(addon.authors_other_addons, 'name')[:6]

    # tags
    tags = addon.tags.not_blacklisted()

    # addon recommendations
    recommended = MiniAddon.objects.valid().filter(
        recommended_for__addon=addon)[:5]

    # popular collections this addon is part of
    collections = Collection.objects.listed().filter(
        addons=addon, application__id=request.APP.id)

    data = {
        'addon': addon,
        'author_addons': author_addons,

        'src': src,
        'tags': tags,

        'grouped_ratings': GroupedRating.get(addon.id),
        'recommendations': recommended,
        'review_form': ReviewForm(),
        'reviews': Review.objects.latest().filter(addon=addon),
        'get_replies': Review.get_replies,

        'collections': collections.order_by('-subscribers')[:3],
    }
    if settings.REPORT_ABUSE:
        data['abuse_form'] = AbuseForm(request=request)

    return jingo.render(request, 'addons/impala/details.html', data)
Example #43
0
 def render_additions(self, name, value, attrs=None):
     language = get_language()
     context = {
         "name": name,
         "language": language,
         "CMS_MEDIA_URL": CMS_MEDIA_URL,
         "WYM_TOOLS": mark_safe(text_settings.WYM_TOOLS),
         "WYM_CONTAINERS": mark_safe(text_settings.WYM_CONTAINERS),
         "WYM_CLASSES": mark_safe(text_settings.WYM_CLASSES),
         "WYM_STYLES": mark_safe(text_settings.WYM_STYLES),
         "installed_plugins": self.installed_plugins,
     }
     return mark_safe(render_to_string("cms/plugins/widgets/wymeditor.html", context))
Example #44
0
 def render_additions(self, name, value, attrs=None):
     language = get_language()
     context = {
         'name': name,
         'language': language,
         'CMS_MEDIA_URL': CMS_MEDIA_URL,
         'WYM_TOOLS': mark_safe(settings.WYM_TOOLS),
         'WYM_CONTAINERS': mark_safe(settings.WYM_CONTAINERS),
         'WYM_CLASSES': mark_safe(settings.WYM_CLASSES),
         'WYM_STYLES': mark_safe(settings.WYM_STYLES),
     }
     return mark_safe(render_to_string(
         'text/widgets/wymeditor.html', context))
Example #45
0
 def render_additions(self, name, value, attrs=None):
     language = get_language()
     context = {
         'name': name,
         'language': language,
         'WYM_TOOLS': mark_safe(text_settings.WYM_TOOLS),
         'WYM_CONTAINERS': mark_safe(text_settings.WYM_CONTAINERS),
         'WYM_CLASSES': mark_safe(text_settings.WYM_CLASSES),
         'WYM_STYLES': mark_safe(text_settings.WYM_STYLES),
         'WYM_STYLESHEET': mark_safe(text_settings.WYM_STYLESHEET),
         'installed_plugins': self.installed_plugins,
     }
     return mark_safe(render_to_string(
         'news/widgets/wymeditor.html', context))
Example #46
0
    def __getitem__(self, key):
        """
        We don't want localizers to take down the site when their string
        interpolation variables don't match the real strings.

        If we have {% trans users=... %}blah {{ users }}{% endtrans %}
        and the localizer has "blah %(user)s" in their gettext catalog, there will
        be a KeyError when Python looks for the users variable.
        """
        try:
            return self.obj[key]
        except KeyError:
            lang = trans_real.get_language()
            log.error(u'[%s] KeyError: %r in %r' % (lang, key, self.obj))
Example #47
0
def impala_extension_detail(request, addon):
    """Extensions details page."""

    # if current version is incompatible with this app, redirect
    comp_apps = addon.compatible_apps
    if comp_apps and request.APP not in comp_apps:
        prefixer = urlresolvers.get_url_prefix()
        prefixer.app = comp_apps.keys()[0].short
        return http.HttpResponsePermanentRedirect(
            reverse('addons.detail', args=[addon.slug]))

    # source tracking
    src = request.GET.get('src', 'addon-detail')

    # get satisfaction only supports en-US
    lang = translation.to_locale(translation.get_language())
    addon.has_satisfaction = (lang == 'en_US'
                              and addon.get_satisfaction_company)

    # other add-ons from the same author(s)
    author_addons = order_by_translation(addon.authors_other_addons,
                                         'name')[:6]

    # tags
    tags = addon.tags.not_blacklisted()

    # addon recommendations
    recommended = MiniAddon.objects.valid().filter(
        recommended_for__addon=addon)[:5]

    # popular collections this addon is part of
    collections = Collection.objects.listed().filter(
        addons=addon, application__id=request.APP.id)

    data = {
        'addon': addon,
        'author_addons': author_addons,
        'src': src,
        'tags': tags,
        'grouped_ratings': GroupedRating.get(addon.id),
        'recommendations': recommended,
        'review_form': ReviewForm(),
        'reviews': Review.objects.latest().filter(addon=addon),
        'get_replies': Review.get_replies,
        'collections': collections.order_by('-subscribers')[:3],
    }
    if settings.REPORT_ABUSE:
        data['abuse_form'] = AbuseForm(request=request)

    return jingo.render(request, 'addons/impala/details.html', data)
Example #48
0
    def __getitem__(self, key):
        """
        We don't want localizers to take down the site when their string
        interpolation variables don't match the real strings.

        If we have {% trans users=... %}blah {{ users }}{% endtrans %}
        and the localizer has "blah %(user)s" in their gettext catalog, there will
        be a KeyError when Python looks for the users variable.
        """
        try:
            return self.obj[key]
        except KeyError:
            lang = trans_real.get_language()
            log.error(u'[%s] KeyError: %r in %r' % (lang, key, self.obj))
 def render_additions(self, name, value, attrs=None):
     language = get_language()
     context = {
         'name': name,
         'language': language,
         'STATIC_URL': settings.STATIC_URL,
         'WYM_TOOLS': mark_safe(text_settings.WYM_TOOLS),
         'WYM_CONTAINERS': mark_safe(text_settings.WYM_CONTAINERS),
         'WYM_CLASSES': mark_safe(text_settings.WYM_CLASSES),
         'WYM_STYLES': mark_safe(text_settings.WYM_STYLES),
         'WYM_STYLESHEET': mark_safe(text_settings.WYM_STYLESHEET),
         'installed_plugins': self.installed_plugins,
     }
     return mark_safe(render_to_string(
         'cms/plugins/widgets/wymeditor.html', context))
def set_language(request):
    lang_code = request.GET.get('LANGUAGES', 'ru')
    lang = get_language()
    if not lang_code:
        lang_code = request.GET.get('LANGUAGE_CODE', settings.LANGUAGE_CODE)
    next_url = request.META.get('HTTP_REFERER', None)
    if not is_safe_url:
        next_url = '/'
    response = http.HttpResponseRedirect(next_url)
    if lang_code and check_for_language(lang_code):
        if hasattr(request, 'session'):
            request.session['django_language'] = lang_code
        response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code)
        translation.activate(lang_code)
    return response
Example #51
0
def contribute_url_params(business,
                          addon_id,
                          item_name,
                          return_url,
                          amount='',
                          item_number='',
                          monthly=False,
                          comment=''):

    lang = translation.get_language()
    try:
        paypal_lang = settings.PAYPAL_COUNTRYMAP[lang]
    except KeyError:
        lang = lang.split('-')[0]
        paypal_lang = settings.PAYPAL_COUNTRYMAP.get(lang, 'US')

    # Get all the data elements that will be URL params
    # on the Paypal redirect URL.
    data = {
        'business': business,
        'item_name': item_name,
        'item_number': item_number,
        'bn': settings.PAYPAL_BN + '-AddonID' + str(addon_id),
        'no_shipping': '1',
        'return': return_url,
        'charset': 'utf-8',
        'lc': paypal_lang,
        'notify_url': "%s%s" % (settings.SERVICES_URL, reverse('amo.paypal'))
    }

    if not monthly:
        data['cmd'] = '_donations'
        if amount:
            data['amount'] = amount
    else:
        data.update({
            'cmd': '_xclick-subscriptions',
            'p3': '12',  # duration: for 12 months
            't3': 'M',  # time unit, 'M' for month
            'a3': amount,  # recurring contribution amount
            'no_note': '1'
        })  # required: no "note" text field for user

    if comment:
        data['custom'] = comment

    return data
Example #52
0
    def post(self, request):
        from django.utils.translation.trans_real import to_locale, get_language
        from rosetta_inpage.utils import save_message

        source = request.POST.get('source', '')
        target_lang = request.POST.get('lang', '')
        target_msg = request.POST.get('msg', '')

        if target_lang:
            locale = to_locale(target_lang)
        else:
            locale = to_locale(get_language())

        files = save_message(source, target_msg, locale)
        return {
            'files': files,
            'msg': target_msg,
        }
Example #53
0
    def do_translate(message, translation_function):
        """Copied from django.utils.translation.trans_real"""
        # str() is allowing a bytestring message to remain bytestring on Python 2
        eol_message = message.replace(str('\r\n'),
                                      str('\n')).replace(str('\r'), str('\n'))

        if len(eol_message) == 0:
            # Returns an empty value of the corresponding type if an empty message
            # is given, instead of metadata, which is the default gettext behavior.
            result = type(message)("")
        else:
            translation_object = translation(get_language())
            result = getattr(translation_object,
                             translation_function)(eol_message)

        if isinstance(message, SafeData):
            return mark_safe(result)

        return result
Example #54
0
    def render_additions(self, name, value, attrs=None):
        language = get_language().split('-')[0]
        containers = getattr(settings, 'WYM_CONTAINERS', None)
        if containers is None:
            containers = text_settings.WYM_CONTAINERS
        context = {
            'name': name,
            'language': language,
            'SEMANTICEDITOR_MEDIA_URL': settings.SEMANTICEDITOR_MEDIA_URL,
            'CMS_MEDIA_URL': getattr(settings, 'CMS_MEDIA_URL', None),
            'WYM_TOOLS': mark_safe(text_settings.WYM_TOOLS),
            'WYM_CONTAINERS': mark_safe(containers),
            'WYM_CLASSES': mark_safe(text_settings.WYM_CLASSES),
            'WYM_STYLES': mark_safe(text_settings.WYM_STYLES),
            'WYM_STYLESHEET': mark_safe(text_settings.WYM_STYLESHEET),
            'installed_plugins': self.installed_plugins,
            'page': self.page,
        }

        return mark_safe(
            render_to_string('semanticeditor/editorwidget.html', context))
Example #55
0
 def parse(self, fileorpath):
     data = self.get_json_data(fileorpath)
     loc = data.get('default_locale', translation.get_language())
     default_locale = self.trans_locale(loc)
     if type(data.get('locales')) == list:
         raise forms.ValidationError(
             _('Your specified app locales are not in the correct format.'))
     localized_descr = self.extract_locale(data.get('locales', {}),
                                           'description',
                                           default='')
     if 'description' in data:
         localized_descr.update({default_locale: data['description']})
     return {
         'guid': None,
         'type': amo.ADDON_WEBAPP,
         'name': {
             default_locale: data['name']
         },
         'summary': self.trans_all_locales(localized_descr),
         'version': data.get('version', '1.0'),
         'default_locale': default_locale
     }
    def test_esperanto_translations_in_student_view(self):
        """
        Checks if the template and its context are both correctly translated.
        """
        xblock = make_xblock('freetextresponse', FreeTextResponse, {})
        current_translation = translation(get_language())

        with django.utils.translation.override('eo'), \
                patch.object(current_translation, 'gettext') as gettext, \
                patch.object(current_translation, 'ngettext') as ngettext:

            gettext.side_effect = mock_gettext
            ngettext.side_effect = mock_gettext
            student_view = xblock.student_view()
            student_view_html = student_view.content

        self.assertIn('Süßmït', student_view_html)

        english_text = 'Your response must be between'
        translated_text = 'Ýöür réspönsé müst ßé ßétwéén'
        self.assertNotIn(english_text, student_view_html)
        self.assertIn(translated_text, student_view_html)