def add_locale(event):
    """
    add a cookie for the language to display (fallback to english).
    """
    LANGUAGE_MAPPING = {
        'de': 'de',
        'en': 'en',
    }

    locale = default_locale_negotiator(event.request)
    if locale is None:
        # default language
        locale = 'en'
        # check browser for language
        browser = event.request.accept_language
        if browser:
            locale_matched = browser.best_match(LANGUAGE_MAPPING, 'en')
            log.debug(
                (
                    "creating cookie for locale:\n"
                    "- locale of browser: %s\n"
                    "- locale matched: %s"
                ) % (
                    browser, locale_matched
                )
            )
            locale = LANGUAGE_MAPPING.get(locale_matched)
        # set cookie
        event.request.response.set_cookie('_LOCALE_', value=locale)

    event.request._LOCALE_ = locale
Beispiel #2
0
def locale_negotiator(request):
    '''This is a locale negotiator that decorates Pyramid's default one.

    If the default locale negotiator's schemes should fail,
    we try to match the browser's stated preferred languages
    with our configured enabled locales.
    '''
    return default_locale_negotiator(request) or locale_from_browser(request)
Beispiel #3
0
 def my_locale_negotiator(request):
     locale = default_locale_negotiator(request)
     available = settings['available_languages'].split()
     locale = locale if locale in available else None
     if not locale:
         locale = request.accept_language.best_match(
             available, settings.get('pyramid.default_locale_name', 'en'))
     request._LOCALE_ = locale
     return locale
Beispiel #4
0
    def __call__(self, request):
        """Negotiate the request locale.

        Uses the pyramid default negotiator the pick up the locale
        from the request parameters or the session. Then falls back to
        the Accept-Language header.
        """
        loc = default_locale_negotiator(request)
        if not loc:
            loc = request.accept_language.best_match(self.locales)
        return loc
Beispiel #5
0
 def my_locale_negotiator(request):
     locale = to_posix_format(default_locale_negotiator(request))
     available = settings['available_languages'].split()
     if locale and locale not in available:
         locale_with_country = ensure_locale_has_country(locale)
         if locale_with_country:
             locale = locale_with_country
     if not locale:
         locale = to_posix_format(request.accept_language.best_match(
             available, settings.get('pyramid.default_locale_name', 'en')))
     request._LOCALE_ = locale
     return locale
Beispiel #6
0
def locale_negotiator(request):
    locale_name = default_locale_negotiator(request)
    if locale_name is None:
        accept_language = request.accept_language

        # Header is set, if not the first offer is returned
        # We want to use the configured default
        if accept_language:
            locale_name = accept_language.best_match(
                request.available_locales,
            )

    return locale_name
Beispiel #7
0
def add_locale_to_cookie(event):
    locale = default_locale_negotiator(event.request)
    #print locale
    if locale is None and event.request.accept_language:
        #print "request.accept_language: " + str(event.request.accept_language)
        #print "locale is None but accept_language exists!"
        locale = event.request.accept_language.best_match(BROWSER_LANGUAGES)
        #print "locale aus accept_language:" + locale
        locale = BROWSER_LANGUAGES.get(locale)
        #print "locale aus BROWSER_LANGUAGES:" + str(locale)
    if locale is None and not event.request.accept_language:
        locale = 'en'

    #print "setting locale: " + str(locale)
    # event.request.cookies['_LOCALE_'] = locale
    event.request.response.set_cookie('_LOCALE_', value=locale)
Beispiel #8
0
def locale_negotiator(request):
    settings = get_config()
    available = settings.get('available_languages').split()
    locale = (request.cookies.get('_LOCALE_', None) or
              request.params.get('_LOCALE_', None))
    # TODO: Set User preference in this function.
    if not locale:
        from pyramid.security import authenticated_userid
        from assembl.auth.util import discussion_from_request
        from assembl.models import get_session_maker
        user_id = authenticated_userid(request)
        if user_id:
            prefs = get_preferred_languages(get_session_maker()(), user_id)
            for locale in prefs:
                if locale in available:
                    break
                if '_' not in locale:
                    locale = ensure_locale_has_country(locale)
                    if locale and locale in available:
                        break
            else:
                locale = None
        if locale is None:
            discussion = discussion_from_request(request)
            if discussion:
                for locale in discussion.discussion_locales:
                    if locale in available:
                        break
                    if '_' not in locale:
                        locale = ensure_locale_has_country(locale)
                        if locale and locale in available:
                            break
                else:
                    locale = None
    if not locale:
        locale = to_posix_format(default_locale_negotiator(request))
    if locale and locale not in available:
        locale_with_country = ensure_locale_has_country(locale)
        if locale_with_country:
            locale = locale_with_country
    if not locale:
        locale = to_posix_format(request.accept_language.best_match(
            available, settings.get('pyramid.default_locale_name', 'en')))
    request._LOCALE_ = locale
    return locale
Beispiel #9
0
 def _callFUT(self, request):
     from pyramid.i18n import default_locale_negotiator
     return default_locale_negotiator(request)
Beispiel #10
0
def add_locale_to_cookie(event):
    """
    give user a cookie to determine the language to display.
    if user has chosen another language by clicking a flag,
    give her that language (cookie & redirect).
    ask users browser for language to display,
    fallback to english if language is not available.
    """
    DEBUG = False

    # if user clicked at particular language flag
    if event.request.query_string is not '':
        # the list of available languages is taken from the .ini file:
        # either development.ini or production.ini
        languages = event.request.registry.settings[
            'available_languages'].split()
        if event.request.query_string in languages:
            # we want to reload the page in this other language
            lang = event.request.query_string

            # so we put it on the request object as locale and redirect info
            event.request._LOCALE_ = event.request._REDIRECT_ = lang
            # and we set a cookie
            event.request.response.set_cookie('_LOCALE_', value=lang)

            if DEBUG:  # pragma: no cover
                print("switching language to " + lang)
            #from pyramid.httpexceptions import HTTPFound
            #print("XXXXXXXXXXXXXXX ==> REDIRECTING in subscriber")
            #return HTTPFound(location=event.request.route_url('intent'),
            #                 headers=event.request.response.headers)
            #
            # redirect not working here!
            # redirects to relevant language,
            # but does not clean URL from query_string in browser
            # redirecting in views.py using _REDIRECT_ attribute of the request

    # get locale from request
    locale = default_locale_negotiator(event.request)

    if DEBUG:  # pragma: no cover
        print("locale (from default_locale_negotiator): " + str(locale))

    # if locale is not already set, look at browser information
    if locale is None and event.request.accept_language:
        #print "request.accept_language: " + str(event.request.accept_language)
        #print "locale is None but accept_language exists!"
        locale = event.request.accept_language.best_match(BROWSER_LANGUAGES)
        #print "locale aus accept_language:" + locale
        locale = BROWSER_LANGUAGES.get(locale)
        #print "locale aus BROWSER_LANGUAGES:" + str(locale)

    # if we have nothing, assume english as fallback
    if locale is None and not event.request.accept_language:
        #print("locale could not be determined by browsers Accept-Language. "
        #      + "defaulting to English")
        locale = 'en'

    #print "setting locale: " + str(locale)
    # make the request know which language to respond with
    event.request._LOCALE_ = locale
    # store language setting in cookie
    event.request.response.set_cookie('_LOCALE_', value=locale)
Beispiel #11
0
def locale_negotiator_with_fallbacks(request):
    locale_name = default_locale_negotiator(request)
    return get_locale_with_fallbacks(locale_name)
Beispiel #12
0
def my_locale_negotiator(request):
    locale = default_locale_negotiator(request)
    if locale is None and getattr(request, 'accept_language', None):
        locale = request.accept_language.best_match(AVAILABLE_LANGUAGES)

    return locale
Beispiel #13
0
def home_view(request):
    user_id = authenticated_userid(request) or Everyone
    context = get_default_context(request)
    discussion = context["discussion"]
    canRead = user_has_permission(discussion.id, user_id, P_READ)
    if not canRead and user_id == Everyone:
        # User isn't logged-in and discussion isn't public:
        # redirect to login page
        login_url = request.route_url(
            'contextual_login', discussion_slug=discussion.slug)
        return HTTPSeeOther(login_url)
    elif not canRead:
        # User is logged-in but doesn't have access to the discussion
        return HTTPUnauthorized()

    # if the route asks for a post, get post content (because this is needed for meta tags)
    route_name = request.matched_route.name
    if route_name == "purl_posts":
        post_id = FrontendUrls.getRequestedPostId(request)
        if post_id:
            post = Post.get_instance(post_id)
            if post and post.discussion_id == discussion.id:
                context['post'] = post
    elif route_name == "purl_idea":
        idea_id = FrontendUrls.getRequestedIdeaId(request)
        if idea_id:
            idea = Idea.get_instance(idea_id)
            if idea and idea.discussion_id == discussion.id:
                context['idea'] = idea

    canAddExtract = user_has_permission(discussion.id, user_id, P_ADD_EXTRACT)
    context['canAddExtract'] = canAddExtract
    context['canDisplayTabs'] = True
    if user_id != Everyone:
        from assembl.models import AgentProfile
        user = AgentProfile.get(user_id)
        # TODO: user may not exist. Case of session with BD change.
        user.is_visiting_discussion(discussion.id)
        session = Discussion.db()
        current_prefs = session.query(UserLanguagePreference).\
            filter_by(user_id = user_id).all()
        user = session.query(User).filter_by(id = user_id).first()

        if '_LOCALE_' in request.cookies:
            locale = request.cookies['_LOCALE_']
            posix_locale = to_posix_format(locale)
            process_locale(posix_locale,user_id,
                           current_prefs, session,
                           LanguagePreferenceOrder.Cookie)

        elif '_LOCALE_' in request.params:
            locale = request.params['_LOCALE_']
            posix_locale = to_posix_format(locale)
            process_locale(posix_locale, user_id,
                           current_prefs, session,
                           LanguagePreferenceOrder.Parameter)
        else:
            locale = default_locale_negotiator(request)
            posix_locale = to_posix_format(locale)
            process_locale(posix_locale, user_id,
                           current_prefs, session,
                           LanguagePreferenceOrder.OS_Default)


    response = render_to_response('../../templates/index.jinja2', context, request=request)
    # Prevent caching the home, especially for proper login/logout
    response.cache_control.max_age = 0
    response.cache_control.prevent_auto = True
    return response