示例#1
0
def classic_chooser_view(request):
    target_lang = util.get_target_lang_from_request(request)
    context = _base_context(request, target_lang)
    gettext = context["gettext"]

    available_jurisdiction_codes = [j.code for j in get_selector_jurisdictions("standard") if j.code != ""]

    requested_jurisdiction = None
    if request.GET.has_key("jurisdiction") and request.GET["jurisdiction"] in available_jurisdiction_codes:
        requested_jurisdiction = request.GET["jurisdiction"]

    # Sort the jurisdictions for the dropdown via the translated name
    jurisdictions_names = [(juris, gettext(mappers.COUNTRY_MAP[juris])) for juris in available_jurisdiction_codes]
    jurisdictions_names = sorted(jurisdictions_names, key=lambda juris: juris[1])

    show_jurisdiction = request.GET.get("jurisdiction_choose") == "1"

    context.update(
        {
            "jurisdictions_names": jurisdictions_names,
            "show_jurisdiction": show_jurisdiction,
            "requested_jurisdiction": requested_jurisdiction,
            "referrer": request.headers.get("REFERER", ""),
            "page_style": "2cols",
        }
    )

    if request.GET.get("partner"):
        context["pd_get_params"] = util.publicdomain_partner_get_params(request.GET)

        return Response(util.render_template(request, target_lang, "chooser_pages/partner/index.html", context))
    else:
        return Response(util.render_template(request, target_lang, "chooser_pages/classic_chooser.html", context))
示例#2
0
def choose_results_view(request):
    target_lang = util.get_target_lang_from_request(request)

    context = _base_context(request, target_lang)
    request_form = request.GET or request.POST

    # Special case: if anyone is linking to GPL/LGPL (mistake on old
    # deeds), redirect them to gnu.org
    if request_form.get('license_code') in ("GPL", "LGPL"):
        return exc.HTTPMovedPermanently(
            location='http://www.gnu.org/licenses/gpl-howto.html')

    # Select a license based on the request form
    license = _issue_license(request_form)

    # If the request didn't have all the required information, we have no license
    if not license:
        return exc.HTTPBadRequest(
            'Could not determine license from parameters.')

    # If the license is retired, redirect to info page
    if license.deprecated:
        # Special case: PDCC should redirect to /publicdomain/
        if license.license_code == 'publicdomain':
            return exc.HTTPMovedPermanently(location="/publicdomain/")
        else:
            return exc.HTTPMovedPermanently(location="/retiredlicenses")

    # Generate the HTML+RDFa for the license + provided work information
    work_dict = _formatter_work_dict(request_form)
    license_slim_logo = license.logo_method('80x15')

    license_html = HTML_FORMATTER.format(license, work_dict, target_lang)

    context.update({
        'license': license,
        'license_slim_logo': license_slim_logo,
        'license_title': license.title(target_lang),
        'license_html': license_html
    })

    if request.GET.get('partner'):
        context.update({
            'exit_url':
            _generate_exit_url(request_form.get('exit_url', ''),
                               request_form.get('referrer', ''), license)
        })

    if request.GET.get('partner'):
        return Response(
            util.render_template(request, target_lang,
                                 'chooser_pages/partner/results.html',
                                 context))
    else:
        return Response(
            util.render_template(request, target_lang,
                                 'chooser_pages/results.html', context))
示例#3
0
def choose_results_view(request):
    target_lang = util.get_target_lang_from_request(request)

    context = _base_context(request, target_lang)
    request_form = request.GET or request.POST

    # Special case: if anyone is linking to GPL/LGPL (mistake on old
    # deeds), redirect them to gnu.org
    if request_form.get('license_code') in ("GPL", "LGPL"):
        return exc.HTTPMovedPermanently(
            location='http://www.gnu.org/licenses/gpl-howto.html')

    # Select a license based on the request form
    license = _issue_license(request_form)

    # If the request didn't have all the required information, we have no license
    if not license:
        return exc.HTTPBadRequest('Could not determine license from parameters.')

    # If the license is retired, redirect to info page
    if license.deprecated:
        # Special case: PDCC should redirect to /publicdomain/
        if license.license_code == 'publicdomain':
            return exc.HTTPMovedPermanently(location="/publicdomain/")
        else:
            return exc.HTTPMovedPermanently(location="/retiredlicenses")

    # Generate the HTML+RDFa for the license + provided work information
    work_dict = _formatter_work_dict(request_form)
    license_slim_logo = license.logo_method('80x15')

    license_html = HTML_FORMATTER.format(
        license, work_dict, target_lang)

    context.update(
        {'license': license,
         'license_slim_logo': license_slim_logo,
         'license_title': license.title(target_lang),
         'license_html': license_html})

    if request.GET.get('partner'):
        context.update(
            {'exit_url': _generate_exit_url(
                    request_form.get('exit_url', ''),
                    request_form.get('referrer', ''),
                    license)})

    if request.GET.get('partner'):
        return Response(
            util.render_template(
                request, target_lang,
                'chooser_pages/partner/results.html', context))
    else:
        return Response(
            util.render_template(
                request, target_lang,
                'chooser_pages/results.html', context))
示例#4
0
def choose_results_view(request):
    target_lang = util.get_target_lang_from_request(request)

    context = _base_context(request, target_lang)
    request_form = request.GET or request.POST

    # Special case: if anyone is linking to GPL/LGPL (mistake on old
    # deeds), redirect them to gnu.org
    if request_form.get("license_code") in ("GPL", "LGPL"):
        return exc.HTTPMovedPermanently(location="http://www.gnu.org/licenses/gpl-howto.html")

    # Select a license based on the request form
    license = _issue_license(request_form)

    # If the license is retired, redirect to info page
    if license.deprecated:
        # Special case: PDCC should redirect to /publicdomain/
        if license.license_code == "publicdomain":
            return exc.HTTPMovedPermanently(location="/publicdomain/")
        else:
            return exc.HTTPMovedPermanently(location="/retiredlicenses")

    # Generate the HTML+RDFa for the license + provided work information
    work_dict = _formatter_work_dict(request_form)
    license_slim_logo = license.logo_method("80x15")

    license_html = HTML_FORMATTER.format(license, work_dict, target_lang)

    context.update(
        {
            "license": license,
            "license_slim_logo": license_slim_logo,
            "license_title": license.title(target_lang),
            "license_html": license_html,
        }
    )

    if request.GET.get("partner"):
        context.update(
            {
                "exit_url": _generate_exit_url(
                    request_form.get("exit_url", ""), request_form.get("referrer", ""), license
                )
            }
        )

    if request.GET.get("partner"):
        return Response(util.render_template(request, target_lang, "chooser_pages/partner/results.html", context))
    else:
        return Response(util.render_template(request, target_lang, "chooser_pages/results.html", context))
示例#5
0
def choose_xmp_view(request):
    request_form = request.GET or request.POST
    license = _issue_license(request_form)
    target_lang = util.get_target_lang_from_request(request)

    def attrib_or_none(field_name):
        return request_form.get(field_name, u"").strip() or None

    context = xmp_template.get_xmp_info(request_form, license, target_lang)
    context["default_lang"] = target_lang
    context["work_title"] = attrib_or_none("field_worktitle")
    context["attrib_name"] = attrib_or_none("field_attribute_to_name")
    context["attrib_url"] = attrib_or_none("field_attribute_to_url")
    context["permissions_url"] = attrib_or_none("field_morepermissionsurl")
    context["licenses"] = [
        {"lang": "x-default", "notice": context["notice"]},
        {"lang": target_lang, "notice": context["notice"]},
    ]
    del context["notice"]
    if target_lang != "en":
        xmp_info_en = xmp_template.get_xmp_info(request_form, license, "en")
        context["licenses"].append({"lang": "en", "notice": xmp_info_en["notice"]})

    xmp_data = util.render_template(request, target_lang, "chooser_pages/metadata.xmp", context)

    return Response(
        xmp_data,
        content_type="application/xmp; charset=UTF-8",
        charset="UTF-8",
        content_disposition='attachment; filename="CC_%s.xmp' % (license.title().strip().replace(" ", "_")),
    )
def publicdomain_result(request):
    target_lang = util.get_target_lang_from_request(request)

    request_form = request.GET or request.POST

    # make sure the user selected "confirm"
    if request_form.get('understand', False) != 'confirm':
        return exc.HTTPFound(
            location='%s?%s' % (
                './publicdomain-3', urlencode(request.GET)))

    work_info = _work_info(request_form)
    license_html = PUBLICDOMAIN_HTML_FORMATTER.format(
        cc.license.by_code('publicdomain'),
        work_info, target_lang)

    context = _base_context(request, target_lang)
    context.update({
            'request_form': request_form,
            'license_html': license_html})

    return Response(
        util.render_template(
            request, target_lang,
            'chooser_pages/publicdomain/publicdomain-4.html', context))
示例#7
0
def license_catcher(request):
    """
    If someone chooses something like /licenses/by/ (fails to select a
    version, etc) help point them to the available licenses.
    """
    target_lang = util.get_target_lang_from_request(request)

    license_versions = util.catch_license_versions_from_request(request)

    if not license_versions:
        return exc.HTTPNotFound()

    context = {
        'request': request,
        'license_versions': reversed(license_versions),
        'license_class': license_versions[0].license_class,
        'page_style': 'bare',
        'target_lang': target_lang
    }
    context.update(util.rtl_context_stuff(target_lang))

    # This is a helper page, but it's still for not-found situations.
    # 404!
    return Response(util.render_template(request, target_lang,
                                         'catalog_pages/license_catcher.html',
                                         context),
                    status=404)
示例#8
0
def license_catcher(request):
    """
    If someone chooses something like /licenses/by/ (fails to select a
    version, etc) help point them to the available licenses.
    """
    target_lang = util.get_target_lang_from_request(request)

    license_versions = util.catch_license_versions_from_request(request)

    if not license_versions:
        return exc.HTTPNotFound()

    context = {'request': request,
               'license_versions': reversed(license_versions),
               'license_class': license_versions[0].license_class,
               'page_style': 'bare',
               'target_lang': target_lang}
    context.update(util.rtl_context_stuff(target_lang))

    # This is a helper page, but it's still for not-found situations.
    # 404!
    return Response(
        util.render_template(
            request, target_lang,
            'catalog_pages/license_catcher.html', context),
        status=404)
def classic_chooser_view(request):
    target_lang = util.get_target_lang_from_request(request)
    context = _base_context(request, target_lang)
    gettext = context['gettext']

    available_jurisdiction_codes = [
        j.code for j in get_selector_jurisdictions('standard')
        if j.code != '']
    
    requested_jurisdiction = None
    if request.GET.has_key('jurisdiction') and \
            request.GET['jurisdiction'] in available_jurisdiction_codes:
        requested_jurisdiction = request.GET['jurisdiction']        

    # Sort the jurisdictions for the dropdown via the translated name
    jurisdictions_names = [
        (juris, gettext(mappers.COUNTRY_MAP[juris]))
        for juris in available_jurisdiction_codes]
    jurisdictions_names = sorted(
        jurisdictions_names, key=lambda juris: juris[1])

    show_jurisdiction = request.GET.get('jurisdiction_choose') == '1'

    context.update(
        {'jurisdictions_names': jurisdictions_names,
         'show_jurisdiction': show_jurisdiction,
         'requested_jurisdiction': requested_jurisdiction,
         'referrer': request.headers.get('REFERER',''),
         'page_style': '2cols'})

    if request.GET.get('partner'):
        context['pd_get_params'] = util.publicdomain_partner_get_params(
            request.GET)

        return Response(
            util.render_template(
                request, target_lang,
                'chooser_pages/partner/index.html', context))
    else:
        return Response(
            util.render_template(
                request, target_lang,
                'chooser_pages/classic_chooser.html', context))
示例#10
0
def classic_chooser_view(request):
    target_lang = util.get_target_lang_from_request(request)
    context = _base_context(request, target_lang)
    gettext = context['gettext']

    available_jurisdiction_codes = [
        j.code for j in get_selector_jurisdictions('standard') if j.code != ''
    ]

    requested_jurisdiction = None
    if request.GET.has_key('jurisdiction') and \
            request.GET['jurisdiction'] in available_jurisdiction_codes:
        requested_jurisdiction = request.GET['jurisdiction']

    # Sort the jurisdictions for the dropdown via the translated name
    jurisdictions_names = [(juris, gettext(mappers.COUNTRY_MAP[juris]))
                           for juris in available_jurisdiction_codes]
    jurisdictions_names = sorted(jurisdictions_names,
                                 key=lambda juris: juris[1])

    show_jurisdiction = request.GET.get('jurisdiction_choose') == '1'

    context.update({
        'jurisdictions_names': jurisdictions_names,
        'show_jurisdiction': show_jurisdiction,
        'requested_jurisdiction': requested_jurisdiction,
        'referrer': request.headers.get('REFERER', ''),
        'page_style': '2cols'
    })

    if request.GET.get('partner'):
        context['pd_get_params'] = util.publicdomain_partner_get_params(
            request.GET)

        return Response(
            util.render_template(request, target_lang,
                                 'chooser_pages/partner/index.html', context))
    else:
        return Response(
            util.render_template(request, target_lang,
                                 'chooser_pages/classic_chooser.html',
                                 context))
示例#11
0
def publicdomain_confirm(request):
    target_lang = util.get_target_lang_from_request(request)

    request_form = request.GET or request.POST

    context = _base_context(request, target_lang)
    context["request_form"] = request_form

    return Response(
        util.render_template(request, target_lang, "chooser_pages/publicdomain/publicdomain-3.html", context)
    )
def publicdomain_landing(request):
    target_lang = util.get_target_lang_from_request(request)

    request_form = request.GET or request.POST

    context = _base_context(request, target_lang)
    context['request_form'] = request_form

    return Response(
        util.render_template(
            request, target_lang,
            'chooser_pages/publicdomain/publicdomain-2.html', context))
示例#13
0
def publicdomain_confirm(request):
    target_lang = util.get_target_lang_from_request(request)

    request_form = request.GET or request.POST

    context = _base_context(request, target_lang)
    context['request_form'] = request_form

    return Response(
        util.render_template(request, target_lang,
                             'chooser_pages/publicdomain/publicdomain-3.html',
                             context))
示例#14
0
def characteristic_view(request):
    """
    Return one of the characteristic description pages.
    """
    target_lang = util.get_target_lang_from_request(request)

    template_name = 'characteristic/%s.html' % (
        request.matchdict['characteristic'])

    context = {'request': request}
    context.update(util.rtl_context_stuff(target_lang))

    return Response(
        util.render_template(request, target_lang, template_name, context))
示例#15
0
def licenses_view(request):
    target_lang = util.get_target_lang_from_request(request)

    context = {
        'active_languages': get_well_translated_langs(),
        'page_style': "bare"
    }
    context.update(util.rtl_context_stuff(target_lang))

    # Don't cache the response for internationalization reasons
    response = Response(
        util.render_template(request, target_lang,
                             'catalog_pages/licenses-index.html', context))
    response.headers.add('Cache-Control', 'no-cache')
    return response
示例#16
0
def licenses_view(request):
    target_lang = util.get_target_lang_from_request(request)

    context = {
        'active_languages': get_well_translated_langs(),
        'page_style': "bare"}
    context.update(util.rtl_context_stuff(target_lang))

    # Don't cache the response for internationalization reasons
    response = Response(
        util.render_template(
            request, target_lang,
            'catalog_pages/licenses-index.html', context))
    response.headers.add('Cache-Control', 'no-cache')
    return response
示例#17
0
def characteristic_view(request):
    """
    Return one of the characteristic description pages.
    """
    target_lang = util.get_target_lang_from_request(request)

    template_name = 'characteristic/%s.html' % (
        request.matchdict['characteristic'])

    context = {'request': request}
    context.update(util.rtl_context_stuff(target_lang))

    return Response(
        util.render_template(
            request, target_lang,
            template_name, context))
示例#18
0
def test_jinja():
    """
    Test that our Jinja environment works by examining this friendly
    bunny field.
    """
    bunnies = [{'name': 'Lilian', 'description': 'lazy'},
               {'name': 'Tobias', 'description': 'furious'},
               {'name': 'Frank', 'description': 'grouch'}]
    fake_request = Request.blank('/bunnies/')
    result = util.render_template(
        fake_request, 'en', 'test/bunnies.html', {'bunnies': bunnies})
    assert 'Welcome to the bunny field!' in result
    assert 'Lilian the lazy' in result

    test_results = util.TEST_TEMPLATE_CONTEXT.pop('test/bunnies.html')
    assert test_results['bunnies'] is bunnies
    assert test_results['request'] is fake_request
示例#19
0
def publicdomain_result(request):
    target_lang = util.get_target_lang_from_request(request)

    request_form = request.GET or request.POST

    # make sure the user selected "confirm"
    if request_form.get("understand", False) != "confirm":
        return exc.HTTPFound(location="%s?%s" % ("./publicdomain-3", urlencode(request.GET)))

    work_info = _work_info(request_form)
    license_html = PUBLICDOMAIN_HTML_FORMATTER.format(cc.license.by_code("publicdomain"), work_info, target_lang)

    context = _base_context(request, target_lang)
    context.update({"request_form": request_form, "license_html": license_html})

    return Response(
        util.render_template(request, target_lang, "chooser_pages/publicdomain/publicdomain-4.html", context)
    )
示例#20
0
def choose_xmp_view(request):
    request_form = request.GET or request.POST
    license = _issue_license(request_form)
    target_lang = util.get_target_lang_from_request(request)

    def attrib_or_none(field_name):
        return request_form.get(field_name, u'').strip() or None

    context = xmp_template.get_xmp_info(request_form, license, target_lang)
    context["default_lang"] = target_lang
    context["work_title"] = attrib_or_none("field_worktitle")
    context["attrib_name"] = attrib_or_none("field_attribute_to_name")
    context["attrib_url"] = attrib_or_none("field_attribute_to_url")
    context["permissions_url"] = attrib_or_none("field_morepermissionsurl")
    context["licenses"] = [{
        "lang": "x-default",
        "notice": context["notice"]
    }, {
        "lang": target_lang,
        "notice": context["notice"]
    }]
    del context["notice"]
    if target_lang != 'en':
        xmp_info_en = xmp_template.get_xmp_info(request_form, license, 'en')
        context["licenses"].append({
            "lang": 'en',
            "notice": xmp_info_en["notice"]
        })

    xmp_data = util.render_template(request, target_lang,
                                    'chooser_pages/metadata.xmp', context)

    return Response(xmp_data,
                    content_type='application/xmp; charset=UTF-8',
                    charset='UTF-8',
                    content_disposition='attachment; filename="CC_%s.xmp' %
                    (license.title().strip().replace(' ', '_')))
示例#21
0
def test_jinja():
    """
    Test that our Jinja environment works by examining this friendly
    bunny field.
    """
    bunnies = [{
        'name': 'Lilian',
        'description': 'lazy'
    }, {
        'name': 'Tobias',
        'description': 'furious'
    }, {
        'name': 'Frank',
        'description': 'grouch'
    }]
    fake_request = Request.blank('/bunnies/')
    result = util.render_template(fake_request, 'en', 'test/bunnies.html',
                                  {'bunnies': bunnies})
    assert 'Welcome to the bunny field!' in result
    assert 'Lilian the lazy' in result

    test_results = util.TEST_TEMPLATE_CONTEXT.pop('test/bunnies.html')
    assert test_results['bunnies'] is bunnies
    assert test_results['request'] is fake_request
示例#22
0
def publicdomain_result(request):
    target_lang = util.get_target_lang_from_request(request)

    request_form = request.GET or request.POST

    # make sure the user selected "confirm"
    if request_form.get('understand', False) != 'confirm':
        return exc.HTTPFound(location='%s?%s' %
                             ('./publicdomain-3', urlencode(request.GET)))

    work_info = _work_info(request_form)
    license_html = PUBLICDOMAIN_HTML_FORMATTER.format(
        cc.license.by_code('publicdomain'), work_info, target_lang)

    context = _base_context(request, target_lang)
    context.update({
        'request_form': request_form,
        'license_html': license_html
    })

    return Response(
        util.render_template(request, target_lang,
                             'chooser_pages/publicdomain/publicdomain-4.html',
                             context))
示例#23
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&jurisdiction=%s&version=%s&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))
def chooser_view(request):
    # Preserve the old partner interface by calling the old chooser view..
    if request.GET.get('partner'):
        return classic_chooser_view(request)

    #
    #  Used by the new-style chooser demos, for now.
    #
    target_lang = util.get_target_lang_from_request(request)
    context = _base_context(request, target_lang)
    request_form = request.GET or request.POST
    gettext = context['gettext']

    available_jurisdiction_codes = [
        j.code for j in get_selector_jurisdictions('standard')
        if j.code != '']
    
    requested_jurisdiction = None
    if request.GET.has_key('jurisdiction') and \
            request.GET['jurisdiction'] in available_jurisdiction_codes:
        requested_jurisdiction = request.GET['jurisdiction']        

    # Sort the jurisdictions for the dropdown via the translated name
    jurisdictions_names = [
        (juris, gettext(mappers.COUNTRY_MAP[juris]))
        for juris in available_jurisdiction_codes]
    jurisdictions_names = sorted(
        jurisdictions_names, key=lambda juris: juris[1])

    show_jurisdiction = request.GET.get('jurisdiction_choose') == '1'

    # Select a license based on the request form
    license = _issue_license(request_form)
    
    # Sets form default values, based on the request form or lack thereof
    defaults = {
        "license" : {
            "nc" : False,
            "sa" : False,
            "nd" : False,
            "jurisdiction" : "",
            "currency" : "",
            },
        "meta" : {
            "standard" : "html+rdfa",
            "format" : "",
            "title" : "",
            "attrib_name" : "",
            "attrib_url" : "",
            "src_url" : "",
            "permissions" : "",
            },
        "out" : {
            "format" : "html",
            "badge" : "normal",
            },
        "misc" : {
            "lang" : "",
            }
        }
    def equal_or_default(field, value, default=False):
        if request_form.has_key(field):
            return request_form[field] == value
        else:
            return default

    def value_or_default(field, default=""):
        if request_form.has_key(field):
            return unquote(request_form[field]).encode("utf-8")
        else:
            return default

    if request_form:
        defaults["license"] = {
            "nc" : equal_or_default('field_commercial', u'n'),
            "sa" : equal_or_default('field_derivatives', u'sa'),
            "nd" : equal_or_default('field_derivatives', u'n'),
            "jurisdiction" : value_or_default('field_jurisdiction'),
            "currency" : util.currency_symbol_from_request_form(request_form),
            }
        defaults["meta"] = {
            "standard"    : value_or_default("field_metadata_standard", "html+rdfa"),
            "format"      : value_or_default("field_format"),
            "title"       : value_or_default("field_worktitle"),
            "attrib_name" : value_or_default("field_attribute_to_name"),
            "attrib_url"  : value_or_default("field_attribute_to_url"),
            "src_url"     : value_or_default("field_sourceurl"),
            "permissions" : value_or_default("field_morepermissionsurl"),
            }
        defaults["out"]["badge"] = value_or_default("field_iconsize", "normal");
        defaults["misc"] = {
            "lang" : value_or_default("lang", ""),
            }

    # If the license is retired, redirect to info page
    if license.deprecated:
        # Special case: PDCC should redirect to /publicdomain/
        if license.license_code == 'publicdomain':
            return exc.HTTPMovedPermanently(location="/publicdomain/")
        else:
            return exc.HTTPMovedPermanently(location="/retiredlicenses")

    # Generate the HTML+RDFa for the license + provided work information
    work_dict = _formatter_work_dict(request_form)
    license_norm_logo = license.logo_method('88x13')
    license_slim_logo = license.logo_method('80x15')
    picked_logo = {
        "normal" : license_norm_logo,
        "small" : license_slim_logo
        }[defaults['out']['badge']]

    license_html = HTML_FORMATTER.format(
        license, work_dict, target_lang)

    if defaults['out']['badge'] == u"small":
        license_html = license_html.replace("88x31.png", "80x15.png")

    def has_code(code):
        return license.license_code.count(code) >= 1

    context.update(
        {'jurisdictions_names': jurisdictions_names,
         'show_jurisdiction': show_jurisdiction,
         'requested_jurisdiction': requested_jurisdiction,
         'referrer': request.headers.get('REFERER',''),
         'page_style': '2cols',
         'last_query': request.query_string,
         'form' : defaults,
         'currency' : util.currency_symbol_from_request_form(request_form),
         'license': license,
         'license_logo': picked_logo,
         'license_norm_logo': license_norm_logo,
         'license_slim_logo': license_slim_logo,
         'license_title': license.title(target_lang),
         'license_html': license_html,
         'license_code' : {
                'sa' : has_code('sa'),
                'nc' : has_code('nc'),
                'nd' : has_code('nd'),
                },
         })

    return Response(util.render_template(
            request, target_lang,
            'chooser_pages/interactive_chooser.html', context))
示例#25
0
def chooser_view(request):
    # Preserve the old partner interface by calling the old chooser view..
    if request.GET.get('partner'):
        return classic_chooser_view(request)

    #
    #  Used by the new-style chooser demos, for now.
    #
    target_lang = util.get_target_lang_from_request(request)
    context = _base_context(request, target_lang)
    request_form = request.GET or request.POST
    gettext = context['gettext']

    available_jurisdiction_codes = [
        j.code for j in get_selector_jurisdictions('standard') if j.code != ''
    ]

    requested_jurisdiction = None
    if request.GET.has_key('jurisdiction') and \
            request.GET['jurisdiction'] in available_jurisdiction_codes:
        requested_jurisdiction = request.GET['jurisdiction']

    # Sort the jurisdictions for the dropdown via the translated name
    jurisdictions_names = [(juris, gettext(mappers.COUNTRY_MAP[juris]))
                           for juris in available_jurisdiction_codes]
    jurisdictions_names = sorted(jurisdictions_names,
                                 key=lambda juris: juris[1])

    show_jurisdiction = request.GET.get('jurisdiction_choose') == '1'

    # Select a license based on the request form
    license = _issue_license(request_form)

    # Sets form default values, based on the request form or lack thereof
    defaults = {
        "license": {
            "nc": False,
            "sa": False,
            "nd": False,
            "jurisdiction": "",
            "currency": "",
        },
        "meta": {
            "standard": "html+rdfa",
            "format": "",
            "title": "",
            "attrib_name": "",
            "attrib_url": "",
            "src_url": "",
            "permissions": "",
        },
        "out": {
            "format": "html",
            "badge": "normal",
        },
        "misc": {
            "lang": "",
        }
    }

    def equal_or_default(field, value, default=False):
        if request_form.has_key(field):
            return request_form[field] == value
        else:
            return default

    def value_or_default(field, default=""):
        if request_form.has_key(field):
            return unquote(request_form[field]).encode("utf-8")
        else:
            return default

    if request_form:
        defaults["license"] = {
            "nc": equal_or_default('field_commercial', u'n'),
            "sa": equal_or_default('field_derivatives', u'sa'),
            "nd": equal_or_default('field_derivatives', u'n'),
            "jurisdiction": value_or_default('field_jurisdiction'),
            "currency": util.currency_symbol_from_request_form(request_form),
        }
        defaults["meta"] = {
            "standard": value_or_default("field_metadata_standard",
                                         "html+rdfa"),
            "format": value_or_default("field_format"),
            "title": value_or_default("field_worktitle"),
            "attrib_name": value_or_default("field_attribute_to_name"),
            "attrib_url": value_or_default("field_attribute_to_url"),
            "src_url": value_or_default("field_sourceurl"),
            "permissions": value_or_default("field_morepermissionsurl"),
        }
        defaults["out"]["badge"] = value_or_default("field_iconsize", "normal")
        defaults["misc"] = {
            "lang": value_or_default("lang", ""),
        }

    # If the license is retired, redirect to info page
    if license.deprecated:
        # Special case: PDCC should redirect to /publicdomain/
        if license.license_code == 'publicdomain':
            return exc.HTTPMovedPermanently(location="/publicdomain/")
        else:
            return exc.HTTPMovedPermanently(location="/retiredlicenses")

    # Generate the HTML+RDFa for the license + provided work information
    work_dict = _formatter_work_dict(request_form)
    license_norm_logo = license.logo_method('88x13')
    license_slim_logo = license.logo_method('80x15')
    picked_logo = {
        "normal": license_norm_logo,
        "small": license_slim_logo
    }[defaults['out']['badge']]

    license_html = HTML_FORMATTER.format(license, work_dict, target_lang)

    if defaults['out']['badge'] == u"small":
        license_html = license_html.replace("88x31.png", "80x15.png")

    def has_code(code):
        return license.license_code.count(code) >= 1

    context.update({
        'jurisdictions_names':
        jurisdictions_names,
        'show_jurisdiction':
        show_jurisdiction,
        'requested_jurisdiction':
        requested_jurisdiction,
        'referrer':
        request.headers.get('REFERER', ''),
        'page_style':
        '2cols',
        'last_query':
        request.query_string,
        'form':
        defaults,
        'currency':
        util.currency_symbol_from_request_form(request_form),
        'license':
        license,
        'license_logo':
        picked_logo,
        'license_norm_logo':
        license_norm_logo,
        'license_slim_logo':
        license_slim_logo,
        'license_title':
        license.title(target_lang),
        'license_html':
        license_html,
        'license_code': {
            'sa': has_code('sa'),
            'nc': has_code('nc'),
            'nd': has_code('nd'),
        },
    })

    return Response(
        util.render_template(request, target_lang,
                             'chooser_pages/interactive_chooser.html',
                             context))
示例#26
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&jurisdiction=%s&version=%s&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))