Ejemplo n.º 1
0
def active_languages():
    """Return a sequence of dicts, where each element consists of the
    following keys:

    * code: the language code
    * name: the translated name of this language

    for each available language."""
    global _ACTIVE_LANGUAGES
    if _ACTIVE_LANGUAGES:
        return _ACTIVE_LANGUAGES

    # get a list of avaialable translations
    domain = base.queryUtility(ITranslationDomain,
                               ccorg_i18n_setup.I18N_DOMAIN)
    lang_codes = set(domain.getCatalogsInfo().keys())

    # determine the intersection of available translations and
    # launched jurisdiction locales
    launched_locales = set()
    jurisdictions = cclicense_functions.get_valid_jurisdictions()

    for jurisdiction in jurisdictions:
        query_string = ('PREFIX dc: <http://purl.org/dc/elements/1.1/> '
                        'SELECT ?lang WHERE {'
                        '  <%s> dc:language ?lang}') % jurisdiction

        query = RDF.Query(str(query_string), query_language='sparql')
        this_juri_locales = set([
            locale_to_lower_upper(str(result['lang']))
            for result in query.execute(rdf_helper.JURI_MODEL)
        ])

        # Append those locales that are applicable to this domain
        launched_locales.update(lang_codes.intersection(this_juri_locales))

    # XXX: Have to hack in Esperanto here because it's technically an
    # "Unported" language but there is no unported RDF jurisdiction in
    # jurisdictions.rdf..
    launched_locales.add('eo')

    # make our sequence have a predictable order
    launched_locales = list(launched_locales)

    # this loop is long hand for clarity; it's only done once, so
    # the additional performance cost should be negligible
    result = []
    for code in launched_locales:

        if code == 'test': continue

        gettext = ugettext_for_locale(negotiate_locale(code))
        name = gettext(mappers.LANG_MAP[code])
        result.append(dict(code=code, name=name))

    result = sorted(result, key=lambda lang: lang['name'].lower())

    _ACTIVE_LANGUAGES = result

    return result
Ejemplo n.º 2
0
def send_license_info_email(license_title, license_html, recipient_email,
                            locale):
    """
    Send license information email to a user.

    Arguments:
     - license_title: title of the license
     - license_html: copy-paste license HTML
     - recipient_email: the user that is getting this email
     - locale: language email should be sent in

    Returns:
      A boolean specifying whether or not the email sent successfully
    """

    gettext = ugettext_for_locale(locale)
    email_body = gettext(LICENSE_INFO_EMAIL_BODY) % {
        'license_title': license_title,
        'license_html': license_html
    }

    try:
        send_email(
            '*****@*****.**', [recipient_email],
            translate(LICENSE_INFO_EMAIL_SUBJECT,
                      target_language=negotiate_locale(locale)), email_body)
        return True
    except smtplib.SMTPException:
        return False
Ejemplo n.º 3
0
def send_license_info_email(license_title, license_html,
                            recipient_email, locale):
    """
    Send license information email to a user.

    Arguments:
     - license_title: title of the license
     - license_html: copy-paste license HTML
     - recipient_email: the user that is getting this email
     - locale: language email should be sent in

    Returns:
      A boolean specifying whether or not the email sent successfully
    """

    gettext = ugettext_for_locale(locale)
    email_body = gettext(LICENSE_INFO_EMAIL_BODY) % {
            'license_title': license_title,
            'license_html': license_html}

    try:
        send_email(
            '*****@*****.**', [recipient_email],
            translate(
                LICENSE_INFO_EMAIL_SUBJECT,
                target_language=negotiate_locale(locale)),
            email_body)
        return True
    except smtplib.SMTPException:
        return False
Ejemplo n.º 4
0
    def translate(self, msgid, domain=None, mapping=None, default=None):
        translation = translate(
            msgid, domain, mapping,
            default=default,
            target_language=negotiate_locale(self.target_language))
        if isinstance(translation, unicode):
            return translation

        try:
            return translation.decode('utf-8')
        except UnicodeError:
            try:
                return translation.decode('latin-1')
            except UnicodeError:
                return translation.decode('utf-8', 'ignore')
Ejemplo n.º 5
0
def test_negotiate_locale():
    """
    Test cc.i18n.util.negotiate_locale()
    """
    ## Make sure we return the right patterns
    assert util.negotiate_locale("en", FAKE_MODIR) == "en"
    assert util.negotiate_locale("en_US", FAKE_MODIR) == "en_US"
    assert util.negotiate_locale("pt_FOO", FAKE_MODIR) == "pt"
    assert util.negotiate_locale("zh", FAKE_MODIR) == "zh"
    assert util.negotiate_locale("zh_TW", FAKE_MODIR) == "zh_TW"
    assert util.negotiate_locale("foobie_BLECH", FAKE_MODIR) == "en"
Ejemplo n.º 6
0
def test_negotiate_locale():
    """
    Test cc.i18n.util.negotiate_locale()
    """
    ## Make sure we return the right patterns
    assert util.negotiate_locale('en', FAKE_MODIR) == 'en'
    assert util.negotiate_locale('en_US', FAKE_MODIR) == 'en_US'
    assert util.negotiate_locale('pt_FOO', FAKE_MODIR) == 'pt'
    assert util.negotiate_locale('zh', FAKE_MODIR) == 'zh'
    assert util.negotiate_locale('zh_TW', FAKE_MODIR) == 'zh_TW'
    assert util.negotiate_locale('foobie_BLECH', FAKE_MODIR) == 'en'
Ejemplo n.º 7
0
    def translate(self, msgid, domain=None, mapping=None, default=None):
        translation = translate(msgid,
                                domain,
                                mapping,
                                default=default,
                                target_language=negotiate_locale(
                                    self.target_language))
        if isinstance(translation, unicode):
            return translation

        try:
            return translation.decode('utf-8')
        except UnicodeError:
            try:
                return translation.decode('latin-1')
            except UnicodeError:
                return translation.decode('utf-8', 'ignore')
Ejemplo n.º 8
0
def license_deed_view(request):
    """
    The main and major deed generating view.
    """
    ##########################
    # Try and get the license.
    ##########################
    license = by_code(request.matchdict['code'],
                      jurisdiction=request.matchdict.get('jurisdiction'),
                      version=request.matchdict.get('version'))
    if not license:
        license_versions = util.catch_license_versions_from_request(request)

        if license_versions:
            # If we can't get it, but others of that code exist, give
            # a special 404.
            return license_catcher(request)
        else:
            # Otherwise, give the normal 404.
            return exc.HTTPNotFound()

    ####################
    # Everything else ;)
    ####################
    # "color" of the license; the color reflects the relative amount
    # of freedom.
    if license.license_code in ('devnations', 'sampling'):
        color = 'red'
    elif license.license_code.find('sampling') > -1 or \
             license.license_code.find('nc') > -1 or \
             license.license_code.find('nd') > -1:
        color = 'yellow'
    else:
        color = 'green'

    # Get the language this view will be displayed in.
    #  - First checks to see if the routing matchdict specifies the language
    #  - Or, next gets the jurisdictions' default language if the jurisdiction
    #    specifies one
    #  - Otherwise it's english!
    if request.matchdict.has_key('target_lang'):
        target_lang = request.matchdict.get('target_lang')
    elif license.jurisdiction.default_language:
        target_lang = locale_to_lower_upper(
            license.jurisdiction.default_language)
    else:
        target_lang = 'en'

    # True if the legalcode for this license is available in
    # multiple languages (or a single language with a language code different
    # than that of the jurisdiction).
    #
    # Stored in the RDF, we'll just check license.legalcodes() :)
    legalcodes = license.legalcodes(target_lang)
    if len(legalcodes) > 1 \
            or list(legalcodes)[0][2] is not None:
        multi_language = True
        legalcodes = sorted(legalcodes, key=lambda lc: lc[2])
    else:
        multi_language = False

    # Use the lower-dash style for all RDF-related locale stuff
    rdf_style_target_lang = locale_to_lower_lower(target_lang)

    license_title = None
    try:
        license_title = license.title(rdf_style_target_lang)
    except KeyError:
        # don't have one for that language, use default
        license_title = license.title()

    conditions = {}
    for code in license.license_code.split('-'):
        conditions[code] = 1

    # Find out all the active languages
    active_languages = get_well_translated_langs()
    negotiated_locale = negotiate_locale(target_lang)

    # If negotiating the locale says that this isn't a valid language,
    # let's fall back to something that is.
    if target_lang != negotiated_locale:
        base_url = REMOVE_DEED_URL_RE.match(request.path_info).groups()[0]
        redirect_to = base_url + 'deed.' + negotiated_locale
        return exc.HTTPFound(location=redirect_to)

    if DEED_TEMPLATE_MAPPING.has_key(license.license_code):
        main_template = DEED_TEMPLATE_MAPPING[license.license_code]
    else:
        main_template = 'licenses/standard_deed.html'

    get_this = "/choose/results-one?license_code=%s&amp;jurisdiction=%s&amp;version=%s&amp;lang=%s" % (
        urllib.quote(license.license_code), license.jurisdiction.code,
        license.version, target_lang)

    context = {
        'request': request,
        'license_code': license.license_code,
        'license_code_quoted': urllib.quote(license.license_code),
        'license_title': license_title,
        'license': license,
        'multi_language': multi_language,
        'legalcodes': legalcodes,
        'color': color,
        'conditions': conditions,
        'active_languages': active_languages,
        'target_lang': target_lang,
        'jurisdiction': license.jurisdiction.code,
        'get_this': get_this,
    }
    context.update(util.rtl_context_stuff(target_lang))

    return Response(
        util.render_template(request, target_lang, main_template, context))
Ejemplo n.º 9
0
def license_deed_view(request):
    """
    The main and major deed generating view.
    """
    ##########################
    # Try and get the license.
    ##########################
    license = by_code(
        request.matchdict['code'],
        jurisdiction=request.matchdict.get('jurisdiction'),
        version=request.matchdict.get('version'))
    if not license:
        license_versions = util.catch_license_versions_from_request(request)

        if license_versions:
            # If we can't get it, but others of that code exist, give
            # a special 404.
            return license_catcher(request)
        else:
            # Otherwise, give the normal 404.
            return exc.HTTPNotFound()

    ####################
    # Everything else ;)
    ####################
    # "color" of the license; the color reflects the relative amount
    # of freedom.
    if license.license_code in ('devnations', 'sampling'):
       color = 'red'
    elif license.license_code.find('sampling') > -1 or \
             license.license_code.find('nc') > -1 or \
             license.license_code.find('nd') > -1:
       color = 'yellow'
    else:
       color = 'green'

    # Get the language this view will be displayed in.
    #  - First checks to see if the routing matchdict specifies the language
    #  - Or, next gets the jurisdictions' default language if the jurisdiction
    #    specifies one
    #  - Otherwise it's english!
    if request.matchdict.has_key('target_lang'):
        target_lang = request.matchdict.get('target_lang')
    elif license.jurisdiction.default_language:
        target_lang = locale_to_lower_upper(
            license.jurisdiction.default_language)
    else:
        target_lang = 'en'

    # True if the legalcode for this license is available in
    # multiple languages (or a single language with a language code different
    # than that of the jurisdiction).
    #
    # Stored in the RDF, we'll just check license.legalcodes() :)
    legalcodes = license.legalcodes(target_lang)
    if len(legalcodes) > 1 \
            or list(legalcodes)[0][2] is not None:
        multi_language = True
        legalcodes = sorted(legalcodes, key=lambda lc: lc[2])
    else:
        multi_language = False

    # Use the lower-dash style for all RDF-related locale stuff
    rdf_style_target_lang = locale_to_lower_lower(target_lang)

    license_title = None
    try:
        license_title = license.title(rdf_style_target_lang)
    except KeyError:
        # don't have one for that language, use default
        license_title = license.title()

    conditions = {}
    for code in license.license_code.split('-'):
        conditions[code] = 1

    # Find out all the active languages
    active_languages = get_well_translated_langs()
    negotiated_locale = negotiate_locale(target_lang)

    # If negotiating the locale says that this isn't a valid language,
    # let's fall back to something that is.
    if target_lang != negotiated_locale:
        base_url = REMOVE_DEED_URL_RE.match(request.path_info).groups()[0]
        redirect_to = base_url + 'deed.' + negotiated_locale
        return exc.HTTPFound(location=redirect_to)

    if DEED_TEMPLATE_MAPPING.has_key(license.license_code):
        main_template = DEED_TEMPLATE_MAPPING[license.license_code]
    else:
        main_template = 'licenses/standard_deed.html'

    get_this = "/choose/results-one?license_code=%s&amp;jurisdiction=%s&amp;version=%s&amp;lang=%s" % (urllib.quote(license.license_code), license.jurisdiction.code, license.version, target_lang)

    context = {
        'request': request,
        'license_code': license.license_code,
        'license_code_quoted': urllib.quote(license.license_code),
        'license_title': license_title,
        'license': license,
        'multi_language': multi_language,
        'legalcodes': legalcodes,
        'color': color,
        'conditions': conditions,
        'active_languages': active_languages,
        'target_lang': target_lang,
        'jurisdiction':license.jurisdiction.code,
        'get_this': get_this,
        }
    context.update(util.rtl_context_stuff(target_lang))

    return Response(
        util.render_template(
            request, target_lang,
            main_template, context))
Ejemplo n.º 10
0
def active_languages():
    """Return a sequence of dicts, where each element consists of the
    following keys:

    * code: the language code
    * name: the translated name of this language

    for each available language."""
    global _ACTIVE_LANGUAGES
    if _ACTIVE_LANGUAGES:
        return _ACTIVE_LANGUAGES

    # get a list of avaialable translations
    domain = base.queryUtility(ITranslationDomain, ccorg_i18n_setup.I18N_DOMAIN)
    lang_codes = set(domain.getCatalogsInfo().keys())

    # determine the intersection of available translations and
    # launched jurisdiction locales
    launched_locales = set()
    jurisdictions = cclicense_functions.get_valid_jurisdictions()

    for jurisdiction in jurisdictions:
        query_string = (
            'PREFIX dc: <http://purl.org/dc/elements/1.1/> '
            'SELECT ?lang WHERE {'
            '  <%s> dc:language ?lang}') % jurisdiction

        query = RDF.Query(
            str(query_string),
            query_language='sparql')
        this_juri_locales = set(
            [locale_to_lower_upper(str(result['lang']))
             for result in query.execute(rdf_helper.JURI_MODEL)])

        # Append those locales that are applicable to this domain
        launched_locales.update(lang_codes.intersection(this_juri_locales))

    # XXX: Have to hack in Esperanto here because it's technically an
    # "Unported" language but there is no unported RDF jurisdiction in
    # jurisdictions.rdf..
    launched_locales.add('eo')

    # make our sequence have a predictable order
    launched_locales = list(launched_locales)

    # this loop is long hand for clarity; it's only done once, so
    # the additional performance cost should be negligible
    result = []
    for code in launched_locales:

        if code == 'test': continue

        gettext = ugettext_for_locale(negotiate_locale(code))
        name = gettext(mappers.LANG_MAP[code])
        result.append(dict(code=code, name=name))

    result = sorted(result, key=lambda lang: lang['name'].lower())

    _ACTIVE_LANGUAGES = result

    return result