Exemplo n.º 1
0
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
Exemplo n.º 2
0
    def getPreferredLanguages(self):
        # If the default locale negotiater can get a value,
        # that means we had a parameter or one of the cookies
        # (because of the subscriber that gets us here).

        negotiated = default_locale_negotiator(self.request)
        if negotiated:
            return [negotiated]

        # Here is where we would check for something during traversal,
        # but we don't actually support that at this time because it
        # relies on implementation details

        # Is there a non-default user preference? Right now we know
        # what a default is due to implementation details above. We also
        # know for sure that we *have* a remote use, otherwise we wouldn't
        # be here
        remote_user = IPrincipal(self.request, None)
        remote_user_langs = IUserPreferredLanguages(remote_user)
        if remote_user_langs is not EnglishUserPreferredLanguagesImpl:
            return remote_user_langs.getPreferredLanguages() # pylint:disable=too-many-function-args

        # Ok, see what the HTTP request can come up with. Note that we're
        # going to the Zope interface so that we don't get into an infinite
        # loop
        browser_request = IBrowserRequest(self.request)
        browser_langs = IModifiableUserPreferredLanguages(browser_request)
        return browser_langs.getPreferredLanguages() # pylint:disable=too-many-function-args
Exemplo n.º 3
0
def adjust_request_interface_for_preferred_languages(event):
    """
    Checks the conditions outlined in this package's documentation and
    adds a marker interface (:class:`.IPreferredLanguagesRequest`) to
    the request if they hold true.

    This is registered as a subscriber for Pyramid's
    :class:`.IContextFound` event by this package's ``configure.zcml``
    """
    request = event.request
    # Does pyramid's default negotiator, which uses explicit settings
    # like a request param or cookie have an answer? If so, we need
    # our custom policy...these override the Accept-Language header
    if default_locale_negotiator(request):
        interface.alsoProvides(request, IPreferredLanguagesRequest)
        return

    # What about the zope/plone cookie?
    if request.cookies.get('I18N_LANGUAGE'):
        # For benefit of the default localization machinery
        # in case it's used, copy
        request._LOCALE_ = request.cookies.get('I18N_LANGUAGE')
        interface.alsoProvides(request, IPreferredLanguagesRequest)
        return

    # Ok, is there an authenticated user with preferred languages?
    # (We leave detecting defaults up to the actual policy)
    remote_user = IPrincipal(request, None)
    if remote_user and not IUnauthenticatedPrincipal.providedBy(remote_user):
        remote_user_langs = IUserPreferredLanguages(remote_user)
        if remote_user_langs and remote_user_langs.getPreferredLanguages():  # pylint:disable=too-many-function-args
            interface.alsoProvides(request, IPreferredLanguagesRequest)
Exemplo n.º 4
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)
Exemplo n.º 5
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)
Exemplo n.º 6
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
Exemplo n.º 7
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
Exemplo n.º 8
0
def locale_negotiator(request):
    available_locales = aslist(request.registry.settings['available_locales'])
    default_locale = request.registry.settings['pyramid.default_locale_name']
    locale = default_locale_negotiator(request)

    if locale in available_locales:
        return locale

    return request.accept_language.best_match(available_locales,
                                              default_locale)
Exemplo n.º 9
0
def _negotiate_locale(request):
    locale_name = getattr(request, LOCALE_ATTR, None)
    if locale_name is not None:
        return locale_name

    locale_name = request.params.get(LOCALE_ATTR)
    if locale_name is not None:
        return locale_name

    locale_name = request.cookies.get(LOCALE_ATTR)
    if locale_name is not None:
        return locale_name

    if not request.accept_language:
        return default_locale_negotiator(request)

    return request.accept_language.best_match(
        tuple(KNOWN_LOCALES.keys()),
        default_match=default_locale_negotiator(request))
Exemplo n.º 10
0
def locale_negotiator(request):
    locale_name = default_locale_negotiator(request)

    # available languages are not handled by pyramid itself
    if locale_name is None:
        available = aslist(
            request.registry.settings['pyramid.available_languages'])
        locale_name = request.accept_language.best_match(available)

    return locale_name
Exemplo n.º 11
0
def locale_negotiator(request):
    locale_name = default_locale_negotiator(request)

    # available languages are not handled by pyramid itself
    if locale_name is None:
        available = aslist(request.registry.settings["pyramid.available_languages"])
        default = request.registry.settings["pyramid.default_locale_name"]
        locale_name = request.accept_language.lookup(available, default=default)

    return locale_name
Exemplo n.º 12
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
Exemplo n.º 13
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
Exemplo n.º 14
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
Exemplo n.º 15
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
Exemplo n.º 16
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)
Exemplo n.º 17
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)
Exemplo n.º 18
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_string(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_string(
            request.accept_language.best_match(
                available, settings.get('pyramid.default_locale_name', 'en')))
    request._LOCALE_ = locale
    return locale
Exemplo n.º 19
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
Exemplo n.º 20
0
 def _callFUT(self, request):
     from pyramid.i18n import default_locale_negotiator
     return default_locale_negotiator(request)
Exemplo n.º 21
0
 def _callFUT(self, request):
     from pyramid.i18n import default_locale_negotiator
     return default_locale_negotiator(request)
Exemplo n.º 22
0
def locale_negotiator_with_fallbacks(request):
    locale_name = default_locale_negotiator(request)
    return get_locale_with_fallbacks(locale_name)
Exemplo n.º 23
0
def home_view(request):
    user_id = authenticated_userid(request) or Everyone
    context = get_default_context(request)
    discussion = context["discussion"]
    request.session["discussion"] = discussion.slug
    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 not post_id:
            return HTTPSeeOther(
                request.route_url('home', discussion_slug=discussion.slug))
        post = Post.get_instance(post_id)
        if not post or post.discussion_id != discussion.id:
            return HTTPSeeOther(
                request.route_url('home', discussion_slug=discussion.slug))
        context['post'] = post
    elif route_name == "purl_idea":
        idea_id = FrontendUrls.getRequestedIdeaId(request)
        if not idea_id:
            return HTTPSeeOther(
                request.route_url('home', discussion_slug=discussion.slug))
        idea = Idea.get_instance(idea_id)
        if not idea or idea.discussion_id != discussion.id:
            return HTTPSeeOther(
                request.route_url('home', discussion_slug=discussion.slug))
        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.default_db
        current_prefs = session.query(UserLanguagePreference).\
            filter_by(user_id = user_id).all()
        user = session.query(User).filter_by(id=user_id).first()

        def validate_locale(l):
            return ensure_locale_has_country(to_posix_format(locale))

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

        elif '_LOCALE_' in request.params:
            locale = request.params['_LOCALE_']
            posix_locale = validate_locale(locale)
            process_locale(posix_locale, user_id, current_prefs, session,
                           LanguagePreferenceOrder.Parameter)
        else:
            locale = default_locale_negotiator(request)
            posix_locale = validate_locale(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
Exemplo n.º 24
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
Exemplo n.º 25
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
Exemplo n.º 26
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)
Exemplo n.º 27
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 '':
        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)