Exemple #1
0
    def format(self, license, work_dict=None, locale='en'):
        gettext = ugettext_for_locale(locale)

        work_dict = work_dict or {}

        work_title = work_dict.get('work_title', False)
        actor_href = work_dict.get('actor_href', '').strip()
        actor = work_dict.get('name', '').strip()

        template = TEMPLATE_ENV.get_template('cc0.html')

        work_jurisdiction = work_dict.get('work_jurisdiction')
        country_name = None
        if work_jurisdiction not in ('', '-', None, False):
            if work_jurisdiction.lower() in mappers.COUNTRY_MAP:
                country_name = gettext(
                    mappers.COUNTRY_MAP[work_jurisdiction.lower()])
            # Crappy fallback to this CSV.  We should homogenize these
            # things...
            elif work_jurisdiction.upper() in util.CODE_COUNTRY_MAP:
                country_name = gettext(
                    util.CODE_COUNTRY_MAP[work_jurisdiction.upper()])

        rendered_template = template.render(
            {"gettext": gettext,
             "license": license,
             "actor": actor,
             "actor_href": actor_href,
             "work_jurisdiction": work_jurisdiction,
             "publisher": actor_href or "[_:publisher]",
             "country_name": country_name,
             "work_title": work_title,
             "form": work_dict})

        return util.remove_blank_lines(rendered_template)
Exemple #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
Exemple #3
0
def cctrans(locale, logical_key, **trans_values):
    """
    A method for translating via logical keys
    """
    ugettext = ugettext_for_locale(locale)
    return string.Template(ugettext(logical_key)).substitute(
        trans_values)
    def format(self, license, work_dict=None, locale='en'):
        work_dict = work_dict or {}

        gettext = ugettext_for_locale(locale)

        dctype = None
        if work_dict.get('format'):
            dctype = _translate_dctype(work_dict['format'].lower())

        image_header = IMAGE_HEADER_TEMPLATE % {
            'license_url':
            license.uri,
            'util.Creative_Commons_License':
            util.escape(gettext(u'Creative Commons License')),
            'license_logo':
            license.logo
        }

        body_template = gettext(
            u'This %(work_type)s is in the '
            u'<a rel="license" href="http://creativecommons.org/licenses/publicdomain/">Public Domain</a>.'
        )
        body_vars = {'work_type': process_work_type(gettext, dctype)}

        message = image_header + body_template % body_vars

        return message
Exemple #5
0
    def legalcodes(self, language='en'):
        """
        Return a list of
        [(legalcode_uri, legalcode_lang, legalcode_lang_translated)]
        for this license.

        If this is a single-legalcode option, it'll probably return
        [(legalcode_uri, None, None)]

        """
        if self._legalcodes.has_key(language):
            return self._legalcodes[language]

        gettext = ugettext_for_locale(language)

        legalcodes = set()
        for legalcode, lang in rdf_helper.get_license_legalcodes(self.uri):
            if lang is None:
                translated_lang = None
            # <terrible_fixable_hacks>
            # We should probably add lang.sr_CYRL and lang.sr_LATN messages
            elif lang == 'sr-Cyrl':
                translated_lang = gettext('Serbian')
            elif lang == 'sr-Latn':
                translated_lang = 'srpski (latinica)'
            # </terrible_fixable_hacks>
            else:
                translated_lang = gettext(
                    mappers.LANG_MAP[locale_to_lower_upper(lang)])

            legalcodes.add((legalcode, lang, translated_lang))

        self._legalcodes[language] = legalcodes

        return legalcodes
Exemple #6
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
Exemple #7
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
Exemple #8
0
def get_well_translated_langs(threshold=TRANSLATION_THRESHOLD,
                              trans_file=DEFAULT_CSV_FILE,
                              append_english=True):
    """
    Get an alphebatized and name-rendered list of all languages above
    a certain threshold of translation.
    
    Keyword arguments:
    - threshold: percentage that languages should be translated at or above
    - trans_file: specify from which CSV file we're gathering statistics.
        Used for testing, You probably don't need this.
    - append_english: Add English to the list, even if it's completely
        "untranslated" (since English is the default for messages,
        nobody translates it)

    Returns:
      An alphebatized 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.
      An unsorted set of all qualified language codes
    """
    from cc.i18n import mappers

    cache_key = (threshold, trans_file, append_english)

    if CACHED_WELL_TRANSLATED_LANGS.has_key(cache_key):
        return CACHED_WELL_TRANSLATED_LANGS[cache_key]

    trans_stats = get_all_trans_stats(trans_file)
    
    qualified_langs = set([
        lang for lang, data in trans_stats.iteritems()
        if data['percent_trans'] >= threshold])

    # Add english if necessary.
    if not 'en' in qualified_langs and append_english:
        qualified_langs.add('en')

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

    for code in qualified_langs:
        from cc.i18n.gettext_i18n import ugettext_for_locale
        gettext = ugettext_for_locale(code)
        if code in mappers.LANG_MAP:
            # we have a translation for this name...
            name = gettext(mappers.LANG_MAP[code])
            result.append(dict(code=code, name=name))

    result = sorted(result, key=lambda lang: lang['name'].lower())
    
    CACHED_WELL_TRANSLATED_LANGS[cache_key] = result
    
    return result
Exemple #9
0
def _base_context(request, target_lang=None):
    context = {
        "request": request,
        "target_lang": (target_lang or util.get_target_lang_from_request(request)),
        "gettext": ugettext_for_locale(target_lang),
        "active_languages": get_well_translated_langs(),
    }

    context.update(util.rtl_context_stuff(target_lang))
    return context
Exemple #10
0
def test_compile_mo_files():
    """
    Test that compile_mo_files compiles translations which actually
    have the appropriate output
    """
    output_dir = tempfile.mkdtemp()
    fake_podir = pkg_resources.resource_filename('cc.i18n.tests', 'fake_podir')

    compile_mo_files(fake_podir, output_dir)

    expected_translations = {
        'en': {
            'New Zealand':
            'New Zealand',
            'Sampling':
            'Sampling',
            ('%(work_title)s by %(work_author)s is licensed under a '
             '<a rel="license" href="%(license_url)s">Creative Commons '
             '%(license_name)s License</a>.'):
            ('%(work_title)s by %(work_author)s is licensed under a '
             '<a rel="license" href="%(license_url)s">Creative Commons '
             '%(license_name)s License</a>.')
        },
        'pt': {
            'New Zealand':
            'Nova Zel\xc3\xa2ndia',
            'Sampling':
            'Sampling',
            ('%(work_title)s by %(work_author)s is licensed under a '
             '<a rel="license" href="%(license_url)s">Creative Commons '
             '%(license_name)s License</a>.'):
            ('A obra %(work_title)s de %(work_author)s '
             'foi licenciada com uma Licen\xc3\xa7a '
             '<a rel="license" href="%(license_url)s">Creative Commons - '
             '%(license_name)s</a>.')
        },
        'es': {
            'New Zealand':
            'Nueva Zelanda',
            'Sampling':
            'Sampling',
            ('%(work_title)s by %(work_author)s is licensed under a '
             '<a rel="license" href="%(license_url)s">Creative Commons '
             '%(license_name)s License</a>.'):
            ('%(work_title)s por %(work_author)s '
             'se encuentra bajo una Licencia '
             '<a rel="license" href="%(license_url)s">Creative Commons '
             '%(license_name)s</a>.')
        }
    }

    for language, expected_translations in expected_translations.iteritems():
        gettext = ugettext_for_locale(language, output_dir)
        for msgid, expected_translation in expected_translations.iteritems():
            assert gettext(msgid) == expected_translation.decode('utf-8')
Exemple #11
0
def _base_context(request, target_lang=None):
    context = {
        'request': request,
        'target_lang': (target_lang
                        or util.get_target_lang_from_request(request)),
        'gettext': ugettext_for_locale(target_lang),
        'active_languages': get_well_translated_langs(),
    }

    context.update(util.rtl_context_stuff(target_lang))
    return context
def _base_context(request, target_lang=None):
    context = {
        'request': request,
        'target_lang': (
            target_lang
            or util.get_target_lang_from_request(request)),
        'gettext': ugettext_for_locale(target_lang),
        'active_languages': get_well_translated_langs(),
        }

    context.update(util.rtl_context_stuff(target_lang))
    return context
Exemple #13
0
def render(template, context, locale=None):
    if locale:
        set_locale(locale)
    jinja = render_jinja(
        TEMPLATE_PATH,
        globals={'gettext' : ugettext_for_locale(LOCALE)},
        extensions=['jinja2.ext.i18n'],
        encoding='utf-8',
        )
    jinja._lookup.filters.update(TEMPLATE_FILTERS)
    template = jinja._lookup.get_template(template)
    return template.render(**context)
Exemple #14
0
    def description(self, language='en'):
        if language == '':
            language = 'en'  # why not?

        gettext = ugettext_for_locale(language)
        return gettext("""\
Use the option "International" if you desire a license using language
and terminology from international treaties.  If the licenses have
been ported to your jurisdiction and you feel that your jurisdiction's
ported licenses account for some aspect of local legislation that the
international licenses do not, then you may want to consider
<a href="http://wiki.creativecommons.org/Frequently_Asked_Questions#Should_I_choose_an_international_license_or_a_ported_license.3F">which
license is better suited for your needs</a>.""")
Exemple #15
0
    def description(self, language='en'):
        if language == '':
            language = 'en' # why not?

        gettext = ugettext_for_locale(language)
        return gettext(
            """\
Use the option "International" if you desire a license using language
and terminology from international treaties.  If the licenses have
been ported to your jurisdiction and you feel that your jurisdiction's
ported licenses account for some aspect of local legislation that the
international licenses do not, then you may want to consider
<a href="http://wiki.creativecommons.org/Frequently_Asked_Questions#Should_I_choose_an_international_license_or_a_ported_license.3F">which
license is better suited for your needs</a>.""")
Exemple #16
0
def convert_file(filename):
    gettext = ugettext_for_locale('en')
    graph = load_graph(os.path.abspath(filename))
    for subject, predicate, obj in graph.triples((
            None, None, None)):
        if hasattr(obj, 'language') and obj.language == 'i18n':
            graph.remove((subject, predicate, obj))
            new_obj = Literal(
                TRANSLATION_BIT_RE.sub(
                    lambda x: '${' + gettext(x.groups()[0]) + '}',
                    str(obj)),
                lang='i18n')
            graph.add((subject, predicate, new_obj))

    save_graph(graph, os.path.abspath(filename))
Exemple #17
0
def get_xmp_info(request_form, license, locale):
    ugettext = ugettext_for_locale(locale)

    # assemble the necessary information for the XMP file before rendering
    year = ('field_year' in request_form and request_form['field_year']) or ""
    creator = ('field_creator' in request_form
               and request_form['field_creator']) or None
    work_type = workType(
        ('field_format' in request_form and request_form['field_format'])
        or "")
    work_url = ('field_url' in request_form
                and request_form['field_url']) or None

    # determine the license notice
    if ('publicdomain' in license.uri):
        notice = "This %s is dedicated to the public domain." % (work_type)
        copyrighted = False
    else:
        if creator:
            notice = "Copyright %s %s.  " % (
                year,
                creator,
            )
        else:
            notice = ""

        i18n_work = ugettext('work')
        work_notice_template = ugettext(
            u'This %(work_type)s is licensed under a '
            u'<a rel="license" href="%(license_url)s">Creative Commons '
            u'%(license_name)s License</a>.')
        work_notice = work_notice_template % {
            'license_name': license.title(locale_to_lower_lower(locale)),
            'license_url': license.uri,
            'work_type': i18n_work
        }

        notice = notice + work_notice

        copyrighted = True

    return {
        'copyrighted': copyrighted,
        'notice': notice,
        'license_url': license.uri,
        'license': license,
        'work_url': work_url
    }
def test_compile_mo_files():
    """
    Test that compile_mo_files compiles translations which actually
    have the appropriate output
    """
    output_dir = tempfile.mkdtemp()
    fake_podir = pkg_resources.resource_filename(
        'cc.i18n.tests', 'fake_podir')

    compile_mo_files(fake_podir, output_dir)

    expected_translations = {
        'en': {
            'New Zealand': 'New Zealand',
            'Sampling': 'Sampling',
            ('%(work_title)s by %(work_author)s is licensed under a '
             '<a rel="license" href="%(license_url)s">Creative Commons '
             '%(license_name)s License</a>.'):
                ('%(work_title)s by %(work_author)s is licensed under a '
                 '<a rel="license" href="%(license_url)s">Creative Commons '
                 '%(license_name)s License</a>.')},
        'pt': {
            'New Zealand': 'Nova Zel\xc3\xa2ndia',
            'Sampling': 'Sampling',
            ('%(work_title)s by %(work_author)s is licensed under a '
             '<a rel="license" href="%(license_url)s">Creative Commons '
             '%(license_name)s License</a>.'):
                ('A obra %(work_title)s de %(work_author)s '
                 'foi licenciada com uma Licen\xc3\xa7a '
                 '<a rel="license" href="%(license_url)s">Creative Commons - '
                 '%(license_name)s</a>.')},
        'es': {
            'New Zealand': 'Nueva Zelanda',
            'Sampling': 'Sampling',
            ('%(work_title)s by %(work_author)s is licensed under a '
             '<a rel="license" href="%(license_url)s">Creative Commons '
             '%(license_name)s License</a>.'):
                ('%(work_title)s por %(work_author)s '
                 'se encuentra bajo una Licencia '
                 '<a rel="license" href="%(license_url)s">Creative Commons '
                 '%(license_name)s</a>.')}}

    for language, expected_translations in expected_translations.iteritems():
        gettext = ugettext_for_locale(language, output_dir)
        for msgid, expected_translation in expected_translations.iteritems():
            assert gettext(msgid) == expected_translation.decode('utf-8')
Exemple #19
0
def render_template(request, locale, template_path, context):
    """
    Render a template with the request in the response.

    Also stores data for unit testing purposes if appropriate.
    """
    template = TEMPLATE_ENV.get_template(template_path)
    context['request'] = request
    context['locale'] = locale
    if not 'gettext' in context:
        context['gettext'] = ugettext_for_locale(locale)

    rendered = template.render(context)

    if TESTS_ENABLED:
        TEST_TEMPLATE_CONTEXT[template_path] = context

    return rendered
Exemple #20
0
def render_template(request, locale, template_path, context):
    """
    Render a template with the request in the response.

    Also stores data for unit testing purposes if appropriate.
    """
    template = TEMPLATE_ENV.get_template(template_path)
    context['request'] = request
    context['locale'] = locale
    if not 'gettext' in context:
       context['gettext'] = ugettext_for_locale(locale)

    rendered = template.render(context)

    if TESTS_ENABLED:
        TEST_TEMPLATE_CONTEXT[template_path] = context

    return rendered
def get_xmp_info(request_form, license, locale):
    ugettext = ugettext_for_locale(locale)

    # assemble the necessary information for the XMP file before rendering
    year = ('field_year' in request_form and
            request_form['field_year']) or ""
    creator = ('field_creator' in request_form and
               request_form['field_creator']) or None
    work_type = workType(('field_format' in request_form and
                          request_form['field_format']) or "")
    work_url = ('field_url' in request_form and
                request_form['field_url']) or None

    # determine the license notice
    if ('publicdomain' in license.uri):
        notice = "This %s is dedicated to the public domain." % (work_type)
        copyrighted = False
    else:
        if creator:
            notice = "Copyright %s %s.  " % (year, creator,)
        else:
            notice = ""

        i18n_work = ugettext('work')
        work_notice_template = ugettext(
                u'This %(work_type)s is licensed under a '
                u'<a rel="license" href="%(license_url)s">Creative Commons '
                u'%(license_name)s License</a>.')
        work_notice = work_notice_template % {
            'license_name': license.title(locale_to_lower_lower(locale)),
            'license_url': license.uri,
            'work_type': i18n_work}

        notice = notice + work_notice

        copyrighted = True

    return {
        'copyrighted': copyrighted,
        'notice':notice,
        'license_url':license.uri,
        'license':license,
        'work_url':work_url}
Exemple #22
0
    def answers(self, language='en'):
        if language == '':
            language = 'en'  # why not?

        gettext = ugettext_for_locale(language)

        answers = []
        for jurisdiction in self._jurisdictions:
            # Answers format is
            # (label, id/key, description)
            # And jurisdictions don't need a description ;)
            juris_code = str(jurisdiction.rstrip('/').split('/')[-1])
            answers.append((gettext(mappers.COUNTRY_MAP[juris_code.lower()]),
                            juris_code, None))

        answers = sorted(answers, key=lambda answer: answer[1])

        if answers:
            answers = [(gettext('International'), '', None)] + answers

        return answers
Exemple #23
0
    def answers(self, language='en'):
        if language == '':
            language = 'en' # why not?
            
        gettext = ugettext_for_locale(language)

        answers = []
        for jurisdiction in self._jurisdictions:
            # Answers format is
            # (label, id/key, description)
            # And jurisdictions don't need a description ;)
            juris_code = str(jurisdiction.rstrip('/').split('/')[-1])
            answers.append(
                (gettext(mappers.COUNTRY_MAP[juris_code.lower()]),
                 juris_code, None))

        answers = sorted(answers, key=lambda answer: answer[1])

        if answers:
            answers = [(gettext('International'), '', None)] + answers

        return answers
Exemple #24
0
def inverse_translate(string, target_language, domain='cc_org'):
    """
    Translate something like "Foo ${bar} baz", where we actually
    preserve "Foo " and " baz" and translate "${bar} (using "bar" as
    the msgid)

       >>> from cc.i18n import ccorg_i18n_setup
       >>> translated_string = inverse_translate(
       ...    'foo ${country.pt} baz ${license.GPL_name_full}',
       ...    target_language='en_US')
       >>> translated_string == 'foo Portugal baz GNU General Public License'
    """
    gettext = ugettext_for_locale(target_language)
    string = unicode_cleaner(string)
    translated_string = u''
    last_pos = 0
    for match in TRANSLATION_BIT_RE.finditer(string):
        translated_string += string[last_pos:match.start()]
        msgid = match.group(1)
        translated_string += gettext(msgid)
        last_pos = match.end()
    translated_string += string[last_pos:]
    return translated_string
Exemple #25
0
    def format(self, license, work_dict=None, locale='en'):
        work_dict = work_dict or {}

        gettext = ugettext_for_locale(locale)

        dctype = None
        if work_dict.get('format'):
            dctype = _translate_dctype(work_dict['format'].lower())

        image_header = IMAGE_HEADER_TEMPLATE % {
            'license_url': license.uri,
            'util.Creative_Commons_License': util.escape(gettext(
                u'Creative Commons License')),
            'license_logo': license.logo}

        body_template = gettext(
            u'This %(work_type)s is in the '
            u'<a rel="license" href="http://creativecommons.org/licenses/publicdomain/">Public Domain</a>.')
        body_vars = {'work_type': process_work_type(gettext, dctype)}

        message = image_header + body_template % body_vars

        return message
Exemple #26
0
def inverse_translate(string, target_language, domain='cc_org'):
    """
    Translate something like "Foo ${bar} baz", where we actually
    preserve "Foo " and " baz" and translate "${bar} (using "bar" as
    the msgid)

       >>> from cc.i18n import ccorg_i18n_setup
       >>> translated_string = inverse_translate(
       ...    'foo ${country.pt} baz ${license.GPL_name_full}',
       ...    target_language='en_US')
       >>> translated_string == 'foo Portugal baz GNU General Public License'
    """
    gettext = ugettext_for_locale(target_language)
    string = unicode_cleaner(string)
    translated_string = u''
    last_pos = 0
    for match in TRANSLATION_BIT_RE.finditer(string):
        translated_string += string[last_pos:match.start()]
        msgid = match.group(1)
        translated_string += gettext(msgid)
        last_pos = match.end()
    translated_string += string[last_pos:]
    return translated_string
Exemple #27
0
    def legalcodes(self, language='en'):
        """
        Return a list of
        [(legalcode_uri, legalcode_lang, legalcode_lang_translated)]
        for this license.

        If this is a single-legalcode option, it'll probably return
        [(legalcode_uri, None, None)]

        """
        if self._legalcodes.has_key(language):
            return self._legalcodes[language]

        gettext = ugettext_for_locale(language)

        legalcodes = set()
        for legalcode, lang in rdf_helper.get_license_legalcodes(self.uri):
            if lang is None:
                translated_lang = None
            # <terrible_fixable_hacks>
            # We should probably add lang.sr_CYRL and lang.sr_LATN messages
            elif lang == 'sr-Cyrl':
                translated_lang = gettext('Serbian')
            elif lang == 'sr-Latn':
                translated_lang = 'srpski (latinica)'
            # </terrible_fixable_hacks>
            else:
                translated_lang = gettext(
                    mappers.LANG_MAP[locale_to_lower_upper(lang)])

            legalcodes.add(
                (legalcode, lang, translated_lang))

        self._legalcodes[language] = legalcodes

        return legalcodes
Exemple #28
0
    def format(self, license, work_dict=None, locale='en'):
        gettext = ugettext_for_locale(locale)

        work_dict = work_dict or {}

        work_title = work_dict.get('work_title', False)
        actor_href = work_dict.get('actor_href', '').strip()
        actor = work_dict.get('name', '').strip()

        template = TEMPLATE_ENV.get_template('cc0.html')

        work_jurisdiction = work_dict.get('work_jurisdiction')
        country_name = None
        if work_jurisdiction not in ('', '-', None, False):
            if work_jurisdiction.lower() in mappers.COUNTRY_MAP:
                country_name = gettext(
                    mappers.COUNTRY_MAP[work_jurisdiction.lower()])
            # Crappy fallback to this CSV.  We should homogenize these
            # things...
            elif work_jurisdiction.upper() in util.CODE_COUNTRY_MAP:
                country_name = gettext(
                    util.CODE_COUNTRY_MAP[work_jurisdiction.upper()])

        rendered_template = template.render({
            "gettext": gettext,
            "license": license,
            "actor": actor,
            "actor_href": actor_href,
            "work_jurisdiction": work_jurisdiction,
            "publisher": actor_href or "[_:publisher]",
            "country_name": country_name,
            "work_title": work_title,
            "form": work_dict
        })

        return util.remove_blank_lines(rendered_template)
Exemple #29
0
try:
    import json
except ImportError:
    import simplejson as json

LOCALE = 'en_US'
TEMPLATE_PATH = os.path.join(os.path.dirname(__file__), 'templates')

__all__ = ['set_locale', 'render', 'response']

def set_locale(locale):
    global LOCALE
    LOCALE = locale

TEMPLATE_GLOBALS = {
    'gettext' : ugettext_for_locale(LOCALE),
    }

TEMPLATE_FILTERS = {
    'get_permissions_link': get_permissions_link,
    'add_qs_parameter': add_qs_parameter,
    }
    
def render(template, context, locale=None):
    if locale:
        set_locale(locale)
    jinja = render_jinja(
        TEMPLATE_PATH,
        globals={'gettext' : ugettext_for_locale(LOCALE)},
        extensions=['jinja2.ext.i18n'],
        encoding='utf-8',
Exemple #30
0
    def label(self, language='en'):
        if language == '':
            language = 'en' # why not?

        gettext = ugettext_for_locale(language)
        return gettext("Jurisdiction of your license")
Exemple #31
0
    def format(self, license, work_dict=None, locale='en'):
        """
        Return an HTML + RDFa string of text for the license.

        work_dict takes the following keys:
         - work_title: Name of the work
         - author_title: Original author of the work
         - author_href: Link to the original author of the work
         - curator_title: The person who identified this work
         - curator_href: Link to the person who identified this work
         - waive_cc0: Whether the author has also waived their rights
           under CC0 (boolean)
        """
        gettext = ugettext_for_locale(locale)

        # Property gathering
        # ------------------
        work_dict = work_dict or {}

        work_title = work_dict.get('work_title', False)

        author_title = work_dict.get('author_title', '').strip()
        author_href = work_dict.get('author_href', '').strip()

        curator_title = work_dict.get('curator_title', '').strip()
        curator_href = work_dict.get('curator_href', '').strip()

        waive_cc0 = work_dict.get('waive_cc0', False)

        # Find the "body" template
        # ------------------------

        has_author = bool(author_title or author_href)
        has_curator = bool(curator_title or curator_href)

        # All (work_title and author and curator)
        if work_title and has_author and has_curator:
            body_msg = PDMARK_WORKTITLE_AUTHOR_CURATOR
        # Only work_title
        elif work_title and not has_author and not has_curator:
            body_msg = PDMARK_WORKTITLE
        # Only author
        elif has_author and not work_title and not has_curator:
            body_msg = PDMARK_AUTHOR
        # Only curator
        elif has_curator and not work_title and not has_author:
            body_msg = PDMARK_CURATOR
        # work_title and author
        elif work_title and has_author and not has_curator:
            body_msg = PDMARK_WORKTITLE_AUTHOR
        # work_title and curator
        elif work_title and has_curator and not has_author:
            body_msg = PDMARK_WORKTITLE_CURATOR
        # author and curator
        elif has_author and has_curator and not work_title:
            body_msg = PDMARK_AUTHOR_CURATOR
        # plain
        else:
            body_msg = PDMARK_PLAIN

        # Translate the body
        # ------------------
        mapping = {}

        if work_title:
            mapping['work_title'] = u'<span property="dct:title">%s</span>' % (
                util.escape(work_title))

        if has_author:
            if author_title and author_href:
                mapping['author'] = PDMARK_AUTHOR_LINK % (
                    {
                        'author_title': util.escape(author_title),
                        'author_href': util.escape(author_href)
                    })
            elif author_title and not author_href:
                mapping['author'] = PDMARK_AUTHOR_NOLINK % ({
                    'author_title':
                    util.escape(author_title)
                })
            elif author_href and not author_title:
                mapping['author'] = PDMARK_AUTHOR_ONLYLINK % ({
                    'author_href':
                    util.escape(author_href)
                })

        if has_curator:
            if curator_title and curator_href:
                mapping['curator'] = PDMARK_CURATOR_LINK % (
                    {
                        'curator_title': util.escape(curator_title),
                        'curator_href': util.escape(curator_href)
                    })
            elif curator_title and not curator_href:
                mapping['curator'] = PDMARK_CURATOR_NOLINK % ({
                    'curator_title':
                    util.escape(curator_title)
                })
            elif curator_href and not curator_title:
                mapping['curator'] = PDMARK_CURATOR_ONLYLINK % ({
                    'curator_href':
                    util.escape(curator_href)
                })

        body = gettext(body_msg) % mapping

        # Add the header and footers
        # --------------------------
        output_sections = []

        # XXX: Norms guidelines may affect opening <p>?
        if work_title or has_author or has_curator:
            output_sections.append(
                u'<p xmlns:dct="http://purl.org/dc/terms/">')
        else:
            output_sections.append(u'<p>')

        # Add logos
        output_sections.append(PDMARK_LOGO_HTML)
        if waive_cc0:
            output_sections.append(CC0_LOGO_HTML)

        output_sections.append(u'<br />')

        # Add body
        output_sections.append(body)

        # Add footer
        output_sections.append(u'</p>')

        return u'\n'.join(output_sections)
# To the extent possible under law, the author(s) have dedicated all
# copyright and related and neighboring rights to this software to the
# public domain worldwide. This software is distributed without any
# warranty.
# 
# You should have received a copy of the CC0 Public Domain Dedication along
# with this software. If not, see
# <http://creativecommons.org/publicdomain/zero/1.0/>.


import re
import sys
from cc.i18n import gettext_i18n


gettext = gettext_i18n.ugettext_for_locale('en')

def countspace(some_str):
    """Count leading whitespace"""
    counter = 0
    for char in some_str:
        if char == " ":
            counter += 1
        else:
            break

    return counter


def nicer_args(args):
    arglines = args.strip().splitlines()
Exemple #33
0
    def format(self, license, work_dict=None, locale='en'):
        """Return an HTML + RDFa string serialization for the license,
            optionally incorporating the work metadata and locale."""
        gettext = ugettext_for_locale(locale)

        work_dict = work_dict or {}

        image_header = IMAGE_HEADER_TEMPLATE % {
            'license_url':
            license.uri,
            'util.Creative_Commons_License':
            util.escape(gettext(u'Creative Commons License')),
            'license_logo':
            license.logo
        }

        dctype = None
        if work_dict.get('format'):
            dctype = _translate_dctype(work_dict['format'].lower())

        body_vars = {
            'license_url':
            license.uri,
            'license_name':
            util.escape(license.title(locale_to_lower_lower(locale)))
        }

        if ((work_dict.get('attribution_url')
             or work_dict.get('attribution_name'))
                and work_dict.get('worktitle')):
            body_template = gettext(
                u'%(work_title)s by %(work_author)s is licensed under a '
                u'<a rel="license" href="%(license_url)s">Creative Commons '
                u'%(license_name)s License</a>.')
            body_vars.update({
                'work_title':
                process_work_title(dctype, work_dict['worktitle']),
                'work_author':
                process_work_author(work_dict.get('attribution_url'),
                                    work_dict.get('attribution_name'))
            })

        elif work_dict.get('attribution_url') \
                or work_dict.get('attribution_name'):
            body_template = gettext(
                u'This %(work_type)s by %(work_author)s is licensed under '
                u'a <a rel="license" href="%(license_url)s">Creative '
                u'Commons %(license_name)s License</a>.')
            body_vars.update({
                'work_type':
                process_work_type(gettext, dctype),
                'work_author':
                process_work_author(work_dict.get('attribution_url'),
                                    work_dict.get('attribution_name'))
            })

        elif work_dict.get('worktitle'):
            body_template = gettext(
                u'%(work_title)s is licensed under a '
                u'<a rel="license" href="%(license_url)s">Creative Commons '
                u'%(license_name)s License</a>.')
            body_vars.update({
                'work_title':
                process_work_title(dctype, work_dict['worktitle'])
            })

        else:
            body_template = gettext(
                u'This %(work_type)s is licensed under a '
                u'<a rel="license" href="%(license_url)s">Creative Commons '
                u'%(license_name)s License</a>.')
            body_vars.update({'work_type': process_work_type(gettext, dctype)})

        message = image_header + body_template % body_vars

        if work_dict.get('source_work'):
            source_work_template = gettext(
                u'Based on a work at %(source_link)s.')
            source_domain = urlparse(work_dict['source_work'])[1]
            if not source_domain.strip():
                source_domain = work_dict['source_work']
            source_work = source_work_template % {
                'source_link': SOURCE_LINK_TEMPLATE % {
                    'source_work': util.escape(work_dict['source_work']),
                    'source_domain': util.escape(source_domain)
                }
            }
            message = message + "<br />" + source_work

        if work_dict.get('more_permissions_url'):
            more_perms_template = gettext(
                u'Permissions beyond the scope of this license may be '
                u'available at %(more_perms_link)s.')
            more_perms = more_perms_template % {
                'more_perms_link': MORE_PERMS_LINK_TEMPATE % {
                    'more_permissions_url':
                    util.escape(work_dict['more_permissions_url'])
                }
            }
            message = message + "<br />" + more_perms

        return message
Exemple #34
0
    def format(self, license, work_dict=None, locale='en'):
        """Return an HTML + RDFa string serialization for the license,
            optionally incorporating the work metadata and locale."""
        gettext = ugettext_for_locale(locale)

        work_dict = work_dict or {}

        localized_deed = license.uri
        default_lang = license.jurisdiction.default_language
        if not default_lang:
            default_lang = "en"
        if locale != default_lang:
            localized_deed += "deed." + locale

        image_header = IMAGE_HEADER_TEMPLATE % {
            'license_url': localized_deed,
            'util.Creative_Commons_License': util.escape(
                gettext(u'Creative Commons License')),
            'license_logo': license.logo}

        dctype = None
        if work_dict.get('format'):
            dctype = _translate_dctype(work_dict['format'].lower())

        body_vars = {
            'license_url': localized_deed,
            'license_name': util.escape(
                license.title(locale_to_lower_lower(locale)))}

        if ((work_dict.get('attribution_url')
             or work_dict.get('attribution_name'))
                and work_dict.get('worktitle')):
            body_template = gettext(
                    u'%(work_title)s by %(work_author)s is licensed under a '
                    u'<a rel="license" href="%(license_url)s">Creative Commons '
                    u'%(license_name)s License</a>.')
            body_vars.update(
                {'work_title': process_work_title(
                        dctype, work_dict['worktitle']),
                 'work_author': process_work_author(
                        work_dict.get('attribution_url'),
                        work_dict.get('attribution_name'))})
                 
        elif work_dict.get('attribution_url') \
                or work_dict.get('attribution_name'):
            body_template = gettext(
                    u'This %(work_type)s by %(work_author)s is licensed under '
                    u'a <a rel="license" href="%(license_url)s">Creative '
                    u'Commons %(license_name)s License</a>.')
            body_vars.update(
                {'work_type': process_work_type(gettext, dctype),
                 'work_author': process_work_author(
                        work_dict.get('attribution_url'),
                        work_dict.get('attribution_name'))})

        elif work_dict.get('worktitle'):
            body_template = gettext(
                    u'%(work_title)s is licensed under a '
                    u'<a rel="license" href="%(license_url)s">Creative Commons '
                    u'%(license_name)s License</a>.')
            body_vars.update(
                {'work_title': process_work_title(
                        dctype, work_dict['worktitle'])})

        else:
            body_template = gettext(
                    u'This %(work_type)s is licensed under a '
                    u'<a rel="license" href="%(license_url)s">Creative Commons '
                    u'%(license_name)s License</a>.')
            body_vars.update(
                {'work_type': process_work_type(gettext, dctype)})

        message = image_header + body_template % body_vars

        if work_dict.get('source_work'):
            source_work_template = gettext(
                u'Based on a work at %(source_link)s.')
            source_domain = urlparse(work_dict['source_work'])[1]
            if not source_domain.strip():
                source_domain = work_dict['source_work']
            source_work = source_work_template % {
                'source_link': SOURCE_LINK_TEMPLATE % {
                    'source_work': util.escape(work_dict['source_work']),
                    'source_domain': util.escape(source_domain)}}
            message = message + "<br />" + source_work

        if work_dict.get('more_permissions_url'):
            more_perms_template = gettext(
                    u'Permissions beyond the scope of this license may be '
                    u'available at %(more_perms_link)s.')
            more_perms = more_perms_template % {
                'more_perms_link': MORE_PERMS_LINK_TEMPATE % {
                    'more_permissions_url': util.escape(
                        work_dict['more_permissions_url'])}}
            message = message + "<br />" + more_perms

        return message
Exemple #35
0
    def label(self, language='en'):
        if language == '':
            language = 'en'  # why not?

        gettext = ugettext_for_locale(language)
        return gettext("Jurisdiction of your license")
Exemple #36
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
Exemple #37
0
    def format(self, license, work_dict=None, locale='en'):
        """
        Return an HTML + RDFa string of text for the license.

        work_dict takes the following keys:
         - work_title: Name of the work
         - author_title: Original author of the work
         - author_href: Link to the original author of the work
         - curator_title: The person who identified this work
         - curator_href: Link to the person who identified this work
         - waive_cc0: Whether the author has also waived their rights
           under CC0 (boolean)
        """
        gettext = ugettext_for_locale(locale)

        # Property gathering
        # ------------------
        work_dict = work_dict or {}

        work_title = work_dict.get('work_title', False)

        author_title = work_dict.get('author_title', '').strip()
        author_href = work_dict.get('author_href', '').strip()

        curator_title = work_dict.get('curator_title', '').strip()
        curator_href = work_dict.get('curator_href', '').strip()

        waive_cc0 = work_dict.get('waive_cc0', False)

        # Find the "body" template
        # ------------------------

        has_author = bool(author_title or author_href)
        has_curator = bool(curator_title or curator_href)

        # All (work_title and author and curator)
        if work_title and has_author and has_curator:
            body_msg = PDMARK_WORKTITLE_AUTHOR_CURATOR
        # Only work_title
        elif work_title and not has_author and not has_curator:
            body_msg = PDMARK_WORKTITLE
        # Only author
        elif has_author and not work_title and not has_curator:
            body_msg = PDMARK_AUTHOR
        # Only curator
        elif has_curator and not work_title and not has_author:
            body_msg = PDMARK_CURATOR
        # work_title and author
        elif work_title and has_author and not has_curator:
            body_msg = PDMARK_WORKTITLE_AUTHOR
        # work_title and curator
        elif work_title and has_curator and not has_author:
            body_msg = PDMARK_WORKTITLE_CURATOR
        # author and curator
        elif has_author and has_curator and not work_title:
            body_msg = PDMARK_AUTHOR_CURATOR
        # plain
        else:
            body_msg = PDMARK_PLAIN

        # Translate the body
        # ------------------
        mapping = {}

        if work_title:
            mapping['work_title'] = u'<span property="dct:title">%s</span>' % (
                util.escape(work_title))

        if has_author:
            if author_title and author_href:
                mapping['author'] = PDMARK_AUTHOR_LINK % (
                    {'author_title': util.escape(author_title),
                     'author_href': util.escape(author_href)})
            elif author_title and not author_href:
                mapping['author'] = PDMARK_AUTHOR_NOLINK % (
                    {'author_title': util.escape(author_title)})
            elif author_href and not author_title:
                mapping['author'] = PDMARK_AUTHOR_ONLYLINK % (
                    {'author_href': util.escape(author_href)})
                
        if has_curator:
            if curator_title and curator_href:
                mapping['curator'] = PDMARK_CURATOR_LINK % (
                    {'curator_title': util.escape(curator_title),
                     'curator_href': util.escape(curator_href)})
            elif curator_title and not curator_href:
                mapping['curator'] = PDMARK_CURATOR_NOLINK % (
                    {'curator_title': util.escape(curator_title)})
            elif curator_href and not curator_title:
                mapping['curator'] = PDMARK_CURATOR_ONLYLINK % (
                    {'curator_href': util.escape(curator_href)})

        body = gettext(body_msg) % mapping

        # Add the header and footers
        # --------------------------
        output_sections = []

        # XXX: Norms guidelines may affect opening <p>?
        if work_title or has_author or has_curator:
            output_sections.append(
                u'<p xmlns:dct="http://purl.org/dc/terms/">')
        else:
            output_sections.append(u'<p>')

        # Add logos
        output_sections.append(PDMARK_LOGO_HTML)
        if waive_cc0:
            output_sections.append(CC0_LOGO_HTML)

        output_sections.append(u'<br />')

        # Add body
        output_sections.append(body)

        # Add footer
        output_sections.append(u'</p>')

        return u'\n'.join(output_sections)